Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(realtime): phase 0 — extract Broadcaster interface + add metrics (MUL-1138) (#1429)
LinYushen91424752acb7
diff --git a/server/cmd/server/listeners.go b/server/cmd/server/listeners.goindex 6827bfe5ea..e672b026e9 100644--- a/server/cmd/server/listeners.go+++ b/server/cmd/server/listeners.go@@ -15,7 +15,13 @@ import (// registerListeners wires up event bus listeners for WS broadcasting.// Personal events (inbox, invites) are sent only to the target user via// SendToUser. All other events are broadcast to the workspace room.-func registerListeners(bus *events.Bus, hub *realtime.Hub) {+//+// The broadcaster parameter is intentionally typed as the realtime.Broadcaster+// interface (not *realtime.Hub) so that this layer can later be swapped out+// for a Redis-backed relay or a feature-flagged dual-write implementation+// without touching any of the event listeners below. This is Phase 0 of the+// horizontal-scaling plan tracked in MUL-1138.+func registerListeners(bus *events.Bus, b realtime.Broadcaster) {// Personal events should NOT be broadcast to the whole workspace.personalEvents := map[string]bool{protocol.EventInboxNew: true,@@ -28,7 +34,7 @@ func registerListeners(bus *events.Bus, hub *realtime.Hub) {}// Helper: marshal event and send to a specific user.- sendToRecipient := func(hub *realtime.Hub, e events.Event, recipientID string) {+ sendToRecipient := func(b realtime.Broadcaster, e events.Event, recipientID string) {if recipientID == "" {return}@@ -36,7 +42,8 @@ func registerListeners(bus *events.Bus, hub *realtime.Hub) {if err != nil {return}- hub.SendToUser(recipientID, data)+ realtime.M.RecordEvent(e.Type)+ b.SendToUser(recipientID, data)}// inbox:new — extract recipient from nested item@@ -50,7 +57,7 @@ func registerListeners(bus *events.Bus, hub *realtime.Hub) {return}recipientID, _ := item["recipient_id"].(string)- sendToRecipient(hub, e, recipientID)+ sendToRecipient(b, e, recipientID)})// inbox:read, inbox:archived, inbox:batch-read, inbox:batch-archived@@ -65,7 +72,7 @@ func registerListeners(bus *events.Bus, hub *realtime.Hub) {return}recipientID, _ := payload["recipient_id"].(string)- sendToRecipient(hub, e, recipientID)+ sendToRecipient(b, e, recipientID)})}@@ -84,7 +91,8 @@ func registerListeners(bus *events.Bus, hub *realtime.Hub) {if err != nil {return}- hub.SendToUser(*uid, data)+ realtime.M.RecordEvent(e.Type)+ b.SendToUser(*uid, data)}}return@@ -94,7 +102,8 @@ func registerListeners(bus *events.Bus, hub *realtime.Hub) {if err != nil {return}- hub.SendToUser(*inv.InviteeUserID, data)+ realtime.M.RecordEvent(e.Type)+ b.SendToUser(*inv.InviteeUserID, data)}})@@ -106,7 +115,7 @@ func registerListeners(bus *events.Bus, hub *realtime.Hub) {}uid, _ := payload["invitee_user_id"].(*string)if uid != nil && *uid != "" {- sendToRecipient(hub, e, *uid)+ sendToRecipient(b, e, *uid)}})@@ -134,7 +143,8 @@ func registerListeners(bus *events.Bus, hub *realtime.Hub) {if err != nil {return}- hub.SendToUser(userID, data, e.WorkspaceID)+ realtime.M.RecordEvent(e.Type)+ b.SendToUser(userID, data, e.WorkspaceID)})// SubscribeAll handles workspace-broadcast for non-personal events.@@ -154,10 +164,29 @@ func registerListeners(bus *events.Bus, hub *realtime.Hub) {slog.Error("failed to marshal event", "event_type", e.Type, "error", err)return}++ // Phase 1 (MUL-1138): the per-resource scope routing for high-frequency+ // task/chat events is intentionally NOT enabled yet. The server-side+ // pieces — Hub.subscribe/unsubscribe protocol, ScopeAuthorizer, Redis+ // Streams relay — have all landed, but the client (WSClient + the+ // per-page chat/task hooks) does not yet send `subscribe` frames or+ // replay subscriptions on reconnect. Routing these events through+ // `BroadcastToScope("task"|"chat", ...)` today would silently drop+ // every chat/task message on the floor, breaking the live chat+ // timeline, chat unread badges, and pending-task UI.+ //+ // Until the client lands its scope-subscription PR, we keep+ // task/chat events on workspace fanout (same behavior as before this+ // PR). The `Event.TaskID` / `Event.ChatSessionID` hints are still+ // populated by producers so that flipping the switch later is a+ // one-line change here. See review on PR #1429 for context.+if e.WorkspaceID != "" {- hub.BroadcastToWorkspace(e.WorkspaceID, data)+ realtime.M.RecordEvent(e.Type)+ b.BroadcastToWorkspace(e.WorkspaceID, data)} else if strings.HasPrefix(e.Type, "daemon:") {- hub.Broadcast(data)+ realtime.M.RecordEvent(e.Type)+ b.Broadcast(data)}// Otherwise drop — no global broadcast for non-daemon events without a workspace.})diff --git a/server/cmd/server/listeners_scope_test.go b/server/cmd/server/listeners_scope_test.gonew file mode 100644index 0000000000..95d85c94ca--- /dev/null+++ b/server/cmd/server/listeners_scope_test.go@@ -0,0 +1,100 @@+package main++import (+ "sync"+ "testing"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// fakeBroadcaster records every fanout call so tests can assert which scope a+// given event landed on.+type fakeBroadcaster struct {+ mu sync.Mutex+ scopeCalls []scopeCall+ workspaceCalls []workspaceCall+ userCalls []userCall+ broadcastCalled int+}++type scopeCall struct {+ scopeType, scopeID string+ msg []byte+}+type workspaceCall struct {+ workspaceID string+ msg []byte+}+type userCall struct {+ userID string+ msg []byte+ exclude []string+}++func (f *fakeBroadcaster) BroadcastToScope(scopeType, scopeID string, message []byte) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.scopeCalls = append(f.scopeCalls, scopeCall{scopeType, scopeID, message})+}+func (f *fakeBroadcaster) BroadcastToWorkspace(workspaceID string, message []byte) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.workspaceCalls = append(f.workspaceCalls, workspaceCall{workspaceID, message})+}+func (f *fakeBroadcaster) SendToUser(userID string, message []byte, excludeWorkspace ...string) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.userCalls = append(f.userCalls, userCall{userID, message, excludeWorkspace})+}+func (f *fakeBroadcaster) Broadcast(message []byte) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.broadcastCalled+++}++// TestRegisterListeners_TaskChatGoToWorkspace pins the must-fix #1 contract+// from the PR #1429 review: until the WS client supports scope-subscribe and+// reconnect-replay, high-frequency task/chat events MUST keep going through+// workspace fanout. Routing them via BroadcastToScope("task"|"chat", ...)+// with no client-side subscriber would silently drop every chat / task+// message and break the live timeline + chat unread badges.+func TestRegisterListeners_TaskChatGoToWorkspace(t *testing.T) {+ cases := []struct {+ name string+ eventType string+ taskID string+ chatID string+ }{+ {"task:message with TaskID", protocol.EventTaskMessage, "task-1", ""},+ {"task:progress with TaskID", protocol.EventTaskProgress, "task-2", ""},+ {"chat:message with ChatSessionID", protocol.EventChatMessage, "", "chat-1"},+ {"chat:done with ChatSessionID", protocol.EventChatDone, "", "chat-2"},+ {"chat:session_read with ChatSessionID", protocol.EventChatSessionRead, "", "chat-3"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ bus := events.New()+ fb := &fakeBroadcaster{}+ registerListeners(bus, fb)++ bus.Publish(events.Event{+ Type: tc.eventType,+ WorkspaceID: "ws-1",+ TaskID: tc.taskID,+ ChatSessionID: tc.chatID,+ Payload: map[string]any{"hello": "world"},+ })++ if len(fb.scopeCalls) != 0 {+ t.Fatalf("expected no BroadcastToScope calls (must-fix #1: keep workspace fanout until client lands), got %+v", fb.scopeCalls)+ }+ if len(fb.workspaceCalls) != 1 {+ t.Fatalf("expected exactly 1 BroadcastToWorkspace call, got %d", len(fb.workspaceCalls))+ }+ if fb.workspaceCalls[0].workspaceID != "ws-1" {+ t.Fatalf("expected workspace ws-1, got %q", fb.workspaceCalls[0].workspaceID)+ }+ })+ }+}diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex 8d0f360697..975fd655c2 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -15,6 +15,7 @@ import ("github.com/multica-ai/multica/server/internal/realtime""github.com/multica-ai/multica/server/internal/service"db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/redis/go-redis/v9")func main() {@@ -57,12 +58,34 @@ func main() {bus := events.New()hub := realtime.NewHub()go hub.Run()- registerListeners(bus, hub)++ // MUL-1138: when REDIS_URL is set, route fanout through a Redis relay so+ // multiple API nodes can deliver each other's events. Without it the hub+ // is the sole broadcaster and the server stays single-node (legacy).+ relayCtx, relayCancel := context.WithCancel(context.Background())+ defer relayCancel()+ var broadcaster realtime.Broadcaster = hub+ if redisURL := os.Getenv("REDIS_URL"); redisURL != "" {+ opts, err := redis.ParseURL(redisURL)+ if err != nil {+ slog.Error("invalid REDIS_URL — falling back to in-memory hub", "error", err)+ } else {+ rdb := redis.NewClient(opts)+ relay := realtime.NewRedisRelay(hub, rdb)+ relay.Start(relayCtx)+ broadcaster = relay+ slog.Info("realtime: Redis relay enabled", "node_id", relay.NodeID())+ }+ } else {+ slog.Info("realtime: REDIS_URL not set — using in-memory hub (single-node mode)")+ }+ registerListeners(bus, broadcaster)analyticsClient := analytics.NewFromEnv()defer analyticsClient.Close()queries := db.New(pool)+ hub.SetAuthorizer(newScopeAuthorizer(queries))// Order matters: subscriber listeners must register BEFORE notification listeners.// The notification listener queries the subscriber table to determine recipients,// so subscribers must be written first within the same synchronous event dispatch.diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 144f6b6a6d..7f0080cebe 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2,6 +2,7 @@ package mainimport ("context"+ "encoding/json""net/http""os""strings"@@ -106,6 +107,15 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analyticsw.Write([]byte(`{"status":"ok"}`))})+ // Realtime subsystem metrics — connection counts, slow-client evictions,+ // and per-event-type send QPS counters. Exposed as JSON so it can be+ // scraped by ops or surfaced in the admin UI without adding a Prometheus+ // dependency. See MUL-1138 (Phase 0).+ r.Get("/health/realtime", func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(realtime.M.Snapshot())+ })+// WebSocketmc := &membershipChecker{queries: queries}pr := &patResolver{queries: queries}diff --git a/server/cmd/server/scope_authorizer.go b/server/cmd/server/scope_authorizer.gonew file mode 100644index 0000000000..11e7f551e7--- /dev/null+++ b/server/cmd/server/scope_authorizer.go@@ -0,0 +1,92 @@+package main++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/realtime"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// scopeAuthQuerier is the narrow subset of db.Queries used by the scope+// authorizer. Declared as an interface so the authorizer can be unit tested+// with an in-memory fake (no DB required).+type scopeAuthQuerier interface {+ GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)+ GetIssue(ctx context.Context, id pgtype.UUID) (db.Issue, error)+ GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error)+}++// dbScopeAuthorizer implements realtime.ScopeAuthorizer for the per-task and+// per-chat scopes (workspace/user scopes are validated by the hub itself+// against the connection identity). It returns true only when the requested+// resource exists, belongs to the caller's workspace, and — for chat+// resources — was created by the caller (mirroring the HTTP creator-only+// access model).+type dbScopeAuthorizer struct{ q scopeAuthQuerier }++func newScopeAuthorizer(q scopeAuthQuerier) *dbScopeAuthorizer { return &dbScopeAuthorizer{q: q} }++func (a *dbScopeAuthorizer) AuthorizeScope(ctx context.Context, userID, workspaceID, scopeType, scopeID string) (bool, error) {+ if workspaceID == "" || scopeID == "" {+ return false, nil+ }+ wsUUID := parseUUID(workspaceID)+ idUUID := parseUUID(scopeID)+ if !wsUUID.Valid || !idUUID.Valid {+ return false, nil+ }+ switch scopeType {+ case realtime.ScopeTask:+ task, err := a.q.GetAgentTask(ctx, idUUID)+ if err != nil {+ return false, nil+ }+ // Issue tasks: visible to any workspace member.+ if task.IssueID.Valid {+ issue, err := a.q.GetIssue(ctx, task.IssueID)+ if err != nil {+ return false, nil+ }+ return issue.WorkspaceID == wsUUID, nil+ }+ // Chat tasks: only the chat session's creator may subscribe, mirroring+ // the HTTP layer's creator-only access on chat resources.+ if task.ChatSessionID.Valid {+ sess, err := a.q.GetChatSession(ctx, task.ChatSessionID)+ if err != nil {+ return false, nil+ }+ if sess.WorkspaceID != wsUUID {+ return false, nil+ }+ uidUUID := parseUUID(userID)+ if !uidUUID.Valid || sess.CreatorID != uidUUID {+ return false, nil+ }+ return true, nil+ }+ return false, nil+ case realtime.ScopeChat:+ sess, err := a.q.GetChatSession(ctx, idUUID)+ if err != nil {+ return false, nil+ }+ if sess.WorkspaceID != wsUUID {+ return false, nil+ }+ // Chat sessions are private to their creator (see handler/chat.go:+ // GetChatSession / SendChatMessage / MarkChatSessionRead all enforce+ // CreatorID == userID). The realtime layer must not weaken this:+ // otherwise any workspace member who learns a session_id could+ // subscribe to chat:message / chat:done / chat:session_read for a+ // peer's private chat.+ uidUUID := parseUUID(userID)+ if !uidUUID.Valid || sess.CreatorID != uidUUID {+ return false, nil+ }+ return true, nil+ default:+ return false, nil+ }+}diff --git a/server/cmd/server/scope_authorizer_test.go b/server/cmd/server/scope_authorizer_test.gonew file mode 100644index 0000000000..975370dc63--- /dev/null+++ b/server/cmd/server/scope_authorizer_test.go@@ -0,0 +1,186 @@+package main++import (+ "context"+ "errors"+ "testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/realtime"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// fakeScopeQuerier implements scopeAuthQuerier with in-memory maps.+type fakeScopeQuerier struct {+ tasks map[[16]byte]db.AgentTaskQueue+ issues map[[16]byte]db.Issue+ sessions map[[16]byte]db.ChatSession+}++func (f *fakeScopeQuerier) GetAgentTask(_ context.Context, id pgtype.UUID) (db.AgentTaskQueue, error) {+ if t, ok := f.tasks[id.Bytes]; ok {+ return t, nil+ }+ return db.AgentTaskQueue{}, errors.New("not found")+}+func (f *fakeScopeQuerier) GetIssue(_ context.Context, id pgtype.UUID) (db.Issue, error) {+ if i, ok := f.issues[id.Bytes]; ok {+ return i, nil+ }+ return db.Issue{}, errors.New("not found")+}+func (f *fakeScopeQuerier) GetChatSession(_ context.Context, id pgtype.UUID) (db.ChatSession, error) {+ if s, ok := f.sessions[id.Bytes]; ok {+ return s, nil+ }+ return db.ChatSession{}, errors.New("not found")+}++func mustUUID(t *testing.T) (string, pgtype.UUID) {+ t.Helper()+ u, err := uuid.NewRandom()+ if err != nil {+ t.Fatal(err)+ }+ return u.String(), pgtype.UUID{Bytes: u, Valid: true}+}++// TestScopeAuthorizer_ChatRequiresCreator pins must-fix #2 from PR #1429:+// ScopeChat MUST verify CreatorID == userID. A workspace peer that knows the+// session_id must NOT be able to subscribe to chat:message / chat:done /+// chat:session_read for that private session.+func TestScopeAuthorizer_ChatRequiresCreator(t *testing.T) {+ wsStr, wsUUID := mustUUID(t)+ creatorStr, creatorUUID := mustUUID(t)+ otherStr, _ := mustUUID(t)+ sessStr, sessUUID := mustUUID(t)+ otherWsStr, _ := mustUUID(t)+ otherWsStrOnly, otherWsUUID := mustUUID(t)+ _ = otherWsStrOnly++ q := &fakeScopeQuerier{+ sessions: map[[16]byte]db.ChatSession{+ sessUUID.Bytes: {+ ID: sessUUID,+ WorkspaceID: wsUUID,+ CreatorID: creatorUUID,+ },+ },+ }+ a := newScopeAuthorizer(q)+ ctx := context.Background()++ // Creator in matching workspace → allowed.+ ok, err := a.AuthorizeScope(ctx, creatorStr, wsStr, realtime.ScopeChat, sessStr)+ if err != nil || !ok {+ t.Fatalf("creator should be allowed: ok=%v err=%v", ok, err)+ }++ // Same workspace, different (peer) member → must be denied.+ ok, err = a.AuthorizeScope(ctx, otherStr, wsStr, realtime.ScopeChat, sessStr)+ if err != nil || ok {+ t.Fatalf("peer must be denied: ok=%v err=%v", ok, err)+ }++ // Cross-workspace creator (e.g. session in workspace A, request in+ // workspace B) → must be denied even though creator matches.+ ok, err = a.AuthorizeScope(ctx, creatorStr, otherWsStr, realtime.ScopeChat, sessStr)+ if err != nil || ok {+ t.Fatalf("cross-workspace must be denied: ok=%v err=%v", ok, err)+ }+ _ = otherWsUUID++ // Empty userID → must be denied (defensive).+ ok, err = a.AuthorizeScope(ctx, "", wsStr, realtime.ScopeChat, sessStr)+ if err != nil || ok {+ t.Fatalf("empty userID must be denied: ok=%v err=%v", ok, err)+ }++ // Unknown session → denied.+ _, missingStr := mustUUID(t)+ _ = missingStr+ missingUUID, _ := uuid.NewRandom()+ ok, err = a.AuthorizeScope(ctx, creatorStr, wsStr, realtime.ScopeChat, missingUUID.String())+ if err != nil || ok {+ t.Fatalf("unknown session must be denied: ok=%v err=%v", ok, err)+ }+}++// TestScopeAuthorizer_ChatTaskRequiresCreator pins must-fix #2 for the+// task-scope path of chat tasks (task.ChatSessionID set, no IssueID): only+// the chat session creator may subscribe to that task's stream, since+// task:message for chat tasks contains assistant chat content.+func TestScopeAuthorizer_ChatTaskRequiresCreator(t *testing.T) {+ wsStr, wsUUID := mustUUID(t)+ creatorStr, creatorUUID := mustUUID(t)+ otherStr, _ := mustUUID(t)+ sessStr, sessUUID := mustUUID(t)+ taskStr, taskUUID := mustUUID(t)+ _ = sessStr++ q := &fakeScopeQuerier{+ tasks: map[[16]byte]db.AgentTaskQueue{+ taskUUID.Bytes: {+ ID: taskUUID,+ ChatSessionID: sessUUID,+ },+ },+ sessions: map[[16]byte]db.ChatSession{+ sessUUID.Bytes: {+ ID: sessUUID,+ WorkspaceID: wsUUID,+ CreatorID: creatorUUID,+ },+ },+ }+ a := newScopeAuthorizer(q)+ ctx := context.Background()++ ok, err := a.AuthorizeScope(ctx, creatorStr, wsStr, realtime.ScopeTask, taskStr)+ if err != nil || !ok {+ t.Fatalf("creator should be allowed for chat task: ok=%v err=%v", ok, err)+ }++ ok, err = a.AuthorizeScope(ctx, otherStr, wsStr, realtime.ScopeTask, taskStr)+ if err != nil || ok {+ t.Fatalf("peer must be denied for chat task: ok=%v err=%v", ok, err)+ }+}++// TestScopeAuthorizer_IssueTaskWorkspaceOnly verifies issue tasks remain+// workspace-scoped (any member who can see the issue may subscribe).+func TestScopeAuthorizer_IssueTaskWorkspaceOnly(t *testing.T) {+ wsStr, wsUUID := mustUUID(t)+ memberStr, _ := mustUUID(t)+ otherWsStr, _ := mustUUID(t)+ taskStr, taskUUID := mustUUID(t)+ _, issueUUID := mustUUID(t)++ q := &fakeScopeQuerier{+ tasks: map[[16]byte]db.AgentTaskQueue{+ taskUUID.Bytes: {+ ID: taskUUID,+ IssueID: issueUUID,+ },+ },+ issues: map[[16]byte]db.Issue{+ issueUUID.Bytes: {+ ID: issueUUID,+ WorkspaceID: wsUUID,+ },+ },+ }+ a := newScopeAuthorizer(q)+ ctx := context.Background()++ ok, err := a.AuthorizeScope(ctx, memberStr, wsStr, realtime.ScopeTask, taskStr)+ if err != nil || !ok {+ t.Fatalf("member in workspace should be allowed: ok=%v err=%v", ok, err)+ }++ ok, err = a.AuthorizeScope(ctx, memberStr, otherWsStr, realtime.ScopeTask, taskStr)+ if err != nil || ok {+ t.Fatalf("cross-workspace must be denied: ok=%v err=%v", ok, err)+ }+}diff --git a/server/go.mod b/server/go.modindex 26b0281177..73fb2915f1 100644--- a/server/go.mod+++ b/server/go.mod@@ -15,6 +15,8 @@ require (github.com/gorilla/websocket v1.5.3github.com/jackc/pgx/v5 v5.8.0github.com/lmittmann/tint v1.1.3+ github.com/oklog/ulid/v2 v2.1.1+ github.com/redis/go-redis/v9 v9.18.0github.com/resend/resend-go/v2 v2.28.0github.com/robfig/cron/v3 v3.0.1github.com/spf13/cobra v1.10.2@@ -36,11 +38,14 @@ require (github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.18 // indirectgithub.com/aws/aws-sdk-go-v2/service/sts v1.41.10 // indirectgithub.com/aws/smithy-go v1.24.2 // indirect+ github.com/cespare/xxhash/v2 v2.3.0 // indirect+ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirectgithub.com/inconshreveable/mousetrap v1.1.0 // indirectgithub.com/jackc/pgpassfile v1.0.0 // indirectgithub.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirectgithub.com/jackc/puddle/v2 v2.2.2 // indirectgithub.com/spf13/pflag v1.0.9 // indirect+ go.uber.org/atomic v1.11.0 // indirectgolang.org/x/sync v0.20.0 // indirectgolang.org/x/text v0.35.0 // indirect)diff --git a/server/go.sum b/server/go.sumindex eced351cc5..b5f8cd6140 100644--- a/server/go.sum+++ b/server/go.sum@@ -38,10 +38,18 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.41.10 h1:p8ogvvLugcR/zLBXTXrTkj0RYBUgithub.com/aws/aws-sdk-go-v2/service/sts v1.41.10/go.mod h1:60dv0eZJfeVXfbT1tFJinbHrDfSJ2GZl4Q//OSSNAVw=github.com/aws/smithy-go v1.24.2 h1:FzA3bu/nt/vDvmnkg+R8Xl46gmzEDam6mZ1hzmwXFng=github.com/aws/smithy-go v1.24.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=+github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=+github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=+github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=+github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0=github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=@@ -62,10 +70,17 @@ github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo=github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw=github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=+github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=+github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=github.com/lmittmann/tint v1.1.3 h1:Hv4EaHWXQr+GTFnOU4VKf8UvAtZgn0VuKT+G0wFlO3I=github.com/lmittmann/tint v1.1.3/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=+github.com/oklog/ulid/v2 v2.1.1 h1:suPZ4ARWLOJLegGFiZZ1dFAkqzhMjL3J1TzI+5wHz8s=+github.com/oklog/ulid/v2 v2.1.1/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ=+github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=+github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=github.com/resend/resend-go/v2 v2.28.0 h1:ttM1/VZR4fApBv3xI1TneSKi1pbfFsVrq7fXFlHKtj4=github.com/resend/resend-go/v2 v2.28.0/go.mod h1:3YCb8c8+pLiqhtRFXTyFwlLvfjQtluxOr9HEh2BwCkQ=github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=@@ -80,6 +95,10 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVgithub.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=+github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=+github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=+go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=+go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=diff --git a/server/internal/events/bus.go b/server/internal/events/bus.goindex cf676adc07..391ba8754f 100644--- a/server/internal/events/bus.go+++ b/server/internal/events/bus.go@@ -12,6 +12,13 @@ type Event struct {ActorType string // "member", "agent", or "system"ActorID stringPayload any // JSON-serializable, same shape as current WS payloads++ // Optional scope hints used by the realtime fanout layer to route the+ // event to a more specific scope than `workspace:{WorkspaceID}`. When set+ // these tell the listener which Redis stream / Hub room to publish on+ // without re-deserializing Payload. See MUL-1138 phase 1.+ TaskID string+ ChatSessionID string}// Handler is a function that processes an event.diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.goindex 4697f220cf..1e880508d7 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -252,7 +252,7 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {}// Broadcast the user message.- h.publish(protocol.EventChatMessage, workspaceID, "member", userID, protocol.ChatMessagePayload{+ h.publishChat(protocol.EventChatMessage, workspaceID, "member", userID, sessionID, protocol.ChatMessagePayload{ChatSessionID: sessionID,MessageID: uuidToString(msg.ID),Role: "user",@@ -337,7 +337,7 @@ func (h *Handler) MarkChatSessionRead(w http.ResponseWriter, r *http.Request) {return}- h.publish(protocol.EventChatSessionRead, workspaceID, "member", userID, protocol.ChatSessionReadPayload{+ h.publishChat(protocol.EventChatSessionRead, workspaceID, "member", userID, sessionID, protocol.ChatSessionReadPayload{ChatSessionID: sessionID,})diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex f562c4fa6e..e8ae547c0f 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1084,7 +1084,7 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {})if workspaceID != "" {- h.publish(protocol.EventTaskMessage, workspaceID, "system", "", protocol.TaskMessagePayload{+ h.publishTask(protocol.EventTaskMessage, workspaceID, "system", "", taskID, protocol.TaskMessagePayload{TaskID: taskID,IssueID: uuidToString(task.IssueID),Seq: msg.Seq,diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 1eb9e16ec3..7a9cd25ac2 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -121,6 +121,32 @@ func (h *Handler) publish(eventType, workspaceID, actorType, actorID string, pay})}+// publishTask is publish() plus a TaskID hint so the realtime layer can route+// the event to the per-task scope rather than the whole workspace.+func (h *Handler) publishTask(eventType, workspaceID, actorType, actorID, taskID string, payload any) {+ h.Bus.Publish(events.Event{+ Type: eventType,+ WorkspaceID: workspaceID,+ ActorType: actorType,+ ActorID: actorID,+ TaskID: taskID,+ Payload: payload,+ })+}++// publishChat is publish() plus a ChatSessionID hint so the realtime layer+// can route the event to the per-chat-session scope.+func (h *Handler) publishChat(eventType, workspaceID, actorType, actorID, chatSessionID string, payload any) {+ h.Bus.Publish(events.Event{+ Type: eventType,+ WorkspaceID: workspaceID,+ ActorType: actorType,+ ActorID: actorID,+ ChatSessionID: chatSessionID,+ Payload: payload,+ })+}+func isNotFound(err error) bool {return errors.Is(err, pgx.ErrNoRows)}diff --git a/server/internal/realtime/broadcaster.go b/server/internal/realtime/broadcaster.gonew file mode 100644index 0000000000..a5aaba7ad3--- /dev/null+++ b/server/internal/realtime/broadcaster.go@@ -0,0 +1,42 @@+package realtime++// Scope types recognised by the broadcaster. Producers and consumers should+// use these constants rather than raw strings so a typo can never silently+// route an event to a non-existent room.+const (+ ScopeWorkspace = "workspace"+ ScopeUser = "user"+ ScopeTask = "task"+ ScopeChat = "chat"+)++// Broadcaster is the abstraction every realtime event producer should depend+// on instead of *Hub directly.+//+// Phase 1 (MUL-1138) extends the surface with BroadcastToScope so events can+// be fanned out to high-frequency per-resource scopes (`task:{id}`,+// `chat:{id}`) instead of the whole workspace. The legacy methods continue to+// work and now route through BroadcastToScope under the hood.+type Broadcaster interface {+ // BroadcastToScope fans a message out to every connection currently+ // subscribed to ({scopeType, scopeID}) on this node.+ BroadcastToScope(scopeType, scopeID string, message []byte)++ // BroadcastToWorkspace is a back-compat shortcut for+ // BroadcastToScope("workspace", workspaceID, message).+ BroadcastToWorkspace(workspaceID string, message []byte)++ // SendToUser is a back-compat shortcut for+ // BroadcastToScope("user", userID, message). The optional+ // excludeWorkspace argument is preserved for the `member:added`+ // dedup path: connections whose workspaceID matches excludeWorkspace+ // are skipped.+ SendToUser(userID string, message []byte, excludeWorkspace ...string)++ // Broadcast fans a message out to every connection on this node.+ // Used for daemon:* events that have no workspace scope.+ Broadcast(message []byte)+}++// Compile-time assertion that *Hub continues to satisfy Broadcaster.+var _ Broadcaster = (*Hub)(nil)diff --git a/server/internal/realtime/hub.go b/server/internal/realtime/hub.goindex 92717d8e16..9b22639993 100644--- a/server/internal/realtime/hub.go+++ b/server/internal/realtime/hub.go@@ -21,16 +21,23 @@ type MembershipChecker interface {IsMember(ctx context.Context, userID, workspaceID string) bool}-// SlugResolver translates a workspace slug to its UUID. Used by HandleWebSocket-// to accept slug-based identification from the frontend.+// SlugResolver translates a workspace slug to its UUID.type SlugResolver func(ctx context.Context, slug string) (workspaceID string, err error)// PATResolver resolves a Personal Access Token to a user ID.-// Returns the user ID and true if the token is valid, or ("", false) otherwise.type PATResolver interface {ResolveToken(ctx context.Context, token string) (userID string, ok bool)}+// ScopeAuthorizer decides whether a connection (identified by userID ++// workspaceID) is allowed to subscribe to a given scope. Implementations+// typically perform a DB lookup on the underlying resource (task / chat+// session) and verify it belongs to workspaceID. Implementations should+// cache positive results to avoid hot-path DB load.+type ScopeAuthorizer interface {+ AuthorizeScope(ctx context.Context, userID, workspaceID, scopeType, scopeID string) (bool, error)+}+var allowedWSOrigins atomic.Value // holds []stringfunc init() {@@ -64,7 +71,7 @@ func loadAllowedOrigins() []string {return origins}-// SetAllowedOrigins overrides the WebSocket origin whitelist (called from router setup).+// SetAllowedOrigins overrides the WebSocket origin whitelist.func SetAllowedOrigins(origins []string) {allowedWSOrigins.Store(origins)}@@ -85,17 +92,8 @@ func checkOrigin(r *http.Request) bool {}const (- // writeWait is the time allowed to write a message to the peer.- writeWait = 10 * time.Second-- // pongWait is the time allowed to read the next pong message from the peer.- // Connections that miss a pong within this window are considered dead and- // are closed, freeing goroutines and channel memory.- pongWait = 60 * time.Second-- // pingPeriod is how often the server sends a ping to keep the connection- // alive through intermediate proxies and load balancers. Must be less than- // pongWait so that a missing pong is detected before the next ping is due.+ writeWait = 10 * time.Second+ pongWait = 60 * time.SecondpingPeriod = (pongWait * 9) / 10)@@ -103,194 +101,469 @@ var upgrader = websocket.Upgrader{CheckOrigin: checkOrigin,}-// Client represents a single WebSocket connection with identity.+// scopeKey is the composite key used to look up a "room" of subscribers.+type scopeKey struct {+ Type string+ ID string+}++func sk(t, id string) scopeKey { return scopeKey{Type: t, ID: id} }++// Client represents a single WebSocket connection with identity and the set+// of scopes it is currently subscribed to.type Client struct {hub *Hubconn *websocket.Connsend chan []byteuserID stringworkspaceID string++ // subscriptions is guarded by hub.mu. Tracks the scopes this client is+ // currently in. Used to clean up rooms on disconnect.+ subscriptions map[scopeKey]bool++ // lastSeenEventIDs is used by the dual-write broadcaster (and any+ // future deliverer) to dedup messages that arrived first via the local+ // fast path and are then re-played from Redis. Bounded LRU semantics+ // are not required because event IDs are ULIDs and we only keep the+ // last few.+ dedupMu sync.Mutex+ seenIDs map[string]struct{}+ seenList []string}-// Hub manages WebSocket connections organized by workspace rooms.+const dedupCapacity = 128++// markSeen records eventID as already delivered to this client. Returns true+// if it was the first time we saw this id (caller should deliver), false if+// it's a duplicate (caller should drop).+func (c *Client) markSeen(eventID string) bool {+ if eventID == "" {+ return true+ }+ c.dedupMu.Lock()+ defer c.dedupMu.Unlock()+ if c.seenIDs == nil {+ c.seenIDs = make(map[string]struct{}, dedupCapacity)+ }+ if _, ok := c.seenIDs[eventID]; ok {+ return false+ }+ c.seenIDs[eventID] = struct{}{}+ c.seenList = append(c.seenList, eventID)+ if len(c.seenList) > dedupCapacity {+ drop := c.seenList[0]+ c.seenList = c.seenList[1:]+ delete(c.seenIDs, drop)+ }+ return true+}++// SubscriptionCallback fires when a scope's local subscriber count crosses+// 0↔1 boundaries. Used by the Redis relay to start/stop XREADGROUP loops on+// demand.+type SubscriptionCallback func(scopeType, scopeID string)++// Hub manages WebSocket connections organized into scope-based rooms.type Hub struct {- rooms map[string]map[*Client]bool // workspaceID -> clients- broadcast chan []byte // global broadcast (daemon events)+ rooms map[scopeKey]map[*Client]bool+ clients map[*Client]bool // every connected client (used by global Broadcast and snapshots)+ broadcast chan []byteregister chan *Clientunregister chan *Clientmu sync.RWMutex++ authorizer ScopeAuthorizer++ // Subscription lifecycle hooks. Both can be nil.+ onFirstSubscriber SubscriptionCallback+ onLastSubscriber SubscriptionCallback}// NewHub creates a new Hub instance.func NewHub() *Hub {return &Hub{- rooms: make(map[string]map[*Client]bool),+ rooms: make(map[scopeKey]map[*Client]bool),+ clients: make(map[*Client]bool),broadcast: make(chan []byte),register: make(chan *Client),unregister: make(chan *Client),}}+// SetAuthorizer wires a ScopeAuthorizer into the hub. Safe to call before Run.+func (h *Hub) SetAuthorizer(a ScopeAuthorizer) {+ h.mu.Lock()+ defer h.mu.Unlock()+ h.authorizer = a+}++// SetSubscriptionCallbacks registers callbacks fired when a scope on this+// node transitions from 0→1 subscribers (onFirst) or 1→0 (onLast). The+// Redis relay uses these to start/stop a per-scope consumer loop.+func (h *Hub) SetSubscriptionCallbacks(onFirst, onLast SubscriptionCallback) {+ h.mu.Lock()+ defer h.mu.Unlock()+ h.onFirstSubscriber = onFirst+ h.onLastSubscriber = onLast+}+// Run starts the hub event loop.func (h *Hub) Run() {for {select {case client := <-h.register:h.mu.Lock()- room := client.workspaceID- if h.rooms[room] == nil {- h.rooms[room] = make(map[*Client]bool)- }- h.rooms[room][client] = true- total := 0- for _, r := range h.rooms {- total += len(r)- }+ h.clients[client] = true+ total := len(h.clients)h.mu.Unlock()- slog.Info("ws client connected", "workspace_id", room, "total_clients", total)+ M.ConnectsTotal.Add(1)+ M.ActiveConnections.Add(1)+ // Auto-subscribe to the workspace and user scopes.+ h.subscribe(client, ScopeWorkspace, client.workspaceID)+ if client.userID != "" {+ h.subscribe(client, ScopeUser, client.userID)+ }+ slog.Info("ws client connected", "workspace_id", client.workspaceID, "user_id", client.userID, "total_clients", total)case client := <-h.unregister:- h.mu.Lock()- room := client.workspaceID- if clients, ok := h.rooms[room]; ok {- if _, exists := clients[client]; exists {- delete(clients, client)- close(client.send)- if len(clients) == 0 {- delete(h.rooms, room)- }- }- }- total := 0- for _, r := range h.rooms {- total += len(r)- }- h.mu.Unlock()- slog.Info("ws client disconnected", "workspace_id", room, "total_clients", total)+ h.removeClient(client)case message := <-h.broadcast:- // Global broadcast for daemon events (no workspace filtering)- h.mu.RLock()- var slow []*Client- for _, clients := range h.rooms {- for client := range clients {- select {- case client.send <- message:- default:- slow = append(slow, client)- }- }- }- h.mu.RUnlock()- if len(slow) > 0 {- h.mu.Lock()- for _, client := range slow {- room := client.workspaceID- if clients, ok := h.rooms[room]; ok {- if _, exists := clients[client]; exists {- delete(clients, client)- close(client.send)- if len(clients) == 0 {- delete(h.rooms, room)- }- }- }- }- h.mu.Unlock()+ h.fanoutAll(message, "")+ }+ }+}++// removeClient drops a client from all rooms and the global set.+func (h *Hub) removeClient(client *Client) {+ h.mu.Lock()+ if !h.clients[client] {+ h.mu.Unlock()+ return+ }+ delete(h.clients, client)+ subs := client.subscriptions+ client.subscriptions = nil+ emptied := make([]scopeKey, 0, len(subs))+ for key := range subs {+ if room, ok := h.rooms[key]; ok {+ delete(room, client)+ if len(room) == 0 {+ delete(h.rooms, key)+ emptied = append(emptied, key)}}}+ close(client.send)+ cb := h.onLastSubscriber+ total := len(h.clients)+ h.mu.Unlock()++ M.DisconnectsTotal.Add(1)+ M.ActiveConnections.Add(-1)+ if cb != nil {+ for _, key := range emptied {+ cb(key.Type, key.ID)+ }+ }+ for _, key := range emptied {+ M.DecRoom(key.Type)+ }+ slog.Info("ws client disconnected", "workspace_id", client.workspaceID, "user_id", client.userID, "total_clients", total)}-// BroadcastToWorkspace sends a message only to clients in the given workspace.-func (h *Hub) BroadcastToWorkspace(workspaceID string, message []byte) {+// subscribe adds client to scope (scopeType, scopeID) and fires the+// onFirstSubscriber callback if the room transitioned from empty to non-empty.+// Returns true if the subscription was newly added.+func (h *Hub) subscribe(client *Client, scopeType, scopeID string) bool {+ if scopeType == "" || scopeID == "" {+ return false+ }+ key := sk(scopeType, scopeID)++ h.mu.Lock()+ if !h.clients[client] {+ h.mu.Unlock()+ return false+ }+ if client.subscriptions == nil {+ client.subscriptions = map[scopeKey]bool{}+ }+ if client.subscriptions[key] {+ h.mu.Unlock()+ return false+ }+ client.subscriptions[key] = true+ room, ok := h.rooms[key]+ first := false+ if !ok {+ room = make(map[*Client]bool)+ h.rooms[key] = room+ first = true+ }+ room[client] = true+ cb := h.onFirstSubscriber+ h.mu.Unlock()++ M.SubscribesTotal(scopeType).Add(1)+ if first {+ M.IncRoom(scopeType)+ if cb != nil {+ cb(scopeType, scopeID)+ }+ }+ return true+}++// unsubscribe removes client from a scope room and fires onLastSubscriber if+// the room is now empty.+func (h *Hub) unsubscribe(client *Client, scopeType, scopeID string) bool {+ if scopeType == "" || scopeID == "" {+ return false+ }+ key := sk(scopeType, scopeID)++ h.mu.Lock()+ if !h.clients[client] {+ h.mu.Unlock()+ return false+ }+ if client.subscriptions == nil || !client.subscriptions[key] {+ h.mu.Unlock()+ return false+ }+ delete(client.subscriptions, key)+ emptied := false+ if room, ok := h.rooms[key]; ok {+ delete(room, client)+ if len(room) == 0 {+ delete(h.rooms, key)+ emptied = true+ }+ }+ cb := h.onLastSubscriber+ h.mu.Unlock()++ M.UnsubscribesTotal(scopeType).Add(1)+ if emptied {+ M.DecRoom(scopeType)+ if cb != nil {+ cb(scopeType, scopeID)+ }+ }+ return true+}++// HasLocalSubscribers reports whether at least one local client is subscribed+// to (scopeType, scopeID). Used by the Redis relay to decide whether to keep+// a per-scope consumer running.+func (h *Hub) HasLocalSubscribers(scopeType, scopeID string) bool {+ h.mu.RLock()+ defer h.mu.RUnlock()+ _, ok := h.rooms[sk(scopeType, scopeID)]+ return ok+}++// LocalScopes returns the set of scopes currently active on this node.+// Snapshot only — callers must not assume thread-stability.+func (h *Hub) LocalScopes() []scopeKey {+ h.mu.RLock()+ defer h.mu.RUnlock()+ out := make([]scopeKey, 0, len(h.rooms))+ for k := range h.rooms {+ out = append(out, k)+ }+ return out+}++// BroadcastToScope sends a message to every client subscribed to+// (scopeType, scopeID). Slow clients are evicted under write lock.+func (h *Hub) BroadcastToScope(scopeType, scopeID string, message []byte) {+ h.BroadcastToScopeDedup(scopeType, scopeID, message, "")+}++// BroadcastToScopeDedup is the same as BroadcastToScope but skips delivery+// to clients that have already seen eventID (used by the Redis relay to+// deduplicate the local fast path of DualWriteBroadcaster).+func (h *Hub) BroadcastToScopeDedup(scopeType, scopeID string, message []byte, eventID string) {+ if scopeType == "" || scopeID == "" {+ return+ }+ key := sk(scopeType, scopeID)+h.mu.RLock()- clients := h.rooms[workspaceID]+ clients := h.rooms[key]var slow []*Client+ var sent int64for client := range clients {+ if !client.markSeen(eventID) {+ continue+ }select {case client.send <- message:+ sent++default:slow = append(slow, client)}}h.mu.RUnlock()- // Remove slow clients under write lock+ if sent > 0 {+ M.MessagesSentTotal.Add(sent)+ }if len(slow) > 0 {- h.mu.Lock()- for _, client := range slow {- if room, ok := h.rooms[workspaceID]; ok {- if _, exists := room[client]; exists {- delete(room, client)- close(client.send)- if len(room) == 0 {- delete(h.rooms, workspaceID)- }- }- }+ h.evictSlow(slow)+ }+}++// fanoutAll delivers message to every connected client. If excludeWorkspace+// is non-empty, clients whose workspaceID matches are skipped (used by the+// member:added dedup semantics carried over from SendToUser). eventID is the+// dedup key (empty disables dedup).+func (h *Hub) fanoutAll(message []byte, excludeWorkspace string) {+ h.fanoutAllDedup(message, excludeWorkspace, "")+}++func (h *Hub) fanoutAllDedup(message []byte, excludeWorkspace, eventID string) {+ h.mu.RLock()+ var slow []*Client+ var sent int64+ for client := range h.clients {+ if excludeWorkspace != "" && client.workspaceID == excludeWorkspace {+ continue}- h.mu.Unlock()+ if !client.markSeen(eventID) {+ continue+ }+ select {+ case client.send <- message:+ sent+++ default:+ slow = append(slow, client)+ }+ }+ h.mu.RUnlock()++ if sent > 0 {+ M.MessagesSentTotal.Add(sent)+ }+ if len(slow) > 0 {+ h.evictSlow(slow)}}-// SendToUser sends a message to all connections belonging to a specific user,-// regardless of which workspace room they are in. Connections in excludeWorkspace-// are skipped (they already receive the message via BroadcastToWorkspace).+// BroadcastToWorkspace is a back-compat shortcut.+func (h *Hub) BroadcastToWorkspace(workspaceID string, message []byte) {+ h.BroadcastToScope(ScopeWorkspace, workspaceID, message)+}++// SendToUser delivers a message to every connection belonging to userID,+// skipping any connections whose workspaceID matches excludeWorkspace.func (h *Hub) SendToUser(userID string, message []byte, excludeWorkspace ...string) {exclude := ""if len(excludeWorkspace) > 0 {exclude = excludeWorkspace[0]}+ h.fanoutUser(userID, message, exclude, "")+}+// Broadcast sends a message to every connected client (daemon events).+func (h *Hub) Broadcast(message []byte) {+ h.broadcast <- message+}++// fanoutUser delivers a message to all clients in the user scope, optionally+// excluding clients in excludeWorkspace and deduping against eventID.+func (h *Hub) fanoutUser(userID string, message []byte, excludeWorkspace, eventID string) {+ key := sk(ScopeUser, userID)h.mu.RLock()- type target struct {- client *Client- workspaceID string- }- var targets []target- for wsID, clients := range h.rooms {- if wsID == exclude {+ clients := h.rooms[key]+ var slow []*Client+ var sent int64+ for client := range clients {+ if excludeWorkspace != "" && client.workspaceID == excludeWorkspace {continue}- for client := range clients {- if client.userID == userID {- targets = append(targets, target{client, wsID})- }+ if !client.markSeen(eventID) {+ continue}- }- h.mu.RUnlock()-- var slow []target- for _, t := range targets {select {- case t.client.send <- message:+ case client.send <- message:+ sent++default:- slow = append(slow, t)+ slow = append(slow, client)}}-- // Remove slow clients under write lock (same pattern as BroadcastToWorkspace)+ h.mu.RUnlock()+ if sent > 0 {+ M.MessagesSentTotal.Add(sent)+ }if len(slow) > 0 {- h.mu.Lock()- for _, t := range slow {- if room, ok := h.rooms[t.workspaceID]; ok {- if _, exists := room[t.client]; exists {- delete(room, t.client)- close(t.client.send)- if len(room) == 0 {- delete(h.rooms, t.workspaceID)- }+ h.evictSlow(slow)+ }+}++// evictSlow removes clients whose send channel was full. Mirrors the+// pre-phase-1 behavior: closes the send channel, decrements counters, fires+// onLastSubscriber for any rooms drained as a side effect.+func (h *Hub) evictSlow(slow []*Client) {+ M.MessagesDroppedTotal.Add(int64(len(slow)))+ M.SlowEvictionsTotal.Add(int64(len(slow)))++ h.mu.Lock()+ evicted := 0+ type emptied struct {+ Type, ID string+ }+ var drainedRooms []emptied+ for _, c := range slow {+ if !h.clients[c] {+ continue+ }+ delete(h.clients, c)+ for key := range c.subscriptions {+ if room, ok := h.rooms[key]; ok {+ delete(room, c)+ if len(room) == 0 {+ delete(h.rooms, key)+ drainedRooms = append(drainedRooms, emptied{key.Type, key.ID})}}}- h.mu.Unlock()+ c.subscriptions = nil+ close(c.send)+ evicted+++ }+ cb := h.onLastSubscriber+ h.mu.Unlock()++ if evicted > 0 {+ M.ActiveConnections.Add(int64(-evicted))+ M.DisconnectsTotal.Add(int64(evicted))+ }+ for _, r := range drainedRooms {+ M.DecRoom(r.Type)+ }+ if cb != nil {+ for _, r := range drainedRooms {+ cb(r.Type, r.ID)+ }}}-// Broadcast sends a message to all connected clients (used for daemon events).-func (h *Hub) Broadcast(message []byte) {- h.broadcast <- message+// Snapshot returns a JSON-friendly summary of the hub state.+func (h *Hub) Snapshot() map[string]any {+ h.mu.RLock()+ defer h.mu.RUnlock()+ rooms := map[string]int{}+ for key := range h.rooms {+ rooms[key.Type]+++ }+ return map[string]any{+ "connections": len(h.clients),+ "rooms": rooms,+ }}// authenticateToken validates a JWT or PAT string and returns the user ID.@@ -329,11 +602,9 @@ func authenticateToken(tokenStr string, pr PATResolver, ctx context.Context) (st}// firstMessageAuth reads the first WebSocket message expecting an auth payload.-// Message format: {"type":"auth","payload":{"token":"..."}}-// Returns the token string or an error description.func firstMessageAuth(conn *websocket.Conn) (string, string) {conn.SetReadDeadline(time.Now().Add(10 * time.Second))- defer conn.SetReadDeadline(time.Time{}) // clear deadline for subsequent reads+ defer conn.SetReadDeadline(time.Time{})_, raw, err := conn.ReadMessage()if err != nil {@@ -353,8 +624,8 @@ func firstMessageAuth(conn *websocket.Conn) (string, string) {return msg.Payload.Token, ""}-// HandleWebSocket upgrades an HTTP connection to WebSocket with cookie or first-message auth.-// resolveSlug may be nil if slug-based identification is not needed (e.g. in tests).+// HandleWebSocket upgrades an HTTP connection to WebSocket with cookie or+// first-message auth.func HandleWebSocket(hub *Hub, mc MembershipChecker, pr PATResolver, resolveSlug SlugResolver, w http.ResponseWriter, r *http.Request) {workspaceID := r.URL.Query().Get("workspace_id")if workspaceID == "" {@@ -372,7 +643,6 @@ func HandleWebSocket(hub *Hub, mc MembershipChecker, pr PATResolver, resolveSlugreturn}- // Try cookie auth first (web clients).var userID stringif cookie, err := r.Cookie(auth.AuthCookieName); err == nil && cookie.Value != "" {uid, errMsg := authenticateToken(cookie.Value, pr, r.Context())@@ -387,15 +657,12 @@ func HandleWebSocket(hub *Hub, mc MembershipChecker, pr PATResolver, resolveSluguserID = uid}- // Upgrade the connection. Clients without cookies (desktop) will authenticate- // via the first WebSocket message, so we must upgrade before we have a token.conn, err := upgrader.Upgrade(w, r, nil)if err != nil {slog.Error("websocket upgrade failed", "error", err)return}- // First-message auth for non-cookie clients (desktop, CLI).if userID == "" {tokenStr, errMsg := firstMessageAuth(conn)if errMsg != "" {@@ -447,15 +714,24 @@ func HandleWebSocket(hub *Hub, mc MembershipChecker, pr PATResolver, resolveSluggo client.readPump()}+// inboundFrame describes the subset of inbound JSON messages the server+// understands today.+type inboundFrame struct {+ Type string `json:"type"`+ Payload json.RawMessage `json:"payload"`+}++type subPayload struct {+ Scope string `json:"scope"`+ ID string `json:"id"`+}+func (c *Client) readPump() {defer func() {c.hub.unregister <- cc.conn.Close()}()- // Require a pong within pongWait of each ping. The deadline is refreshed- // every time a pong frame arrives, so a healthy connection stays open- // indefinitely. A dead connection (no pong) is detected within pongWait.c.conn.SetReadDeadline(time.Now().Add(pongWait))c.conn.SetPongHandler(func(string) error {c.conn.SetReadDeadline(time.Now().Add(pongWait))@@ -463,15 +739,127 @@ func (c *Client) readPump() {})for {- _, _, err := c.conn.ReadMessage()+ _, raw, err := c.conn.ReadMessage()if err != nil {if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure) {slog.Debug("websocket read error", "error", err, "user_id", c.userID, "workspace_id", c.workspaceID)}break}- // TODO: Route inbound messages to appropriate handlers- slog.Debug("ws message received", "user_id", c.userID, "workspace_id", c.workspaceID)+ c.handleFrame(raw)+ }+}++func (c *Client) handleFrame(raw []byte) {+ var f inboundFrame+ if err := json.Unmarshal(raw, &f); err != nil {+ slog.Debug("ws inbound: invalid json", "error", err, "user_id", c.userID)+ return+ }+ switch f.Type {+ case "subscribe", "unsubscribe":+ var p subPayload+ if err := json.Unmarshal(f.Payload, &p); err != nil || p.Scope == "" || p.ID == "" {+ c.sendJSON(map[string]any{+ "type": f.Type + "_error",+ "payload": map[string]string{+ "scope": p.Scope,+ "id": p.ID,+ "error": "invalid payload",+ },+ })+ return+ }+ if f.Type == "subscribe" {+ c.handleSubscribe(p.Scope, p.ID)+ } else {+ c.handleUnsubscribe(p.Scope, p.ID)+ }+ case "ping":+ c.sendJSON(map[string]string{"type": "pong"})+ default:+ // Unknown frame — ignore silently for forward compat.+ slog.Debug("ws inbound: unknown frame", "type", f.Type, "user_id", c.userID)+ }+}++func (c *Client) handleSubscribe(scope, id string) {+ switch scope {+ case ScopeWorkspace, ScopeUser:+ // Implicit scopes — only allowed if it matches the connection identity.+ if (scope == ScopeWorkspace && id != c.workspaceID) || (scope == ScopeUser && id != c.userID) {+ M.SubscribeDeniedTotal(scope).Add(1)+ c.sendJSON(map[string]any{+ "type": "subscribe_error",+ "payload": map[string]string{+ "scope": scope,+ "id": id,+ "error": "forbidden",+ },+ })+ return+ }+ // Already auto-subscribed at connect time; reply ack idempotently.+ c.hub.subscribe(c, scope, id)+ case ScopeTask, ScopeChat:+ auth := c.hub.authorizer+ if auth != nil {+ ok, err := auth.AuthorizeScope(context.Background(), c.userID, c.workspaceID, scope, id)+ if err != nil || !ok {+ M.SubscribeDeniedTotal(scope).Add(1)+ reason := "forbidden"+ if err != nil {+ reason = "lookup_failed"+ }+ c.sendJSON(map[string]any{+ "type": "subscribe_error",+ "payload": map[string]string{+ "scope": scope,+ "id": id,+ "error": reason,+ },+ })+ return+ }+ }+ c.hub.subscribe(c, scope, id)+ default:+ M.SubscribeDeniedTotal(scope).Add(1)+ c.sendJSON(map[string]any{+ "type": "subscribe_error",+ "payload": map[string]string{+ "scope": scope,+ "id": id,+ "error": "unknown_scope",+ },+ })+ return+ }+ c.sendJSON(map[string]any{+ "type": "subscribe_ack",+ "payload": map[string]string{"scope": scope, "id": id},+ })+}++func (c *Client) handleUnsubscribe(scope, id string) {+ c.hub.unsubscribe(c, scope, id)+ c.sendJSON(map[string]any{+ "type": "unsubscribe_ack",+ "payload": map[string]string{"scope": scope, "id": id},+ })+}++// sendJSON best-effort encodes v and pushes it to the client's send channel.+// Drops the message if the channel is full (the writePump will be evicted by+// the next BroadcastToScope cycle).+func (c *Client) sendJSON(v any) {+ data, err := json.Marshal(v)+ if err != nil {+ return+ }+ select {+ case c.send <- data:+ default:}}@@ -487,7 +875,6 @@ func (c *Client) writePump() {case message, ok := <-c.send:c.conn.SetWriteDeadline(time.Now().Add(writeWait))if !ok {- // Hub closed the channel (slow-client eviction or shutdown).c.conn.WriteMessage(websocket.CloseMessage, []byte{})return}diff --git a/server/internal/realtime/hub_test.go b/server/internal/realtime/hub_test.goindex 06b5c02e99..a7dc9d2b77 100644--- a/server/internal/realtime/hub_test.go+++ b/server/internal/realtime/hub_test.go@@ -81,15 +81,11 @@ func connectWS(t *testing.T, server *httptest.Server) *websocket.Conn {return conn}-// totalClients counts all clients across all rooms.+// totalClients counts all currently registered clients.func totalClients(hub *Hub) int {hub.mu.RLock()defer hub.mu.RUnlock()- count := 0- for _, clients := range hub.rooms {- count += len(clients)- }- return count+ return len(hub.clients)}func TestHub_ClientRegistration(t *testing.T) {diff --git a/server/internal/realtime/metrics.go b/server/internal/realtime/metrics.gonew file mode 100644index 0000000000..c610a6238e--- /dev/null+++ b/server/internal/realtime/metrics.go@@ -0,0 +1,178 @@+package realtime++import (+ "sort"+ "sync"+ "sync/atomic"+)++// Metrics collects lightweight counters describing the realtime subsystem.+//+// Phase 1 (MUL-1138) extends the phase-0 counter set with subscribe / Redis /+// per-scope-room counters. We keep using std-library atomics rather than a+// Prometheus dependency; a future phase can re-export the same numbers.+type Metrics struct {+ ConnectsTotal atomic.Int64+ DisconnectsTotal atomic.Int64+ ActiveConnections atomic.Int64+ SlowEvictionsTotal atomic.Int64+ MessagesSentTotal atomic.Int64+ MessagesDroppedTotal atomic.Int64++ // Per-event-type send counters keyed by event type string.+ // Value is *atomic.Int64.+ eventSent sync.Map++ // Per-scope subscribe / unsubscribe / deny counters. Keyed by scope+ // type string ("workspace", "user", "task", "chat"). Value is+ // *atomic.Int64. Scope-room gauges follow the same pattern.+ subscribeTotal sync.Map+ unsubscribeTotal sync.Map+ subscribeDeniedTotal sync.Map+ scopeRooms sync.Map++ // Redis relay counters. Zero unless the Redis broadcaster is enabled.+ RedisXAddTotal atomic.Int64+ RedisXAddErrors atomic.Int64+ RedisXReadTotal atomic.Int64+ RedisXReadErrors atomic.Int64+ RedisAckTotal atomic.Int64+ RedisLastXAddLagMicros atomic.Int64++ // RedisConnected is set by the relay on startup / reconnect.+ RedisConnected atomic.Bool+ // RedisLastError stores the most recent consumer error message.+ redisLastErrMu sync.RWMutex+ redisLastErr string++ // NodeID is set once at boot by the relay (or empty in single-node mode).+ NodeID atomic.Value // string+}++// M is the package-level metrics singleton.+var M = &Metrics{}++func loadOrInitCounter(m *sync.Map, key string) *atomic.Int64 {+ if v, ok := m.Load(key); ok {+ return v.(*atomic.Int64)+ }+ c := new(atomic.Int64)+ if existing, loaded := m.LoadOrStore(key, c); loaded {+ return existing.(*atomic.Int64)+ }+ return c+}++// RecordEvent increments the per-event-type send counter.+func (m *Metrics) RecordEvent(eventType string) {+ if eventType == "" {+ return+ }+ loadOrInitCounter(&m.eventSent, eventType).Add(1)+}++// SubscribesTotal returns the per-scope-type counter for successful subscribes.+func (m *Metrics) SubscribesTotal(scopeType string) *atomic.Int64 {+ return loadOrInitCounter(&m.subscribeTotal, scopeType)+}++// UnsubscribesTotal returns the per-scope-type counter for unsubscribes.+func (m *Metrics) UnsubscribesTotal(scopeType string) *atomic.Int64 {+ return loadOrInitCounter(&m.unsubscribeTotal, scopeType)+}++// SubscribeDeniedTotal returns the per-scope-type counter for denied subscribes.+func (m *Metrics) SubscribeDeniedTotal(scopeType string) *atomic.Int64 {+ return loadOrInitCounter(&m.subscribeDeniedTotal, scopeType)+}++// IncRoom / DecRoom adjust the active-rooms gauge for scopeType.+func (m *Metrics) IncRoom(scopeType string) { loadOrInitCounter(&m.scopeRooms, scopeType).Add(1) }+func (m *Metrics) DecRoom(scopeType string) { loadOrInitCounter(&m.scopeRooms, scopeType).Add(-1) }++// SetRedisLastError stores msg as the most recent Redis consumer error. An+// empty msg clears it.+func (m *Metrics) SetRedisLastError(msg string) {+ m.redisLastErrMu.Lock()+ m.redisLastErr = msg+ m.redisLastErrMu.Unlock()+}++func (m *Metrics) lastRedisErr() string {+ m.redisLastErrMu.RLock()+ defer m.redisLastErrMu.RUnlock()+ return m.redisLastErr+}++func snapshotCounters(s *sync.Map) map[string]int64 {+ out := map[string]int64{}+ s.Range(func(k, v any) bool {+ out[k.(string)] = v.(*atomic.Int64).Load()+ return true+ })+ keys := make([]string, 0, len(out))+ for k := range out {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ ordered := make(map[string]int64, len(out))+ for _, k := range keys {+ ordered[k] = out[k]+ }+ return ordered+}++// Snapshot returns a JSON-friendly copy of the current counter values.+func (m *Metrics) Snapshot() map[string]any {+ nodeID := ""+ if v := m.NodeID.Load(); v != nil {+ nodeID, _ = v.(string)+ }+ return map[string]any{+ "connects_total": m.ConnectsTotal.Load(),+ "disconnects_total": m.DisconnectsTotal.Load(),+ "active_connections": m.ActiveConnections.Load(),+ "slow_evictions_total": m.SlowEvictionsTotal.Load(),+ "messages_sent_total": m.MessagesSentTotal.Load(),+ "messages_dropped_total": m.MessagesDroppedTotal.Load(),+ "events_sent_by_type": snapshotCounters(&m.eventSent),+ "subscribes_total": snapshotCounters(&m.subscribeTotal),+ "unsubscribes_total": snapshotCounters(&m.unsubscribeTotal),+ "subscribe_denied_total": snapshotCounters(&m.subscribeDeniedTotal),+ "active_scope_rooms": snapshotCounters(&m.scopeRooms),+ "redis": map[string]any{+ "connected": m.RedisConnected.Load(),+ "node_id": nodeID,+ "xadd_total": m.RedisXAddTotal.Load(),+ "xadd_errors": m.RedisXAddErrors.Load(),+ "xread_total": m.RedisXReadTotal.Load(),+ "xread_errors": m.RedisXReadErrors.Load(),+ "ack_total": m.RedisAckTotal.Load(),+ "last_xadd_lag_micros": m.RedisLastXAddLagMicros.Load(),+ "last_error": m.lastRedisErr(),+ },+ }+}++// Reset zeroes all counters. Tests only.+func (m *Metrics) Reset() {+ m.ConnectsTotal.Store(0)+ m.DisconnectsTotal.Store(0)+ m.ActiveConnections.Store(0)+ m.SlowEvictionsTotal.Store(0)+ m.MessagesSentTotal.Store(0)+ m.MessagesDroppedTotal.Store(0)+ m.eventSent.Range(func(k, _ any) bool { m.eventSent.Delete(k); return true })+ m.subscribeTotal.Range(func(k, _ any) bool { m.subscribeTotal.Delete(k); return true })+ m.unsubscribeTotal.Range(func(k, _ any) bool { m.unsubscribeTotal.Delete(k); return true })+ m.subscribeDeniedTotal.Range(func(k, _ any) bool { m.subscribeDeniedTotal.Delete(k); return true })+ m.scopeRooms.Range(func(k, _ any) bool { m.scopeRooms.Delete(k); return true })+ m.RedisXAddTotal.Store(0)+ m.RedisXAddErrors.Store(0)+ m.RedisXReadTotal.Store(0)+ m.RedisXReadErrors.Store(0)+ m.RedisAckTotal.Store(0)+ m.RedisLastXAddLagMicros.Store(0)+ m.RedisConnected.Store(false)+ m.SetRedisLastError("")+}diff --git a/server/internal/realtime/metrics_test.go b/server/internal/realtime/metrics_test.gonew file mode 100644index 0000000000..5d791bc4bf--- /dev/null+++ b/server/internal/realtime/metrics_test.go@@ -0,0 +1,84 @@+package realtime++import (+ "sync"+ "testing"+)++func TestMetrics_RecordEvent(t *testing.T) {+ m := &Metrics{}++ m.RecordEvent("issue:updated")+ m.RecordEvent("issue:updated")+ m.RecordEvent("task:message")+ m.RecordEvent("") // ignored++ snap := m.Snapshot()+ events, ok := snap["events_sent_by_type"].(map[string]int64)+ if !ok {+ t.Fatalf("expected events_sent_by_type to be map[string]int64, got %T", snap["events_sent_by_type"])+ }+ if events["issue:updated"] != 2 {+ t.Errorf("issue:updated count = %d, want 2", events["issue:updated"])+ }+ if events["task:message"] != 1 {+ t.Errorf("task:message count = %d, want 1", events["task:message"])+ }+ if _, ok := events[""]; ok {+ t.Errorf("empty event type should not be recorded")+ }+}++func TestMetrics_RecordEvent_Concurrent(t *testing.T) {+ m := &Metrics{}+ var wg sync.WaitGroup+ const goroutines = 50+ const perGoroutine = 200+ for i := 0; i < goroutines; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ for j := 0; j < perGoroutine; j++ {+ m.RecordEvent("comment:created")+ }+ }()+ }+ wg.Wait()++ snap := m.Snapshot()+ events := snap["events_sent_by_type"].(map[string]int64)+ want := int64(goroutines * perGoroutine)+ if events["comment:created"] != want {+ t.Errorf("comment:created count = %d, want %d", events["comment:created"], want)+ }+}++func TestMetrics_Snapshot_IncludesCounters(t *testing.T) {+ m := &Metrics{}+ m.ConnectsTotal.Store(10)+ m.DisconnectsTotal.Store(3)+ m.ActiveConnections.Store(7)+ m.SlowEvictionsTotal.Store(2)+ m.MessagesSentTotal.Store(123)+ m.MessagesDroppedTotal.Store(4)++ snap := m.Snapshot()+ for k, want := range map[string]int64{+ "connects_total": 10,+ "disconnects_total": 3,+ "active_connections": 7,+ "slow_evictions_total": 2,+ "messages_sent_total": 123,+ "messages_dropped_total": 4,+ } {+ if got, _ := snap[k].(int64); got != want {+ t.Errorf("snapshot[%q] = %v, want %d", k, snap[k], want)+ }+ }+}++// Compile-time guarantee that *Hub continues to satisfy Broadcaster, in case+// someone changes hub.go method signatures without updating the interface.+func TestHubImplementsBroadcaster(t *testing.T) {+ var _ Broadcaster = NewHub()+}diff --git a/server/internal/realtime/redis_relay.go b/server/internal/realtime/redis_relay.gonew file mode 100644index 0000000000..f164a7ac9b--- /dev/null+++ b/server/internal/realtime/redis_relay.go@@ -0,0 +1,483 @@+package realtime++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+ "strings"+ "sync"+ "time"++ "github.com/oklog/ulid/v2"+ "github.com/redis/go-redis/v9"+)++// Stream / registry key naming. Centralised so tests can introspect.+func StreamKey(scopeType, scopeID string) string {+ return fmt.Sprintf("ws:scope:%s:%s:stream", scopeType, scopeID)+}+func NodesKey(scopeType, scopeID string) string {+ return fmt.Sprintf("ws:scope:%s:%s:nodes", scopeType, scopeID)+}+func HeartbeatKey(nodeID string) string {+ return fmt.Sprintf("ws:node:%s:heartbeat", nodeID)+}++const (+ streamMaxLen int64 = 10000+ heartbeatTTL = 90 * time.Second+ heartbeatPeriod = 30 * time.Second+ consumerIdleGrace = 10 * time.Minute+ consumerSweepPeriod = 5 * time.Minute+)++// envelope is what we serialise into each XADD message. It is opaque to the+// hub: the relay decodes payload_json before fanning out.+type envelope struct {+ EventID string `json:"event_id"`+ EventType string `json:"event_type"`+ Scope string `json:"scope"`+ ScopeID string `json:"scope_id"`+ WorkspaceID string `json:"workspace_id"`+ ActorID string `json:"actor_id"`+ CreatedAt string `json:"created_at"`+ NodeID string `json:"node_id"`+ PayloadJSON string `json:"payload_json"` // raw JSON of the original ws frame+}++// RedisRelay is a Broadcaster implementation that writes every message to a+// per-scope Redis Stream and consumes streams for which there are local+// subscribers. Local fanout is delegated to the wrapped *Hub.+type RedisRelay struct {+ hub *Hub+ rdb *redis.Client+ nodeID string++ mu sync.Mutex+ consumers map[scopeKey]*scopeConsumer+}++type scopeConsumer struct {+ cancel context.CancelFunc+ done chan struct{}+}++// NewRedisRelay constructs a relay. The caller is responsible for invoking+// Start before producing messages.+func NewRedisRelay(hub *Hub, rdb *redis.Client) *RedisRelay {+ return &RedisRelay{+ hub: hub,+ rdb: rdb,+ nodeID: ulid.Make().String(),+ consumers: make(map[scopeKey]*scopeConsumer),+ }+}++// NodeID returns this relay's randomly-assigned node identifier.+func (r *RedisRelay) NodeID() string { return r.nodeID }++// Start wires the hub→relay subscription callbacks, kicks off the heartbeat+// goroutine, and spins up consumers for any scopes the hub already knows+// about. ctx controls all background goroutines: cancelling it shuts the+// relay down.+func (r *RedisRelay) Start(ctx context.Context) {+ M.NodeID.Store(r.nodeID)+ if err := r.rdb.Ping(ctx).Err(); err != nil {+ slog.Error("realtime/redis: initial ping failed", "error", err)+ M.RedisConnected.Store(false)+ M.SetRedisLastError(err.Error())+ } else {+ M.RedisConnected.Store(true)+ }++ r.hub.SetSubscriptionCallbacks(+ func(scopeType, scopeID string) { r.startConsumer(ctx, scopeType, scopeID) },+ func(scopeType, scopeID string) { r.stopConsumer(scopeType, scopeID) },+ )++ for _, key := range r.hub.LocalScopes() {+ r.startConsumer(ctx, key.Type, key.ID)+ }++ go r.heartbeatLoop(ctx)+ go r.consumerSweeper(ctx)+}++// BroadcastToScope publishes message into the scope's Redis stream. The+// envelope contains an event_id for client-side dedup. Local fanout happens+// when this node consumes its own write back through XREADGROUP — except in+// the dual-write configuration where the local hub is invoked directly.+func (r *RedisRelay) BroadcastToScope(scopeType, scopeID string, message []byte) {+ r.publish(scopeType, scopeID, "", message)+}++// BroadcastToWorkspace / SendToUser / Broadcast satisfy the back-compat+// portion of Broadcaster.+func (r *RedisRelay) BroadcastToWorkspace(workspaceID string, message []byte) {+ r.publish(ScopeWorkspace, workspaceID, "", message)+}+func (r *RedisRelay) SendToUser(userID string, message []byte, excludeWorkspace ...string) {+ exclude := ""+ if len(excludeWorkspace) > 0 {+ exclude = excludeWorkspace[0]+ }+ r.publish(ScopeUser, userID, exclude, message)+}+func (r *RedisRelay) Broadcast(message []byte) {+ // Daemon broadcast — write to a special "global" stream so other nodes+ // can fan out to all clients regardless of subscriptions.+ r.publish("global", "all", "", message)+}++func (r *RedisRelay) publish(scopeType, scopeID, exclude string, frame []byte) {+ ev := envelope{+ EventID: ulid.Make().String(),+ Scope: scopeType,+ ScopeID: scopeID,+ NodeID: r.nodeID,+ CreatedAt: time.Now().UTC().Format(time.RFC3339Nano),+ PayloadJSON: string(frame),+ }+ if exclude != "" {+ ev.WorkspaceID = exclude+ }+ // Best-effort: peek inside the JSON for event_type / actor_id.+ if t, a := peekTypeActor(frame); t != "" {+ ev.EventType = t+ ev.ActorID = a+ }++ args := &redis.XAddArgs{+ Stream: StreamKey(scopeType, scopeID),+ MaxLen: streamMaxLen,+ Approx: true,+ Values: map[string]any{+ "event_id": ev.EventID,+ "event_type": ev.EventType,+ "scope": ev.Scope,+ "scope_id": ev.ScopeID,+ "workspace_id": ev.WorkspaceID,+ "actor_id": ev.ActorID,+ "created_at": ev.CreatedAt,+ "node_id": ev.NodeID,+ "payload_json": ev.PayloadJSON,+ },+ }+ start := time.Now()+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer cancel()+ if err := r.rdb.XAdd(ctx, args).Err(); err != nil {+ M.RedisXAddErrors.Add(1)+ M.SetRedisLastError(err.Error())+ slog.Warn("realtime/redis: XADD failed", "error", err, "scope", scopeType, "scope_id", scopeID)+ return+ }+ M.RedisXAddTotal.Add(1)+ M.RedisLastXAddLagMicros.Store(time.Since(start).Microseconds())+}++// startConsumer kicks off a single per-scope XREADGROUP loop if not already+// running.+func (r *RedisRelay) startConsumer(parent context.Context, scopeType, scopeID string) {+ key := sk(scopeType, scopeID)+ r.mu.Lock()+ if _, exists := r.consumers[key]; exists {+ r.mu.Unlock()+ return+ }+ ctx, cancel := context.WithCancel(parent)+ c := &scopeConsumer{cancel: cancel, done: make(chan struct{})}+ r.consumers[key] = c+ r.mu.Unlock()++ go r.runConsumer(ctx, c, scopeType, scopeID)+}++func (r *RedisRelay) stopConsumer(scopeType, scopeID string) {+ key := sk(scopeType, scopeID)+ r.mu.Lock()+ c, ok := r.consumers[key]+ if ok {+ delete(r.consumers, key)+ }+ r.mu.Unlock()+ if !ok {+ return+ }+ c.cancel()+}++func (r *RedisRelay) runConsumer(ctx context.Context, c *scopeConsumer, scopeType, scopeID string) {+ defer close(c.done)++ stream := StreamKey(scopeType, scopeID)+ group := "node:" + r.nodeID+ consumerName := r.nodeID++ // MKSTREAM ensures the stream exists. Ignore BUSYGROUP.+ createCtx, createCancel := context.WithTimeout(ctx, 2*time.Second)+ if err := r.rdb.XGroupCreateMkStream(createCtx, stream, group, "$").Err(); err != nil && !strings.Contains(err.Error(), "BUSYGROUP") {+ slog.Warn("realtime/redis: XGROUP CREATE failed", "error", err, "scope", scopeType, "scope_id", scopeID)+ }+ createCancel()++ // Register ourselves as a node interested in this scope.+ regCtx, regCancel := context.WithTimeout(ctx, 2*time.Second)+ r.rdb.ZAdd(regCtx, NodesKey(scopeType, scopeID), redis.Z{Score: float64(time.Now().Add(heartbeatTTL).Unix()), Member: r.nodeID})+ regCancel()++ for {+ if ctx.Err() != nil {+ break+ }+ readCtx, readCancel := context.WithTimeout(ctx, 6*time.Second)+ res, err := r.rdb.XReadGroup(readCtx, &redis.XReadGroupArgs{+ Group: group,+ Consumer: consumerName,+ Streams: []string{stream, ">"},+ Count: 32,+ Block: 5 * time.Second,+ }).Result()+ readCancel()+ if errors.Is(err, redis.Nil) || (err != nil && (errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled))) {+ continue+ }+ if err != nil {+ M.RedisXReadErrors.Add(1)+ M.SetRedisLastError(err.Error())+ // Brief backoff to avoid busy-looping on a flapping connection.+ select {+ case <-ctx.Done():+ return+ case <-time.After(time.Second):+ }+ continue+ }+ for _, s := range res {+ for _, msg := range s.Messages {+ M.RedisXReadTotal.Add(1)+ r.deliverMessage(scopeType, scopeID, msg)+ ackCtx, ackCancel := context.WithTimeout(ctx, time.Second)+ if err := r.rdb.XAck(ackCtx, stream, group, msg.ID).Err(); err != nil {+ slog.Debug("realtime/redis: XACK failed", "error", err, "id", msg.ID)+ } else {+ M.RedisAckTotal.Add(1)+ }+ ackCancel()+ }+ }+ }++ // Best-effort consumer cleanup.+ cleanCtx, cleanCancel := context.WithTimeout(context.Background(), 2*time.Second)+ r.rdb.XGroupDelConsumer(cleanCtx, stream, group, consumerName)+ cleanCancel()+}++func (r *RedisRelay) deliverMessage(scopeType, scopeID string, msg redis.XMessage) {+ payloadAny, ok := msg.Values["payload_json"]+ if !ok {+ return+ }+ payload, _ := payloadAny.(string)+ if payload == "" {+ return+ }+ exclude, _ := msg.Values["workspace_id"].(string)+ eventID, _ := msg.Values["event_id"].(string)++ // Inject event_id into the outgoing frame for client-side dedup.+ frame := injectEventID([]byte(payload), eventID)++ switch scopeType {+ case "global":+ r.hub.fanoutAllDedup(frame, "", eventID)+ case ScopeUser:+ r.hub.fanoutUser(scopeID, frame, exclude, eventID)+ default:+ r.hub.BroadcastToScopeDedup(scopeType, scopeID, frame, eventID)+ }+}++// fanoutUser is implemented in hub.go.++func (r *RedisRelay) heartbeatLoop(ctx context.Context) {+ t := time.NewTicker(heartbeatPeriod)+ defer t.Stop()+ for {+ r.heartbeatOnce(ctx)+ select {+ case <-ctx.Done():+ return+ case <-t.C:+ }+ }+}++func (r *RedisRelay) heartbeatOnce(ctx context.Context) {+ hbCtx, cancel := context.WithTimeout(ctx, 2*time.Second)+ defer cancel()+ if err := r.rdb.Set(hbCtx, HeartbeatKey(r.nodeID), time.Now().UTC().Format(time.RFC3339Nano), heartbeatTTL).Err(); err != nil {+ M.RedisConnected.Store(false)+ M.SetRedisLastError(err.Error())+ return+ }+ M.RedisConnected.Store(true)+ expiry := float64(time.Now().Add(heartbeatTTL).Unix())+ for _, key := range r.hub.LocalScopes() {+ r.rdb.ZAdd(hbCtx, NodesKey(key.Type, key.ID), redis.Z{Score: expiry, Member: r.nodeID})+ }+}++// consumerSweeper periodically drops stale ZSET entries (nodes whose TTL+// expired). Best-effort: we only sweep the scopes this node currently has+// local subscribers for, since they're the only ones we can reason about+// without scanning all keys.+func (r *RedisRelay) consumerSweeper(ctx context.Context) {+ t := time.NewTicker(consumerSweepPeriod)+ defer t.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-t.C:+ }+ now := float64(time.Now().Unix())+ for _, key := range r.hub.LocalScopes() {+ swCtx, cancel := context.WithTimeout(ctx, 2*time.Second)+ r.rdb.ZRemRangeByScore(swCtx, NodesKey(key.Type, key.ID), "-inf", fmt.Sprintf("%f", now))+ cancel()+ }+ }+}++// peekTypeActor parses the WS frame just enough to lift event_type / actor_id+// for the envelope. Failures yield empty strings — the envelope still works.+func peekTypeActor(frame []byte) (string, string) {+ var probe struct {+ Type string `json:"type"`+ ActorID string `json:"actor_id"`+ }+ _ = json.Unmarshal(frame, &probe)+ return probe.Type, probe.ActorID+}++// injectEventID inserts the event_id field into an existing JSON object frame+// without re-encoding the payload. The frame must be a JSON object.+func injectEventID(frame []byte, eventID string) []byte {+ if eventID == "" || len(frame) == 0 || frame[0] != '{' {+ return frame+ }+ // Decode-encode round-trip is simplest and avoids edge cases with+ // trailing whitespace / nested escapes. A few extra allocations per+ // message are fine relative to the network cost.+ var obj map[string]json.RawMessage+ if err := json.Unmarshal(frame, &obj); err != nil {+ return frame+ }+ if _, exists := obj["event_id"]; exists {+ return frame+ }+ idJSON, _ := json.Marshal(eventID)+ obj["event_id"] = idJSON+ out, err := json.Marshal(obj)+ if err != nil {+ return frame+ }+ return out+}++// DualWriteBroadcaster delivers each message both to the local hub (immediate+// fanout) AND to the Redis relay (cross-node fanout). It dedups via+// Client.markSeen so the same client doesn't see the same event twice when+// the Redis relay loops the message back.+type DualWriteBroadcaster struct {+ local *Hub+ relay *RedisRelay+}++func NewDualWriteBroadcaster(local *Hub, relay *RedisRelay) *DualWriteBroadcaster {+ return &DualWriteBroadcaster{local: local, relay: relay}+}++func (d *DualWriteBroadcaster) BroadcastToScope(scopeType, scopeID string, message []byte) {+ id := ulid.Make().String()+ frame := injectEventID(message, id)+ // Local fast path: BroadcastToScopeDedup marks each client as having+ // seen `id`, so the Redis loopback for the same id will be ignored.+ d.local.BroadcastToScopeDedup(scopeType, scopeID, frame, id)+ d.relay.publishWithID(scopeType, scopeID, "", message, id)+}++func (d *DualWriteBroadcaster) BroadcastToWorkspace(workspaceID string, message []byte) {+ d.BroadcastToScope(ScopeWorkspace, workspaceID, message)+}++func (d *DualWriteBroadcaster) SendToUser(userID string, message []byte, excludeWorkspace ...string) {+ exclude := ""+ if len(excludeWorkspace) > 0 {+ exclude = excludeWorkspace[0]+ }+ id := ulid.Make().String()+ frame := injectEventID(message, id)+ d.local.fanoutUser(userID, frame, exclude, id)+ d.relay.publishWithID(ScopeUser, userID, exclude, message, id)+}++func (d *DualWriteBroadcaster) Broadcast(message []byte) {+ id := ulid.Make().String()+ frame := injectEventID(message, id)+ d.local.fanoutAllDedup(frame, "", id)+ d.relay.publishWithID("global", "all", "", message, id)+}++// publishWithID is like publish but uses a caller-supplied event id so the+// dual-write path can dedup.+func (r *RedisRelay) publishWithID(scopeType, scopeID, exclude string, frame []byte, id string) {+ ev := envelope{+ EventID: id,+ Scope: scopeType,+ ScopeID: scopeID,+ NodeID: r.nodeID,+ CreatedAt: time.Now().UTC().Format(time.RFC3339Nano),+ PayloadJSON: string(frame),+ }+ if exclude != "" {+ ev.WorkspaceID = exclude+ }+ if t, a := peekTypeActor(frame); t != "" {+ ev.EventType = t+ ev.ActorID = a+ }+ args := &redis.XAddArgs{+ Stream: StreamKey(scopeType, scopeID),+ MaxLen: streamMaxLen,+ Approx: true,+ Values: map[string]any{+ "event_id": ev.EventID,+ "event_type": ev.EventType,+ "scope": ev.Scope,+ "scope_id": ev.ScopeID,+ "workspace_id": ev.WorkspaceID,+ "actor_id": ev.ActorID,+ "created_at": ev.CreatedAt,+ "node_id": ev.NodeID,+ "payload_json": ev.PayloadJSON,+ },+ }+ start := time.Now()+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer cancel()+ if err := r.rdb.XAdd(ctx, args).Err(); err != nil {+ M.RedisXAddErrors.Add(1)+ M.SetRedisLastError(err.Error())+ return+ }+ M.RedisXAddTotal.Add(1)+ M.RedisLastXAddLagMicros.Store(time.Since(start).Microseconds())+}++var _ Broadcaster = (*RedisRelay)(nil)+var _ Broadcaster = (*DualWriteBroadcaster)(nil)diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex d175bb686a..f76694bc1c 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -780,6 +780,7 @@ func (s *TaskService) ReportProgress(ctx context.Context, taskID string, workspaWorkspaceID: workspaceID,ActorType: "system",ActorID: "",+ TaskID: taskID,Payload: protocol.TaskProgressPayload{TaskID: taskID,Summary: summary,@@ -947,10 +948,11 @@ func (s *TaskService) broadcastChatDone(ctx context.Context, task db.AgentTaskQureturn}s.Bus.Publish(events.Event{- Type: protocol.EventChatDone,- WorkspaceID: workspaceID,- ActorType: "system",- ActorID: "",+ Type: protocol.EventChatDone,+ WorkspaceID: workspaceID,+ ActorType: "system",+ ActorID: "",+ ChatSessionID: util.UUIDToString(task.ChatSessionID),Payload: protocol.ChatDonePayload{ChatSessionID: util.UUIDToString(task.ChatSessionID),TaskID: util.UUIDToString(task.ID),