diff --git a/examples/quorum/room.test.ts b/examples/quorum/room.test.ts index c8e0d1e2..a56122a5 100644 --- a/examples/quorum/room.test.ts +++ b/examples/quorum/room.test.ts @@ -374,7 +374,10 @@ describe("quorum voting", () => { presenceNamespace: roomNamespace(roomB), reconnect: false, }); - await expect(client.connect()).rejects.toThrow(); + await client.connect(); + await expect(client.presence.subscribe(() => {})).rejects.toMatchObject({ + code: "NAMESPACE_UNAUTHORIZED", + }); client.disconnect(); }); diff --git a/sdk/typescript/src/actions.test.ts b/sdk/typescript/src/actions.test.ts index 3526bfec..4bfe6430 100644 --- a/sdk/typescript/src/actions.test.ts +++ b/sdk/typescript/src/actions.test.ts @@ -31,6 +31,7 @@ async function setupSchema(schema: SchemaDictionary): Promise { function createMockConnection(options?: { response?: OkResponse; error?: unknown; + errorFor?: (msg: OutboundRequest) => unknown; ready?: boolean; }) { const schema = new SchemaDictionary(); @@ -42,7 +43,8 @@ function createMockConnection(options?: { return { dispatchNoRetry: (msg: OutboundRequest) => { dispatched.push(msg); - if (options?.error) return Promise.reject(options.error); + const error = options?.errorFor?.(msg) ?? options?.error; + if (error) return Promise.reject(error); return Promise.resolve( options?.response ?? ({ type: "ok", id: 0 } as OkResponse), ); @@ -350,4 +352,78 @@ describe("ActionsImpl.handle", () => { action_ids: ["checkout"], }); }); + test("replayRegistrations partitions store and presence batches", async () => { + const conn = createMockConnection(); + await setupSchema(conn.schemaDictionary); + const actions = new ActionsImpl(conn); + await actions.handle("checkout", () => ({})); + await actions.handle("player_move", () => {}); + conn.dispatched.length = 0; + actions.replayRegistrations(); + await nextTick(); + expect(conn.dispatched).toHaveLength(2); + expect(conn.dispatched).toContainEqual({ + type: "ActionRegister", + action_ids: ["checkout"], + }); + expect(conn.dispatched).toContainEqual({ + type: "ActionRegister", + action_ids: ["player_move"], + }); + }); + test("a presence registration failure does not block store replay", async () => { + let failPresence = false; + const presenceError = new ZyncBaseError("presence denied", { + code: ErrorCodes.NAMESPACE_UNAUTHORIZED, + category: "authorization", + retryable: false, + }); + const errors: ZyncBaseError[] = []; + const conn = createMockConnection({ + errorFor: (msg) => + failPresence && + msg.type === "ActionRegister" && + msg.action_ids.includes("player_move") + ? presenceError + : undefined, + }); + await setupSchema(conn.schemaDictionary); + const actions = new ActionsImpl(conn, (err) => errors.push(err)); + await actions.handle("checkout", () => ({})); + await actions.handle("player_move", () => {}); + conn.dispatched.length = 0; + failPresence = true; + const replay = actions.replayRegistrations(); + await Promise.allSettled([replay.store, replay.presence]); + expect(conn.dispatched).toHaveLength(2); + expect(conn.dispatched).toContainEqual({ + type: "ActionRegister", + action_ids: ["checkout"], + }); + expect(errors.some((err) => err.code === "NAMESPACE_UNAUTHORIZED")).toBe( + true, + ); + }); + test("a retryable registration failure stays retryable", async () => { + let fail = false; + const registrationError = new ZyncBaseError("server busy", { + code: ErrorCodes.INTERNAL_ERROR, + category: "server", + retryable: true, + }); + const conn = createMockConnection({ + errorFor: (msg) => + fail && msg.type === "ActionRegister" ? registrationError : undefined, + }); + await setupSchema(conn.schemaDictionary); + const actions = new ActionsImpl(conn); + await actions.handle("checkout", () => ({})); + fail = true; + const replay = actions.replayRegistrations(); + const rejected = await replay.store.then( + () => null, + (err: { retryable?: boolean }) => err, + ); + expect(rejected?.retryable).toBe(true); + }); }); diff --git a/sdk/typescript/src/actions.ts b/sdk/typescript/src/actions.ts index 3813e42e..7a4ee5bc 100644 --- a/sdk/typescript/src/actions.ts +++ b/sdk/typescript/src/actions.ts @@ -29,6 +29,8 @@ import type { /** The subset of ConnectionManager that ActionsImpl depends on. */ export interface ActionsConnection { + /** Send a request with automatic retry (e.g. registration). */ + dispatch?(msg: OutboundRequest): Promise; /** Send a request without automatic retry (action calls are never retried). */ dispatchNoRetry(msg: OutboundRequest): Promise; /** Encode a one-way outbound message (ActionReply). */ @@ -92,30 +94,53 @@ export class ActionsImpl implements Actions { } /** Re-register all handlers after reconnect or a bound-scope namespace switch. */ - replayRegistrations(): void { - if (this.handlers.size === 0 || !this.conn.isSchemaReady()) return; + replayRegistrations(): { + store: Promise; + presence: Promise; + } { + if (this.handlers.size === 0 || !this.conn.isSchemaReady()) { + return { store: Promise.resolve(), presence: Promise.resolve() }; + } - const names: string[] = []; + const storeNames: string[] = []; + const presenceNames: string[] = []; for (const name of this.handlers.keys()) { try { - this.conn.schemaDictionary.getAction(name); - names.push(name); + const action = this.conn.schemaDictionary.getAction(name); + if (action.scope === "presence") { + presenceNames.push(name); + } else { + storeNames.push(name); + } } catch { // Schema changed and the action no longer exists; drop the handler. this.handlers.delete(name); } } - if (names.length > 0) void this.register(names).catch(() => {}); + return { + store: + storeNames.length > 0 ? this.register(storeNames) : Promise.resolve(), + presence: + presenceNames.length > 0 + ? this.register(presenceNames) + : Promise.resolve(), + }; } private async register(names: string[]): Promise { try { - await this.conn.dispatchNoRetry({ + const dispatch = this.conn.dispatch + ? (msg: OutboundRequest) => this.conn.dispatch?.(msg) + : (msg: OutboundRequest) => this.conn.dispatchNoRetry(msg); + await dispatch({ type: "ActionRegister", action_ids: names, }); } catch (err) { - const error = mapActionError(err); + const error = + err instanceof ZyncBaseError && err.retryable + ? err + : mapActionError(err); this.emitError(error); throw error; } diff --git a/sdk/typescript/src/client.test.ts b/sdk/typescript/src/client.test.ts index f1189128..9ddbad22 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -122,34 +122,23 @@ describe("ZyncBaseClient", () => { } /** - * Reply to a namespace handshake with whatever ids the connection actually - * used (reconnects continue the id sequence, so ids are not always 1/2). + * Reply to the namespace handshake with whatever id the connection actually + * used (reconnects continue the id sequence, so it is not always 1). */ async function handshakeNamespaces(ws: MockWebSocket): Promise { - const first = decode(ws.sentMessages.at(-1) as Uint8Array) as { + const handshake = decode(ws.sentMessages.at(-1) as Uint8Array) as { id: number; + type: number; }; + expect(handshake.type).toBe(WireMessageType.StoreSetNamespace); ws.triggerMessage( encodeToBuffer({ type: "ok", - id: first.id, + id: handshake.id, userId: packDocId(TEST_USER_ID), }), ); await new Promise((r) => setTimeout(r, 0)); - const second = decode(ws.sentMessages.at(-1) as Uint8Array) as { - id: number; - }; - if (second.id !== first.id) { - ws.triggerMessage( - encodeToBuffer({ - type: "ok", - id: second.id, - userId: packDocId("019c1e50-7d11-7000-8000-000000000001"), - }), - ); - await new Promise((r) => setTimeout(r, 0)); - } } test("lifecycle: first connect emits connected + synced, a reconnect adds reconnected", async () => { @@ -451,6 +440,964 @@ describe("ZyncBaseClient", () => { restoreWebSocket(); }); + test("a presence denial during restore does not block store restoration", async () => { + installMockWebSocket(); + const client = createClient(defaultOptions); + const errors: Array<{ code?: string }> = []; + const synced: string[] = []; + client.on("error", (err) => errors.push(err)); + client.on("synced", () => synced.push("synced")); + + const connected = client.connect(); + await new Promise((r) => setTimeout(r, 0)); + mockWs.triggerOpen(); + triggerNamespaceOk(mockWs); + triggerSchemaSync(mockWs); + await connected; + + const pendingListen = client.store.listen(["users", "u1"], () => {}); + await new Promise((r) => setTimeout(r, 0)); + const storeSub = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + expect(storeSub.type).toBe(WireMessageType.StoreSubscribe); + mockWs.triggerMessage( + encodeToBuffer({ type: "ok", id: storeSub.id, subId: 7, value: [] }), + ); + await pendingListen; + + const pendingPresence = client.presence.subscribe(() => {}); + await new Promise((r) => setTimeout(r, 0)); + const presenceScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + expect(presenceScope.type).toBe(WireMessageType.PresenceSetNamespace); + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: presenceScope.id, + userId: packDocId(TEST_USER_ID), + }), + ); + await new Promise((r) => setTimeout(r, 0)); + const presenceSub = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + expect(presenceSub.type).toBe(WireMessageType.PresenceSubscribe); + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: presenceSub.id, + subId: 30, + users: [], + }), + ); + await pendingPresence; + client.disconnect(); + + const reconnecting = client.connect(); + await new Promise((r) => setTimeout(r, 0)); + const marker = mockWs.sentMessages.length; + mockWs.triggerOpen(); + await handshakeNamespaces(mockWs); + triggerSchemaSync(mockWs); + await waitFor(() => { + const replayed = mockWs.sentMessages + .slice(marker) + .map((message) => decode(message) as { type: number }); + return ( + replayed.some( + (message) => message.type === WireMessageType.PresenceSetNamespace, + ) && + replayed.some( + (message) => message.type === WireMessageType.StoreSubscribe, + ) + ); + }, 1_000); + const replayed = mockWs.sentMessages + .slice(marker) + .map((message) => decode(message) as { id: number; type: number }); + const presenceScopeReplay = replayed.find( + (message) => message.type === WireMessageType.PresenceSetNamespace, + ); + const storeReplay = replayed.find( + (message) => message.type === WireMessageType.StoreSubscribe, + ); + expect(presenceScopeReplay).toBeDefined(); + expect(storeReplay).toBeDefined(); + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: presenceScopeReplay?.id, + code: "NAMESPACE_UNAUTHORIZED", + message: "No presence access", + }), + ); + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: storeReplay?.id, + subId: 8, + value: [], + }), + ); + await reconnecting; + await waitFor(() => synced.length === 2); + expect(errors.some((err) => err.code === "NAMESPACE_UNAUTHORIZED")).toBe( + true, + ); + client.disconnect(); + restoreWebSocket(); + }); + + test("a retryable store action replay blocks synced until it recovers", async () => { + installMockWebSocket(); + const client = createClient({ + ...defaultOptions, + retryRateLimits: false, + }); + try { + const synced: string[] = []; + client.on("synced", () => synced.push("synced")); + const triggerActionSchema = () => + mockWs.triggerMessage( + encodeToBuffer({ + type: "SchemaSync", + version: "1.0.0", + tables: ["users"], + fields: [["id", "name"]], + fieldFlags: [[0b10, 0]], + actions: ["checkout"], + actionParams: [[]], + actionReturns: [["order_id"]], + actionFlags: [0b00], + }), + ); + + const connected = client.connect(); + await new Promise((r) => setTimeout(r, 0)); + mockWs.triggerOpen(); + triggerNamespaceOk(mockWs); + triggerActionSchema(); + await connected; + + const registered = client.actions.handle("checkout", () => ({ + order_id: "order-1", + })); + await new Promise((r) => setTimeout(r, 0)); + const initial = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + expect(initial.type).toBe(WireMessageType.ActionRegister); + mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: initial.id })); + await registered; + client.disconnect(); + + const reconnecting = client.connect(); + reconnecting.catch(() => {}); + await new Promise((r) => setTimeout(r, 0)); + mockWs.triggerOpen(); + await handshakeNamespaces(mockWs); + const marker = mockWs.sentMessages.length; + triggerActionSchema(); + await waitFor( + () => + mockWs.sentMessages + .slice(marker) + .some( + (message) => + (decode(message) as { type: number }).type === + WireMessageType.ActionRegister, + ), + 2_000, + ); + const failed = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: failed.id, + code: "RATE_LIMITED", + message: "Too many requests", + }), + ); + await new Promise((r) => setTimeout(r, 50)); + expect(synced).toHaveLength(1); + + await waitFor( + () => + mockWs.sentMessages + .slice(marker) + .filter( + (message) => + (decode(message) as { type: number }).type === + WireMessageType.ActionRegister, + ).length >= 2, + 2_000, + ); + const retried = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: retried.id })); + await reconnecting; + await waitFor(() => synced.length === 2); + } finally { + client.disconnect(); + restoreWebSocket(); + } + }); + test("a retryable presence action replay survives store action failure", async () => { + installMockWebSocket(); + const client = createClient({ + ...defaultOptions, + retryRateLimits: false, + }); + try { + const synced: string[] = []; + client.on("synced", () => synced.push("synced")); + const triggerActionSchema = () => + mockWs.triggerMessage( + encodeToBuffer({ + type: "SchemaSync", + version: "1.0.0", + tables: ["users"], + fields: [["id", "name"]], + fieldFlags: [[0b10, 0]], + actions: ["checkout", "ping"], + actionParams: [[], []], + actionReturns: [[], []], + actionFlags: [0b00, 0b10], + }), + ); + + const connected = client.connect(); + await new Promise((r) => setTimeout(r, 0)); + mockWs.triggerOpen(); + triggerNamespaceOk(mockWs); + triggerActionSchema(); + await connected; + + const storeRegistered = client.actions.handle("checkout", () => ({})); + await new Promise((r) => setTimeout(r, 0)); + const storeRegister = decode( + mockWs.sentMessages.at(-1) as Uint8Array, + ) as { id: number }; + mockWs.triggerMessage( + encodeToBuffer({ type: "ok", id: storeRegister.id }), + ); + await storeRegistered; + + const presenceRegistered = client.actions.handle("ping", () => {}); + await waitFor( + () => + ( + decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + type: number; + } + ).type === WireMessageType.PresenceSetNamespace, + 1_000, + ); + const presenceScope = decode( + mockWs.sentMessages.at(-1) as Uint8Array, + ) as { id: number }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: presenceScope.id, + userId: packDocId(TEST_USER_ID), + }), + ); + await new Promise((r) => setTimeout(r, 0)); + const presenceRegister = decode( + mockWs.sentMessages.at(-1) as Uint8Array, + ) as { id: number }; + mockWs.triggerMessage( + encodeToBuffer({ type: "ok", id: presenceRegister.id }), + ); + await presenceRegistered; + client.disconnect(); + + const reconnecting = client.connect(); + reconnecting.catch(() => {}); + await new Promise((r) => setTimeout(r, 0)); + mockWs.triggerOpen(); + await handshakeNamespaces(mockWs); + const marker = mockWs.sentMessages.length; + triggerActionSchema(); + await waitFor(() => { + const messages = mockWs.sentMessages + .slice(marker) + .map((message) => decode(message) as { type: number }); + return ( + messages.some( + (message) => message.type === WireMessageType.PresenceSetNamespace, + ) && + messages.some( + (message) => message.type === WireMessageType.ActionRegister, + ) + ); + }, 2_000); + const scope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: scope.id, + userId: packDocId(TEST_USER_ID), + }), + ); + await waitFor( + () => + mockWs.sentMessages + .slice(marker) + .filter( + (message) => + (decode(message) as { type: number }).type === + WireMessageType.ActionRegister, + ).length >= 2, + 2_000, + ); + const registers = mockWs.sentMessages + .slice(marker) + .map( + (message) => decode(message) as { id: number; action_ids: number[] }, + ) + .filter((message) => Array.isArray(message.action_ids)); + const storeReplay = registers.find((message) => + message.action_ids.includes(0), + ); + const presenceReplay = registers.find((message) => + message.action_ids.includes(1), + ); + expect(storeReplay).toBeDefined(); + expect(presenceReplay).toBeDefined(); + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: storeReplay?.id, + code: "PERMISSION_DENIED", + message: "Store registration denied", + }), + ); + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: presenceReplay?.id, + code: "RATE_LIMITED", + message: "Too many requests", + }), + ); + await new Promise((r) => setTimeout(r, 50)); + expect(synced).toHaveLength(1); + + await waitFor( + () => + mockWs.sentMessages + .slice(marker) + .filter( + (message) => + (decode(message) as { type: number }).type === + WireMessageType.ActionRegister, + ).length >= 4, + 2_000, + ); + const retried = mockWs.sentMessages + .slice(-2) + .map((message) => decode(message) as { id: number }); + for (const request of retried) { + mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: request.id })); + } + await reconnecting; + await waitFor(() => synced.length === 2); + } finally { + client.disconnect(); + restoreWebSocket(); + } + }); + test("a rejected presence switch preserves active presence consumers", async () => { + installMockWebSocket(); + const client = createClient({ + ...defaultOptions, + presenceNamespace: "public", + }); + const connected = client.connect(); + await new Promise((r) => setTimeout(r, 0)); + mockWs.triggerOpen(); + triggerNamespaceOk(mockWs); + triggerSchemaSync(mockWs); + await connected; + + const deliveries: number[] = []; + const pendingPresence = client.presence.subscribe((users) => + deliveries.push(users.length), + ); + await new Promise((r) => setTimeout(r, 0)); + const presenceScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: presenceScope.id, + userId: packDocId(TEST_USER_ID), + }), + ); + await new Promise((r) => setTimeout(r, 0)); + const presenceSub = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: presenceSub.id, + subId: 30, + users: [], + }), + ); + await pendingPresence; + + const switching = client.setPresenceNamespace("other"); + await new Promise((r) => setTimeout(r, 0)); + const rejected = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: rejected.id, + code: "NAMESPACE_SWITCH_REJECTED", + message: "Namespace switching is not allowed", + }), + ); + await expect(switching).rejects.toMatchObject({ + code: "NAMESPACE_SWITCH_REJECTED", + }); + mockWs.triggerMessage( + encodeToBuffer([ + WireMessageType.PresenceBroadcast, + 30, + [[packDocId("019c1e50-7d11-7000-8000-000000000002"), 0, [], 1]], + ]), + ); + await waitFor(() => deliveries.length === 2); + expect(deliveries.at(-1)).toBe(1); + + const scopeRequestCount = () => + mockWs.sentMessages.filter((message) => { + const msg = decode(message) as { type: number }; + return msg.type === WireMessageType.PresenceSetNamespace; + }).length; + const beforeSet = scopeRequestCount(); + const setting = client.presence.set({}); + await new Promise((r) => setTimeout(r, 0)); + const setMessage = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + expect(setMessage.type).toBe(WireMessageType.PresenceSet); + mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: setMessage.id })); + await setting; + expect(scopeRequestCount()).toBe(beforeSet); + client.disconnect(); + restoreWebSocket(); + }); + + test("a superseded presence switch does not invalidate presence state", async () => { + installMockWebSocket(); + const client = createClient(defaultOptions); + const connected = client.connect(); + await new Promise((r) => setTimeout(r, 0)); + mockWs.triggerOpen(); + triggerNamespaceOk(mockWs); + triggerSchemaSync(mockWs); + await connected; + + const deliveries: number[] = []; + client.presence.subscribe((users) => deliveries.push(users.length)); + await new Promise((r) => setTimeout(r, 0)); + const presenceScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: presenceScope.id, + userId: packDocId(TEST_USER_ID), + }), + ); + await new Promise((r) => setTimeout(r, 0)); + const presenceSub = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: presenceSub.id, + subId: 30, + users: [], + }), + ); + mockWs.triggerMessage( + encodeToBuffer([ + WireMessageType.PresenceBroadcast, + 30, + [[packDocId("019c1e50-7d11-7000-8000-000000000002"), 0, [], 1]], + ]), + ); + await waitFor(() => deliveries.length === 2); + expect(client.presence.getAll()).toHaveLength(1); + + const switching = client.setPresenceNamespace("other"); + await new Promise((r) => setTimeout(r, 0)); + const rejected = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: rejected.id, + code: "REQUEST_SUPERSEDED", + message: "Superseded by a newer switch", + }), + ); + await expect(switching).rejects.toMatchObject({ + code: "REQUEST_SUPERSEDED", + }); + expect(client.presence.getAll()).toHaveLength(1); + expect(deliveries).toHaveLength(2); + client.disconnect(); + restoreWebSocket(); + }); + + test("a queued presence set is rejected when the namespace switches", async () => { + installMockWebSocket(); + const client = createClient({ + ...defaultOptions, + presenceNamespace: "public", + }); + try { + const connected = client.connect(); + await new Promise((r) => setTimeout(r, 0)); + mockWs.triggerOpen(); + triggerNamespaceOk(mockWs); + triggerSchemaSync(mockWs); + await connected; + + const scopeSetup = client.setPresenceNamespace("public"); + await new Promise((r) => setTimeout(r, 0)); + const scope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + expect(scope.type).toBe(WireMessageType.PresenceSetNamespace); + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: scope.id, + userId: packDocId(TEST_USER_ID), + }), + ); + await scopeSetup; + + const immediate = client.presence.set({}); + await new Promise((r) => setTimeout(r, 0)); + const immediateSet = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + expect(immediateSet.type).toBe(WireMessageType.PresenceSet); + mockWs.triggerMessage( + encodeToBuffer({ type: "ok", id: immediateSet.id }), + ); + await immediate; + + const queued = client.presence.set({}); + const queuedOutcome = queued.then( + () => null, + (err: { code?: string }) => err.code, + ); + const switching = client.setPresenceNamespace("other"); + await new Promise((r) => setTimeout(r, 20)); + const replacement = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + expect(replacement.type).toBe(WireMessageType.PresenceSetNamespace); + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: replacement.id, + userId: packDocId(TEST_USER_ID), + }), + ); + await switching; + await new Promise((r) => setTimeout(r, 0)); + + const presenceSets = mockWs.sentMessages.filter((message) => { + const msg = decode(message) as { type: number }; + return msg.type === WireMessageType.PresenceSet; + }); + expect(presenceSets).toHaveLength(1); + expect(await queuedOutcome).toBe("REQUEST_SUPERSEDED"); + } finally { + client.disconnect(); + restoreWebSocket(); + } + }); + + test("a rejected switch resumes a queued presence set in the old namespace", async () => { + installMockWebSocket(); + const client = createClient({ + ...defaultOptions, + presenceNamespace: "public", + }); + try { + const connected = client.connect(); + await new Promise((r) => setTimeout(r, 0)); + mockWs.triggerOpen(); + triggerNamespaceOk(mockWs); + triggerSchemaSync(mockWs); + await connected; + + const scopeSetup = client.setPresenceNamespace("public"); + await new Promise((r) => setTimeout(r, 0)); + const scope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: scope.id, + userId: packDocId(TEST_USER_ID), + }), + ); + await scopeSetup; + + const immediate = client.presence.set({}); + await new Promise((r) => setTimeout(r, 0)); + const immediateSet = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ type: "ok", id: immediateSet.id }), + ); + await immediate; + + const queued = client.presence.set({}); + const queuedOutcome = queued.then( + () => null, + (err: { code?: string }) => err.code, + ); + const switching = client.setPresenceNamespace("other"); + await new Promise((r) => setTimeout(r, 0)); + const rejected = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: rejected.id, + code: "NAMESPACE_SWITCH_REJECTED", + message: "Namespace switching is not allowed", + }), + ); + await expect(switching).rejects.toMatchObject({ + code: "NAMESPACE_SWITCH_REJECTED", + }); + await new Promise((r) => setTimeout(r, 20)); + + const presenceSets = mockWs.sentMessages.filter((message) => { + const msg = decode(message) as { type: number }; + return msg.type === WireMessageType.PresenceSet; + }); + expect(presenceSets).toHaveLength(2); + const resumed = decode(presenceSets.at(-1) as Uint8Array) as { + id: number; + }; + mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: resumed.id })); + await queued; + expect(await queuedOutcome).toBeNull(); + } finally { + client.disconnect(); + restoreWebSocket(); + } + }); + + test("a delayed rejected switch resumes a queued presence set in the old namespace", async () => { + installMockWebSocket(); + const client = createClient({ + ...defaultOptions, + presenceNamespace: "public", + }); + try { + const connected = client.connect(); + await new Promise((r) => setTimeout(r, 0)); + mockWs.triggerOpen(); + triggerNamespaceOk(mockWs); + triggerSchemaSync(mockWs); + await connected; + + const scopeSetup = client.setPresenceNamespace("public"); + await new Promise((r) => setTimeout(r, 0)); + const scope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: scope.id, + userId: packDocId(TEST_USER_ID), + }), + ); + await scopeSetup; + + const immediate = client.presence.set({}); + await new Promise((r) => setTimeout(r, 0)); + const immediateSet = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ type: "ok", id: immediateSet.id }), + ); + await immediate; + + const queued = client.presence.set({}); + const queuedOutcome = queued.then( + () => null, + (err: { code?: string }) => err.code, + ); + const switching = client.setPresenceNamespace("other"); + await new Promise((r) => setTimeout(r, 0)); + const rejected = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + await new Promise((r) => setTimeout(r, 30)); + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: rejected.id, + code: "NAMESPACE_SWITCH_REJECTED", + message: "Namespace switching is not allowed", + }), + ); + await expect(switching).rejects.toMatchObject({ + code: "NAMESPACE_SWITCH_REJECTED", + }); + await new Promise((r) => setTimeout(r, 20)); + + const presenceSets = mockWs.sentMessages.filter((message) => { + const msg = decode(message) as { type: number }; + return msg.type === WireMessageType.PresenceSet; + }); + expect(presenceSets).toHaveLength(2); + const resumed = decode(presenceSets.at(-1) as Uint8Array) as { + id: number; + }; + mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: resumed.id })); + await queued; + expect(await queuedOutcome).toBeNull(); + } finally { + client.disconnect(); + restoreWebSocket(); + } + }); + + test("a stale switch promise rejects with REQUEST_SUPERSEDED", async () => { + installMockWebSocket(); + const client = createClient(defaultOptions); + try { + const connected = client.connect(); + await new Promise((r) => setTimeout(r, 0)); + mockWs.triggerOpen(); + triggerNamespaceOk(mockWs); + triggerSchemaSync(mockWs); + await connected; + + const first = client.setPresenceNamespace("room1"); + first.catch(() => {}); + await new Promise((r) => setTimeout(r, 0)); + const firstScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + const second = client.setPresenceNamespace("room2"); + second.catch(() => {}); + await new Promise((r) => setTimeout(r, 0)); + + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: firstScope.id, + userId: packDocId(TEST_USER_ID), + }), + ); + await expect(first).rejects.toMatchObject({ + code: "REQUEST_SUPERSEDED", + }); + } finally { + client.disconnect(); + restoreWebSocket(); + } + }); + + test("a stale switch completion does not invalidate a newer switch", async () => { + installMockWebSocket(); + const client = createClient(defaultOptions); + try { + const connected = client.connect(); + await new Promise((r) => setTimeout(r, 0)); + mockWs.triggerOpen(); + triggerNamespaceOk(mockWs); + triggerSchemaSync(mockWs); + await connected; + + const deliveries: number[] = []; + client.presence.subscribe((users) => deliveries.push(users.length)); + await new Promise((r) => setTimeout(r, 0)); + const presenceScope = decode( + mockWs.sentMessages.at(-1) as Uint8Array, + ) as { id: number; type: number }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: presenceScope.id, + userId: packDocId(TEST_USER_ID), + }), + ); + await new Promise((r) => setTimeout(r, 0)); + const presenceSub = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: presenceSub.id, + subId: 30, + users: [], + }), + ); + mockWs.triggerMessage( + encodeToBuffer([ + WireMessageType.PresenceBroadcast, + 30, + [[packDocId("019c1e50-7d11-7000-8000-000000000002"), 0, [], 1]], + ]), + ); + await waitFor(() => deliveries.length === 2); + expect(client.presence.getAll()).toHaveLength(1); + + const first = client.setPresenceNamespace("room1"); + first.catch(() => {}); + await new Promise((r) => setTimeout(r, 0)); + const firstScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + const second = client.setPresenceNamespace("room2"); + second.catch(() => {}); + await new Promise((r) => setTimeout(r, 0)); + + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: firstScope.id, + userId: packDocId(TEST_USER_ID), + }), + ); + await new Promise((r) => setTimeout(r, 0)); + + expect(client.presence.getAll()).toHaveLength(1); + expect(deliveries).toHaveLength(2); + } finally { + client.disconnect(); + restoreWebSocket(); + } + }); + + test("a failed presence switch invalidates the server-reset scope", async () => { + installMockWebSocket(); + const client = createClient(defaultOptions); + try { + const connected = client.connect(); + await new Promise((r) => setTimeout(r, 0)); + mockWs.triggerOpen(); + triggerNamespaceOk(mockWs); + triggerSchemaSync(mockWs); + await connected; + + const deliveries: number[] = []; + client.presence.subscribe((users) => deliveries.push(users.length)); + await new Promise((r) => setTimeout(r, 0)); + const presenceScope = decode( + mockWs.sentMessages.at(-1) as Uint8Array, + ) as { id: number; type: number }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: presenceScope.id, + userId: packDocId(TEST_USER_ID), + }), + ); + await new Promise((r) => setTimeout(r, 0)); + const presenceSub = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: presenceSub.id, + subId: 30, + users: [], + }), + ); + mockWs.triggerMessage( + encodeToBuffer([ + WireMessageType.PresenceBroadcast, + 30, + [[packDocId("019c1e50-7d11-7000-8000-000000000002"), 0, [], 1]], + ]), + ); + await waitFor(() => deliveries.length === 2); + expect(client.presence.getAll()).toHaveLength(1); + + const switching = client.setPresenceNamespace("other"); + await new Promise((r) => setTimeout(r, 0)); + const rejected = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: rejected.id, + code: "NAMESPACE_UNAUTHORIZED", + message: "No presence access", + }), + ); + await expect(switching).rejects.toMatchObject({ + code: "NAMESPACE_UNAUTHORIZED", + }); + await new Promise((r) => setTimeout(r, 0)); + expect(client.presence.getAll()).toHaveLength(0); + } finally { + client.disconnect(); + restoreWebSocket(); + } + }); + test("setStoreNamespace replays store subscriptions without touching presence", async () => { installMockWebSocket(); const client = createClient(defaultOptions); @@ -463,6 +1410,19 @@ describe("ZyncBaseClient", () => { const pendingPresence = client.presence.subscribe(() => {}); await new Promise((r) => setTimeout(r, 0)); + const presenceScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + expect(presenceScope.type).toBe(WireMessageType.PresenceSetNamespace); + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: presenceScope.id, + userId: packDocId(TEST_USER_ID), + }), + ); + await new Promise((r) => setTimeout(r, 0)); const presenceSubscribe = decode( mockWs.sentMessages.at(-1) as Uint8Array, ) as { id: number; type: number }; @@ -509,6 +1469,148 @@ describe("ZyncBaseClient", () => { restoreWebSocket(); }); + test("setPresenceNamespace establishes a same-namespace scope once and waits for it", async () => { + installMockWebSocket(); + const client = createClient({ + ...defaultOptions, + presenceNamespace: "public", + }); + const connected = client.connect(); + await new Promise((r) => setTimeout(r, 0)); + mockWs.triggerOpen(); + triggerNamespaceOk(mockWs); + triggerSchemaSync(mockWs); + await connected; + + const first = client.setPresenceNamespace("public"); + const second = client.setPresenceNamespace("public"); + await new Promise((r) => setTimeout(r, 0)); + const setups = mockWs.sentMessages + .map((message) => decode(message) as { id: number; type: number }) + .filter( + (message) => message.type === WireMessageType.PresenceSetNamespace, + ); + expect(setups).toHaveLength(1); + + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: setups[0].id, + userId: packDocId(TEST_USER_ID), + }), + ); + await Promise.all([first, second]); + + await client.setPresenceNamespace("public"); + const setupCount = mockWs.sentMessages.filter((message) => { + const msg = decode(message) as { type: number }; + return msg.type === WireMessageType.PresenceSetNamespace; + }).length; + expect(setupCount).toBe(1); + client.disconnect(); + restoreWebSocket(); + }); + + test("concurrent same-target switches replay presence once", async () => { + installMockWebSocket(); + const client = createClient(defaultOptions); + try { + const connected = client.connect(); + await new Promise((r) => setTimeout(r, 0)); + mockWs.triggerOpen(); + triggerNamespaceOk(mockWs); + triggerSchemaSync(mockWs); + await connected; + + const pendingPresence = client.presence.subscribe(() => {}); + await new Promise((r) => setTimeout(r, 0)); + const presenceScope = decode( + mockWs.sentMessages.at(-1) as Uint8Array, + ) as { id: number; type: number }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: presenceScope.id, + userId: packDocId(TEST_USER_ID), + }), + ); + await new Promise((r) => setTimeout(r, 0)); + const presenceSub = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: presenceSub.id, + subId: 30, + users: [], + }), + ); + await pendingPresence; + + const marker = mockWs.sentMessages.length; + let firstSettled = false; + let secondSettled = false; + const first = client.setPresenceNamespace("room"); + first.then( + () => { + firstSettled = true; + }, + () => { + firstSettled = true; + }, + ); + const second = client.setPresenceNamespace("room"); + second.then( + () => { + secondSettled = true; + }, + () => { + secondSettled = true; + }, + ); + await new Promise((r) => setTimeout(r, 0)); + const scope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; + expect(scope.type).toBe(WireMessageType.PresenceSetNamespace); + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: scope.id, + userId: packDocId(TEST_USER_ID), + }), + ); + await new Promise((r) => setTimeout(r, 10)); + + const replays = mockWs.sentMessages + .slice(marker) + .map((message) => decode(message) as { id: number; type: number }) + .filter( + (message) => message.type === WireMessageType.PresenceSubscribe, + ); + expect(replays).toHaveLength(1); + expect(firstSettled).toBe(false); + expect(secondSettled).toBe(false); + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: replays[0].id, + subId: 31, + users: [], + }), + ); + await Promise.all([first, second]); + expect(firstSettled).toBe(true); + expect(secondSettled).toBe(true); + } finally { + client.disconnect(); + restoreWebSocket(); + } + }); + test("a rejected namespace switch restores session readiness", async () => { installMockWebSocket(); const client = createClient(defaultOptions); diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts index f04e008d..82735ea0 100644 --- a/sdk/typescript/src/client.ts +++ b/sdk/typescript/src/client.ts @@ -2,7 +2,7 @@ import { ActionsImpl } from "./actions.js"; import { ConnectionManager } from "./connection.js"; -import { toZyncError, ZyncBaseError } from "./errors.js"; +import { ErrorCodes, toZyncError, ZyncBaseError } from "./errors.js"; import { PresenceImpl } from "./presence.js"; import { backoffDelay } from "./retry_policy.js"; import { StoreImpl } from "./store.js"; @@ -48,6 +48,11 @@ export class ZyncBaseClient< >(); /** Whether a connection existed earlier in this process. */ private hasConnectedOnce = false; + private presenceSwitchGeneration = 0; + private presenceSwitchInFlight: { + namespace: string; + promise: Promise; + } | null = null; /** Backoff state for retrying a failed restore. */ private restoreAttempt = 0; private restoreTimer: ReturnType | null = null; @@ -223,14 +228,51 @@ export class ZyncBaseClient< } /** Switch the active presence namespace. */ - async setPresenceNamespace(namespace: string): Promise { + setPresenceNamespace(namespace: string): Promise { const oldNs = this.conn.getPresenceNamespace(); - if (oldNs === namespace) return; + if (oldNs === namespace && this.conn.isPresenceScopeReady()) { + return Promise.resolve(); + } + + const inFlight = this.presenceSwitchInFlight; + if (inFlight?.namespace === namespace) return inFlight.promise; + const promise = this.performPresenceSwitch(namespace); + this.presenceSwitchInFlight = { namespace, promise }; + const clear = () => { + if (this.presenceSwitchInFlight?.promise === promise) { + this.presenceSwitchInFlight = null; + } + }; + promise.then(clear, clear); + return promise; + } + private async performPresenceSwitch(namespace: string): Promise { + const switchGeneration = ++this.presenceSwitchGeneration; + try { + await this.conn.setPresenceNamespace(namespace); + } catch (err) { + if (this.presenceSwitchGeneration === switchGeneration) { + if ( + err instanceof ZyncBaseError && + (err.code === ErrorCodes.NAMESPACE_SWITCH_REJECTED || + err.code === ErrorCodes.REQUEST_SUPERSEDED) + ) { + // Server rejected or superseded switch; previous presence state is preserved + } else { + // Server unauthorized or reset presence scope; invalidate local cache + this.presenceImpl.invalidate(); + } + } + throw err; + } + if (this.presenceSwitchGeneration !== switchGeneration) return; + if (this.conn.getPresenceNamespace() !== namespace) return; this.presenceImpl.invalidate(); - await this.conn.setPresenceNamespace(namespace); await this.presenceImpl.replaySubscriptions(); - this.actionsImpl.replayRegistrations(); + const replay = this.actionsImpl.replayRegistrations(); + replay.store.catch(() => {}); + replay.presence.catch(() => {}); } /** @@ -297,9 +339,43 @@ export class ZyncBaseClient< * readiness queue. On a connection cycle this ends with `synced`. */ private async _restore(): Promise { - await this.presenceImpl.replaySubscriptions(); - this.actionsImpl.replayRegistrations(); - await this._restoreStore(); + const [store, presence] = await Promise.allSettled([ + this._restoreStore(), + this.presenceImpl.replaySubscriptions(), + ]); + await this.conn.awaitSchemaSync(); + const actions = this.actionsImpl.replayRegistrations(); + const [storeActions, presenceActions] = await Promise.allSettled([ + actions.store, + actions.presence, + ]); + if (storeActions.status === "rejected") { + const error = toZyncError( + storeActions.reason, + "Store action registration failed", + false, + ); + if (error.retryable) throw error; + } + if (presenceActions.status === "rejected") { + const error = toZyncError( + presenceActions.reason, + "Presence action registration failed", + false, + ); + if (error.retryable && store.status !== "rejected") { + throw error; + } + } + if (presence.status === "rejected") { + const error = toZyncError(presence.reason, "Restore failed", false); + if (!error.retryable || store.status === "rejected") { + this.emitError(error); + } else { + throw error; + } + } + if (store.status === "rejected") throw store.reason; } /** diff --git a/sdk/typescript/src/connection.test.ts b/sdk/typescript/src/connection.test.ts index 7e161305..bdc4c991 100644 --- a/sdk/typescript/src/connection.test.ts +++ b/sdk/typescript/src/connection.test.ts @@ -21,6 +21,10 @@ afterEach(() => { restoreFetch(); }); +function sentType(bytes: Uint8Array): number { + return (decode(bytes) as { type: number }).type; +} + async function useCanonicalDeltaSchema( manager: ConnectionManager, ): Promise { @@ -88,36 +92,18 @@ describe("ConnectionManager", () => { userId: packDocId(TEST_USER_ID), }), ); - await new Promise((r) => setTimeout(r, 0)); - expect(manager.userId).toBe(TEST_USER_ID); - - const presenceAck = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { - id: number; - type: number; - }; - expect(presenceAck.type).toBe(WireMessageType.PresenceSetNamespace); - mockWs.triggerMessage( - encodeToBuffer({ - type: "ok", - id: presenceAck.id, - userId: packDocId(TEST_USER_ID), - }), - ); await reconnected; + expect(manager.userId).toBe(TEST_USER_ID); }); test("rejects a presence namespace response without a binary user id", async () => { const { manager, mockWs } = makeManager(); - const connected = manager.connect(); - await new Promise((resolve) => setTimeout(resolve, 0)); - mockWs.triggerOpen(); - mockWs.triggerMessage( - encodeToBuffer({ type: "ok", id: 1, userId: packDocId(TEST_USER_ID) }), - ); - await new Promise((resolve) => setTimeout(resolve, 0)); + await connectManager(manager, mockWs); + + const presence = manager.dispatch({ type: "PresenceSet", data: {} }); mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: 2 })); - await expect(connected).rejects.toThrow( + await expect(presence).rejects.toThrow( "PresenceSetNamespace response missing binary userId", ); }); @@ -135,32 +121,21 @@ describe("ConnectionManager", () => { expect(manager.userId).toBeNull(); }); - test("the store scope ack alone provides the user id", async () => { + test("connects with the store scope alone, which provides the user id", async () => { const { manager, mockWs } = makeManager(); - const connected = manager.connect(); - await new Promise((resolve) => setTimeout(resolve, 0)); - mockWs.triggerOpen(); - mockWs.triggerMessage( - encodeToBuffer({ type: "ok", id: 1, userId: packDocId(TEST_USER_ID) }), - ); - await new Promise((resolve) => setTimeout(resolve, 0)); + await connectManager(manager, mockWs); expect(manager.userId).toBe(TEST_USER_ID); - mockWs.triggerMessage( - encodeToBuffer({ type: "ok", id: 2, userId: packDocId(TEST_USER_ID) }), - ); - await connected; + expect(mockWs.sentMessages.map((bytes) => sentType(bytes))).toEqual([ + WireMessageType.StoreSetNamespace, + ]); }); test("rejects a presence namespace response with a malformed user id", async () => { const { manager, mockWs } = makeManager(); - const connected = manager.connect(); - await new Promise((resolve) => setTimeout(resolve, 0)); - mockWs.triggerOpen(); - mockWs.triggerMessage( - encodeToBuffer({ type: "ok", id: 1, userId: packDocId(TEST_USER_ID) }), - ); - await new Promise((resolve) => setTimeout(resolve, 0)); + await connectManager(manager, mockWs); + + const presence = manager.dispatch({ type: "PresenceSet", data: {} }); mockWs.triggerMessage( encodeToBuffer({ type: "ok", @@ -169,9 +144,7 @@ describe("ConnectionManager", () => { }), ); - await expect(connected).rejects.toThrow( - "invalid userId binary length 15", - ); + await expect(presence).rejects.toThrow("invalid userId binary length 15"); }); test("emits 'statusChange' with 'connected' on open", async () => { @@ -193,6 +166,558 @@ describe("ConnectionManager", () => { }); }); + describe("presence scope", () => { + const tick = () => new Promise((r) => setTimeout(r, 0)); + const ack = (mockWs: MockWebSocket, id: number) => + mockWs.triggerMessage( + encodeToBuffer({ type: "ok", id, userId: packDocId(TEST_USER_ID) }), + ); + + test("the first presence message requests the scope once, then everything queued on it", async () => { + const { manager, mockWs } = makeManager(); + await connectManager(manager, mockWs); + + const set = manager.dispatch({ type: "PresenceSet", data: {} }); + const subscribe = manager.dispatch({ type: "PresenceSubscribe" }); + expect(mockWs.sentMessages.map(sentType)).toEqual([ + WireMessageType.StoreSetNamespace, + WireMessageType.PresenceSetNamespace, + ]); + + ack(mockWs, 2); + await tick(); + expect(mockWs.sentMessages.slice(2).map(sentType)).toEqual([ + WireMessageType.PresenceSet, + WireMessageType.PresenceSubscribe, + ]); + mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: 3 })); + mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: 4 })); + await Promise.all([set, subscribe]); + + await Promise.all([ + manager.dispatch({ type: "PresenceRemove" }), + Promise.resolve().then(() => + mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: 5 })), + ), + ]); + expect(sentType(mockWs.sentMessages[4])).toBe( + WireMessageType.PresenceRemove, + ); + }); + + test("store messages never request the presence scope", async () => { + const { manager, mockWs } = makeManager(); + await connectManager(manager, mockWs); + + const query = manager.dispatch({ type: "StoreQuery", table_index: "a" }); + mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: 2, value: [] })); + await query; + + expect(mockWs.sentMessages.map(sentType)).toEqual([ + WireMessageType.StoreSetNamespace, + WireMessageType.StoreQuery, + ]); + }); + + test("a denied presence scope fails the presence message, not the session", async () => { + const { manager, mockWs } = makeManager(); + await connectManager(manager, mockWs); + + const denied = manager.dispatch({ type: "PresenceSet", data: {} }); + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: 2, + code: "NAMESPACE_UNAUTHORIZED", + message: "No access to namespace", + }), + ); + await expect(denied).rejects.toMatchObject({ + code: "NAMESPACE_UNAUTHORIZED", + }); + expect(manager.status).toBe("connected"); + + // The next presence message asks again. + const retried = manager.dispatch({ type: "PresenceSet", data: {} }); + expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( + WireMessageType.PresenceSetNamespace, + ); + retried.catch(() => {}); + manager.disconnect(); + }); + + test("only presence-scoped actions request the presence scope", async () => { + const { manager, mockWs } = makeManager(); + await manager.schemaDictionary.processSchemaSync({ + version: "1.0.0", + tables: [], + fields: [], + fieldFlags: [], + actions: ["checkout", "ping"], + actionParams: [[], []], + actionReturns: [[], []], + actionFlags: [0b00, 0b10], + }); + await connectManager(manager, mockWs); + + manager + .dispatchNoRetry({ type: "ActionCall", action_id: "checkout" }) + .catch(() => {}); + expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( + WireMessageType.ActionCall, + ); + + manager + .dispatchNoRetry({ type: "ActionCall", action_id: "ping" }) + .catch(() => {}); + expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( + WireMessageType.PresenceSetNamespace, + ); + ack(mockWs, 3); + await tick(); + expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( + WireMessageType.ActionCall, + ); + manager.disconnect(); + }); + + test("a reconnect starts without the presence scope", async () => { + const { manager, mockWs } = makeManager(); + await connectManager(manager, mockWs); + const first = manager.dispatch({ type: "PresenceSet", data: {} }); + ack(mockWs, 2); + await tick(); + mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: 3 })); + await first; + + mockWs.triggerClose(1006, "gone"); + const reconnected = manager.connect(); + await tick(); + mockWs.triggerOpen(); + ack(mockWs, 4); + await reconnected; + expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( + WireMessageType.StoreSetNamespace, + ); + + const again = manager.dispatch({ type: "PresenceSet", data: {} }); + expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( + WireMessageType.PresenceSetNamespace, + ); + again.catch(() => {}); + manager.disconnect(); + }); + + test("an old namespace setup retry does not survive a reconnect", async () => { + const { manager, mockWs } = makeManager(); + await connectManager(manager, mockWs); + const first = manager.setPresenceNamespace("public"); + const outcome = first.then( + () => null, + (err: { code?: string }) => err.code, + ); + const scope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: scope.id, + code: "RATE_LIMITED", + message: "Too many requests", + retryAfter: 100, + }), + ); + await tick(); + + mockWs.triggerClose(1006, "gone"); + const reconnected = manager.connect(); + await tick(); + mockWs.triggerOpen(); + const store = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + const marker = mockWs.sentMessages.length; + + await new Promise((r) => setTimeout(r, 150)); + const retried = mockWs.sentMessages + .slice(marker) + .map((message) => decode(message) as { type: number }); + expect( + retried.some( + (message) => message.type === WireMessageType.PresenceSetNamespace, + ), + ).toBe(false); + expect(await outcome).toBe("REQUEST_SUPERSEDED"); + ack(mockWs, store.id); + await reconnected; + manager.disconnect(); + }); + + test("a same-namespace call joins a pending scope request", async () => { + const { manager, mockWs } = makeManager(); + await connectManager(manager, mockWs); + const first = manager.setPresenceNamespace("public"); + const second = manager.setPresenceNamespace("public"); + expect(mockWs.sentMessages.map(sentType)).toEqual([ + WireMessageType.StoreSetNamespace, + WireMessageType.PresenceSetNamespace, + ]); + + ack(mockWs, 2); + await Promise.all([first, second]); + await manager.setPresenceNamespace("public"); + expect(mockWs.sentMessages).toHaveLength(2); + }); + + test("rapid namespace switch ignores stale responses from superseded requests", async () => { + const { manager, mockWs } = makeManager(); + await connectManager(manager, mockWs); + const first = manager.setPresenceNamespace("room1"); + const firstOutcome = first.catch((err: { code?: string }) => err.code); + const second = manager.setPresenceNamespace("room2"); + + expect(mockWs.sentMessages.map(sentType)).toEqual([ + WireMessageType.StoreSetNamespace, + WireMessageType.PresenceSetNamespace, + WireMessageType.PresenceSetNamespace, + ]); + + const [firstScope, secondScope] = mockWs.sentMessages + .slice(1) + .map((bytes) => decode(bytes) as { id: number }); + + // Acknowledge firstScope late (with a distinct userId) + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: firstScope.id, + userId: packDocId("019c1e50-7d11-7000-8000-000000000002"), + }), + ); + await tick(); + + // Stale response must not overwrite target namespace or adopt old userId + expect(manager.getPresenceNamespace()).toBe("room2"); + expect(manager.userId).toBe(TEST_USER_ID); + + // Acknowledge secondScope + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: secondScope.id, + userId: packDocId("019c1e50-7d11-7000-8000-000000000003"), + }), + ); + await second; + expect(await firstOutcome).toBe("REQUEST_SUPERSEDED"); + + expect(manager.getPresenceNamespace()).toBe("room2"); + expect(manager.userId).toBe("019c1e50-7d11-7000-8000-000000000003"); + }); + + test("a superseded namespace setup is not retried after a newer switch", async () => { + const { manager, mockWs } = makeManager({ reconnectDelay: 10 }); + await connectManager(manager, mockWs); + const first = manager.setPresenceNamespace("first"); + first.catch(() => {}); + const firstScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: firstScope.id, + code: "RATE_LIMITED", + message: "Too many requests", + retryAfter: 50, + }), + ); + await tick(); + + const second = manager.setPresenceNamespace("second"); + const secondScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + ack(mockWs, secondScope.id); + await second; + await new Promise((r) => setTimeout(r, 100)); + + const namespaces = mockWs.sentMessages + .map( + (message) => decode(message) as { type: number; namespace?: string }, + ) + .filter( + (message) => message.type === WireMessageType.PresenceSetNamespace, + ) + .map((message) => message.namespace); + expect(namespaces).toEqual(["first", "second"]); + manager.disconnect(); + }); + test("an old setup retry stays superseded after returning to the same namespace", async () => { + const { manager, mockWs } = makeManager({ reconnectDelay: 10 }); + await connectManager(manager, mockWs); + const first = manager.setPresenceNamespace("first"); + first.catch(() => {}); + const firstScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: firstScope.id, + code: "RATE_LIMITED", + message: "Too many requests", + retryAfter: 50, + }), + ); + await tick(); + + const second = manager.setPresenceNamespace("second"); + const secondScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + ack(mockWs, secondScope.id); + await second; + + const third = manager.setPresenceNamespace("first"); + const thirdScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + ack(mockWs, thirdScope.id); + await third; + await new Promise((r) => setTimeout(r, 100)); + + const namespaces = mockWs.sentMessages + .map( + (message) => decode(message) as { type: number; namespace?: string }, + ) + .filter( + (message) => message.type === WireMessageType.PresenceSetNamespace, + ) + .map((message) => message.namespace); + expect(namespaces).toEqual(["first", "second", "first"]); + manager.disconnect(); + }); + test("a shared presence retry is rejected after a namespace switch", async () => { + const { manager, mockWs } = makeManager({ reconnectDelay: 10 }); + await connectManager(manager, mockWs); + const setup = manager.setPresenceNamespace("public"); + ack(mockWs, 2); + await setup; + + const shared = manager.dispatch({ + type: "PresenceSetShared", + data: {}, + }); + const outcome = shared.then( + () => null, + (err: { code?: string }) => err.code, + ); + const sharedRequest = decode( + mockWs.sentMessages.at(-1) as Uint8Array, + ) as { id: number }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: sharedRequest.id, + code: "RATE_LIMITED", + message: "Too many requests", + retryAfter: 50, + }), + ); + await tick(); + + const switched = manager.setPresenceNamespace("other"); + const scope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + ack(mockWs, scope.id); + await switched; + await new Promise((r) => setTimeout(r, 100)); + + const sharedMessages = mockWs.sentMessages + .map((message) => decode(message) as { type: number }) + .filter( + (message) => message.type === WireMessageType.PresenceSetShared, + ); + expect(sharedMessages).toHaveLength(1); + expect(await outcome).toBe("REQUEST_SUPERSEDED"); + manager.disconnect(); + }); + test("a queued subscription is rejected when its scope is replaced", async () => { + const { manager, mockWs } = makeManager(); + await connectManager(manager, mockWs); + const subscribe = manager.dispatch({ type: "PresenceSubscribe" }); + const outcome = subscribe.then( + () => null, + (err: { code?: string }) => err.code, + ); + const switched = manager.setPresenceNamespace("other"); + const [initial, replacement] = mockWs.sentMessages + .slice(1) + .map((bytes) => decode(bytes) as { id: number }); + ack(mockWs, initial.id); + await tick(); + expect(mockWs.sentMessages.map(sentType)).toEqual([ + WireMessageType.StoreSetNamespace, + WireMessageType.PresenceSetNamespace, + WireMessageType.PresenceSetNamespace, + ]); + expect(await outcome).toBe("REQUEST_SUPERSEDED"); + ack(mockWs, replacement.id); + await switched; + manager.disconnect(); + }); + test("a rejected presence switch keeps the previous namespace usable", async () => { + const { manager, mockWs } = makeManager(); + await connectManager(manager, mockWs); + const initial = manager.setPresenceNamespace("public"); + ack(mockWs, 2); + await initial; + + const rejected = manager.setPresenceNamespace("other"); + const rejectedScope = decode( + mockWs.sentMessages.at(-1) as Uint8Array, + ) as { + id: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: rejectedScope.id, + code: "NAMESPACE_SWITCH_REJECTED", + message: "Namespace switching is not allowed", + }), + ); + await expect(rejected).rejects.toMatchObject({ + code: "NAMESPACE_SWITCH_REJECTED", + }); + expect(manager.getPresenceNamespace()).toBe("public"); + + const retried = manager.dispatch({ type: "PresenceSet", data: {} }); + const presence = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( + WireMessageType.PresenceSet, + ); + mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: presence.id })); + await retried; + expect(manager.getPresenceNamespace()).toBe("public"); + }); + + test("a presence retry does not cross a replacement socket", async () => { + const { manager, mockWs } = makeManager({ + reconnect: false, + reconnectDelay: 10, + }); + await connectManager(manager, mockWs); + const presence = manager.dispatch({ type: "PresenceSet", data: {} }); + const outcome = presence.then( + () => null, + (err: { code?: string }) => err.code, + ); + const scope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( + WireMessageType.PresenceSetNamespace, + ); + ack(mockWs, scope.id); + await tick(); + const firstAttempt = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( + WireMessageType.PresenceSet, + ); + + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: firstAttempt.id, + code: "RATE_LIMITED", + message: "Too many requests", + retryAfter: 100, + }), + ); + await tick(); + mockWs.triggerClose(1006, "gone"); + const reconnected = manager.connect(); + await tick(); + mockWs.triggerOpen(); + const store = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( + WireMessageType.StoreSetNamespace, + ); + ack(mockWs, store.id); + await reconnected; + const marker = mockWs.sentMessages.length; + + await new Promise((r) => setTimeout(r, 150)); + const retried = mockWs.sentMessages + .slice(marker) + .map((message) => decode(message) as { type: number }); + expect( + retried.some( + (message) => + message.type === WireMessageType.PresenceSet || + message.type === WireMessageType.PresenceSetNamespace, + ), + ).toBe(false); + expect(await outcome).toBe("REQUEST_SUPERSEDED"); + manager.disconnect(); + }); + + test("a same-namespace call after disconnect fails with CONNECTION_FAILED", async () => { + const { manager, mockWs } = makeManager(); + await connectManager(manager, mockWs); + const ready = manager.setPresenceNamespace("public"); + ack(mockWs, 2); + await ready; + manager.disconnect(); + await expect( + manager.setPresenceNamespace("public"), + ).rejects.toMatchObject({ code: "CONNECTION_FAILED" }); + }); + + test("numeric presence action registrations request the presence scope", async () => { + const { manager, mockWs } = makeManager(); + await manager.schemaDictionary.processSchemaSync({ + version: "1.0.0", + tables: [], + fields: [], + fieldFlags: [], + actions: ["checkout", "ping"], + actionParams: [[], []], + actionReturns: [[], []], + actionFlags: [0b00, 0b10], + }); + await connectManager(manager, mockWs); + manager + .dispatchNoRetry({ type: "ActionRegister", action_ids: [0] }) + .catch(() => {}); + expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( + WireMessageType.ActionRegister, + ); + manager + .dispatchNoRetry({ type: "ActionRegister", action_ids: [1] }) + .catch(() => {}); + expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( + WireMessageType.PresenceSetNamespace, + ); + ack(mockWs, 3); + await tick(); + expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( + WireMessageType.ActionRegister, + ); + manager.disconnect(); + }); + }); + describe("liveness", () => { test("enables liveness by default and closes when a probe times out", async () => { const { manager, mockWs } = makeManager({ @@ -256,14 +781,14 @@ describe("ConnectionManager", () => { value: 2, }); - const msg1 = decode(mockWs.sentMessages[2]) as Record; - const msg2 = decode(mockWs.sentMessages[3]) as Record; + const msg1 = decode(mockWs.sentMessages[1]) as Record; + const msg2 = decode(mockWs.sentMessages[2]) as Record; - expect(msg1.id).toBe(3); - expect(msg2.id).toBe(4); + expect(msg1.id).toBe(2); + expect(msg2.id).toBe(3); + mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: 2 })); mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: 3 })); - mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: 4 })); await p1; await p2; }); @@ -278,11 +803,11 @@ describe("ConnectionManager", () => { value: 1, }); mockWs.triggerMessage( - encodeToBuffer({ type: "ok", id: 3, value: [{ x: 1 }] }), + encodeToBuffer({ type: "ok", id: 2, value: [{ x: 1 }] }), ); const result = await p; - expect(result).toMatchObject({ type: "ok", id: 3 }); + expect(result).toMatchObject({ type: "ok", id: 2 }); }); test("rejects promise on type:error response with matching id", async () => { @@ -297,7 +822,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 3, + id: 2, code: "PERMISSION_DENIED", message: "Not allowed", }), @@ -330,7 +855,7 @@ describe("ConnectionManager", () => { await connectManager(manager, mockWs); const p = manager.dispatchWrite(write); - mockWs.triggerMessage(encodeToBuffer({ type: "WriteCommitted", id: 3 })); + mockWs.triggerMessage(encodeToBuffer({ type: "WriteCommitted", id: 2 })); await expect(p).resolves.toBeUndefined(); }); @@ -346,7 +871,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "WriteError", - id: 3, + id: 2, code: "UNIQUE_CONSTRAINT_VIOLATED", message: "duplicate", phase: "write", @@ -369,7 +894,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 3, + id: 2, code: "PERMISSION_DENIED", message: "Not allowed", }), @@ -393,7 +918,7 @@ describe("ConnectionManager", () => { "Write outcome not received within 20 ms; the write may still commit", }); // A late outcome for the timed-out id is ignored. - mockWs.triggerMessage(encodeToBuffer({ type: "WriteCommitted", id: 3 })); + mockWs.triggerMessage(encodeToBuffer({ type: "WriteCommitted", id: 2 })); }); test("rejects writeTimeoutMs outside the timer range", () => { @@ -418,7 +943,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 3, + id: 2, code: "RATE_LIMITED", message: "Too many requests", retryAfter: 5, @@ -427,7 +952,7 @@ describe("ConnectionManager", () => { await expect(p).rejects.toMatchObject({ code: "RATE_LIMITED" }); await wait(20); - expect(mockWs.sentMessages).toHaveLength(3); + expect(mockWs.sentMessages).toHaveLength(2); }); test("WriteCommitted counts as a liveness response", async () => { @@ -528,8 +1053,8 @@ describe("ConnectionManager", () => { }; mockWs.triggerMessage(encodeToBuffer(delta)); - mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: 3 })); - await expect(p).resolves.toMatchObject({ type: "ok", id: 3 }); + mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: 2 })); + await expect(p).resolves.toMatchObject({ type: "ok", id: 2 }); }); }); @@ -770,19 +1295,10 @@ describe("ConnectionManager", () => { }); expect(mockWs.sentMessages).toHaveLength(1); - // Complete the handshake: the rejected StoreSet consumed id=2, so - // PresenceSetNamespace goes out as id=3. + // Complete the handshake. mockWs.triggerMessage( encodeToBuffer({ type: "ok", id: 1, userId: packDocId(TEST_USER_ID) }), ); - await new Promise((r) => setTimeout(r, 0)); - mockWs.triggerMessage( - encodeToBuffer({ - type: "ok", - id: 3, - userId: packDocId("019c1e50-7d11-7000-8000-000000000001"), - }), - ); await connected; manager.disconnect(); }); @@ -1089,7 +1605,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 3, + id: 2, code: "RATE_LIMITED", message: "Too many requests", retryAfter: 50, @@ -1100,11 +1616,11 @@ describe("ConnectionManager", () => { await new Promise((r) => setTimeout(r, 100)); // Second attempt: send ok - mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: 4 })); + mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: 3 })); const result = await p; - expect(result).toMatchObject({ type: "ok", id: 4 }); - expect(mockWs.sentMessages.length).toBeGreaterThanOrEqual(4); + expect(result).toMatchObject({ type: "ok", id: 3 }); + expect(mockWs.sentMessages.length).toBeGreaterThanOrEqual(3); }); test("does not retry validation errors", async () => { @@ -1120,7 +1636,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 3, + id: 2, code: "SCHEMA_VALIDATION_FAILED", message: "Invalid data", }), @@ -1131,7 +1647,7 @@ describe("ConnectionManager", () => { }); // Only one message sent (no retry) - expect(mockWs.sentMessages.length).toBe(3); + expect(mockWs.sentMessages.length).toBe(2); }); test("gives up after maxServerRetries for server errors", async () => { @@ -1152,7 +1668,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 3, + id: 2, code: "INTERNAL_ERROR", message: "Server error", }), @@ -1165,7 +1681,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 4, + id: 3, code: "INTERNAL_ERROR", message: "Server error", }), @@ -1178,7 +1694,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 5, + id: 4, code: "INTERNAL_ERROR", message: "Server error", }), @@ -1200,7 +1716,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 3, + id: 2, code: "RATE_LIMITED", message: "Too many requests", }), @@ -1209,7 +1725,7 @@ describe("ConnectionManager", () => { await expect(p).rejects.toMatchObject({ code: "RATE_LIMITED" }); // Only one message sent (no retry) - expect(mockWs.sentMessages.length).toBe(3); + expect(mockWs.sentMessages.length).toBe(2); }); test("respects retryAfter delay", async () => { @@ -1228,7 +1744,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 3, + id: 2, code: "RATE_LIMITED", message: "Too many requests", retryAfter: 200, @@ -1238,15 +1754,15 @@ describe("ConnectionManager", () => { // Wait for retry (should take ~200ms, not ~10ms) await new Promise((r) => setTimeout(r, 100)); // Should still be waiting - expect(mockWs.sentMessages.length).toBe(3); + expect(mockWs.sentMessages.length).toBe(2); // Wait for retry to happen await new Promise((r) => setTimeout(r, 150)); // Now retry should have happened - expect(mockWs.sentMessages.length).toBe(4); + expect(mockWs.sentMessages.length).toBe(3); // Send ok to resolve - mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: 4 })); + mockWs.triggerMessage(encodeToBuffer({ type: "ok", id: 3 })); await p; const elapsed = Date.now() - startTime; diff --git a/sdk/typescript/src/connection.ts b/sdk/typescript/src/connection.ts index 5b97a565..b9304fa3 100644 --- a/sdk/typescript/src/connection.ts +++ b/sdk/typescript/src/connection.ts @@ -140,6 +140,11 @@ export class ConnectionManager { private storeNamespace: string; private currentUserId: string | null = null; private presenceNamespace: string; + /** The presence scope request of this socket; null until presence is first used. */ + private presenceScopePromise: Promise | null = null; + private presenceScopeReady = false; + private presenceScopeGen = 0; + private connectionGeneration = 0; private processingPromise: Promise = Promise.resolve(); @@ -200,13 +205,136 @@ export class ConnectionManager { return this.presenceNamespace; } - async setPresenceNamespace(ns: string): Promise { - const ok = await this.dispatch({ - type: "PresenceSetNamespace", - namespace: ns, - }); - this.adoptUserId(ok, "PresenceSetNamespace"); + isPresenceScopeReady(): boolean { + return this.presenceScopeReady; + } + + /** + * Establish the presence scope in `ns`, or switch it there. Presence + * messages sent meanwhile wait for it. + */ + setPresenceNamespace(ns: string): Promise { + if ( + this.currentStatus === "connected" && + this.presenceScopeReady && + this.presenceNamespace === ns + ) { + return Promise.resolve(); + } + if (this.presenceScopePromise && this.presenceNamespace === ns) { + return this.presenceScopePromise; + } + + const gen = ++this.presenceScopeGen; + const previousNs = this.presenceNamespace; + const previousReady = this.presenceScopeReady; + this.presenceScopeReady = false; this.presenceNamespace = ns; + + const scope: Promise = this.dispatchWithRetry( + { type: "PresenceSetNamespace", namespace: ns }, + 0, + undefined, + gen, + ) + .then((ok) => { + if (gen !== this.presenceScopeGen) { + throw new ZyncBaseError( + "Request was superseded by a newer operation", + { + code: ErrorCodes.REQUEST_SUPERSEDED, + category: "state", + retryable: false, + }, + ); + } + this.adoptUserId(ok, "PresenceSetNamespace"); + this.presenceScopeReady = true; + }) + .catch((err: unknown) => { + if (gen === this.presenceScopeGen) { + if ( + err instanceof ZyncBaseError && + err.code === ErrorCodes.NAMESPACE_SWITCH_REJECTED + ) { + this.presenceNamespace = previousNs; + this.presenceScopeReady = previousReady; + } else { + this.presenceScopeReady = false; + } + } + throw err; + }) + .finally(() => { + if (this.presenceScopePromise === scope) { + this.presenceScopePromise = null; + } + }); + this.presenceScopePromise = scope; + return scope; + } + + /** + * Sends `msg` once the scope it needs exists. A session starts with the + * store scope only; the first message that needs the presence scope + * requests it, so a store-only app needs no presence authorization. + */ + private withPresenceScope( + msg: OutboundRequest, + send: () => Promise, + target = "targetNamespace" in msg && typeof msg.targetNamespace === "string" + ? msg.targetNamespace + : this.presenceNamespace, + ): Promise { + if (this.currentStatus !== "connected" || !this.needsPresenceScope(msg)) { + return send(); + } + const pending = this.presenceScopePromise; + if (pending) { + return pending.then( + () => this.withPresenceScope(msg, send, target), + (err) => { + if (this.presenceScopeReady && this.presenceNamespace === target) { + return this.withPresenceScope(msg, send, target); + } + throw err; + }, + ); + } + if (this.presenceNamespace !== target) { + return Promise.reject(this.supersededError()); + } + if (this.presenceScopeReady) return send(); + return this.setPresenceNamespace(target).then(() => + this.withPresenceScope(msg, send, target), + ); + } + private supersededError(): ZyncBaseError { + return new ZyncBaseError("Request was superseded by a newer operation", { + code: ErrorCodes.REQUEST_SUPERSEDED, + category: "state", + retryable: false, + }); + } + + /** Presence messages, and action messages naming a presence-scoped action. */ + private needsPresenceScope(msg: OutboundRequest): boolean { + switch (msg.type) { + case "ActionCall": + return this.isPresenceAction(msg.action_id); + case "ActionRegister": + return msg.action_ids.some((id) => this.isPresenceAction(id)); + default: + return ( + msg.type.startsWith("Presence") && msg.type !== "PresenceSetNamespace" + ); + } + } + + private isPresenceAction(id: string | number): boolean { + const name = + typeof id === "number" ? this.schemaDictionary.getActionName(id) : id; + return this.schemaDictionary.getAction(name).scope === "presence"; } private adoptUserId(ok: OkResponse, request: string): void { @@ -242,6 +370,7 @@ export class ConnectionManager { } private teardownSocket(): void { + this.connectionGeneration++; this.currentUserId = null; if (this.ws) { const ws = this.ws; @@ -288,6 +417,10 @@ export class ConnectionManager { this.intentionalDisconnect = false; this.pendingDisconnectError = null; this.currentUserId = null; + this.presenceScopePromise = null; + this.presenceScopeReady = false; + this.presenceScopeGen++; + this.connectionGeneration++; this.stopLiveness(); this.setStatus("connecting"); this.processingPromise = Promise.resolve(); @@ -305,7 +438,6 @@ export class ConnectionManager { ws.onopen = () => { this.startLiveness(); this.setStoreNamespace(this.storeNamespace) - .then(() => this.setPresenceNamespace(this.presenceNamespace)) .then(() => { this.reconnectAttempt = 0; this.setStatus("connected"); @@ -426,7 +558,7 @@ export class ConnectionManager { * which must never be retried because the first attempt may have executed. */ dispatchNoRetry(msg: OutboundRequest): Promise { - return this.sendRequest(msg).result; + return this.withPresenceScope(msg, () => this.sendRequest(msg).result); } /** @@ -489,25 +621,61 @@ export class ConnectionManager { return { id, result, debugType: encoded.debugMessage.type }; } - private async dispatchWithRetry( + private dispatchWithRetry( msg: OutboundRequest, attempt: number, responseTableIndex?: number, + expectedScopeGen?: number, + targetNamespace?: string, + sessionGeneration?: number, ): Promise { - const { result, debugType } = this.sendRequest(msg, responseTableIndex); - - try { - return await result; - } catch (err) { - if (this.intentionalDisconnect) throw err; - return this.handleRetryOrThrow( - msg, - attempt, - err, - debugType, - responseTableIndex, - ); + const target = + targetNamespace ?? + ("targetNamespace" in msg && typeof msg.targetNamespace === "string" + ? msg.targetNamespace + : this.presenceNamespace); + const session = + sessionGeneration ?? + (this.needsPresenceScope(msg) || msg.type === "PresenceSetNamespace" + ? this.connectionGeneration + : undefined); + if (session !== undefined && session !== this.connectionGeneration) { + return Promise.reject(this.supersededError()); } + return this.withPresenceScope( + msg, + async () => { + if (session !== undefined && session !== this.connectionGeneration) { + throw this.supersededError(); + } + const scopeGen = + expectedScopeGen ?? + (msg.type === "PresenceSetNamespace" + ? this.presenceScopeGen + : undefined); + if (scopeGen !== undefined && scopeGen !== this.presenceScopeGen) { + throw this.supersededError(); + } + const { result, debugType } = this.sendRequest(msg, responseTableIndex); + + try { + return await result; + } catch (err) { + if (this.intentionalDisconnect) throw err; + return this.handleRetryOrThrow( + msg, + attempt, + err, + debugType, + responseTableIndex, + scopeGen, + target, + session, + ); + } + }, + target, + ); } private async handleRetryOrThrow( @@ -516,7 +684,20 @@ export class ConnectionManager { err: unknown, debugType: string, responseTableIndex?: number, + expectedScopeGen?: number, + targetNamespace?: string, + sessionGeneration?: number, ): Promise { + if ( + (expectedScopeGen !== undefined && + expectedScopeGen !== this.presenceScopeGen) || + (sessionGeneration !== undefined && + sessionGeneration !== this.connectionGeneration) || + (msg.type === "PresenceSetNamespace" && + msg.namespace !== this.presenceNamespace) + ) { + throw this.supersededError(); + } if (!this.retryPolicy.shouldRetry(err, attempt)) throw err; const delay = this.retryPolicy.getDelay(err, attempt); @@ -527,7 +708,24 @@ export class ConnectionManager { } await sleep(delay); if (this.intentionalDisconnect) throw err; - return this.dispatchWithRetry(msg, attempt + 1, responseTableIndex); + if ( + (expectedScopeGen !== undefined && + expectedScopeGen !== this.presenceScopeGen) || + (sessionGeneration !== undefined && + sessionGeneration !== this.connectionGeneration) || + (msg.type === "PresenceSetNamespace" && + msg.namespace !== this.presenceNamespace) + ) { + throw this.supersededError(); + } + return this.dispatchWithRetry( + msg, + attempt + 1, + responseTableIndex, + expectedScopeGen, + targetNamespace, + sessionGeneration, + ); } authRefresh(token: string): Promise { @@ -550,6 +748,10 @@ export class ConnectionManager { disconnect(): void { this.intentionalDisconnect = true; + this.presenceScopePromise = null; + this.presenceScopeReady = false; + this.presenceScopeGen++; + this.connectionGeneration++; this.currentUserId = null; this.stopLiveness(); if (this.reconnectTimer !== null) { @@ -614,6 +816,7 @@ export class ConnectionManager { } private handleSocketClose(code: number, reason: string): void { + this.connectionGeneration++; this.currentUserId = null; this.stopLiveness(); const closeError = socketCloseError(code, reason); diff --git a/sdk/typescript/src/connection_wire.test.ts b/sdk/typescript/src/connection_wire.test.ts index 985b5df6..2fe27e76 100644 --- a/sdk/typescript/src/connection_wire.test.ts +++ b/sdk/typescript/src/connection_wire.test.ts @@ -55,6 +55,21 @@ describe("ConnectionWireCodec", () => { expect(decode(encode(timestamp))).toBe(timestamp); }); + test("strips client-only presence target metadata from the wire", async () => { + const codec = await makeCodec(); + const encoded = codec.encode( + { + type: "PresenceSet", + data: { status: "active" }, + targetNamespace: "room-a", + } as unknown as Parameters[0], + 9, + ); + const wire = decode(encoded.bytes) as Record; + expect(wire).not.toHaveProperty("targetNamespace"); + expect(wire.data).toEqual([2, "active"]); + }); + test("encodes schema-aware query fields", async () => { const codec = await makeCodec(); const encoded = codec.encode( diff --git a/sdk/typescript/src/connection_wire.ts b/sdk/typescript/src/connection_wire.ts index f6fa71ec..19534280 100644 --- a/sdk/typescript/src/connection_wire.ts +++ b/sdk/typescript/src/connection_wire.ts @@ -474,6 +474,8 @@ export class ConnectionWireCodec { type: string, ): Record { const wire: Record = { ...msg }; + // Client-only routing metadata; never send it to the server. + delete wire.targetNamespace; if (type === "PresenceSet" && wire.data && typeof wire.data === "object") { wire.data = this.schema.encodePresenceUserValue( diff --git a/sdk/typescript/src/msgid.property.test.ts b/sdk/typescript/src/msgid.property.test.ts index 02b69af8..b992fdcd 100644 --- a/sdk/typescript/src/msgid.property.test.ts +++ b/sdk/typescript/src/msgid.property.test.ts @@ -77,7 +77,7 @@ async function runMsgIdPropertyTest(n: number): Promise { manager.disconnect(); - if (ids.length !== n + 2) return false; + if (ids.length !== n + 1) return false; if (ids[0] !== 1) return false; diff --git a/sdk/typescript/src/presence.test.ts b/sdk/typescript/src/presence.test.ts index 5a50ae44..edf7b359 100644 --- a/sdk/typescript/src/presence.test.ts +++ b/sdk/typescript/src/presence.test.ts @@ -117,6 +117,24 @@ describe("PresenceImpl", () => { } }); + test("queued sets for different targets are not merged", async () => { + const conn = createMockConnection(); + let targetNs = "room-a"; + Object.assign(conn, { getPresenceNamespace: () => targetNs }); + await setupSchema(conn.schema); + const presence = new PresenceImpl(conn); + presence.set({ status: "active" }); + const queuedA = presence.set({ cursor: { x: 1, y: 2 } }); + queuedA.catch(() => {}); + targetNs = "room-b"; + const queuedB = presence.set({ status: "away" }); + queuedB.catch(() => {}); + await new Promise((resolve) => setTimeout(resolve, 20)); + const sets = conn.dispatched.filter((msg) => msg.type === "PresenceSet"); + expect(sets).toHaveLength(2); + expect(sets.at(-1)?.data).toEqual([2, "away"]); + }); + test("setShared() dispatches PresenceSetShared with encoded data", async () => { const conn = createMockConnection(); await setupSchema(conn.schema); @@ -680,6 +698,346 @@ describe("PresenceImpl", () => { expect(presence.get(staleUserId)).toBeUndefined(); }); + test("a listener joining during stale unsubscribe gets a new subscription", async () => { + const conn = createMockConnection(); + await setupSchema(conn.schema); + const presence = new PresenceImpl(conn); + let subscribeCalls = 0; + let unsubscribeCalls = 0; + let resolveReplay: (value: OkResponse) => void = () => {}; + const replayPromise = new Promise((resolve) => { + resolveReplay = resolve; + }); + let resolveUnsubscribe: (value: OkResponse) => void = () => {}; + const unsubscribePromise = new Promise((resolve) => { + resolveUnsubscribe = resolve; + }); + conn.dispatch = (msg: Record) => { + if (msg.type === "PresenceSubscribe") { + subscribeCalls++; + if (subscribeCalls === 1) { + return Promise.resolve({ + type: "ok", + id: 0, + subId: 100, + users: [], + } as OkResponse); + } + if (subscribeCalls === 2) return replayPromise; + return Promise.resolve({ + type: "ok", + id: 0, + subId: 300, + users: [], + } as OkResponse); + } + if (msg.type === "PresenceUnsubscribe") { + unsubscribeCalls++; + return unsubscribePromise; + } + return Promise.resolve({ type: "ok", id: 0 } as OkResponse); + }; + + const unsubscribe = await presence.subscribe(() => {}); + presence.invalidate(); + const replaying = presence.replaySubscriptions(); + const closing = unsubscribe(); + closing.catch(() => {}); + resolveReplay({ + type: "ok", + id: 0, + subId: 200, + users: [], + } as OkResponse); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(unsubscribeCalls).toBe(1); + + const next = presence.subscribe(() => {}); + next.catch(() => {}); + expect(subscribeCalls).toBe(2); + resolveUnsubscribe({ type: "ok", id: 0 } as OkResponse); + await replaying; + await next; + + expect(subscribeCalls).toBe(3); + }); + test("a shared listener joining during stale unsubscribe gets a new subscription", async () => { + const conn = createMockConnection(); + await setupSchema(conn.schema); + const presence = new PresenceImpl(conn); + let subscribeCalls = 0; + let unsubscribeCalls = 0; + let resolveReplay: (value: OkResponse) => void = () => {}; + const replayPromise = new Promise((resolve) => { + resolveReplay = resolve; + }); + let resolveUnsubscribe: (value: OkResponse) => void = () => {}; + const unsubscribePromise = new Promise((resolve) => { + resolveUnsubscribe = resolve; + }); + conn.dispatch = (msg: Record) => { + if (msg.type === "PresenceSubscribeShared") { + subscribeCalls++; + if (subscribeCalls === 1) { + return Promise.resolve({ + type: "ok", + id: 0, + subId: 100, + } as OkResponse); + } + if (subscribeCalls === 2) return replayPromise; + return Promise.resolve({ + type: "ok", + id: 0, + subId: 300, + } as OkResponse); + } + if (msg.type === "PresenceUnsubscribeShared") { + unsubscribeCalls++; + return unsubscribePromise; + } + return Promise.resolve({ type: "ok", id: 0 } as OkResponse); + }; + + const unsubscribe = await presence.subscribeShared(() => {}); + presence.invalidate(); + const replaying = presence.replaySubscriptions(); + const closing = unsubscribe(); + closing.catch(() => {}); + resolveReplay({ type: "ok", id: 0, subId: 200 } as OkResponse); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(unsubscribeCalls).toBe(1); + + const next = presence.subscribeShared(() => {}); + next.catch(() => {}); + expect(subscribeCalls).toBe(2); + resolveUnsubscribe({ type: "ok", id: 0 } as OkResponse); + await replaying; + await next; + + expect(subscribeCalls).toBe(3); + }); + test("a listener joining during failed cleanup still subscribes", async () => { + const conn = createMockConnection(); + await setupSchema(conn.schema); + const presence = new PresenceImpl(conn); + let subscribeCalls = 0; + let unsubscribeCalls = 0; + let resolveReplay: (value: OkResponse) => void = () => {}; + const replayPromise = new Promise((resolve) => { + resolveReplay = resolve; + }); + let rejectUnsubscribe: (reason?: unknown) => void = () => {}; + const unsubscribePromise = new Promise((_, reject) => { + rejectUnsubscribe = reject; + }); + conn.dispatch = (msg: Record) => { + if (msg.type === "PresenceSubscribe") { + subscribeCalls++; + if (subscribeCalls === 1) { + return Promise.resolve({ + type: "ok", + id: 0, + subId: 100, + users: [], + } as OkResponse); + } + if (subscribeCalls === 2) return replayPromise; + return Promise.resolve({ + type: "ok", + id: 0, + subId: 300, + users: [], + } as OkResponse); + } + if (msg.type === "PresenceUnsubscribe") { + unsubscribeCalls++; + return unsubscribePromise; + } + return Promise.resolve({ type: "ok", id: 0 } as OkResponse); + }; + + const unsubscribe = await presence.subscribe(() => {}); + presence.invalidate(); + const replaying = presence.replaySubscriptions(); + const replayOutcome = replaying.then( + () => null, + (err: unknown) => err, + ); + const closing = unsubscribe(); + const closingOutcome = closing.then( + () => null, + (err: unknown) => err, + ); + resolveReplay({ + type: "ok", + id: 0, + subId: 200, + users: [], + } as OkResponse); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(unsubscribeCalls).toBe(1); + + const next = presence.subscribe(() => {}); + const nextOutcome = next.then( + () => null, + (err: unknown) => err, + ); + expect(subscribeCalls).toBe(2); + rejectUnsubscribe(new Error("unsubscribe failed")); + + expect(await replayOutcome).toBeInstanceOf(Error); + expect(await closingOutcome).toBeInstanceOf(Error); + expect(await nextOutcome).toBeNull(); + expect(subscribeCalls).toBe(3); + }); + test("a shared listener joining during failed cleanup still subscribes", async () => { + const conn = createMockConnection(); + await setupSchema(conn.schema); + const presence = new PresenceImpl(conn); + let subscribeCalls = 0; + let unsubscribeCalls = 0; + let resolveReplay: (value: OkResponse) => void = () => {}; + const replayPromise = new Promise((resolve) => { + resolveReplay = resolve; + }); + let rejectUnsubscribe: (reason?: unknown) => void = () => {}; + const unsubscribePromise = new Promise((_, reject) => { + rejectUnsubscribe = reject; + }); + conn.dispatch = (msg: Record) => { + if (msg.type === "PresenceSubscribeShared") { + subscribeCalls++; + if (subscribeCalls === 1) { + return Promise.resolve({ + type: "ok", + id: 0, + subId: 100, + } as OkResponse); + } + if (subscribeCalls === 2) return replayPromise; + return Promise.resolve({ + type: "ok", + id: 0, + subId: 300, + } as OkResponse); + } + if (msg.type === "PresenceUnsubscribeShared") { + unsubscribeCalls++; + return unsubscribePromise; + } + return Promise.resolve({ type: "ok", id: 0 } as OkResponse); + }; + + const unsubscribe = await presence.subscribeShared(() => {}); + presence.invalidate(); + const replaying = presence.replaySubscriptions(); + const replayOutcome = replaying.then( + () => null, + (err: unknown) => err, + ); + const closing = unsubscribe(); + const closingOutcome = closing.then( + () => null, + (err: unknown) => err, + ); + resolveReplay({ type: "ok", id: 0, subId: 200 } as OkResponse); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(unsubscribeCalls).toBe(1); + + const next = presence.subscribeShared(() => {}); + const nextOutcome = next.then( + () => null, + (err: unknown) => err, + ); + expect(subscribeCalls).toBe(2); + rejectUnsubscribe(new Error("unsubscribe failed")); + + expect(await replayOutcome).toBeInstanceOf(Error); + expect(await closingOutcome).toBeInstanceOf(Error); + expect(await nextOutcome).toBeNull(); + expect(subscribeCalls).toBe(3); + }); + test("a stale subscription completion does not unsubscribe a replacement", async () => { + const conn = createMockConnection(); + await setupSchema(conn.schema); + const presence = new PresenceImpl(conn); + let resolveStale: (value: OkResponse) => void = () => {}; + const stalePromise = new Promise((resolve) => { + resolveStale = resolve; + }); + let subscribeCall = 0; + let unsubscribes = 0; + conn.dispatch = (msg: Record) => { + if (msg.type === "PresenceSubscribe") { + subscribeCall++; + if (subscribeCall === 1) return stalePromise; + return Promise.resolve({ + type: "ok", + id: 0, + subId: 200, + users: [], + } as OkResponse); + } + if (msg.type === "PresenceUnsubscribe") { + unsubscribes++; + } + return Promise.resolve({ type: "ok", id: 0 } as OkResponse); + }; + + presence.subscribe(() => {}); + presence.invalidate(); + presence.replaySubscriptions(); + await new Promise((resolve) => setTimeout(resolve, 10)); + + resolveStale({ + type: "ok", + id: 0, + subId: 100, + users: [], + } as OkResponse); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(unsubscribes).toBe(0); + }); + test("a stale shared subscription completion does not unsubscribe a replacement", async () => { + const conn = createMockConnection(); + await setupSchema(conn.schema); + const presence = new PresenceImpl(conn); + let resolveStale: (value: OkResponse) => void = () => {}; + const stalePromise = new Promise((resolve) => { + resolveStale = resolve; + }); + let subscribeCall = 0; + let unsubscribes = 0; + conn.dispatch = (msg: Record) => { + if (msg.type === "PresenceSubscribeShared") { + subscribeCall++; + if (subscribeCall === 1) return stalePromise; + return Promise.resolve({ + type: "ok", + id: 0, + subId: 200, + } as OkResponse); + } + if (msg.type === "PresenceUnsubscribeShared") { + unsubscribes++; + } + return Promise.resolve({ type: "ok", id: 0 } as OkResponse); + }; + + presence.subscribeShared(() => {}); + presence.invalidate(); + presence.replaySubscriptions(); + await new Promise((resolve) => setTimeout(resolve, 10)); + + resolveStale({ + type: "ok", + id: 0, + subId: 100, + } as OkResponse); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(unsubscribes).toBe(0); + }); test("invalidate() resets lastSetTime so first set() after reconnect is not throttled", async () => { const conn = createMockConnection(); await setupSchema(conn.schema); diff --git a/sdk/typescript/src/presence.ts b/sdk/typescript/src/presence.ts index f27c495c..29724a81 100644 --- a/sdk/typescript/src/presence.ts +++ b/sdk/typescript/src/presence.ts @@ -17,7 +17,6 @@ interface SetWaiter { resolve: () => void; reject: (reason?: unknown) => void; } - export interface PresenceConnection { dispatch(msg: Record): Promise; onPresenceBroadcast( @@ -26,6 +25,7 @@ export interface PresenceConnection { on(event: LifecycleEvent, handler: (...args: unknown[]) => void): void; schemaDictionary: SchemaDictionary; readonly userId: string | null; + getPresenceNamespace?(): string; } export class PresenceImpl implements Presence { @@ -35,7 +35,9 @@ export class PresenceImpl implements Presence { private userSubId: number | null = null; private sharedSubId: number | null = null; private userSubPromise: Promise | null = null; + private userCleanupPromise: Promise | null = null; private sharedSubPromise: Promise | null = null; + private sharedCleanupPromise: Promise | null = null; private userSubGen = 0; private sharedSubGen = 0; private userCallbacks = new Set<(users: PresenceEntry[]) => void>(); @@ -64,7 +66,27 @@ export class PresenceImpl implements Presence { return this.conn.userId; } + private pendingSetTargetNs: string | null = null; + set(data: Record): Promise { + const currentNs = this.conn.getPresenceNamespace?.() ?? null; + if ( + this.pendingSetTargetNs !== null && + this.pendingSetTargetNs !== currentNs + ) { + for (const waiter of this.pendingSetWaiters) { + waiter.reject( + new ZyncBaseError("Presence set superseded by scope change", { + code: ErrorCodes.REQUEST_SUPERSEDED, + category: "state", + retryable: false, + }), + ); + } + this.pendingSetWaiters = []; + this.pendingSetData = null; + } + this.pendingSetTargetNs = currentNs; let resolve!: () => void; let reject!: (reason?: unknown) => void; const accepted = new Promise((res, rej) => { @@ -106,8 +128,9 @@ export class PresenceImpl implements Presence { } setShared(data: Record): Promise { + const targetNamespace = this.conn.getPresenceNamespace?.() ?? null; return this.dispatchAccepted( - { type: "PresenceSetShared", data }, + { type: "PresenceSetShared", data, targetNamespace }, "Presence setShared failed", ); } @@ -118,7 +141,20 @@ export class PresenceImpl implements Presence { private ensureUserSubscription(): Promise { if (this.userSubId !== null) return Promise.resolve(); - if (this.userSubPromise !== null) return this.userSubPromise; + if (this.userSubPromise !== null) { + const retryIfNeeded = () => { + if (this.userSubId === null && this.hasUserSubscribers()) { + return this.ensureUserSubscription(); + } + }; + return this.userSubPromise.then(retryIfNeeded, retryIfNeeded); + } + if (this.userCleanupPromise !== null) { + return this.userCleanupPromise.then( + () => this.ensureUserSubscription(), + () => this.ensureUserSubscription(), + ); + } const gen = this.userSubGen; const pending = this.establishUserSubscription(gen).catch((err) => { const error = toZyncError(err, "Presence subscribe failed"); @@ -149,13 +185,21 @@ export class PresenceImpl implements Presence { retryable: false, }); } - if (gen !== this.userSubGen || !this.hasUserSubscribers()) { - await this.dispatchAccepted( + if (gen !== this.userSubGen) { + return; + } + if (!this.hasUserSubscribers()) { + const unsub = this.dispatchAccepted( { type: "PresenceUnsubscribe", subId: ok.subId }, "Presence unsubscribe failed", ); - if (gen !== this.userSubGen || !this.hasUserSubscribers()) return; - continue; + this.userCleanupPromise = unsub; + const clear = () => { + if (this.userCleanupPromise === unsub) this.userCleanupPromise = null; + }; + unsub.then(clear, clear); + await unsub; + return; } this.userSubId = ok.subId; this.populateUserCacheFromSnapshot(ok); @@ -178,10 +222,16 @@ export class PresenceImpl implements Presence { this.userSubId = null; this.clearUserCache(); if (subId !== null) { - return this.dispatchAccepted( + const unsub = this.dispatchAccepted( { type: "PresenceUnsubscribe", subId }, "Presence unsubscribe failed", ); + this.userCleanupPromise = unsub; + const clear = () => { + if (this.userCleanupPromise === unsub) this.userCleanupPromise = null; + }; + unsub.then(clear, clear); + return unsub; } if (this.userSubPromise !== null) return this.userSubPromise; } @@ -190,7 +240,20 @@ export class PresenceImpl implements Presence { private ensureSharedSubscription(): Promise { if (this.sharedSubId !== null) return Promise.resolve(); - if (this.sharedSubPromise !== null) return this.sharedSubPromise; + if (this.sharedSubPromise !== null) { + const retryIfNeeded = () => { + if (this.sharedSubId === null && this.sharedCallbacks.size > 0) { + return this.ensureSharedSubscription(); + } + }; + return this.sharedSubPromise.then(retryIfNeeded, retryIfNeeded); + } + if (this.sharedCleanupPromise !== null) { + return this.sharedCleanupPromise.then( + () => this.ensureSharedSubscription(), + () => this.ensureSharedSubscription(), + ); + } const gen = this.sharedSubGen; const pending = this.establishSharedSubscription(gen).catch((err) => { const error = toZyncError(err, "Presence subscribeShared failed"); @@ -224,13 +287,23 @@ export class PresenceImpl implements Presence { }, ); } - if (!this.hasCurrentSharedSubscribers(gen)) { - await this.dispatchAccepted( + if (gen !== this.sharedSubGen) { + return; + } + if (this.sharedCallbacks.size === 0) { + const unsub = this.dispatchAccepted( { type: "PresenceUnsubscribeShared", subId: ok.subId }, "Presence unsubscribeShared failed", ); - if (!this.hasCurrentSharedSubscribers(gen)) return; - continue; + this.sharedCleanupPromise = unsub; + const clear = () => { + if (this.sharedCleanupPromise === unsub) { + this.sharedCleanupPromise = null; + } + }; + unsub.then(clear, clear); + await unsub; + return; } this.sharedSubId = ok.subId; this.sharedCache = @@ -245,10 +318,6 @@ export class PresenceImpl implements Presence { }); } - private hasCurrentSharedSubscribers(gen: number): boolean { - return gen === this.sharedSubGen && this.sharedCallbacks.size > 0; - } - private cleanupSharedSubscription(): Promise { if ( this.sharedCallbacks.size === 0 && @@ -258,10 +327,18 @@ export class PresenceImpl implements Presence { this.sharedSubId = null; this.sharedCache = null; if (subId !== null) { - return this.dispatchAccepted( + const unsub = this.dispatchAccepted( { type: "PresenceUnsubscribeShared", subId }, "Presence unsubscribeShared failed", ); + this.sharedCleanupPromise = unsub; + const clear = () => { + if (this.sharedCleanupPromise === unsub) { + this.sharedCleanupPromise = null; + } + }; + unsub.then(clear, clear); + return unsub; } if (this.sharedSubPromise !== null) return this.sharedSubPromise; } @@ -431,8 +508,10 @@ export class PresenceImpl implements Presence { } private sendSet(data: Record, waiters: SetWaiter[]): void { + const targetNamespace = + this.pendingSetTargetNs ?? this.conn.getPresenceNamespace?.() ?? null; this.dispatchAccepted( - { type: "PresenceSet", data }, + { type: "PresenceSet", data, targetNamespace }, "Presence set failed", ).then( () => { @@ -610,7 +689,7 @@ export class PresenceImpl implements Presence { ); } - private clearThrottle(reason?: Error): void { + clearThrottle(reason?: Error): void { if (this.throttleTimer !== null) { clearTimeout(this.throttleTimer); this.throttleTimer = null; diff --git a/sdk/typescript/src/test-helpers.ts b/sdk/typescript/src/test-helpers.ts index 9195313e..adb8ec93 100644 --- a/sdk/typescript/src/test-helpers.ts +++ b/sdk/typescript/src/test-helpers.ts @@ -96,7 +96,7 @@ export class MockWebSocket { } } -/** MockWebSocket that auto-triggers open and auto-responds to StoreSetNamespace. */ +/** MockWebSocket that auto-triggers open and auto-responds to StoreSetNamespace (id=1). */ export class AutoMockWebSocket { static readonly OPEN = 1; static readonly CLOSED = 3; @@ -116,7 +116,6 @@ export class AutoMockWebSocket { Promise.resolve().then(() => { if (this.onopen) this.onopen(); this._autoRespondOk(1); - this._autoRespondOk(2); }); } @@ -237,14 +236,11 @@ function testUserId(): Uint8Array { return packDocId(TEST_USER_ID); } -/** Trigger ok responses for initial StoreSetNamespace (id=1) and PresenceSetNamespace (id=2). */ +/** Trigger the ok response for the initial StoreSetNamespace (id=1). */ export function triggerNamespaceOk(mockWs: MockWebSocket) { mockWs.triggerMessage( encodeToBuffer({ type: "ok", id: 1, userId: testUserId() }), ); - mockWs.triggerMessage( - encodeToBuffer({ type: "ok", id: 2, userId: testUserId() }), - ); } /** Full connect flow: acquire ticket + open + namespace ok. */ diff --git a/specs/api-design/actions-api.md b/specs/api-design/actions-api.md index 7dbcdcef..10df62d5 100644 --- a/specs/api-design/actions-api.md +++ b/specs/api-design/actions-api.md @@ -90,7 +90,7 @@ An action's operational mode is determined directly by the presence or absence o Actions reuse the existing store and presence scopes; there is no separate action namespace. - An action's `scope` (default `"store"`) selects which scope resolves its namespace and user identity. -- Calls and registrations require the bound scope to be ready. Before readiness they fail with `SESSION_NOT_READY`. +- Calls and registrations require the bound scope to be ready. Before readiness they fail with `SESSION_NOT_READY`. The SDK requests the presence scope before the first presence-scoped call or registration on a session. - Namespace admission uses the bound scope's existing rules: `storeFilter` for store-scoped actions, `presenceRead` for presence-scoped actions. - Switching the bound scope's namespace clears that connection's registrations for the scope, mirroring subscription invalidation. Workers must re-register after a switch. - The SDK selects the bound scope per action from the `SchemaSync` dictionaries. diff --git a/specs/api-design/configuration.md b/specs/api-design/configuration.md index db78a9b0..87f53f3c 100644 --- a/specs/api-design/configuration.md +++ b/specs/api-design/configuration.md @@ -443,7 +443,7 @@ Presence auth rules are defined in `authorization.json` alongside store rules: | Rule | Applies to | |---|---| -| `presenceRead` | `presence.subscribe()` and `presence.subscribeShared()` | +| `presenceRead` | Entering the namespace's presence scope: every presence call and presence-scoped action. A store-only app never needs it. | | `presenceWrite` | `presence.set()` and `presence.remove()` | | `presenceSharedWrite` | `presence.setShared()` — defaults to same value as `presenceWrite` when omitted | diff --git a/specs/api-design/connection-management.md b/specs/api-design/connection-management.md index 27e12833..c769dc5f 100644 --- a/specs/api-design/connection-management.md +++ b/specs/api-design/connection-management.md @@ -89,10 +89,10 @@ Initiates the connection sequence: 1. **Ticket exchange** (HTTP POST `/auth/ticket`) — obtains a single-use ticket from the external JWT 2. **WebSocket upgrade** (`GET /ws?ticket=...`) — opens the WebSocket connection 3. **`SchemaSync` push** — the server sends a `SchemaSync` message with table and field arrays; the SDK builds its integer routing dictionary from this payload (per ADR-009) -4. **Scope resolution** — the SDK sends initial store/presence namespace selections; the server resolves each namespace and internal `users.id` -5. **Recovery** — the SDK replays the application's store subscriptions, presence subscriptions, and action registrations +4. **Scope resolution** — the SDK sends the store namespace selection; the server resolves the namespace and internal `users.id`. The presence scope is requested later, by the first presence call or presence-scoped action ([Presence API](./presence-api.md)), so a store-only app needs no presence authorization. +5. **Recovery** — the SDK replays the application's store subscriptions, presence subscriptions, and action registrations; replaying presence subscriptions or presence-scoped registrations requests the presence scope again -The SDK waits for all five steps before resolving the `connect()` promise, so a resolved promise means the client is fully restored. Presence scope acknowledgement installs the canonical internal user UUID before replay begins. +The SDK waits for all five steps before resolving the `connect()` promise, so a resolved promise means the client is fully restored. The store scope acknowledgement installs the canonical internal user UUID before replay begins. ```typescript await client.connect() @@ -134,7 +134,7 @@ The SDK therefore emits three ordered events: | Event | Fires when | |-------|-----------| -| `connected` | The WebSocket is open and the initial required store and presence scopes are resolved. | +| `connected` | The WebSocket is open and the store scope is resolved. | | `reconnected` | The same, but a connection existed earlier in this process. Does not fire on a first connect. | | `synced` | Store subscriptions, presence subscriptions, and action registrations have all been replayed. The client is fully restored. | diff --git a/specs/api-design/presence-api.md b/specs/api-design/presence-api.md index b403c9b1..1e611715 100644 --- a/specs/api-design/presence-api.md +++ b/specs/api-design/presence-api.md @@ -6,7 +6,7 @@ Two tiers of presence state exist: - **User state** (`presence.user` fields): one record per connected user, owned by that user, automatically cleaned up on disconnect. - **Shared state** (`presence.shared` fields): one record per namespace, writable by any authorized user, persists until all users leave (with a 5-second grace period for reconnects). -Presence methods require a ready presence scope. `client.connect()` and `client.setPresenceNamespace(namespace)` resolve only after the server has resolved the namespace string and returned the internal presence `users.id` as bin16. The SDK decodes that canonical UUID before replaying subscriptions. Calling presence methods before scope is ready fails with `SESSION_NOT_READY`. +Presence methods run in a presence scope. The SDK requests it when the first presence call (or presence-scoped action) is made on a connected session, and every presence call waits for it; `client.setPresenceNamespace(namespace)` requests it immediately and resolves once the server has resolved the namespace string and returned the internal `users.id` as bin16. A session that never uses presence never requests the scope, so a store-only app needs no `presenceRead` grant. When the namespace denies presence, the presence call rejects with `NAMESPACE_UNAUTHORIZED` and the session stays connected. Calling presence methods before the session is connected fails with `CONNECTION_FAILED`. ## Table of Contents 1. [Schema Definition](#schema-definition) @@ -251,7 +251,7 @@ Defined in `authorization.json` under each namespace pattern: | Rule | Controls | |---|---| -| `presenceRead` | Who can subscribe to user presence and shared state in this namespace | +| `presenceRead` | Who can enter this namespace's presence scope: required for every presence call and presence-scoped action | | `presenceWrite` | Who can call `presence.set()` and `presence.remove()` | | `presenceSharedWrite` | Who can call `presence.setShared()` | diff --git a/specs/implementation/auth-exchange.md b/specs/implementation/auth-exchange.md index dcd3631f..aed7e106 100644 --- a/specs/implementation/auth-exchange.md +++ b/specs/implementation/auth-exchange.md @@ -46,7 +46,7 @@ ZyncBase acts as a **resource server**, not an identity provider. It validates i | **1. Ticket Request (JWT)** | `POST /auth/ticket` | `Authorization: Bearer ` | `{"ticket": "zyc_tk_...", "expiresAt": 1741551234}` | Validates JWT (signature, issuer, aud, exp, algorithms). Projects claims. | | **1. Ticket Request (Anon)** | `POST /auth/ticket` | `{"anonymousSubject": "anon:6c6f8b0d..."}` | `{"ticket": "zyc_tk_...", "expiresAt": 1741551234}` | Checks if anonymous auth is enabled. Validates subject entropy. | | **2. WebSocket Upgrade** | `ws://server/ws?ticket=zyc_tk_...` | Ticket in query parameter | WebSocket Upgrade established | Verifies ticket signature, expiry, and single-use state. Hydrates base session. | -| **3. Scoped Readiness** | WS Msg: `StoreSetNamespace`, `PresenceSetNamespace` | Namespace identifier string | `ok` with bin16 `userId` | Resolves namespace to internal ID and subject to internal `users.id` (global/namespaced). Both acknowledgements expose the connection's internal ID, used for canonical self filtering. | +| **3. Scoped Readiness** | WS Msg: `StoreSetNamespace` on open; `PresenceSetNamespace` when presence is first used | Namespace identifier string | `ok` with bin16 `userId` | Resolves namespace to internal ID and subject to internal `users.id` (global/namespaced). Both acknowledgements expose the connection's internal ID, used for canonical self filtering. | --- diff --git a/specs/implementation/typescript-sdk.md b/specs/implementation/typescript-sdk.md index e4d181ca..d411ec80 100644 --- a/specs/implementation/typescript-sdk.md +++ b/specs/implementation/typescript-sdk.md @@ -67,7 +67,7 @@ The TypeScript SDK owns the browser/application API surface, connection lifecycl ## Request Flow 1. Public store/presence method validates SDK inputs and builds a semantic command. -2. `ConnectionManager` ensures the connection and required namespace scope are ready. +2. `ConnectionManager` ensures the connection and required namespace scope are ready. The connect handshake resolves only the store scope. `dispatch` and `dispatchNoRetry` hold a presence message, or an action message naming a presence-scoped action, until `PresenceSetNamespace` succeeds; the first such message on a socket sends it. A failed request clears it, so the next presence message asks again. 3. `ConnectionWireCodec` encodes the command using current schema dictionaries and replaces the logical `type` name with its numeric wire ID from the shared registry (`WireMessageType`); `decodeMessage` maps numeric IDs back to the logical `InboundMessage` type names, so the rest of the SDK never sees numeric wire IDs. 4. `PendingRequests` records the request id; store writes also get the `writeTimeoutMs` timer. Once a write is sent, `StoreImpl` adds it to the overlay and delivers it ([Optimistic Overlay](#optimistic-overlay)). 5. An `ok` or `error` response resolves/rejects the request. A store write gets no `ok`: `WriteCommitted` resolves it, `WriteError` or `error` rejects it, and writes are never retried. diff --git a/tests/e2e/auth-store-only.json b/tests/e2e/auth-store-only.json new file mode 100644 index 00000000..18ee3e8f --- /dev/null +++ b/tests/e2e/auth-store-only.json @@ -0,0 +1,11 @@ +{ + "namespaces": [ + { + "pattern": "*", + "storeFilter": true, + "presenceRead": false, + "presenceWrite": false + } + ], + "store": [{ "collection": "*", "read": true, "write": true }] +} diff --git a/tests/e2e/src/e2e.test.ts b/tests/e2e/src/e2e.test.ts index 89e53fb8..9e6ac35f 100644 --- a/tests/e2e/src/e2e.test.ts +++ b/tests/e2e/src/e2e.test.ts @@ -30,6 +30,7 @@ import { run as runPresenceStress } from "./test-presence-stress"; import { run as runResponseLimit } from "./test-response-limit"; import { run as runShutdown } from "./test-shutdown"; import { run as runSorting } from "./test-sorting"; +import { run as runStoreOnly } from "./test-store-only"; import { run as runSync } from "./test-sync"; setDefaultTimeout(90_000); @@ -69,6 +70,23 @@ describe("ZyncBase E2E", () => { ); }); + test("a store-only app connects without presence authorization", async () => { + await runE2ETest("Store-only session", async (ctx) => { + await withServer( + ctx, + { + schemaPath: ctx.schemaPath("schema-sync.json"), + dataDir: ctx.dataPath("store-only"), + configName: "zyncbase-config-store-only.json", + authPath: ctx.schemaPath("auth-store-only.json"), + }, + async ({ port }) => { + await runStoreOnly(port); + }, + ); + }); + }); + test("conditional writes and atomic increments", async () => { await runE2ETest( "Conditional writes and atomic increments", diff --git a/tests/e2e/src/test-store-only.ts b/tests/e2e/src/test-store-only.ts new file mode 100644 index 00000000..f20581a1 --- /dev/null +++ b/tests/e2e/src/test-store-only.ts @@ -0,0 +1,33 @@ +import { ZyncBaseClient } from "./client"; + +/** + * A store-only app connects and writes without presence authorization; only + * a presence call needs it, and only that call fails. + */ +export async function run(port: number): Promise { + const client = new ZyncBaseClient(`ws://127.0.0.1:${port}`); + try { + await client.connect(); + await client.store.set(["tasks", "store-only"], { title: "no presence" }); + const task = await client.store.get(["tasks", "store-only"]); + if ((task as { title?: unknown } | null)?.title !== "no presence") { + throw new Error(`Expected the stored task, got ${JSON.stringify(task)}`); + } + + const denied = await client.presence.set({}).then( + () => null, + (err: { code?: string }) => err.code, + ); + if (denied !== "NAMESPACE_UNAUTHORIZED") { + throw new Error(`Expected NAMESPACE_UNAUTHORIZED, got ${denied}`); + } + if (client.status !== "connected") { + throw new Error( + `Expected the session to stay connected, got ${client.status}`, + ); + } + console.log("E2E store-only session passed."); + } finally { + client.close(); + } +}