From b03f070a5147dcf753dced1eb57977accab00592 Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 20:43:41 -0500 Subject: [PATCH] feat(web): notify open pages over WebSocket after every mutation The companion never told an open page that its data changed: broadcastToUser() had no caller, and the client set existed twice because server.ts is bundled apart from the Next routes, so the routes (and /api/health) saw an empty set. - Keep the client set on globalThis.__wsClients, like the ticket store. - WsMessage sync variant is now { type: 'sync' } with no detail. - notifyUserChanged(userId) coalesces per account with a 1 s trailing debounce; a send that throws drops the socket instead of crashing. - POST /api/sync notifies once per batch when at least one operation is applied; every REST mutation handler of lists, tasks and tags notifies after success. - useSync refreshes only on a sync message, debounced 500 ms; auth_expired no longer triggers a refresh. Tests: ws.test.ts (payload, coalescing, shared set across module instances, source guard on mutation handlers) and sync route tests (one notification per applied batch, none for refused or duplicate batches, never another account). Refs #177 Refs #167 Co-Authored-By: Claude Opus 5.5 --- web/src/app/api/lists/[id]/route.ts | 3 + web/src/app/api/lists/reorder/route.ts | 2 + web/src/app/api/lists/route.ts | 2 + web/src/app/api/sync/route.test.ts | 56 +++++- web/src/app/api/sync/route.ts | 5 + web/src/app/api/tags/[id]/route.ts | 3 + web/src/app/api/tags/route.ts | 2 + web/src/app/api/tasks/[id]/route.ts | 3 + .../app/api/tasks/[id]/tags/[tagId]/route.ts | 2 + web/src/app/api/tasks/[id]/tags/route.ts | 2 + web/src/app/api/tasks/reorder/route.ts | 2 + web/src/app/api/tasks/route.ts | 2 + web/src/components/useSync.ts | 23 ++- web/src/lib/ws.test.ts | 168 ++++++++++++++++++ web/src/lib/ws.ts | 58 +++++- 15 files changed, 326 insertions(+), 7 deletions(-) create mode 100644 web/src/lib/ws.test.ts diff --git a/web/src/app/api/lists/[id]/route.ts b/web/src/app/api/lists/[id]/route.ts index 59b40dc..ceabcc0 100644 --- a/web/src/app/api/lists/[id]/route.ts +++ b/web/src/app/api/lists/[id]/route.ts @@ -4,6 +4,7 @@ import { slLists } from '@/db/schema'; import { eq, and } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { updateListSchema } from '@/lib/validators'; export async function PUT( @@ -29,6 +30,7 @@ export async function PUT( return NextResponse.json({ error: 'Not found' }, { status: 404 }); } + notifyUserChanged(auth.userId); return NextResponse.json(updated); } @@ -53,5 +55,6 @@ export async function DELETE( return NextResponse.json({ error: 'Not found' }, { status: 404 }); } + notifyUserChanged(auth.userId); return NextResponse.json({ ok: true }); } diff --git a/web/src/app/api/lists/reorder/route.ts b/web/src/app/api/lists/reorder/route.ts index 885689e..afe2a77 100644 --- a/web/src/app/api/lists/reorder/route.ts +++ b/web/src/app/api/lists/reorder/route.ts @@ -4,6 +4,7 @@ import { slLists } from '@/db/schema'; import { eq, and, inArray } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { reorderSchema } from '@/lib/validators'; export async function PUT(request: Request) { @@ -35,5 +36,6 @@ export async function PUT(request: Request) { ) ); + notifyUserChanged(auth.userId); return NextResponse.json({ ok: true }); } diff --git a/web/src/app/api/lists/route.ts b/web/src/app/api/lists/route.ts index f300a74..d62df43 100644 --- a/web/src/app/api/lists/route.ts +++ b/web/src/app/api/lists/route.ts @@ -4,6 +4,7 @@ import { slLists } from '@/db/schema'; import { eq, isNull, and, asc } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { createListSchema } from '@/lib/validators'; export async function GET() { @@ -35,5 +36,6 @@ export async function POST(request: Request) { .values({ ...body.data, userId: auth.userId }) .returning(); + notifyUserChanged(auth.userId); return NextResponse.json(list, { status: 201 }); } diff --git a/web/src/app/api/sync/route.test.ts b/web/src/app/api/sync/route.test.ts index 1d59dbf..5baa212 100644 --- a/web/src/app/api/sync/route.test.ts +++ b/web/src/app/api/sync/route.test.ts @@ -10,7 +10,7 @@ import type { PGlite } from 'electric-sql-pglite'; const h = await vi.hoisted(async () => { const { PGlite } = await import('electric-sql-pglite'); - return { pg: new PGlite() as PGlite, userId: '', cleanups: 0 }; + return { pg: new PGlite() as PGlite, userId: '', cleanups: 0, notified: [] as string[] }; }); vi.mock('@/db/client', async () => { @@ -28,6 +28,9 @@ vi.mock('@/lib/api', async (importOriginal) => ({ vi.mock('@/lib/rateLimit', () => ({ rateLimit: () => null })); +// WebSocket notifications (#177): record which accounts the route notifies. +vi.mock('@/lib/ws', () => ({ notifyUserChanged: (userId: string) => { h.notified.push(userId); } })); + // Real idempotency store, with its cleanup counted: the route must call it (#147). vi.mock('@/lib/idempotency', async (importOriginal) => { const mod = await importOriginal(); @@ -626,3 +629,54 @@ describe('POST /api/sync: results contract (#151)', () => { expect((replay.error as string).length).toBeGreaterThan(0); }); }); + +describe('POST /api/sync: open pages notified over WebSocket (#177)', () => { + // Calls made during one push, by any account: tests run one at a time. + async function notifiedBy(fn: () => Promise): Promise { + h.notified.length = 0; + await fn(); + return [...h.notified]; + } + + it('notifies the caller once for a batch that applies at least one operation', async () => { + const { B } = await seed(); + const t1 = u(); + const t2 = u(); + const calls = await notifiedBy(async () => { + expect(await push(B.userId, [ + ['task', 'create', t1, { title: 'one', listId: B.list }], + ['task', 'create', t2, { title: 'two', listId: B.list }], + ['task', 'update', u(), { title: 'missing' }], + ])).toEqual(['applied', 'applied', 'skipped']); + }); + expect(calls).toEqual([B.userId]); + }); + + it('does not notify for a batch entirely refused, and never another account', async () => { + const { A, B } = await seed(); + const calls = await notifiedBy(async () => { + expect(await push(B.userId, [ + ['task', 'update', A.task, { title: 'stolen' }], + ['list', 'delete', A.list], + ['taskTag', 'create', A.task, { tagId: B.tag }], + ])).toEqual(['skipped', 'skipped', 'skipped']); + }); + expect(calls).toEqual([]); + }); + + it('does not notify for a batch of duplicates already applied', async () => { + const { B } = await seed(); + h.userId = B.userId; + const body = JSON.stringify({ operations: [{ + idempotencyKey: u(), entityType: 'task', action: 'update', entityId: B.task, data: { title: 'once' }, + }] }); + const send = () => POST(new Request('http://localhost/api/sync', { method: 'POST', body })); + expect(await notifiedBy(send)).toEqual([B.userId]); + const calls = await notifiedBy(async () => { + const res = await send(); + const { results } = await res.json() as { results: Result[] }; + expect(results.map((r) => r.status)).toEqual(['skipped']); + }); + expect(calls).toEqual([]); + }); +}); diff --git a/web/src/app/api/sync/route.ts b/web/src/app/api/sync/route.ts index df799f0..2972174 100644 --- a/web/src/app/api/sync/route.ts +++ b/web/src/app/api/sync/route.ts @@ -6,6 +6,7 @@ import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; import { syncPushSchema, type SyncOperation } from '@/lib/validators'; import { createIdempotencyStore } from '@/lib/idempotency'; +import { notifyUserChanged } from '@/lib/ws'; import { listCreateData, listUpdateData, @@ -181,6 +182,10 @@ export async function POST(request: Request) { } } + // One notification per batch, and none when nothing was written: a batch of + // duplicates or refusals changes nothing an open page shows (#177). + if (results.some((r) => r.status === 'applied')) notifyUserChanged(auth.userId); + return NextResponse.json({ results, syncedAt: new Date().toISOString() }); } diff --git a/web/src/app/api/tags/[id]/route.ts b/web/src/app/api/tags/[id]/route.ts index 3c4a1f3..dfa7af5 100644 --- a/web/src/app/api/tags/[id]/route.ts +++ b/web/src/app/api/tags/[id]/route.ts @@ -4,6 +4,7 @@ import { slTags } from '@/db/schema'; import { eq, and } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { updateTagSchema } from '@/lib/validators'; export async function PUT( @@ -29,6 +30,7 @@ export async function PUT( return NextResponse.json({ error: 'Not found' }, { status: 404 }); } + notifyUserChanged(auth.userId); return NextResponse.json(updated); } @@ -53,5 +55,6 @@ export async function DELETE( return NextResponse.json({ error: 'Not found' }, { status: 404 }); } + notifyUserChanged(auth.userId); return NextResponse.json({ ok: true }); } diff --git a/web/src/app/api/tags/route.ts b/web/src/app/api/tags/route.ts index aa7d48f..378dc3d 100644 --- a/web/src/app/api/tags/route.ts +++ b/web/src/app/api/tags/route.ts @@ -4,6 +4,7 @@ import { slTags } from '@/db/schema'; import { eq, isNull, and, asc } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { createTagSchema } from '@/lib/validators'; export async function GET() { @@ -35,5 +36,6 @@ export async function POST(request: Request) { .values({ ...body.data, userId: auth.userId }) .returning(); + notifyUserChanged(auth.userId); return NextResponse.json(tag, { status: 201 }); } diff --git a/web/src/app/api/tasks/[id]/route.ts b/web/src/app/api/tasks/[id]/route.ts index 3bc57f3..f1fa13a 100644 --- a/web/src/app/api/tasks/[id]/route.ts +++ b/web/src/app/api/tasks/[id]/route.ts @@ -4,6 +4,7 @@ import { slTasks } from '@/db/schema'; import { eq, and } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { updateTaskSchema } from '@/lib/validators'; export async function PUT( @@ -44,6 +45,7 @@ export async function PUT( return NextResponse.json({ error: 'Not found' }, { status: 404 }); } + notifyUserChanged(auth.userId); return NextResponse.json(updated); } @@ -68,5 +70,6 @@ export async function DELETE( return NextResponse.json({ error: 'Not found' }, { status: 404 }); } + notifyUserChanged(auth.userId); return NextResponse.json({ ok: true }); } diff --git a/web/src/app/api/tasks/[id]/tags/[tagId]/route.ts b/web/src/app/api/tasks/[id]/tags/[tagId]/route.ts index 32e9b55..6d64375 100644 --- a/web/src/app/api/tasks/[id]/tags/[tagId]/route.ts +++ b/web/src/app/api/tasks/[id]/tags/[tagId]/route.ts @@ -4,6 +4,7 @@ import { slTasks, slTaskTags } from '@/db/schema'; import { eq, and } from 'drizzle-orm'; import { requireAuth } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; export async function DELETE( _request: Request, @@ -30,5 +31,6 @@ export async function DELETE( .delete(slTaskTags) .where(and(eq(slTaskTags.taskId, taskId), eq(slTaskTags.tagId, tagId))); + notifyUserChanged(auth.userId); return NextResponse.json({ ok: true }); } diff --git a/web/src/app/api/tasks/[id]/tags/route.ts b/web/src/app/api/tasks/[id]/tags/route.ts index 04139ad..4389920 100644 --- a/web/src/app/api/tasks/[id]/tags/route.ts +++ b/web/src/app/api/tasks/[id]/tags/route.ts @@ -4,6 +4,7 @@ import { slTasks, slTags, slTaskTags } from '@/db/schema'; import { eq, and, inArray } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { assignTagsSchema } from '@/lib/validators'; export async function POST( @@ -46,5 +47,6 @@ export async function POST( .values(body.data.tagIds.map((tagId) => ({ taskId, tagId }))) .onConflictDoNothing(); + notifyUserChanged(auth.userId); return NextResponse.json({ ok: true }, { status: 201 }); } diff --git a/web/src/app/api/tasks/reorder/route.ts b/web/src/app/api/tasks/reorder/route.ts index 1db89d8..9eac9cc 100644 --- a/web/src/app/api/tasks/reorder/route.ts +++ b/web/src/app/api/tasks/reorder/route.ts @@ -4,6 +4,7 @@ import { slTasks } from '@/db/schema'; import { eq, and, inArray } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { reorderSchema } from '@/lib/validators'; export async function PUT(request: Request) { @@ -34,5 +35,6 @@ export async function PUT(request: Request) { ) ); + notifyUserChanged(auth.userId); return NextResponse.json({ ok: true }); } diff --git a/web/src/app/api/tasks/route.ts b/web/src/app/api/tasks/route.ts index ad9c9e7..da82273 100644 --- a/web/src/app/api/tasks/route.ts +++ b/web/src/app/api/tasks/route.ts @@ -4,6 +4,7 @@ import { slTasks, slLists } from '@/db/schema'; import { eq, and } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { notifyUserChanged } from '@/lib/ws'; import { createTaskSchema } from '@/lib/validators'; export async function POST(request: Request) { @@ -50,5 +51,6 @@ export async function POST(request: Request) { }) .returning(); + notifyUserChanged(auth.userId); return NextResponse.json(task, { status: 201 }); } diff --git a/web/src/components/useSync.ts b/web/src/components/useSync.ts index 6f69c5c..99e2002 100644 --- a/web/src/components/useSync.ts +++ b/web/src/components/useSync.ts @@ -3,12 +3,22 @@ import { useEffect } from "react"; import { useRouter } from "next/navigation"; +// Client-side debounce on top of the server's per-account coalescing (#177): +// several messages close together trigger a single refresh. +const REFRESH_DEBOUNCE_MS = 500; + export function useSync() { const router = useRouter(); useEffect(() => { let ws: WebSocket | null = null; let retryTimeout: ReturnType; + let refreshTimeout: ReturnType | undefined; + + function scheduleRefresh() { + clearTimeout(refreshTimeout); + refreshTimeout = setTimeout(() => router.refresh(), REFRESH_DEBOUNCE_MS); + } async function connect() { try { @@ -20,9 +30,15 @@ export function useSync() { const proto = window.location.protocol === "https:" ? "wss:" : "ws:"; ws = new WebSocket(`${proto}//${window.location.host}/ws?ticket=${ticket}`); - ws.onmessage = () => { - // Any sync message triggers a data refresh - router.refresh(); + ws.onmessage = (event) => { + // Only a sync message refreshes the data; auth_expired does not. + let type: unknown; + try { + type = (JSON.parse(String(event.data)) as { type?: unknown }).type; + } catch { + return; + } + if (type === "sync") scheduleRefresh(); }; ws.onclose = () => { @@ -39,6 +55,7 @@ export function useSync() { return () => { ws?.close(); clearTimeout(retryTimeout); + clearTimeout(refreshTimeout); }; }, [router]); } diff --git a/web/src/lib/ws.test.ts b/web/src/lib/ws.test.ts new file mode 100644 index 0000000..c310b71 --- /dev/null +++ b/web/src/lib/ws.test.ts @@ -0,0 +1,168 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { EventEmitter } from 'node:events'; +import type { Server } from 'node:http'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; + +// WebSocket notifications of the companion (#177): payload, per-account +// coalescing, and the client set shared between the two bundles (server.ts is +// bundled apart from the Next routes, each gets its own copy of ws.ts). + +type FakeSocket = EventEmitter & { + userId: string; + readyState: number; + send: ReturnType; +}; + +const OPEN = 1; // WebSocket.OPEN + +const g = globalThis as unknown as { + __wsClients?: Set; + __wsNotifyTimers?: Map>; +}; + +function fakeSocket(userId: string): FakeSocket { + return Object.assign(new EventEmitter(), { userId, readyState: OPEN, send: vi.fn() }); +} + +async function freshModule() { + vi.resetModules(); + return import('./ws'); +} + +beforeEach(() => { + vi.useFakeTimers(); + for (const t of g.__wsNotifyTimers?.values() ?? []) clearTimeout(t); + delete g.__wsClients; + delete g.__wsNotifyTimers; +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('notifyUserChanged', () => { + it('sends exactly {"type":"sync"}', async () => { + const ws = await freshModule(); + const a = fakeSocket('user-a'); + g.__wsClients!.add(a); + + ws.notifyUserChanged('user-a'); + vi.advanceTimersByTime(ws.NOTIFY_DEBOUNCE_MS); + + expect(a.send).toHaveBeenCalledTimes(1); + expect(a.send.mock.calls[0][0]).toBe('{"type":"sync"}'); + }); + + it('coalesces N calls within 1 s into one message', async () => { + const ws = await freshModule(); + const a = fakeSocket('user-a'); + g.__wsClients!.add(a); + + for (let i = 0; i < 20; i++) { + ws.notifyUserChanged('user-a'); + vi.advanceTimersByTime(ws.NOTIFY_DEBOUNCE_MS - 1); + } + expect(a.send).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(1); + expect(a.send).toHaveBeenCalledTimes(1); + + // Nothing left pending afterwards. + vi.advanceTimersByTime(10 * ws.NOTIFY_DEBOUNCE_MS); + expect(a.send).toHaveBeenCalledTimes(1); + }); + + it('notifies only the sockets of that account, each account on its own timer', async () => { + const ws = await freshModule(); + const a1 = fakeSocket('user-a'); + const a2 = fakeSocket('user-a'); + const b = fakeSocket('user-b'); + const closed = fakeSocket('user-a'); + closed.readyState = 3; // CLOSED + for (const s of [a1, a2, b, closed]) g.__wsClients!.add(s); + + ws.notifyUserChanged('user-a'); + vi.advanceTimersByTime(ws.NOTIFY_DEBOUNCE_MS / 2); + ws.notifyUserChanged('user-b'); + vi.advanceTimersByTime(ws.NOTIFY_DEBOUNCE_MS / 2); + + expect(a1.send).toHaveBeenCalledTimes(1); + expect(a2.send).toHaveBeenCalledTimes(1); + expect(closed.send).not.toHaveBeenCalled(); + expect(b.send).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(ws.NOTIFY_DEBOUNCE_MS / 2); + expect(b.send).toHaveBeenCalledTimes(1); + expect(a1.send).toHaveBeenCalledTimes(1); + }); + + it('drops a socket whose send throws instead of crashing the timer', async () => { + const ws = await freshModule(); + const a = fakeSocket('user-a'); + a.send.mockImplementation(() => { throw new Error('broken'); }); + g.__wsClients!.add(a); + + ws.notifyUserChanged('user-a'); + expect(() => vi.advanceTimersByTime(ws.NOTIFY_DEBOUNCE_MS)).not.toThrow(); + expect(ws.getActiveConnections()).toBe(0); + }); +}); + +describe('client set shared between module instances', () => { + it('a socket accepted by one instance is seen and notified by another', async () => { + const serverSide = await freshModule(); + const routeSide = await freshModule(); + expect(routeSide).not.toBe(serverSide); + + const wss = serverSide.setupWebSocket(new EventEmitter() as unknown as Server); + const a = fakeSocket('user-a'); + wss.emit('connection', a); + + expect(serverSide.getActiveConnections()).toBe(1); + expect(routeSide.getActiveConnections()).toBe(1); + + routeSide.notifyUserChanged('user-a'); + vi.advanceTimersByTime(routeSide.NOTIFY_DEBOUNCE_MS); + expect(a.send).toHaveBeenCalledWith('{"type":"sync"}'); + + a.emit('close'); + expect(routeSide.getActiveConnections()).toBe(0); + wss.close(); + }); +}); + +// Source guard: every mutation handler of the REST routes notifies open pages. +describe('REST mutation routes call notifyUserChanged', () => { + const apiDir = path.join(__dirname, '../app/api'); + + function routeFiles(dir: string): string[] { + return fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => { + const p = path.join(dir, e.name); + if (e.isDirectory()) return routeFiles(p); + return e.name === 'route.ts' ? [p] : []; + }); + } + + const files = ['lists', 'tasks', 'tags'].flatMap((d) => routeFiles(path.join(apiDir, d))); + const MUTATIONS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']); + + it('finds the route files', () => { + expect(files.length).toBeGreaterThanOrEqual(12); + }); + + it.each(files.map((f) => [path.relative(apiDir, f), f]))('%s', (_rel, file) => { + const src = fs.readFileSync(file, 'utf8'); + // Only `export async function NAME` handlers are parsed: any other export + // form of a method would escape the guard, so it fails here instead. + expect(src).not.toMatch(/export\s+(const|let|var)\s+(GET|POST|PUT|PATCH|DELETE)\b/); + expect(src).not.toMatch(/export\s*\{[^}]*\b(POST|PUT|PATCH|DELETE)\b/); + + const chunks = src.split(/(?=export\s+(?:async\s+)?function\s+)/); + for (const chunk of chunks) { + const m = chunk.match(/^export\s+(?:async\s+)?function\s+(\w+)/); + if (!m || !MUTATIONS.has(m[1])) continue; + expect(chunk, `${m[1]} handler`).toContain('notifyUserChanged(auth.userId)'); + } + }); +}); diff --git a/web/src/lib/ws.ts b/web/src/lib/ws.ts index 2384ba5..a454e77 100644 --- a/web/src/lib/ws.ts +++ b/web/src/lib/ws.ts @@ -2,8 +2,11 @@ import { WebSocketServer, WebSocket } from 'ws'; import type { IncomingMessage } from 'http'; import type { Server } from 'http'; +// A sync message carries no detail: a socket stays bound to its userId up to +// 15 min after a web sign-out (REVALIDATION_INTERVAL), so it must never learn +// what changed, only that something did (#177). Never add fields here. export type WsMessage = - | { type: 'sync'; entity: 'list' | 'task' | 'tag'; action: 'create' | 'update' | 'delete'; id: string } + | { type: 'sync' } | { type: 'auth_expired' }; interface AuthenticatedSocket extends WebSocket { @@ -33,7 +36,34 @@ const ALLOWED_ORIGINS = [ const REVALIDATION_INTERVAL = 15 * 60 * 1000; // 15 minutes const HEARTBEAT_INTERVAL = 30 * 1000; // 30 seconds -const clients = new Set(); +// server.ts is bundled apart from the Next routes (web/Dockerfile, esbuild): +// each bundle gets its own copy of this module. The client set lives on +// globalThis, like the ticket store, so the routes see the sockets server.ts +// accepted (#177). +const shared = globalThis as unknown as { + __wsClients?: Set; + __wsNotifyTimers?: Map>; +}; + +function getClients() { + if (!shared.__wsClients) { + shared.__wsClients = new Set(); + } + return shared.__wsClients; +} + +function getNotifyTimers() { + if (!shared.__wsNotifyTimers) { + shared.__wsNotifyTimers = new Map(); + } + return shared.__wsNotifyTimers; +} + +const clients = getClients(); + +// Trailing debounce per account: a burst of mutations (a reorder of N items, +// a sync batch) sends one message, 1 s after the last one. +export const NOTIFY_DEBOUNCE_MS = 1000; export function setupWebSocket(server: Server) { const wss = new WebSocketServer({ noServer: true }); @@ -137,11 +167,33 @@ export function broadcastToUser(userId: string, message: WsMessage) { const payload = JSON.stringify(message); for (const ws of clients) { if (ws.userId === userId && ws.readyState === WebSocket.OPEN) { - ws.send(payload); + // Runs from a timer (notifyUserChanged): a throw here would be uncaught. + try { + ws.send(payload); + } catch { + clients.delete(ws); + } } } } +/** + * Tell every open page of an account that its data changed. Coalesced per + * account: N calls within NOTIFY_DEBOUNCE_MS of each other send one message. + */ +export function notifyUserChanged(userId: string) { + const timers = getNotifyTimers(); + const pending = timers.get(userId); + if (pending) clearTimeout(pending); + const timer = setTimeout(() => { + timers.delete(userId); + broadcastToUser(userId, { type: 'sync' }); + }, NOTIFY_DEBOUNCE_MS); + // Never keep the process alive for a pending notification. + timer.unref?.(); + timers.set(userId, timer); +} + export function getActiveConnections(): number { return clients.size; }