From 1d6dce827f9f27bdaf88df9933aa4034d6bd14fc Mon Sep 17 00:00:00 2001 From: Denys Bahachuk Date: Sun, 8 Nov 2026 15:36:10 +0000 Subject: [PATCH 1/2] feat(EM-26): deliver Email Workspace events over WebSocket --- README.md | 10 + app/web_conn.go | 2 + app/web_email.go | 341 ++++++++++++++++ app/web_email_test.go | 513 +++++++++++++++++++++++++ app/web_hub.go | 14 + docs/email-events.md | 243 ++++++++++++ go.mod | 2 +- model/config.go | 2 + model/email_event.go | 126 ++++++ model/email_event_test.go | 43 +++ model/email_ws.go | 43 +++ model/email_ws_test.go | 33 ++ mq/mq.go | 4 + mq/rabbit/domain_queue.go | 93 ++++- mq/rabbit/domain_queue_test.go | 21 +- mq/rabbit/email_binder.go | 252 ++++++++++++ mq/rabbit/email_domain_queue_test.go | 323 ++++++++++++++++ mq/rabbit/email_ws_integration_test.go | 190 +++++++++ wsapi/email.go | 15 + 19 files changed, 2260 insertions(+), 10 deletions(-) create mode 100644 app/web_email.go create mode 100644 app/web_email_test.go create mode 100644 docs/email-events.md create mode 100644 model/email_event.go create mode 100644 model/email_event_test.go create mode 100644 model/email_ws.go create mode 100644 model/email_ws_test.go create mode 100644 mq/rabbit/email_binder.go create mode 100644 mq/rabbit/email_domain_queue_test.go create mode 100644 mq/rabbit/email_ws_integration_test.go diff --git a/README.md b/README.md index 6bd0759c..83abd738 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,15 @@ # engine +## Email events — EM-26 + +Stage 17 delivers the Workspace events of `email-service` to the operator over +WebSocket (`subscribe_email`, event `email`): as for calls and chats, the queue +of a node with the operator's sockets is bound to the key of the user. +Workspace reads the changed Thread through the read API. Contract, client +synchronization and the flag `EMAIL_WORKSPACE` (off by default): +[docs/email-events.md](docs/email-events.md). +The WebSocket part waits for confirmation by Workspace. + ## Email commands — EM-25 Workspace sends the Email attempt commands of an operator over WebSocket: diff --git a/app/web_conn.go b/app/web_conn.go index 2d9fc268..15361a91 100644 --- a/app/web_conn.go +++ b/app/web_conn.go @@ -52,6 +52,8 @@ type WebConn struct { endWritePump chan struct{} pumpFinished chan struct{} listenEvents map[string]*model.BindQueueEvent + emailMx sync.Mutex + emailSub atomic.Pointer[emailSubscription] createdAt time.Time applicationName string applicationVer string diff --git a/app/web_email.go b/app/web_email.go new file mode 100644 index 00000000..fc0f0fad --- /dev/null +++ b/app/web_email.go @@ -0,0 +1,341 @@ +package app + +import ( + "context" + "sync" + "sync/atomic" + "time" + + "github.com/webitel/engine/model" + "github.com/webitel/engine/pkg/wbt/auth_manager" + "github.com/webitel/wlog" +) + +// Email events of Workspace (EM-26, docs/email-events.md "WebSocket"). The hub never waits +// for the network: a worker of every subscribed socket checks the session and the read +// right, then hands the event back to the hub, the only writer of conn.Send. + +const ( + emailQueueSize = 64 + emailSeenSize = 256 + emailOutSize = 1024 + emailBindTimeout = 5 * time.Second + emailAuthTimeout = 5 * time.Second +) + +// The pause after a failed session check doubles from emailAuthRetry to emailAuthRetryMax. +var ( + emailAuthRetry = 5 * time.Second + emailAuthRetryMax = 60 * time.Second +) + +type emailSubscription struct { + conn *WebConn + bind atomic.Pointer[model.BindQueueEvent] + in chan *model.EmailEvent + kick chan struct{} + overflow atomic.Bool + ended atomic.Bool + stop chan struct{} + stopOnce sync.Once + seen emailSeen // used by the hub alone +} + +// emailOut is a message of a worker for the hub; id is empty for resync_required, which +// goes even after the subscription ended. +type emailOut struct { + sub *emailSubscription + msg *model.WebSocketEvent + id string +} + +// emailSeen keeps the last ids sent to one socket. +type emailSeen struct { + ids map[string]struct{} + ring []string + next int +} + +func (s *emailSeen) has(id string) bool { + _, ok := s.ids[id] + + return ok +} + +func (s *emailSeen) add(id string) { + if s.ids == nil { + s.ids, s.ring = make(map[string]struct{}, emailSeenSize), make([]string, emailSeenSize) + } + delete(s.ids, s.ring[s.next]) + s.ring[s.next] = id + s.ids[id] = struct{}{} + s.next = (s.next + 1) % emailSeenSize +} + +// SubscribeEmail subscribes the socket to the Email events of its own session; it returns +// after the broker confirmed the binding. +func (a *App) SubscribeEmail(ctx context.Context, conn *WebConn, session *auth_manager.Session) model.AppError { + if !a.config.EmailWorkspace { + return model.NewBadRequestError("app.email.subscribe.disabled", "Email events are not enabled") + } + permission := session.GetPermission(model.PERMISSION_SCOPE_EMAIL_THREAD) + if !permission.CanRead() { + return a.MakePermissionError(session, permission, auth_manager.PERMISSION_ACCESS_READ) + } + if session.UserId != conn.UserId || session.DomainId != conn.DomainId { + return model.NewForbiddenError("app.email.subscribe.identity", "the session belongs to another user") + } + h, err := a.GetHubById(session.DomainId) + if err != nil { + return err + } + + return h.subscribeEmail(ctx, conn) +} + +// UnsubscribeEmail ends the subscription of this socket only. +func (a *App) UnsubscribeEmail(conn *WebConn) model.AppError { + h, err := a.GetHubById(conn.DomainId) + if err != nil { + return err + } + conn.emailMx.Lock() + defer conn.emailMx.Unlock() + if sub := conn.emailSub.Load(); sub != nil { + h.endEmail(sub) + } + + return nil +} + +func (wh *Hub) subscribeEmail(ctx context.Context, conn *WebConn) model.AppError { + conn.emailMx.Lock() + defer conn.emailMx.Unlock() + if conn.emailSub.Load() != nil { + return nil + } + + // Registered first: an event that comes with the binding is not lost. + sub := &emailSubscription{conn: conn, in: make(chan *model.EmailEvent, emailQueueSize), + kick: make(chan struct{}, 1), stop: make(chan struct{})} + conn.emailSub.Store(sub) + go wh.runEmail(sub) + + ctx, cancel := context.WithTimeout(ctx, emailBindTimeout) + defer cancel() + // Every subscription binds under its own id: the cleanup of an older one never + // removes a newer one of the same socket. + b, err := wh.domainQueue.BindUserEmailWait(ctx, conn.Id()+"/"+model.NewId()[:8], conn.UserId) + if err != nil { + wh.endEmail(sub) + + return model.NewInternalError("app.email.subscribe.bind", err.Error()) + } + sub.bind.Store(b) + if sub.ended.Load() { + // The socket closed meanwhile; whoever takes the binding removes it. + if b := sub.bind.Swap(nil); b != nil { + wh.domainQueue.UnbindEmail(b) + } + + return model.NewInternalError("app.email.subscribe.closed", "the socket closed") + } + + return nil +} + +// endEmail stops the worker and removes the binding of this socket without waiting for the +// broker; it may run more than once. +func (wh *Hub) endEmail(sub *emailSubscription) { + sub.ended.Store(true) + sub.conn.emailSub.CompareAndSwap(sub, nil) + sub.stopOnce.Do(func() { close(sub.stop) }) + if b := sub.bind.Swap(nil); b != nil { + wh.domainQueue.UnbindEmail(b) + } +} + +// dispatchEmail hands the event to the worker of every subscribed socket of the user; a full +// worker queue loses the event and asks for a resync. +func (wh *Hub) dispatchEmail(connections *hubConnectionIndex, e *model.EmailEvent) { + for _, webCon := range connections.ForUser(e.UserId) { + sub := webCon.emailSub.Load() + if sub == nil || webCon.DomainId != e.DomainId { + continue + } + select { + case sub.in <- e: + default: + if !sub.overflow.Swap(true) { + webCon.Log().Warn("webhub.email: queue is full, resync", wlog.String("event_type", "email")) + } + select { + case sub.kick <- struct{}{}: + default: + } + } + } +} + +// sendEmail writes a checked event to the socket; a full socket is closed as for the other +// events. An id goes once to a socket, counted only once it is in the send buffer. +func (wh *Hub) sendEmail(connections *hubConnectionIndex, out emailOut) { + conn := out.sub.conn + if !connections.Has(conn) { + return + } + if out.id != "" && (conn.emailSub.Load() != out.sub || out.sub.seen.has(out.id)) { + return + } + select { + case conn.Send <- out.msg: + if out.id != "" { + out.sub.seen.add(out.id) + } + default: + conn.Log().Error("webhub.broadcast.email: cannot send, closing websocket", wlog.String("event_type", "email")) + close(conn.Send) + connections.Remove(conn) + } +} + +// emailRebound: the node queue came back after a loss with no Email bindings, so the events +// in between are lost. Every subscription ends; the client subscribes again. +func (wh *Hub) emailRebound(connections *hubConnectionIndex) { + ended := 0 + for webCon := range connections.All() { + if sub := webCon.emailSub.Load(); sub != nil { + wh.endEmail(sub) + wh.sendEmail(connections, emailOut{sub: sub, msg: model.NewEmailResyncEvent(model.EmailResyncSubscriptionLost)}) + ended++ + } + } + if ended > 0 { + wh.log.Warn("webhub.email: node queue was lost, subscriptions ended, clients resync", wlog.Int("subscriptions", ended)) + } +} + +type emailVerdict int + +const ( + emailAllow emailVerdict = iota + emailDeny // auth is unavailable: nothing goes, a resync follows + emailRevoked // the session ended or lost the read right + emailIdentity // the token now names another user +) + +// emailAuth is the last check of the session of one socket. +type emailAuth struct { + session *auth_manager.Session + checked time.Time + retryAt time.Time + pause time.Duration + lost bool +} + +// access checks the session at most once per auth_cache_expire and when it expires; an +// unavailable auth never lets an event through. +func (wh *Hub) emailAccess(sub *emailSubscription, a *emailAuth) emailVerdict { + now := time.Now() + ttl := time.Duration(max(wh.app.config.AuthCacheExpire, 1)) * time.Second + // Expire is in milliseconds, as WebConn reads it. + if a.session != nil && now.Sub(a.checked) < ttl && (a.session.Expire == 0 || a.session.Expire > model.GetMillis()) { + return emailAllow + } + if now.Before(a.retryAt) { + return emailDeny + } + + ctx, cancel := context.WithTimeout(context.Background(), emailAuthTimeout) + defer cancel() + s, err := wh.app.GetSessionWitchContext(ctx, sub.conn.GetSessionToken()) + switch { + case err != nil && err.GetStatusCode() >= 500: + sub.conn.Log().Warn("webhub.email: session check failed, events wait", wlog.Err(err)) + a.pause = min(max(2*a.pause, emailAuthRetry), emailAuthRetryMax) + a.session, a.retryAt, a.lost = nil, now.Add(a.pause), true + + return emailDeny + case err != nil: + return emailRevoked + case s.UserId != sub.conn.UserId || s.DomainId != sub.conn.DomainId: + return emailIdentity + case !s.GetPermission(model.PERMISSION_SCOPE_EMAIL_THREAD).CanRead(): + return emailRevoked + } + a.session, a.checked, a.pause = s, now, 0 + + return emailAllow +} + +// runEmail delivers the events of one socket. While auth is unavailable a timer checks the +// session again, so the resync comes also when no other event does. +func (wh *Hub) runEmail(sub *emailSubscription) { + var auth emailAuth + retry := time.NewTimer(time.Hour) + retry.Stop() + defer retry.Stop() + retrying := false + for { + var e *model.EmailEvent + recheck := false + select { + case <-sub.stop: + return + case <-wh.stop: + return + case <-sub.kick: + case e = <-sub.in: + case <-retry.C: + retrying, recheck = false, true + } + if sub.overflow.Swap(false) && !wh.emitEmail(sub, model.NewEmailResyncEvent(model.EmailResyncOverflow), "") { + return + } + if e == nil && !recheck { + continue + } + + switch wh.emailAccess(sub, &auth) { + case emailDeny: + if !retrying { + retry.Reset(time.Until(auth.retryAt)) + retrying = true + } + + continue + case emailRevoked: + sub.conn.Log().Info("webhub.email: session may not read Email, subscription ended") + wh.emitEmail(sub, model.NewEmailResyncEvent(model.EmailResyncSubscriptionLost), "") + wh.endEmail(sub) + + return + case emailIdentity: + sub.conn.Log().Warn("webhub.email: session of another user, closing websocket") + wh.endEmail(sub) + _ = sub.conn.WebSocket.Close() + + return + } + if auth.lost { + auth.lost = false + if !wh.emitEmail(sub, model.NewEmailResyncEvent(model.EmailResyncSubscriptionLost), "") { + return + } + } + if e != nil && !wh.emitEmail(sub, e.WebSocketEvent(), e.EventId) { + return + } + } +} + +func (wh *Hub) emitEmail(sub *emailSubscription, msg *model.WebSocketEvent, id string) bool { + select { + case wh.emailOut <- emailOut{sub: sub, msg: msg, id: id}: + return true + case <-sub.stop: + return false + case <-wh.stop: + return false + } +} diff --git a/app/web_email_test.go b/app/web_email_test.go new file mode 100644 index 00000000..3fc0030c --- /dev/null +++ b/app/web_email_test.go @@ -0,0 +1,513 @@ +package app + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/gorilla/websocket" + "github.com/webitel/engine/model" + "github.com/webitel/engine/mq" + "github.com/webitel/engine/pkg/wbt/auth_manager" + "github.com/webitel/engine/store" + "github.com/webitel/wlog" +) + +// fakeEmailQueue is the node queue of domain 1: the test pushes events and reconnects. +type fakeEmailQueue struct { + mq.DomainQueue + email chan *model.EmailEvent + chat chan *model.ChatEvent + rebound chan struct{} + + mu sync.Mutex + bound map[string]bool + binds int + unbinds []string + bindErr error +} + +func newFakeEmailQueue() *fakeEmailQueue { + return &fakeEmailQueue{email: make(chan *model.EmailEvent), chat: make(chan *model.ChatEvent), + rebound: make(chan struct{}), bound: map[string]bool{}} +} + +func (q *fakeEmailQueue) Start() {} +func (q *fakeEmailQueue) Stop() {} +func (q *fakeEmailQueue) Events() <-chan *model.WebSocketEvent { return nil } +func (q *fakeEmailQueue) CallEvents() <-chan *model.CallEvent { return nil } +func (q *fakeEmailQueue) UserStateEvents() <-chan *model.UserState { return nil } +func (q *fakeEmailQueue) NotificationEvents() <-chan *model.Notification { return nil } +func (q *fakeEmailQueue) ChatEvents() <-chan *model.ChatEvent { return q.chat } +func (q *fakeEmailQueue) EmailEvents() <-chan *model.EmailEvent { return q.email } +func (q *fakeEmailQueue) Rebound() <-chan struct{} { return q.rebound } +func (q *fakeEmailQueue) BulkUnbind(_ []*model.BindQueueEvent) model.AppError { return nil } + +func (q *fakeEmailQueue) BindUserEmailWait(_ context.Context, id string, userId int64) (*model.BindQueueEvent, error) { + q.mu.Lock() + defer q.mu.Unlock() + if q.bindErr != nil { + return nil, q.bindErr + } + q.binds++ + q.bound[id] = true + + return &model.BindQueueEvent{Id: id, UserId: userId, Exchange: model.EmailServiceExchange, + Routing: model.EmailBindingKey(1, userId)}, nil +} + +func (q *fakeEmailQueue) HasBinding(b *model.BindQueueEvent) bool { + q.mu.Lock() + defer q.mu.Unlock() + + return q.bound[b.Id] +} + +func (q *fakeEmailQueue) Unbind(b *model.BindQueueEvent) model.AppError { + q.mu.Lock() + defer q.mu.Unlock() + delete(q.bound, b.Id) + q.unbinds = append(q.unbinds, b.Id) + + return nil +} + +func (q *fakeEmailQueue) UnbindEmail(b *model.BindQueueEvent) { _ = q.Unbind(b) } + +func (q *fakeEmailQueue) state() (bound, unbound int) { + q.mu.Lock() + defer q.mu.Unlock() + + return len(q.bound), len(q.unbinds) +} + +func (q *fakeEmailQueue) unbound(id string) bool { + q.mu.Lock() + defer q.mu.Unlock() + + return !q.bound[id] +} + +func (q *fakeEmailQueue) bindCalls() int { + q.mu.Lock() + defer q.mu.Unlock() + + return q.binds +} + +type fakeMQ struct { + mq.MQ + q *fakeEmailQueue +} + +func (m *fakeMQ) NewDomainQueue(int64, model.GetAllBindings) (mq.DomainQueue, model.AppError) { + return m.q, nil +} +func (m *fakeMQ) RegisterWebsocket(int64, *model.RegisterToWebsocketEvent) model.AppError { return nil } +func (m *fakeMQ) UnRegisterWebsocket(int64, *model.RegisterToWebsocketEvent) model.AppError { + return nil +} + +// fakeAuth answers by token; block holds every check until it is closed. +type fakeAuth struct { + auth_manager.AuthManager + mu sync.Mutex + sessions map[string]*auth_manager.Session + err error + block chan struct{} +} + +func (f *fakeAuth) GetSession(ctx context.Context, token string) (*auth_manager.Session, error) { + f.mu.Lock() + block, err, s := f.block, f.err, f.sessions[token] + f.mu.Unlock() + if block != nil { + select { + case <-block: + case <-ctx.Done(): + return nil, auth_manager.ErrInternal + } + } + if err != nil { + return nil, err + } + if s == nil { + return nil, auth_manager.ErrStatusUnauthenticated + } + c := *s + + return &c, nil +} + +func (f *fakeAuth) set(change func()) { + f.mu.Lock() + defer f.mu.Unlock() + change() +} + +type fakeStore struct{ store.Store } + +func (fakeStore) SocketSession() store.SocketSessionStore { return fakeSockets{} } + +type fakeSockets struct{ store.SocketSessionStore } + +func (fakeSockets) Create(context.Context, model.SocketSession) model.AppError { return nil } +func (fakeSockets) SetUpdatedAt(context.Context, string, time.Time) model.AppError { return nil } +func (fakeSockets) DeleteById(context.Context, string) model.AppError { return nil } + +func emailSession(token string, user int64, read bool) *auth_manager.Session { + s := &auth_manager.Session{Id: token, Token: token, UserId: user, DomainId: 1, Expire: model.GetMillis() + 3600_000} + if read { + s.Scopes = []auth_manager.SessionPermission{{Name: model.PERMISSION_SCOPE_EMAIL_THREAD, Obac: true, + Access: auth_manager.PERMISSION_ACCESS_READ.Value()}} + } + + return s +} + +type emailEnv struct { + app *App + q *fakeEmailQueue + auth *fakeAuth + srv *httptest.Server + hub *Hub +} + +func newEmailEnv(t *testing.T) *emailEnv { + t.Helper() + q := newFakeEmailQueue() + auth := &fakeAuth{sessions: map[string]*auth_manager.Session{ + "tab-a": emailSession("tab-a", 42, true), "tab-b": emailSession("tab-b", 42, true), + "other": emailSession("other", 43, true)}} + a := &App{config: &model.Config{EmailWorkspace: true, AuthCacheExpire: 30}, ctx: context.Background(), + Log: wlog.NewLogger(&wlog.LoggerConfiguration{}), tracer: NewTrace(), MessageQueue: &fakeMQ{q: q}, + sessionManager: auth, Store: fakeStore{}} + a.Hubs = NewHubs(a) + env := &emailEnv{app: a, q: q, auth: auth} + env.hub, _ = a.GetHubById(1) + up := websocket.Upgrader{} + env.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ws, err := up.Upgrade(w, r, nil) + if err != nil { + return + } + token := r.URL.Query().Get("token") + wc := a.NewWebConn(ws, *auth.sessions[token], "test", "1", "ua", "127.0.0.1") + wc.DomainId = 1 + // Hub.Register, not App.HubRegister: that one reads conn.log while the hub sets it, + // a race of the existing code outside the Email events. + env.hub.Register(wc) + sockets.Store(token, wc) + wc.Pump() + })) + t.Cleanup(env.srv.Close) + emailAuthRetry, emailAuthRetryMax = 50*time.Millisecond, 200*time.Millisecond + + return env +} + +var sockets sync.Map + +// tab is the client side of a socket: it keeps the "email" events and the chat ones. +type tab struct { + t *testing.T + ws *websocket.Conn + conn *WebConn + events chan map[string]any + closed chan struct{} +} + +func (env *emailEnv) open(t *testing.T, token string) *tab { + t.Helper() + ws, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(env.srv.URL, "http")+"/?token="+token, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = ws.Close() }) + c := &tab{t: t, ws: ws, events: make(chan map[string]any, 1000), closed: make(chan struct{})} + go func() { + defer close(c.closed) + for { + var m struct { + Event string `json:"event"` + Data map[string]any `json:"data"` + } + if err := ws.ReadJSON(&m); err != nil { + return + } + if m.Event == model.WebsocketEmailEvent || m.Event == model.WEBSOCKET_EVENT_CHAT { + c.events <- m.Data + } + } + }() + for deadline := time.Now().Add(5 * time.Second); c.conn == nil; time.Sleep(5 * time.Millisecond) { + if v, ok := sockets.Load(token); ok && v.(*WebConn).UserId != 0 { + c.conn = v.(*WebConn) + } + if time.Now().After(deadline) { + t.Fatal("no socket") + } + } + sockets.Delete(token) + + return c +} + +func (c *tab) subscribe(env *emailEnv) { + c.t.Helper() + if err := env.app.SubscribeEmail(context.Background(), c.conn, c.conn.GetSession()); err != nil { + c.t.Fatal(err) + } +} + +func (c *tab) next() map[string]any { + c.t.Helper() + select { + case m := <-c.events: + return m + case <-time.After(5 * time.Second): + c.t.Fatal("no event") + } + + return nil +} + +func (c *tab) none() { + c.t.Helper() + select { + case m := <-c.events: + c.t.Fatalf("unexpected event %v", m) + case <-time.After(200 * time.Millisecond): + } +} + +func emailEvent(id string, user int64) *model.EmailEvent { + return &model.EmailEvent{EventId: id, DomainId: 1, UserId: user, ThreadId: 1024, EventType: model.EmailWorkspaceThreadChanged, + Access: "current", WorkspaceVersion: 17, Changes: []string{"projection"}} +} + +func (env *emailEnv) push(e *model.EmailEvent) { + select { + case env.q.email <- e: + case <-time.After(5 * time.Second): + panic("the hub does not read Email events") + } +} + +func TestEmailSubscriptionDelivery(t *testing.T) { + env := newEmailEnv(t) + a, b, other := env.open(t, "tab-a"), env.open(t, "tab-b"), env.open(t, "other") + a.subscribe(env) + a.subscribe(env) // a repeat binds nothing more + b.subscribe(env) + other.subscribe(env) + if bound, _ := env.q.state(); bound != 3 || env.q.bindCalls() != 3 { + t.Fatalf("bound %d, binds %d", bound, env.q.bindCalls()) + } + + env.push(emailEvent("e-1", 42)) + for _, c := range []*tab{a, b} { + if m := c.next(); m["event_id"] != "e-1" || m["thread_id"] != "1024" || m["workspace_version"] != "17" { + t.Fatalf("event %v", m) + } + } + other.none() + + env.push(emailEvent("e-1", 42)) // a repeat goes nowhere + a.none() + + if err := env.app.UnsubscribeEmail(b.conn); err != nil { + t.Fatal(err) + } + env.push(emailEvent("e-2", 42)) + if m := a.next(); m["event_id"] != "e-2" { + t.Fatalf("event %v", m) + } + b.none() + + // A new subscription of the same socket binds under a new id and gets the events. + first := b.conn.Id() + b.subscribe(env) + if id := b.conn.emailSub.Load().bind.Load().Id; !strings.HasPrefix(id, first+"/") || env.q.unbound(id) { + t.Fatalf("binding %s", id) + } + env.push(emailEvent("e-3", 42)) + for _, c := range []*tab{a, b} { + if m := c.next(); m["event_id"] != "e-3" { + t.Fatalf("event %v", m) + } + } + + _ = a.ws.Close() + waitEmail(t, "binding of the closed socket removed", func() bool { _, unbound := env.q.state(); return unbound == 2 }) +} + +func TestEmailSubscribeChecks(t *testing.T) { + env := newEmailEnv(t) + a := env.open(t, "tab-a") + + env.app.config.EmailWorkspace = false + if err := env.app.SubscribeEmail(context.Background(), a.conn, a.conn.GetSession()); err == nil || err.GetStatusCode() != 400 { + t.Fatalf("disabled: %v", err) + } + env.app.config.EmailWorkspace = true + + if err := env.app.SubscribeEmail(context.Background(), a.conn, emailSession("tab-a", 42, false)); err == nil || err.GetStatusCode() != 403 { + t.Fatalf("no read: %v", err) + } + if err := env.app.SubscribeEmail(context.Background(), a.conn, emailSession("other", 43, true)); err == nil || err.GetStatusCode() != 403 { + t.Fatalf("other user: %v", err) + } + env.q.mu.Lock() + env.q.bindErr = errors.New("broker refused") + env.q.mu.Unlock() + if err := env.app.SubscribeEmail(context.Background(), a.conn, a.conn.GetSession()); err == nil || a.conn.emailSub.Load() != nil { + t.Fatalf("refused binding: %v", err) + } +} + +func TestEmailSessionChecks(t *testing.T) { + t.Run("the read right is gone", func(t *testing.T) { + env := newEmailEnv(t) + a := env.open(t, "tab-a") + a.subscribe(env) + env.auth.set(func() { env.auth.sessions["tab-a"] = emailSession("tab-a", 42, false) }) + env.push(emailEvent("e-1", 42)) + if m := a.next(); m["type"] != "resync_required" || m["reason"] != "subscription_lost" { + t.Fatalf("event %v", m) + } + waitEmail(t, "unbound", func() bool { _, unbound := env.q.state(); return unbound == 1 }) + env.push(emailEvent("e-2", 42)) + a.none() + }) + + // Nothing goes while auth is unavailable; once it is back, the resync comes even when + // the lost event was the last one, and later events go again. + t.Run("auth is unavailable", func(t *testing.T) { + env := newEmailEnv(t) + a := env.open(t, "tab-a") + a.subscribe(env) + env.auth.set(func() { env.auth.err = auth_manager.ErrInternal }) + env.push(emailEvent("e-1", 42)) + a.none() + + env.auth.set(func() { env.auth.err = nil }) + if m := a.next(); m["reason"] != "subscription_lost" { + t.Fatalf("event %v", m) + } + a.none() + env.push(emailEvent("e-2", 42)) + if m := a.next(); m["event_id"] != "e-2" { + t.Fatalf("event %v", m) + } + }) + + t.Run("the token names another user", func(t *testing.T) { + env := newEmailEnv(t) + a := env.open(t, "tab-a") + a.subscribe(env) + env.auth.set(func() { env.auth.sessions["tab-a"] = emailSession("tab-a", 43, true) }) + env.push(emailEvent("e-1", 42)) + select { + case <-a.closed: + case <-time.After(5 * time.Second): + t.Fatal("the socket stays open") + } + }) +} + +// A worker waiting for auth neither stops the hub nor the other events; its full queue +// asks for a resync. +func TestEmailSlowAuthAndOverflow(t *testing.T) { + env := newEmailEnv(t) + a := env.open(t, "tab-a") + a.subscribe(env) + block := make(chan struct{}) + env.auth.set(func() { env.auth.block = block }) + + for i := range emailQueueSize + 5 { + env.push(emailEvent("e-"+string(rune('A'+i%26))+string(rune('a'+i/26)), 42)) + } + select { + case env.q.chat <- &model.ChatEvent{UserId: 42, Event: "message", Data: map[string]any{}}: + case <-time.After(5 * time.Second): + t.Fatal("the hub is blocked") + } + if m := a.next(); m["action"] != "message" { + t.Fatalf("chat event %v", m) + } + + env.auth.set(func() { env.auth.block = nil }) + close(block) + got := 0 + resync := false + for deadline := time.After(5 * time.Second); got < emailQueueSize; { + select { + case m := <-a.events: + if m["type"] == "resync_required" && m["reason"] == "overflow" { + resync = true + } else { + got++ + } + case <-deadline: + t.Fatalf("got %d events", got) + } + } + if !resync { + t.Fatal("no resync after the overflow") + } +} + +// After the node queue came back every subscription ends with subscription_lost. +func TestEmailRebound(t *testing.T) { + env := newEmailEnv(t) + a, b := env.open(t, "tab-a"), env.open(t, "tab-b") + a.subscribe(env) + b.subscribe(env) + + env.q.rebound <- struct{}{} + for _, c := range []*tab{a, b} { + if m := c.next(); m["reason"] != "subscription_lost" { + t.Fatalf("event %v", m) + } + } + waitEmail(t, "both ended", func() bool { return a.conn.emailSub.Load() == nil && b.conn.emailSub.Load() == nil }) + a.subscribe(env) + env.push(emailEvent("e-1", 42)) + if m := a.next(); m["event_id"] != "e-1" { + t.Fatalf("event %v", m) + } + b.none() +} + +// A full socket buffer closes the socket, as for the other events. +func TestEmailFullSocket(t *testing.T) { + wh := &Hub{} + conn := &WebConn{Send: make(chan model.WebSocketMessage), log: wlog.NewLogger(&wlog.LoggerConfiguration{})} + sub := &emailSubscription{conn: conn} + conn.emailSub.Store(sub) + connections := newHubConnectionIndex() + connections.Add(conn) + wh.sendEmail(connections, emailOut{sub: sub, msg: emailEvent("e-1", 42).WebSocketEvent(), id: "e-1"}) + if connections.Has(conn) { + t.Fatal("the full socket stays") + } + if _, ok := <-conn.Send; ok { + t.Fatal("send buffer open") + } +} + +func waitEmail(t *testing.T, what string, ok func() bool) { + t.Helper() + for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) { + if ok() { + return + } + } + t.Fatalf("timed out: %s", what) +} diff --git a/app/web_hub.go b/app/web_hub.go index 2834a3e3..9e3278cc 100644 --- a/app/web_hub.go +++ b/app/web_hub.go @@ -29,6 +29,7 @@ type Hub struct { ExplicitStop bool domainQueue mq.DomainQueue lastUnregisterAt int64 + emailOut chan emailOut log *wlog.Logger } @@ -45,6 +46,7 @@ func (a *App) NewWebHub(name string, id int64) *Hub { didStop: make(chan struct{}), lastUnregisterAt: model.GetMillis(), invalidateUser: make(chan string), + emailOut: make(chan emailOut, emailOutSize), ExplicitStop: false, log: a.Log.With(wlog.Namespace("context"), wlog.String("scope", "wsHub"), @@ -113,6 +115,9 @@ func (wh *Hub) start() { atomic.StoreInt64(&wh.connectionCount, int64(len(connections.All()))) wh.lastUnregisterAt = model.GetMillis() + if sub := webCon.emailSub.Load(); sub != nil { + wh.endEmail(sub) + } wh.domainQueue.BulkUnbind(webCon.GetAllBindings()) err := wh.app.MessageQueue.UnRegisterWebsocket(webCon.DomainId, &model.RegisterToWebsocketEvent{ @@ -165,6 +170,15 @@ func (wh *Hub) start() { } } + case e := <-wh.domainQueue.EmailEvents(): + wh.dispatchEmail(connections, e) + + case out := <-wh.emailOut: + wh.sendEmail(connections, out) + + case <-wh.domainQueue.Rebound(): + wh.emailRebound(connections) + case ev := <-wh.domainQueue.ChatEvents(): candidates := connections.ForUser(ev.UserId) msg := model.NewWebSocketChatEvent(ev) diff --git a/docs/email-events.md b/docs/email-events.md new file mode 100644 index 00000000..c8f316cf --- /dev/null +++ b/docs/email-events.md @@ -0,0 +1,243 @@ +# Email events for Workspace — EM-26 + +`engine` delivers the Workspace events of `email-service` to the operator's +Workspace over the existing WebSocket. An event tells Workspace that a Thread +changed; Workspace then reads it through the `EmailThreads` read API of +`email-service`. Events carry no email content and grant no access. + +**Status.** This is the backend contract of stage 17. The WebSocket part +("WebSocket" and "Client synchronization" below) is a working contract waiting +for confirmation by Workspace; until then it may change, and only the mapping +in `engine` and this document change with it. The flag is off by default. + +## Source + +As for calls and chats, the sender addresses the event and RabbitMQ brings it +to the nodes: `email-service` writes one event per recipient, and the queue of +every node with a subscribed socket of that user is bound to its key. There is +no queue or dispatcher of `engine` in between. + +| Exchange | Routing key | Contract | +|---|---|---| +| `email.events` (`topic`, durable) | `email.workspace..v1..`, `` one of `thread.changed`, `message.created`, `message.delivery` | Workspace events, `webitel-emails/docs/events.md` | + +- `email-service` declares the exchange and publishes with confirms and + without `mandatory`: a user without an open socket is the usual case and + blocks nothing. `engine` declares the same exchange with the same parameters, + so a binding never waits for the producer. +- A subscription binds the queue of its node with + `email.workspace.*.*.v1..`; `email.message.inbound.v1`, + the Flow event on the same exchange, never matches. +- A node takes an event only when it is `application/json` within the size + limit, a known type and schema, its type, domain and user equal those of the + routing key, and the domain and user equal those of its hub and of the + socket session; any other is dropped and counted, as the queues of the nodes + acknowledge automatically. +- `call_center` sends `engine` nothing for Email: its snapshots reach + `email-service` alone, which turns them into these events once its read model + changed. +- Confirmed means accepted by the broker, also when no socket is bound. A lost + queue of a node is seen and answered with `subscription_lost` ("Delivery"); a + binding deleted by hand while the socket stays open is not seen until the + next resync, as for calls and chats. + +## WebSocket + +With `email_workspace` (`EMAIL_WORKSPACE`) a socket subscribes to the Email +events of its own session. The domain and the user come from the session; a +client never names a user, an agent, a Thread or a routing key. + +### Subscribe + +```json +{"seq": 7, "action": "subscribe_email", "data": {}} +``` + +```json +{"status": "OK", "seq_reply": 7, "data": {"schema_version": 1}} +``` + +The session needs `email_thread` read; update alone is not enough, and no agent +or online status is needed. Without `email_workspace` the reply is an error +with status 400, without the right 403. The reply comes after the broker +binding of the node is confirmed, so no event of the session after the reply is +lost by the subscription itself; a binding not confirmed in 5 seconds is an +error, and the client subscribes again. Events may arrive before the reply. A +repeated subscribe answers `OK`; `unsubscribe_email` removes only this socket. A +subscription ends with the socket: after a reconnect the client subscribes +again. + +### Delivery + +- Every delivery checks that the session is valid, of the same user and domain, + and has `email_thread` read. The check is repeated at most once per + `auth_cache_expire` (`AUTH_CACHE_EXPIRE`, 30 seconds by default) and when the + session expires, so a revoked right or session stops the events within that + time, not at once. The check runs beside the hub: a slow auth delays only the + Email events of that socket. +- A session that ended or lost the right gets `resync_required` with + `subscription_lost`, and its subscription ends; the next `subscribe_email` + answers with the error. A token of another user closes the socket. +- While auth is unavailable no event goes. The check is repeated by a timer, + after 5 seconds and then twice as long up to 60, also when no other event + comes; once auth answers, the socket gets `subscription_lost`. +- Each socket queues up to 64 events; a fuller queue loses events and sends + `overflow`. A socket whose send buffer is full is closed, as for the other + events. +- When the queue of the node comes back after a broker failure, it has no Email + bindings: every subscription of the node ends and its socket gets + `subscription_lost`. +- After `subscription_lost` the client sends `subscribe_email` again (it answers + `OK` when the subscription is still there) and then reads everything in view; + after `overflow` it reads everything in view. +- A socket gets an `event_id` once among its last 256 events; other sockets of + the user get their own copy. +- Every subscription binds the node queue under its own id, so a subscribe that + timed out and finished late never removes the next one of the socket. The + bindings change on a channel of their own, one after another: a slow broker + delays only them, not the other events of the node or its reconnect. A + removal that failed is repeated after 1 second, then twice as long up to 30. + +### Event + +Every event is `event: "email"`; `data.type` tells its kind: + +```json +{"event": "email", "seq": 42, "data": { + "type": "thread_changed", + "schema_version": 1, + "event_id": "5b247aa1-9433-53ce-b37d-346cec14bff5", + "thread_id": "1024", + "access": "current", + "workspace_version": "17", + "changes": ["projection", "actions"] +}} +``` + +| `type` | Source | Fields besides `type`, `schema_version` | +|---|---|---| +| `thread_changed` | `email-service` | `event_id`, `thread_id`, `access`, `workspace_version`, `changes` | +| `message_created` | `email-service` | `event_id`, `thread_id`, `access`, `workspace_version`, `message_id` | +| `message_delivery` | `email-service` | As `message_created`; reserved for stage 17.7 | +| `resync_required` | `engine` | `reason`: `subscription_lost` or `overflow` | + +- `access` is `current`, `history` or `none`; `none` keeps the version, has no + `message_id` and an empty `changes`. +- Ids and versions are decimal **strings**, as `int64` in the read API + (protojson). Compare them as integers (`BigInt`, or length, then text), never + through `Number`. +- The Email commands (EM-25) keep JSON numbers. Before sending a command the + client checks each string against `^[0-9]+$` and, as `BigInt`, the range + 1…9007199254740991 for `thread_id` and `attempt_id` and + 0…9007199254740991 for `expected_version`; outside it the command is not + sent, since a rounded number would name another value. `engine` itself still + accepts up to 2^53, one above that range; narrowing it is left for a change + of the command contract. +- `seq` numbers the messages of one socket; it is not a cursor and does not + survive a reconnect. Duplicates are possible, so a client removes repeats by + `event_id`. Unknown `type` values and fields are ignored. +- No subject, body, address, attachment, reason or comment is ever sent. + +## Client synchronization + +The read API is the state; events only say when to read it, as for calls and +chats: subscribe, load the state, let events start reads, reload everything +after a reconnect. + +The change of a Thread, its `workspace_version` and the outbox row of its event +are one transaction, the event is published after the commit, and the read API +reads the same database, without replicas or a cache. A read started after an +event with version W therefore returns version W or later, or `NotFound` when a +later change hid the Thread, and that change has its own event. + +1. **Events.** The client acts on `thread_changed`, `message_created`, + `message_delivery` and `resync_required`; it ignores unknown types. +2. **Subscription and sync cycle.** + - Send `subscribe_email` until it answers `OK`, with a growing pause; no live + sync starts without it. + - After `OK`, load CURRENT, the HISTORY in view and the open Thread; events + that came meanwhile are handled after this load. + - Every full load is a new local sync cycle; answers of an earlier cycle are + dropped and start no retry. + - `Unauthenticated` or `PermissionDenied`, of the subscription or of a read, + stops the sync: the client asks for a new sign-in, without a reconnect + loop. + - A reconnect, `resync_required` or a failed subscription start a new cycle; + after `subscription_lost` the client subscribes again first. +3. **State of a Thread:** the applied version, which never goes down; the + highest event version; "read needed"; "read running"; a removal mark with a + floor; "Thread read" and "screen in sync" as two flags; unfinished loads of + messages and actions. + - An event with a version not above the applied one is ignored; otherwise + the Thread needs a read. + - One read of a Thread runs at a time; an event during it keeps "read + needed", and the read repeats after the answer. +4. **Answers**, of a Thread read and of a list page: + - Every read keeps a floor taken at its start: the higher of the applied + version and the highest event version. + - An answer above the applied version is applied. An answer with the same + version is taken too: it refreshes the cache or ends an unfinished load. A + lower one is ignored, and so is one not above the floor of a removal mark. + - A Thread missing from a list page is not removed. On a full load, a Thread + missing from every loaded page is read on its own. +5. **`NotFound` of a Thread read.** + - It counts only when no later state was applied after the read started, + from a list page or another answer; otherwise it is dropped and the Thread + needs a read. + - A counted `NotFound` removes the card and leaves a removal mark with the + floor of that read; a later event reads the Thread again. + - `NotFound` of a message or an attachment does not remove the Thread: the + client reads the Thread and decides by that answer. +6. **Messages and actions.** A Thread version does not prove them current. + - The open Thread loads its messages, from the start of the list since a + later ready message may have an earlier receive time, and its actions + after every applied answer, also one of the same version. + - An unfinished load stays marked until it succeeds. Its failure keeps + "Thread read" but not "screen in sync", and is retried by the error rules. + - For one consistent screen the Thread version is read before and after + the messages and actions; when it changed the load repeats a few times, + then the Thread stays marked. + - A cache of closed Threads, if any, turns stale on any event of the Thread. +7. **Read errors**, by gRPC code (the HTTP mapping of the Gateway for a browser + is checked on the stand with F2): + - `Unavailable`, `DeadlineExceeded`, `ResourceExhausted`, `Internal`: retry + after 0.2, 0.4, 0.8, 1.6 and 3.2 seconds, then show "syncing" and retry + every 30 seconds; + - `NotFound`: rule 5; + - `Unauthenticated`, `PermissionDenied`: rule 2; + - `InvalidArgument`: a client error, logged, never retried. +8. **Commands (EM-25)** are allowed on CURRENT of the last applied answer. + - No error repeats a command by itself: a version conflict, a wrong owner or + state, `NotFound`, `PermissionDenied` or a temporary failure. The client + shows the error and reads the Thread. + - After an unknown result the client keeps the whole request: `command_id`, + `attempt_id`, `expected_version`, the Transfer target, the reason, the + comment and the other fields. Only the user repeats it, with the same + request; a version from a later read is never put in. + - After a command was refused for good, a new action of the user gets a new + `command_id`: other fields under the old id answer + `command_id_conflict`. + +Between a change in `call_center` and the `email-service` event passes the time +the projection needs; when the projection fails, it may be long. All that time +the client shows the last confirmed state, and the checks of EM-25 (owner, +state, version) keep the commands correct. Events go to open sockets only: +there is no offline queue and no client acknowledgement. + +## Configuration + +| Flag | Env | Default | Effect | +|---|---|---|---| +| `email_workspace` | `EMAIL_WORKSPACE` | `false` | Accept `subscribe_email`, bind the queues of the nodes and deliver events | + +The integration tests need RabbitMQ 4: +`EMAIL_TEST_AMQP_URL=amqp://… go test -tags=integration ./mq/rabbit/`. + +## Rollout + +Deploy `engine` first; turn on `WORKSPACE_EVENTS_ENABLED` in `email-service` +after it, and `EMAIL_WORKSPACE` last, for a client that follows "Client +synchronization". The format of the routing key is fixed by `email-service` +and `engine` together: a release that changes it changes both. The full order, checks +and rollback are in stage 17.8 of `Emails_Tasks.md` (not shipped in this +repository). diff --git a/go.mod b/go.mod index c9c87b46..15644241 100644 --- a/go.mod +++ b/go.mod @@ -67,7 +67,7 @@ require ( github.com/golang-jwt/jwt/v4 v4.5.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/google/s2a-go v0.1.7 // indirect - github.com/google/uuid v1.6.0 // indirect + github.com/google/uuid v1.6.0 github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect github.com/googleapis/gax-go/v2 v2.12.3 // indirect github.com/hashicorp/consul/api v1.33.2 // indirect diff --git a/model/config.go b/model/config.go index c867c417..8b3ed7ef 100644 --- a/model/config.go +++ b/model/config.go @@ -59,6 +59,8 @@ type Config struct { TriggersSettings TriggersSettings `json:"triggers_settings"` RTCConfiguration string `json:"rtc_configuration" flag:"rtc_configuration||RTCConfiguration" default:"" env:"RTC_CONFIGURATION"` EmailCommandTimeout int `json:"email_command_timeout" flag:"email_command_timeout|10|Seconds an Email command waits for call_center" env:"EMAIL_COMMAND_TIMEOUT"` + // EmailWorkspace opens the Email subscription of WebSocket (stage 17.5). + EmailWorkspace bool `json:"email_workspace" flag:"email_workspace|false|Deliver Email events to WebSocket subscribers" env:"EMAIL_WORKSPACE"` } type PushConfig struct { diff --git a/model/email_event.go b/model/email_event.go new file mode 100644 index 00000000..18ade204 --- /dev/null +++ b/model/email_event.go @@ -0,0 +1,126 @@ +package model + +import ( + "encoding/json" + "errors" + "fmt" + "strconv" + "time" + + "github.com/google/uuid" +) + +// The Workspace events of email-service, addressed to one user by their routing key, as the +// events of calls and chats are; docs/email-events.md describes them. +const ( + EmailServiceExchange = "email.events" + EmailContentType = "application/json" + EmailMaxEventSize = 16 << 10 + EmailSchema = 1 + + EmailWorkspaceThreadChanged = "email.workspace.thread.changed" + EmailWorkspaceMessageCreated = "email.workspace.message.created" + EmailWorkspaceMessageDelivery = "email.workspace.message.delivery" +) + +// ErrEmailEventInvalid marks an event no node delivers. +var ErrEmailEventInvalid = errors.New("email event: invalid") + +func emailInvalid(format string, args ...any) error { + return fmt.Errorf("%w: %s", ErrEmailEventInvalid, fmt.Sprintf(format, args...)) +} + +// EmailRoutingKey is the routing key of an event for one user. +func EmailRoutingKey(eventType string, domainId, userId int64) string { + return eventType + ".v1." + strconv.FormatInt(domainId, 10) + "." + strconv.FormatInt(userId, 10) +} + +// EmailBindingKey matches every Workspace event of one user, never the Flow event. +func EmailBindingKey(domainId, userId int64) string { + return EmailRoutingKey("email.workspace.*.*", domainId, userId) +} + +// EmailEvent is a Workspace event of email-service for one user. +type EmailEvent struct { + EventId string `json:"event_id"` + EventType string `json:"event_type"` + SchemaVersion int `json:"schema_version"` + OccurredAt time.Time `json:"occurred_at"` + DomainId int64 `json:"domain_id"` + UserId int64 `json:"user_id"` + ThreadId int64 `json:"thread_id"` + Access string `json:"access"` + WorkspaceVersion int64 `json:"workspace_version"` + ProjectionVersion *int64 `json:"projection_version"` + MessageId *int64 `json:"message_id"` + Changes []string `json:"changes"` +} + +var ( + emailTypes = map[string]bool{EmailWorkspaceThreadChanged: true, EmailWorkspaceMessageCreated: true, EmailWorkspaceMessageDelivery: true} + emailAccess = map[string]bool{"current": true, "history": true, "none": true} + emailChanges = map[string]bool{"projection": true, "actions": true, "participants": true, "contact": true} +) + +// ParseEmailEvent accepts an event of the queue of a node: JSON within the size limit, the +// envelope of webitel-emails docs/events.md, and its type, domain and user equal to those of +// the routing key. Unknown fields are ignored. +func ParseEmailEvent(routingKey, contentType string, body []byte) (*EmailEvent, error) { + if contentType != EmailContentType { + return nil, emailInvalid("content type %q", contentType) + } + if len(body) > EmailMaxEventSize { + return nil, emailInvalid("%d bytes", len(body)) + } + var e EmailEvent + if err := json.Unmarshal(body, &e); err != nil { + return nil, emailInvalid("json: %v", err) + } + if err := e.validate(); err != nil { + return nil, err + } + if routingKey != EmailRoutingKey(e.EventType, e.DomainId, e.UserId) { + return nil, emailInvalid("routing key %q of another type, domain or user", routingKey) + } + + return &e, nil +} + +func (e *EmailEvent) validate() error { + switch { + case !emailEventId(e.EventId): + return emailInvalid("event_id") + case !emailTypes[e.EventType] || e.SchemaVersion != EmailSchema: + return emailInvalid("type %q schema %d", e.EventType, e.SchemaVersion) + case e.OccurredAt.IsZero(): + return emailInvalid("occurred_at") + case e.DomainId <= 0 || e.UserId <= 0 || e.ThreadId <= 0 || e.WorkspaceVersion <= 0: + return emailInvalid("ids and version must be positive") + case e.ProjectionVersion != nil && *e.ProjectionVersion <= 0: + return emailInvalid("projection_version") + case !emailAccess[e.Access]: + return emailInvalid("access %q", e.Access) + case (e.EventType == EmailWorkspaceThreadChanged) == (e.MessageId != nil) || (e.MessageId != nil && *e.MessageId <= 0): + return emailInvalid("message_id") + case e.Changes == nil: + return emailInvalid("changes must be a list") + case e.Access == "none" && (e.EventType != EmailWorkspaceThreadChanged || len(e.Changes) > 0): + return emailInvalid("access none is a bare invalidation") + case e.EventType != EmailWorkspaceThreadChanged && len(e.Changes) > 0: + return emailInvalid("changes belong to thread events") + } + for _, c := range e.Changes { + if !emailChanges[c] { + return emailInvalid("change %q", c) + } + } + + return nil +} + +// emailEventId accepts a canonical UUID other than nil, as email-service does. +func emailEventId(s string) bool { + u, err := uuid.Parse(s) + + return err == nil && u != uuid.Nil && u.String() == s +} diff --git a/model/email_event_test.go b/model/email_event_test.go new file mode 100644 index 00000000..470241ef --- /dev/null +++ b/model/email_event_test.go @@ -0,0 +1,43 @@ +package model + +import ( + "errors" + "strings" + "testing" +) + +const testEventId = "5b247aa1-9433-53ce-b37d-346cec14bff5" + +func threadJSON(access, changes string) string { + return `{"event_id":"` + testEventId + `","event_type":"email.workspace.thread.changed","schema_version":1, +"occurred_at":"2026-11-06T09:00:00Z","domain_id":1,"user_id":42,"thread_id":1024,"access":"` + access + `", +"workspace_version":17,"projection_version":905,"message_id":null,"changes":` + changes + `,"future":1}` +} + +func TestParseEmailEvent(t *testing.T) { + key := "email.workspace.thread.changed.v1.1.42" + if EmailBindingKey(1, 42) != "email.workspace.*.*.v1.1.42" { + t.Fatalf("binding %s", EmailBindingKey(1, 42)) + } + e, err := ParseEmailEvent(key, EmailContentType, []byte(threadJSON("current", `["projection"]`))) + if err != nil || e.UserId != 42 || e.WorkspaceVersion != 17 || e.Changes[0] != "projection" { + t.Fatalf("%+v, %v", e, err) + } + + valid := threadJSON("none", `[]`) + for name, c := range map[string]struct{ key, contentType, body string }{ + "other user in the key": {"email.workspace.thread.changed.v1.1.43", EmailContentType, valid}, + "other type in the key": {"email.workspace.message.created.v1.1.42", EmailContentType, valid}, + "content type": {key, "text/json", valid}, + "oversized": {key, EmailContentType, strings.Replace(valid, `"future":1`, `"x":"`+strings.Repeat("x", EmailMaxEventSize)+`"`, 1)}, + "nil event id": {key, EmailContentType, strings.Replace(valid, testEventId, "00000000-0000-0000-0000-000000000000", 1)}, + "upper case event id": {key, EmailContentType, strings.Replace(valid, testEventId, strings.ToUpper(testEventId), 1)}, + "none with changes": {key, EmailContentType, threadJSON("none", `["actions"]`)}, + "changes are not a list": {key, EmailContentType, threadJSON("current", `null`)}, + "schema": {key, EmailContentType, strings.Replace(valid, `"schema_version":1`, `"schema_version":2`, 1)}, + } { + if _, err := ParseEmailEvent(c.key, c.contentType, []byte(c.body)); !errors.Is(err, ErrEmailEventInvalid) { + t.Errorf("%s: err = %v", name, err) + } + } +} diff --git a/model/email_ws.go b/model/email_ws.go new file mode 100644 index 00000000..88af3274 --- /dev/null +++ b/model/email_ws.go @@ -0,0 +1,43 @@ +package model + +import "strconv" + +const ( + WebsocketEmailEvent = "email" + + EmailResyncSubscriptionLost = "subscription_lost" + EmailResyncOverflow = "overflow" +) + +var emailWsTypes = map[string]string{ + EmailWorkspaceThreadChanged: "thread_changed", + EmailWorkspaceMessageCreated: "message_created", + EmailWorkspaceMessageDelivery: "message_delivery", +} + +// WebSocketEvent is the event "email" of docs/email-events.md: only the fields of its type, +// ids and versions as decimal strings. +func (e *EmailEvent) WebSocketEvent() *WebSocketEvent { + d := map[string]interface{}{ + "type": emailWsTypes[e.EventType], + "schema_version": EmailSchema, + "event_id": e.EventId, + "thread_id": strconv.FormatInt(e.ThreadId, 10), + "access": e.Access, + "workspace_version": strconv.FormatInt(e.WorkspaceVersion, 10), + } + if e.EventType == EmailWorkspaceThreadChanged { + d["changes"] = e.Changes + } else { + d["message_id"] = strconv.FormatInt(*e.MessageId, 10) + } + + return &WebSocketEvent{Event: WebsocketEmailEvent, Data: d} +} + +// NewEmailResyncEvent tells the client to read everything in view again. +func NewEmailResyncEvent(reason string) *WebSocketEvent { + return &WebSocketEvent{Event: WebsocketEmailEvent, Data: map[string]interface{}{ + "type": "resync_required", "schema_version": EmailSchema, "reason": reason, + }} +} diff --git a/model/email_ws_test.go b/model/email_ws_test.go new file mode 100644 index 00000000..27985d28 --- /dev/null +++ b/model/email_ws_test.go @@ -0,0 +1,33 @@ +package model + +import ( + "encoding/json" + "testing" +) + +func TestEmailWebSocketEvent(t *testing.T) { + big := int64(9007199254740993) // above 2^53: a JSON number would round it + pv, msg := int64(905), int64(31) + for name, c := range map[string]struct { + e EmailEvent + want string + }{ + "thread_changed": {EmailEvent{EventType: EmailWorkspaceThreadChanged, EventId: "e", ThreadId: big, Access: "current", + WorkspaceVersion: 17, ProjectionVersion: &pv, Changes: []string{"projection"}}, + `{"access":"current","changes":["projection"],"event_id":"e","schema_version":1,"thread_id":"9007199254740993","type":"thread_changed","workspace_version":"17"}`}, + "message_created": {EmailEvent{EventType: EmailWorkspaceMessageCreated, EventId: "e", ThreadId: 1, Access: "current", + WorkspaceVersion: 17, MessageId: &msg, Changes: []string{}}, + `{"access":"current","event_id":"e","message_id":"31","schema_version":1,"thread_id":"1","type":"message_created","workspace_version":"17"}`}, + } { + ev := c.e.WebSocketEvent() + got, _ := json.Marshal(ev.Data) + if ev.Event != "email" || string(got) != c.want { + t.Errorf("%s: %s %s", name, ev.Event, got) + } + } + + got, _ := json.Marshal(NewEmailResyncEvent(EmailResyncOverflow).Data) + if string(got) != `{"reason":"overflow","schema_version":1,"type":"resync_required"}` { + t.Errorf("resync: %s", got) + } +} diff --git a/mq/mq.go b/mq/mq.go index bc762395..da7ab77f 100644 --- a/mq/mq.go +++ b/mq/mq.go @@ -39,9 +39,13 @@ type DomainQueue interface { UserStateEvents() <-chan *model.UserState ChatEvents() <-chan *model.ChatEvent NotificationEvents() <-chan *model.Notification + EmailEvents() <-chan *model.EmailEvent BindUserCall(id string, userId int64) *model.BindQueueEvent BindUserChat(id string, userId int64) *model.BindQueueEvent + BindUserEmailWait(ctx context.Context, id string, userId int64) (*model.BindQueueEvent, error) + UnbindEmail(b *model.BindQueueEvent) + Rebound() <-chan struct{} BulkUnbind(b []*model.BindQueueEvent) model.AppError Unbind(bind *model.BindQueueEvent) model.AppError diff --git a/mq/rabbit/domain_queue.go b/mq/rabbit/domain_queue.go index d4ba3bff..4756a935 100644 --- a/mq/rabbit/domain_queue.go +++ b/mq/rabbit/domain_queue.go @@ -17,6 +17,7 @@ import ( // amqpChannel is the part of *amqp.Channel a domain queue uses. Tests put a // fake behind it to take the channel away. type amqpChannel interface { + ExchangeDeclare(name, kind string, durable, autoDelete, internal, noWait bool, args amqp.Table) error QueueDeclare(name string, durable, autoDelete, exclusive, noWait bool, args amqp.Table) (amqp.Queue, error) QueueBind(name, key, exchange string, noWait bool, args amqp.Table) error QueueUnbind(name, key, exchange string, args amqp.Table) error @@ -42,10 +43,20 @@ type DomainQueue struct { userStateEvents chan *model.UserState chatEvents chan *model.ChatEvent notificationEvent chan *model.Notification + emailEvents chan *model.EmailEvent bindChan chan *model.BindQueueEvent bindings map[string]*model.BindQueueEvent down bool + rebound chan struct{} + + // The Email bindings go over a channel of their own, never through Listen. + emailOps chan emailOp + emailOnce sync.Once + emailUnbinds map[string]emailUnbind + emailQueues map[string]string // the queue each confirmed Email binding is on + emailKick chan struct{} + newEmailChannel func() (amqpChannel, error) fnGetAllBindings model.GetAllBindings @@ -79,10 +90,16 @@ func newDomainQueue(client *AMQP, id int64, bindings model.GetAllBindings) mq.Do userStateEvents: make(chan *model.UserState), chatEvents: make(chan *model.ChatEvent), notificationEvent: make(chan *model.Notification), + emailEvents: make(chan *model.EmailEvent), fnGetAllBindings: bindings, - bindChan: make(chan *model.BindQueueEvent, 1000), //TODO - bindings: make(map[string]*model.BindQueueEvent), + bindChan: make(chan *model.BindQueueEvent, 1000), //TODO + emailOps: make(chan emailOp, emailOpsSize), + emailUnbinds: make(map[string]emailUnbind), + emailQueues: make(map[string]string), + emailKick: make(chan struct{}, 1), + bindings: make(map[string]*model.BindQueueEvent), + rebound: make(chan struct{}, 1), closeChannel: make(chan *amqp.Error, 1), reconnect: make(chan error, 1), @@ -93,6 +110,7 @@ func newDomainQueue(client *AMQP, id int64, bindings model.GetAllBindings) mq.Do wlog.Int64("domain_id", id), ), } + q.newEmailChannel = func() (amqpChannel, error) { return q.newChannel() } q.newChannel = func() (amqpChannel, error) { ch, err := client.NewChannel() if err != nil { @@ -136,6 +154,7 @@ func (dq *DomainQueue) enqueue(b *model.BindQueueEvent) { func (dq *DomainQueue) forget(b *model.BindQueueEvent) { dq.Lock() delete(dq.bindings, bindKey(b)) + delete(dq.emailQueues, bindKey(b)) dq.Unlock() } @@ -190,6 +209,21 @@ func (dq *DomainQueue) BindUserChat(id string, userId int64) *model.BindQueueEve return b } +// HasBinding reports whether the binding is still kept; a refused one is forgotten. +func (dq *DomainQueue) HasBinding(b *model.BindQueueEvent) bool { + dq.RLock() + defer dq.RUnlock() + _, ok := dq.bindings[bindKey(b)] + + return ok +} + +// Rebound tells that the queue came back after a loss and restored its bindings; the +// events in between are lost. +func (dq *DomainQueue) Rebound() <-chan struct{} { + return dq.rebound +} + func (dq *DomainQueue) BindAgentStatusEvents(id string, userId int64, agentId int) *model.BindQueueEvent { b := &model.BindQueueEvent{ UserId: userId, @@ -316,6 +350,13 @@ func (dq *DomainQueue) readMessage(m amqp.Delivery) { wlog.String("exchange", m.Exchange), wlog.String("routing", m.RoutingKey), ) + // Email events are JSON of their own contract; other exchanges keep their checks. + if m.Exchange == model.EmailServiceExchange { + dq.readEmailEvent(m) + + return + } + if m.ContentType != "text/json" && m.Exchange != model.ChatExchange { log.Warn("failed receive event content type") return @@ -345,6 +386,21 @@ func (dq *DomainQueue) readMessage(m amqp.Delivery) { } } +// readEmailEvent delivers only a valid event for a user of this domain. +func (dq *DomainQueue) readEmailEvent(m amqp.Delivery) { + e, err := model.ParseEmailEvent(m.RoutingKey, m.ContentType, m.Body) + if err == nil && e.DomainId != dq.id { + err = fmt.Errorf("domain %d", e.DomainId) + } + if err != nil { + dq.log.Warn("drop email event", wlog.String("routing", m.RoutingKey), wlog.Err(err)) + + return + } + + dq.emailEvents <- e +} + func parseNotification(data []byte) (*model.Notification, error) { var n model.Notification err := json.Unmarshal(data, &n) @@ -589,7 +645,8 @@ func (dq *DomainQueue) connect() error { dq.closeChannel = make(chan *amqp.Error, 1) ch.NotifyClose(dq.closeChannel) - dq.queue, err = ch.QueueDeclare( + var q amqp.Queue + q, err = ch.QueueDeclare( fmt.Sprintf("engine.ws.%s.%d", model.NewId()[0:10], dq.id), true, false, @@ -605,6 +662,10 @@ func (dq *DomainQueue) connect() error { dq.log.Error("declare error", wlog.Err(err)) return err } + // The Email binder reads the name from its own goroutine. + dq.Lock() + dq.queue = q + dq.Unlock() err = ch.QueueBind(dq.queue.Name, fmt.Sprintf("notification.%d", dq.id), model.AppExchange, false, nil) @@ -638,12 +699,19 @@ func (dq *DomainQueue) connect() error { dq.log.Debug("connected") + reconnected := dq.down if dq.down { dq.down = false dq.client.domainQueuesDown.Add(-1) } dq.rebindingUsers() + if reconnected { + select { + case dq.rebound <- struct{}{}: + default: + } + } go func() { if err := dq.Listen(); err != nil { @@ -655,14 +723,23 @@ func (dq *DomainQueue) connect() error { } func (dq *DomainQueue) rebindingUsers() { - dq.RLock() + dq.Lock() bindings := make([]*model.BindQueueEvent, 0, len(dq.bindings)) - for _, v := range dq.bindings { + for k, v := range dq.bindings { + // An Email binding goes through the Email binder, never here. One on an older + // queue went with it; one already on this queue stays, so its cleanup finds it. + if v.Exchange == model.EmailServiceExchange { + if q, ok := dq.emailQueues[k]; ok && q != dq.queue.Name { + delete(dq.bindings, k) + delete(dq.emailQueues, k) + } + continue + } bindings = append(bindings, v) } - dq.RUnlock() + dq.Unlock() for _, v := range bindings { if dq.getChannel().IsClosed() { @@ -728,6 +805,10 @@ func (dq *DomainQueue) UserStateEvents() <-chan *model.UserState { return dq.userStateEvents } +func (dq *DomainQueue) EmailEvents() <-chan *model.EmailEvent { + return dq.emailEvents +} + func (dq *DomainQueue) NotificationEvents() <-chan *model.Notification { return dq.notificationEvent } diff --git a/mq/rabbit/domain_queue_test.go b/mq/rabbit/domain_queue_test.go index 1cde6349..668b17be 100644 --- a/mq/rabbit/domain_queue_test.go +++ b/mq/rabbit/domain_queue_test.go @@ -102,6 +102,10 @@ func (f *fakeChannel) command(name string, noWait bool, refuse *amqp.Error, appl return refuse } +func (f *fakeChannel) ExchangeDeclare(_, _ string, _, _, _, noWait bool, _ amqp.Table) error { + return f.command("exchange.declare", noWait, nil, func() {}) +} + func (f *fakeChannel) QueueDeclare(name string, _, _, _, noWait bool, _ amqp.Table) (amqp.Queue, error) { err := f.command("queue.declare", noWait, f.broker.declareRefusal(), func() { f.queue = name }) @@ -110,6 +114,9 @@ func (f *fakeChannel) QueueDeclare(name string, _, _, _, noWait bool, _ amqp.Tab func (f *fakeChannel) QueueBind(_, key, exchange string, noWait bool, args amqp.Table) error { sock, _ := args["x-sock-id"].(string) + if hold := f.broker.holding(); hold != nil { + <-hold // a slow broker: the bind is sent, its answer waits + } return f.command("queue.bind", noWait, f.broker.bindRefusal(exchange, sock), func() { f.binds = append(f.binds, fakeBind{exchange, key, sock, noWait}) @@ -237,9 +244,17 @@ type fakeBroker struct { missing map[string]bool // exchanges that do not exist failReplay int // the next n socket binds die with the connection channels []*fakeChannel - overlap bool // a channel was opened while an earlier one was still open - runaway bool // the queue reconnected without end - budget int // channels it may still open + overlap bool // a channel was opened while an earlier one was still open + runaway bool // the queue reconnected without end + budget int // channels it may still open + hold chan struct{} // while set, every bind waits until it is closed +} + +func (b *fakeBroker) holding() chan struct{} { + b.mu.Lock() + defer b.mu.Unlock() + + return b.hold } // More channels than any test needs: a queue that reconnects in a loop runs diff --git a/mq/rabbit/email_binder.go b/mq/rabbit/email_binder.go new file mode 100644 index 00000000..198eafbd --- /dev/null +++ b/mq/rabbit/email_binder.go @@ -0,0 +1,252 @@ +package rabbit + +import ( + "context" + "errors" + "maps" + "time" + + amqp "github.com/rabbitmq/amqp091-go" + "github.com/webitel/engine/model" + "github.com/webitel/wlog" +) + +const emailOpsSize = 1000 + +// The pause after a failed unbind doubles from emailUnbindRetry to emailUnbindRetryMax. +var ( + emailUnbindRetry = time.Second + emailUnbindRetryMax = 30 * time.Second +) + +var ( + errBindingGone = errors.New("binding removed before the broker confirmed it") + errQueueChanged = errors.New("the node queue changed while binding") + errNoQueue = errors.New("the node queue is not declared yet") +) + +// emailOp is a bind whose caller waits for the broker. +type emailOp struct { + b *model.BindQueueEvent + done chan error +} + +// emailUnbind is a binding to remove from the node queue it was made on. +type emailUnbind struct { + b *model.BindQueueEvent + queue string +} + +// BindUserEmailWait binds the Email events of a user to this node's queue for the +// subscription id and returns once the broker confirmed it; a failed or late binding is removed. +func (dq *DomainQueue) BindUserEmailWait(ctx context.Context, id string, userId int64) (*model.BindQueueEvent, error) { + b := &model.BindQueueEvent{ + UserId: userId, + Id: id, + Routing: model.EmailBindingKey(dq.Id(), userId), + Exchange: model.EmailServiceExchange, + } + dq.Lock() + dq.bindings[bindKey(b)] = b + dq.Unlock() + + dq.startEmailBinder() + op := emailOp{b: b, done: make(chan error, 1)} + select { + case dq.emailOps <- op: + case <-ctx.Done(): + dq.forget(b) + + return nil, ctx.Err() + } + + select { + case err := <-op.done: + if err != nil { + dq.UnbindEmail(b) + + return nil, err + } + + return b, nil + case <-ctx.Done(): + dq.UnbindEmail(b) + + return nil, ctx.Err() + } +} + +// UnbindEmail forgets the binding at once and has the binder remove it from the queue it is +// on, again after a failure; it never waits. A binding already forgotten went with its queue. +func (dq *DomainQueue) UnbindEmail(b *model.BindQueueEvent) { + key := bindKey(b) + dq.Lock() + _, ok := dq.bindings[key] + if ok { + queue, bound := dq.emailQueues[key] + if !bound { + queue = dq.queue.Name + } + delete(dq.bindings, key) + delete(dq.emailQueues, key) + dq.emailUnbinds[key] = emailUnbind{b: b, queue: queue} + } + dq.Unlock() + + if ok { + dq.startEmailBinder() + select { + case dq.emailKick <- struct{}{}: + default: + } + } +} + +// startEmailBinder runs the binder from the first Email binding of the domain on. +func (dq *DomainQueue) startEmailBinder() { + dq.emailOnce.Do(func() { go dq.runEmailBinder() }) +} + +func (dq *DomainQueue) queueName() string { + dq.RLock() + defer dq.RUnlock() + + return dq.queue.Name +} + +// runEmailBinder changes the Email bindings on a channel of its own, so a slow broker holds +// neither the listener nor the hub. After every bind it removes the bindings waiting for +// that, so a late bind is always followed by its unbind. +func (dq *DomainQueue) runEmailBinder() { + var ch amqpChannel + retry := time.NewTimer(time.Hour) + retry.Stop() + var pause time.Duration + retrying := false + defer func() { + retry.Stop() + if ch != nil { + _ = ch.Close() + } + }() + + for { + select { + case <-dq.stop: + return + case op := <-dq.emailOps: + op.done <- dq.emailBind(&ch, op.b) + case <-dq.emailKick: + case <-retry.C: + retrying = false + } + + if !dq.emailUnbindAll(&ch) { + pause = 0 + } else if !retrying { + pause = min(max(2*pause, emailUnbindRetry), emailUnbindRetryMax) + retry.Reset(pause) + retrying = true + } + } +} + +// emailChannel opens a channel when needed and declares on it the exchange of email-service +// with the parameters of its sender, so a node binds before the first event is sent. +func (dq *DomainQueue) emailChannel(ch *amqpChannel) (amqpChannel, error) { + if *ch == nil || (*ch).IsClosed() { + c, err := dq.newEmailChannel() + if err != nil { + return nil, err + } + if err = c.ExchangeDeclare(model.EmailServiceExchange, model.MQ_TOPIC, true, false, false, false, nil); err != nil { + _ = c.Close() + + return nil, err + } + *ch = c + } + + return *ch, nil +} + +// emailDrop closes a channel a command failed on; the next change opens another. +func emailDrop(ch *amqpChannel) { + if *ch != nil { + _ = (*ch).Close() + *ch = nil + } +} + +func (dq *DomainQueue) emailBind(ch *amqpChannel, b *model.BindQueueEvent) error { + if !dq.HasBinding(b) { + return errBindingGone + } + name := dq.queueName() + if name == "" { + return errNoQueue + } + c, err := dq.emailChannel(ch) + if err != nil { + return err + } + if err = c.QueueBind(name, b.Routing, b.Exchange, false, amqp.Table{"x-sock-id": b.Id}); err != nil { + emailDrop(ch) + + return err + } + // The queue name tells the queue generation: the binding is kept for this one only. + dq.Lock() + defer dq.Unlock() + if dq.queue.Name != name { + return errQueueChanged + } + if _, ok := dq.bindings[bindKey(b)]; ok { + dq.emailQueues[bindKey(b)] = name + } + + return nil +} + +// emailUnbindAll reports whether some unbind waits for a retry. A refusal of the broker is +// final; an unbind for an older queue is dropped, as that queue went with its bindings. +func (dq *DomainQueue) emailUnbindAll(ch *amqpChannel) bool { + dq.RLock() + pending := maps.Clone(dq.emailUnbinds) + dq.RUnlock() + + current := dq.queueName() + for key, u := range pending { + if u.queue != current { + dq.emailUnbound(key) + continue + } + c, err := dq.emailChannel(ch) + if err == nil { + err = c.QueueUnbind(u.queue, u.b.Routing, u.b.Exchange, amqp.Table{"x-sock-id": u.b.Id}) + } + if err == nil { + dq.emailUnbound(key) + continue + } + + emailDrop(ch) + var refused *amqp.Error + if errors.As(err, &refused) && refused.Recover { + dq.log.Warn("email unbind refused", wlog.String("sock_id", u.b.Id), wlog.Err(err)) + dq.emailUnbound(key) + continue + } + dq.log.Warn("email unbind failed, will retry", wlog.String("sock_id", u.b.Id), wlog.Err(err)) + + return true + } + + return false +} + +func (dq *DomainQueue) emailUnbound(key string) { + dq.Lock() + delete(dq.emailUnbinds, key) + dq.Unlock() +} diff --git a/mq/rabbit/email_domain_queue_test.go b/mq/rabbit/email_domain_queue_test.go new file mode 100644 index 00000000..de7193ee --- /dev/null +++ b/mq/rabbit/email_domain_queue_test.go @@ -0,0 +1,323 @@ +package rabbit + +import ( + "context" + "errors" + "fmt" + "slices" + "testing" + "testing/synctest" + "time" + + amqp "github.com/rabbitmq/amqp091-go" + "github.com/webitel/engine/model" + "github.com/webitel/wlog" +) + +func TestDomainQueueEmailEvents(t *testing.T) { + dq := newDomainQueue(&AMQP{log: wlog.NewLogger(&wlog.LoggerConfiguration{})}, 1, nil).(*DomainQueue) + + body := func(domain string) string { + return `{"event_id":"5b247aa1-9433-53ce-b37d-346cec14bff5","event_type":"email.workspace.thread.changed", +"schema_version":1,"occurred_at":"2026-11-06T09:00:00Z","domain_id":` + domain + `,"user_id":42,"thread_id":1024, +"access":"current","workspace_version":17,"projection_version":905,"message_id":null,"changes":["projection"]}` + } + deliver := func(key, body string) *model.EmailEvent { + got := make(chan *model.EmailEvent, 1) + go func() { + select { + case e := <-dq.EmailEvents(): + got <- e + case <-time.After(100 * time.Millisecond): + got <- nil + } + }() + dq.readMessage(amqp.Delivery{Exchange: model.EmailServiceExchange, RoutingKey: key, + ContentType: model.EmailContentType, Body: []byte(body)}) + + return <-got + } + + if e := deliver("email.workspace.thread.changed.v1.1.42", body("1")); e == nil || e.UserId != 42 || e.WorkspaceVersion != 17 { + t.Fatalf("event %+v", e) + } + if e := deliver("email.workspace.thread.changed.v1.2.42", body("2")); e != nil { + t.Errorf("other domain: delivered %+v", e) + } +} + +// emailQueue starts a domain queue whose Email binder has a broker of its own, so the +// checks of startQueue still see one consumer channel at a time. +func emailQueue(t *testing.T) (dq *DomainQueue, consumer, binder *fakeBroker) { + t.Helper() + consumer, binder = newFakeBroker(), newFakeBroker() + dq = startQueue(t, consumer) + dq.newEmailChannel = binder.open + + return dq, consumer, binder +} + +func emailBind(id string) fakeBind { + return fakeBind{model.EmailServiceExchange, "email.workspace.*.*.v1.1.42", id, false} +} + +// binderLog is every bind and unbind the binder made, over all its channels. +func binderLog(b *fakeBroker) (binds, unbinds []fakeBind) { + b.mu.Lock() + channels := slices.Clone(b.channels) + b.mu.Unlock() + for _, c := range channels { + bs, us, _ := c.snapshot() + binds, unbinds = append(binds, bs...), append(unbinds, us...) + } + for i := range unbinds { + unbinds[i].noWait = false + } + + return binds, unbinds +} + +// The reply to subscribe_email waits for the broker: a confirmed binding is kept, a refused +// one is not left behind. +func TestDomainQueueEmailBindWait(t *testing.T) { + t.Run("confirmed", func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + dq, _, binder := emailQueue(t) + bind, err := dq.BindUserEmailWait(context.Background(), "sock-1/a", 42) + if err != nil || bind.Exchange != model.EmailServiceExchange || bind.Routing != "email.workspace.*.*.v1.1.42" { + t.Fatalf("bind %+v, %v", bind, err) + } + if binds, _ := binderLog(binder); !slices.Contains(binds, emailBind("sock-1/a")) || !dq.HasBinding(bind) { + t.Fatalf("bound %+v", binds) + } + }) + }) + + t.Run("refused", func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + dq, _, binder := emailQueue(t) + binder.set(func() { binder.missing = map[string]bool{model.EmailServiceExchange: true} }) + if _, err := dq.BindUserEmailWait(context.Background(), "sock-1/a", 42); !errors.Is(err, errNotFound) { + t.Fatalf("err = %v", err) + } + if registered(dq) != 0 { + t.Fatal("a refused binding is kept") + } + }) + }) +} + +// A subscribe that timed out and finished late never removes the next subscription of the +// same socket, and a slow broker holds neither the listener nor UnbindEmail. +func TestDomainQueueEmailLateBind(t *testing.T) { + for _, late := range []string{"success", "error"} { + t.Run(late, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + dq, consumer, binder := emailQueue(t) + hold := make(chan struct{}) + binder.set(func() { binder.hold = hold }) + + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if _, err := dq.BindUserEmailWait(ctx, "sock-1/a", 42); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("first: %v", err) + } + var retry *model.BindQueueEvent + var retryErr error + done := make(chan struct{}) + go func() { + retry, retryErr = dq.BindUserEmailWait(context.Background(), "sock-1/b", 42) + close(done) + }() + synctest.Wait() + + expectEventReachesHub(t, dq, consumer.last(t)) + dq.UnbindEmail(&model.BindQueueEvent{Id: "sock-9/x", Exchange: model.EmailServiceExchange, Routing: "email.workspace.*.*.v1.1.9"}) + + binder.set(func() { + binder.hold = nil + if late == "error" { + binder.failReplay = 1 + } + }) + close(hold) + <-done + if retryErr != nil { + t.Fatalf("retry: %v", retryErr) + } + + binds, unbinds := binderLog(binder) + if !slices.Contains(binds, emailBind("sock-1/b")) || slices.Contains(unbinds, emailBind("sock-1/b")) { + t.Fatalf("binds %+v, unbinds %+v", binds, unbinds) + } + if slices.Contains(binds, emailBind("sock-1/a")) && !slices.Contains(unbinds, emailBind("sock-1/a")) { + t.Fatalf("the late binding stays: binds %+v, unbinds %+v", binds, unbinds) + } + if registered(dq) != 1 || !dq.HasBinding(retry) { + t.Fatalf("registered %d", registered(dq)) + } + }) + }) + } +} + +// After a lost channel the queue tells the hub once its bindings are back. The Email +// bindings are not restored there: they belonged to the old queue, and a slow Email bind +// holds neither the reconnect nor the listener. +func TestDomainQueueRebound(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + dq, consumer, binder := emailQueue(t) + select { + case <-dq.Rebound(): + t.Fatal("the first connect is no reconnect") + default: + } + bind, err := dq.BindUserEmailWait(context.Background(), "sock-1/a", 42) + if err != nil { + t.Fatal(err) + } + call := dq.BindUserCall("sock-1", 42) + + hold := make(chan struct{}) + binder.set(func() { binder.hold = hold }) + var pendingErr error + done := make(chan struct{}) + go func() { + _, pendingErr = dq.BindUserEmailWait(context.Background(), "sock-2/a", 42) + close(done) + }() + synctest.Wait() + + consumer.last(t).drop(errConnectionForced) + pass(1) + select { + case <-dq.Rebound(): + default: + t.Fatal("no signal after the reconnect") + } + expectBound(t, consumer.last(t), "after the reconnect", call) + if consumer.last(t).bound(bind) || dq.HasBinding(bind) { + t.Fatal("an Email binding is restored on the consumer channel") + } + expectEventReachesHub(t, dq, consumer.last(t)) + + binder.set(func() { binder.hold = nil }) + close(hold) + <-done + if !errors.Is(pendingErr, errQueueChanged) && !errors.Is(pendingErr, errBindingGone) { + t.Fatalf("a bind across the reconnect: %v", pendingErr) + } + }) +} + +// A subscribe confirmed on the new queue while the reconnect still runs keeps its binding, +// so its cleanup removes it from the broker. +func TestDomainQueueEmailBindDuringReconnect(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + dq, consumer, binder := emailQueue(t) + hold := make(chan struct{}) + consumer.set(func() { consumer.hold = hold }) + consumer.last(t).drop(errConnectionForced) + pass(1) // the new queue is declared, the reconnect waits on its first bind + + bind, err := dq.BindUserEmailWait(context.Background(), "sock-1/a", 42) + if err != nil { + t.Fatal(err) + } + consumer.set(func() { consumer.hold = nil }) + close(hold) + synctest.Wait() + select { + case <-dq.Rebound(): + default: + t.Fatal("no signal after the reconnect") + } + if !dq.HasBinding(bind) { + t.Fatal("the binding on the new queue is forgotten") + } + + dq.UnbindEmail(bind) + synctest.Wait() + if _, unbinds := binderLog(binder); !slices.Contains(unbinds, emailBind("sock-1/a")) { + t.Fatalf("not removed from the broker: %+v", unbinds) + } + }) +} + +// An unbind is never dropped: not for many at once, not after a broker failure; one for an +// older queue goes without a command. +func TestDomainQueueEmailUnbind(t *testing.T) { + register := func(dq *DomainQueue, n int) []*model.BindQueueEvent { + out := make([]*model.BindQueueEvent, n) + dq.Lock() + for i := range out { + out[i] = &model.BindQueueEvent{Id: fmt.Sprintf("sock-%d/a", i), Exchange: model.EmailServiceExchange, Routing: "email.workspace.*.*.v1.1.42"} + dq.bindings[bindKey(out[i])] = out[i] + } + dq.Unlock() + + return out + } + pending := func(dq *DomainQueue) int { + dq.RLock() + defer dq.RUnlock() + + return len(dq.emailUnbinds) + } + + t.Run("many while the binder is busy", func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + dq, _, binder := emailQueue(t) + hold := make(chan struct{}) + binder.set(func() { binder.hold = hold }) + go func() { _, _ = dq.BindUserEmailWait(context.Background(), "busy/a", 42) }() + synctest.Wait() + + for _, b := range register(dq, emailOpsSize+500) { + dq.UnbindEmail(b) + } + binder.set(func() { binder.hold = nil }) + close(hold) + synctest.Wait() + if _, unbinds := binderLog(binder); len(unbinds) != emailOpsSize+500 || pending(dq) != 0 { + t.Fatalf("unbinds %d, pending %d", len(unbinds), pending(dq)) + } + }) + }) + + t.Run("after a broker failure", func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + dq, _, binder := emailQueue(t) + binder.set(func() { binder.down = true }) + dq.UnbindEmail(register(dq, 1)[0]) + synctest.Wait() + if pending(dq) != 1 { + t.Fatal("a failed unbind is dropped") + } + + binder.set(func() { binder.down = false }) + time.Sleep(2 * emailUnbindRetry) + synctest.Wait() + if _, unbinds := binderLog(binder); len(unbinds) != 1 || pending(dq) != 0 { + t.Fatalf("unbinds %d, pending %d", len(unbinds), pending(dq)) + } + }) + }) + + t.Run("an older queue", func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + dq, _, binder := emailQueue(t) + b := register(dq, 1)[0] + dq.Lock() + delete(dq.bindings, bindKey(b)) + dq.emailUnbinds[bindKey(b)] = emailUnbind{b: b, queue: "engine.ws.old.1"} + dq.Unlock() + dq.startEmailBinder() + dq.emailKick <- struct{}{} + synctest.Wait() + if _, unbinds := binderLog(binder); len(unbinds) != 0 || pending(dq) != 0 { + t.Fatalf("unbinds %d, pending %d", len(unbinds), pending(dq)) + } + }) + }) +} diff --git a/mq/rabbit/email_ws_integration_test.go b/mq/rabbit/email_ws_integration_test.go new file mode 100644 index 00000000..117a0c54 --- /dev/null +++ b/mq/rabbit/email_ws_integration_test.go @@ -0,0 +1,190 @@ +//go:build integration + +package rabbit + +import ( + "context" + "fmt" + "os" + "testing" + "time" + + amqp "github.com/rabbitmq/amqp091-go" + "github.com/webitel/engine/model" + "github.com/webitel/engine/mq" + "github.com/webitel/wlog" +) + +// Needs RabbitMQ 4: EMAIL_TEST_AMQP_URL=amqp://guest:guest@localhost:5672/ go test -tags=integration ./mq/rabbit/ +func emailTestConn(t *testing.T) *amqp.Connection { + t.Helper() + url := os.Getenv("EMAIL_TEST_AMQP_URL") + if url == "" { + t.Fatal("EMAIL_TEST_AMQP_URL is required for the integration tests") + } + wlog.InitGlobalLogger(wlog.NewLogger(&wlog.LoggerConfiguration{EnableConsole: false})) + conn, err := amqp.Dial(url) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + + return conn +} + +func emailChannel(t *testing.T, conn *amqp.Connection) *amqp.Channel { + t.Helper() + ch, err := conn.Channel() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = ch.Close() }) + + return ch +} + +func waitFor(t *testing.T, what string, ok func() bool) { + t.Helper() + for deadline := time.Now().Add(15 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) { + if ok() { + return + } + } + t.Fatalf("timed out: %s", what) +} + +// emailNode is the domain queue of domain 1 on one engine node. +func emailNode(t *testing.T, conn *amqp.Connection) *DomainQueue { + t.Helper() + client := &AMQP{log: wlog.NewLogger(&wlog.LoggerConfiguration{}), connection: conn, + domainQueues: map[int64]mq.DomainQueue{}} + dq := newDomainQueue(client, 1, nil).(*DomainQueue) + dq.Start() + t.Cleanup(dq.Stop) + + return dq +} + +func publishEmail(t *testing.T, ch *amqp.Channel, id string, user int64) { + t.Helper() + body := fmt.Sprintf(`{"event_id":"%s","event_type":"email.workspace.thread.changed","schema_version":1, +"occurred_at":"2026-11-06T09:00:00Z","domain_id":1,"user_id":%d,"thread_id":1024,"access":"current", +"workspace_version":17,"projection_version":905,"message_id":null,"changes":["projection"]}`, id, user) + key := model.EmailRoutingKey(model.EmailWorkspaceThreadChanged, 1, user) + if err := ch.Publish(model.EmailServiceExchange, key, false, false, amqp.Publishing{ + ContentType: model.EmailContentType, Body: []byte(body)}); err != nil { + t.Fatal(err) + } +} + +func expectEmail(t *testing.T, dq *DomainQueue, id string) { + t.Helper() + select { + case e := <-dq.EmailEvents(): + if e.EventId != id { + t.Fatalf("event %s, want %s", e.EventId, id) + } + case <-time.After(10 * time.Second): + t.Fatalf("no event %s", id) + } +} + +func expectNoEmail(t *testing.T, dq *DomainQueue) { + t.Helper() + select { + case e := <-dq.EmailEvents(): + t.Fatalf("unexpected event %s", e.EventId) + case <-time.After(500 * time.Millisecond): + } +} + +// barrier waits until the binder of the node removed every binding it was asked to. +func barrier(t *testing.T, dq *DomainQueue) { + t.Helper() + waitFor(t, "unbinds done", func() bool { + dq.RLock() + defer dq.RUnlock() + + return len(dq.emailUnbinds) == 0 + }) +} + +// Two tabs on node a and one on node b: each node gets one copy for its sockets; a closed +// tab keeps the other; a node that lost its channel binds again and says so. +func TestEmailNodeSubscriptions(t *testing.T) { + // Every connection first: emailTestConn sets the global logger the nodes use. + conn := emailTestConn(t) + connA := emailTestConn(t) + connB := emailTestConn(t) + ch := emailChannel(t, conn) + for _, e := range []string{model.AppExchange, model.EventExchange} { + if err := ch.ExchangeDeclare(e, "topic", true, false, false, false, nil); err != nil { + t.Fatal(err) + } + } + // The binder of a node declares email.events. + if err := ch.ExchangeDelete(model.EmailServiceExchange, false, false); err != nil { + t.Fatal(err) + } + a, b := emailNode(t, connA), emailNode(t, connB) + ctx := context.Background() + a1, err := a.BindUserEmailWait(ctx, "sock-a1/g1", 42) + if err != nil { + t.Fatal(err) + } + a2, err := a.BindUserEmailWait(ctx, "sock-a2/g1", 42) + if err != nil { + t.Fatal(err) + } + if _, err := b.BindUserEmailWait(ctx, "sock-b1/g1", 42); err != nil { + t.Fatal(err) + } + + const first, second, third, fourth = "00000000-0000-4000-8000-000000000501", "00000000-0000-4000-8000-000000000502", + "00000000-0000-4000-8000-000000000503", "00000000-0000-4000-8000-000000000504" + publishEmail(t, ch, first, 42) + expectEmail(t, a, first) + expectEmail(t, b, first) + expectNoEmail(t, a) // one copy per node, not per tab + publishEmail(t, ch, "00000000-0000-4000-8000-000000000509", 43) + expectNoEmail(t, b) // the key of another user + + a.UnbindEmail(a1) + barrier(t, a) + publishEmail(t, ch, second, 42) + expectEmail(t, a, second) + expectEmail(t, b, second) + + a.UnbindEmail(a2) + barrier(t, a) + publishEmail(t, ch, third, 42) + expectEmail(t, b, third) + expectNoEmail(t, a) + + // The same socket subscribes again under a new id; the late cleanup of the old one + // does not touch it. + again, err := a.BindUserEmailWait(ctx, "sock-a2/g2", 42) + if err != nil { + t.Fatal(err) + } + a.UnbindEmail(a2) + barrier(t, a) + const fifth = "00000000-0000-4000-8000-000000000505" + publishEmail(t, ch, fifth, 42) + expectEmail(t, a, fifth) + expectEmail(t, b, fifth) + a.UnbindEmail(again) + + // After a reconnect the node has no Email bindings; the socket subscribes again. + _ = b.getChannel().Close() + select { + case <-b.Rebound(): + case <-time.After(3 * RECONNECT_SEC * time.Second): + t.Fatal("no signal after the reconnect") + } + if _, err := b.BindUserEmailWait(ctx, "sock-b1/g2", 42); err != nil { + t.Fatal(err) + } + publishEmail(t, ch, fourth, 42) + expectEmail(t, b, fourth) +} diff --git a/wsapi/email.go b/wsapi/email.go index f0db0ac5..f8082f91 100644 --- a/wsapi/email.go +++ b/wsapi/email.go @@ -25,6 +25,21 @@ func (api *API) InitEmail() { })) } api.Router.Handle("cc_email_transfer_agents", api.ApiWebSocketHandler(api.emailTransferAgents)) + api.Router.Handle("subscribe_email", api.ApiWebSocketHandler(api.subscribeEmail)) + api.Router.Handle("unsubscribe_email", api.ApiWebSocketHandler(api.unsubscribeEmail)) +} + +// subscribeEmail answers after the broker binding; user and domain come from req.Session. +func (api *API) subscribeEmail(ctx context.Context, conn *app.WebConn, req *model.WebSocketRequest) (map[string]interface{}, model.AppError) { + if err := api.App.SubscribeEmail(ctx, conn, &req.Session); err != nil { + return nil, err + } + + return map[string]interface{}{"schema_version": model.EmailSchema}, nil +} + +func (api *API) unsubscribeEmail(_ context.Context, conn *app.WebConn, _ *model.WebSocketRequest) (map[string]interface{}, model.AppError) { + return nil, api.App.UnsubscribeEmail(conn) } // The handlers check req.Session, read for this request, never the session cached in the connection. From 42a5b2d9074f54b3963baf51163b35f5261d9df2 Mon Sep 17 00:00:00 2001 From: Denys Bahachuk Date: Mon, 23 Nov 2026 14:37:42 +0000 Subject: [PATCH 2/2] fix(EM-26): address review comments --- app/web_email_test.go | 4 ++-- model/config.go | 6 +++--- model/email_ws.go | 4 ++-- wsapi/email.go | 6 +++--- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/app/web_email_test.go b/app/web_email_test.go index 3fc0030c..fc733abd 100644 --- a/app/web_email_test.go +++ b/app/web_email_test.go @@ -44,7 +44,7 @@ func (q *fakeEmailQueue) CallEvents() <-chan *model.CallEvent { func (q *fakeEmailQueue) UserStateEvents() <-chan *model.UserState { return nil } func (q *fakeEmailQueue) NotificationEvents() <-chan *model.Notification { return nil } func (q *fakeEmailQueue) ChatEvents() <-chan *model.ChatEvent { return q.chat } -func (q *fakeEmailQueue) EmailEvents() <-chan *model.EmailEvent { return q.email } +func (q *fakeEmailQueue) EmailEvents() <-chan *model.EmailEvent { return q.email } func (q *fakeEmailQueue) Rebound() <-chan struct{} { return q.rebound } func (q *fakeEmailQueue) BulkUnbind(_ []*model.BindQueueEvent) model.AppError { return nil } @@ -184,7 +184,7 @@ func newEmailEnv(t *testing.T) *emailEnv { auth := &fakeAuth{sessions: map[string]*auth_manager.Session{ "tab-a": emailSession("tab-a", 42, true), "tab-b": emailSession("tab-b", 42, true), "other": emailSession("other", 43, true)}} - a := &App{config: &model.Config{EmailWorkspace: true, AuthCacheExpire: 30}, ctx: context.Background(), + a := &App{config: &model.Config{EmailSettings: model.EmailSettings{EmailWorkspace: true}, AuthCacheExpire: 30}, ctx: context.Background(), Log: wlog.NewLogger(&wlog.LoggerConfiguration{}), tracer: NewTrace(), MessageQueue: &fakeMQ{q: q}, sessionManager: auth, Store: fakeStore{}} a.Hubs = NewHubs(a) diff --git a/model/config.go b/model/config.go index b730456f..051c2c5d 100644 --- a/model/config.go +++ b/model/config.go @@ -59,14 +59,14 @@ type Config struct { TriggersSettings TriggersSettings `json:"triggers_settings"` RTCConfiguration string `json:"rtc_configuration" flag:"rtc_configuration||RTCConfiguration" default:"" env:"RTC_CONFIGURATION"` EmailSettings - // EmailWorkspace opens the Email subscription of WebSocket (stage 17.5). - EmailWorkspace bool `json:"email_workspace" flag:"email_workspace|false|Deliver Email events to WebSocket subscribers" env:"EMAIL_WORKSPACE"` } -// EmailSettings configures the Email commands of operators; embedded without a json tag, +// EmailSettings configures the Email commands and events of operators; embedded without a json tag, // so its keys stay at the top level of the JSON configuration file. type EmailSettings struct { EmailCommandTimeout int `json:"email_command_timeout" flag:"email_command_timeout|10|Seconds an Email command waits for call_center" env:"EMAIL_COMMAND_TIMEOUT"` + // EmailWorkspace opens the Email subscription of WebSocket (stage 17.5). + EmailWorkspace bool `json:"email_workspace" flag:"email_workspace|false|Deliver Email events to WebSocket subscribers" env:"EMAIL_WORKSPACE"` } type PushConfig struct { diff --git a/model/email_ws.go b/model/email_ws.go index 88af3274..3a265dc9 100644 --- a/model/email_ws.go +++ b/model/email_ws.go @@ -18,7 +18,7 @@ var emailWsTypes = map[string]string{ // WebSocketEvent is the event "email" of docs/email-events.md: only the fields of its type, // ids and versions as decimal strings. func (e *EmailEvent) WebSocketEvent() *WebSocketEvent { - d := map[string]interface{}{ + d := map[string]any{ "type": emailWsTypes[e.EventType], "schema_version": EmailSchema, "event_id": e.EventId, @@ -37,7 +37,7 @@ func (e *EmailEvent) WebSocketEvent() *WebSocketEvent { // NewEmailResyncEvent tells the client to read everything in view again. func NewEmailResyncEvent(reason string) *WebSocketEvent { - return &WebSocketEvent{Event: WebsocketEmailEvent, Data: map[string]interface{}{ + return &WebSocketEvent{Event: WebsocketEmailEvent, Data: map[string]any{ "type": "resync_required", "schema_version": EmailSchema, "reason": reason, }} } diff --git a/wsapi/email.go b/wsapi/email.go index b9c7c484..8d62574f 100644 --- a/wsapi/email.go +++ b/wsapi/email.go @@ -23,15 +23,15 @@ func (api *API) InitEmail() { } // subscribeEmail answers after the broker binding; user and domain come from req.Session. -func (api *API) subscribeEmail(ctx context.Context, conn *app.WebConn, req *model.WebSocketRequest) (map[string]interface{}, model.AppError) { +func (api *API) subscribeEmail(ctx context.Context, conn *app.WebConn, req *model.WebSocketRequest) (map[string]any, model.AppError) { if err := api.App.SubscribeEmail(ctx, conn, &req.Session); err != nil { return nil, err } - return map[string]interface{}{"schema_version": model.EmailSchema}, nil + return map[string]any{"schema_version": model.EmailSchema}, nil } -func (api *API) unsubscribeEmail(_ context.Context, conn *app.WebConn, _ *model.WebSocketRequest) (map[string]interface{}, model.AppError) { +func (api *API) unsubscribeEmail(_ context.Context, conn *app.WebConn, _ *model.WebSocketRequest) (map[string]any, model.AppError) { return nil, api.App.UnsubscribeEmail(conn) }