From 207f71094722a6d4d626cf887f4babb18e13966b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sat, 21 Nov 2026 19:26:25 +0100 Subject: [PATCH 01/17] Defer presence namespace handshake until first presence operation --- examples/quorum/room.test.ts | 5 +- sdk/typescript/src/client.test.ts | 36 +-- sdk/typescript/src/connection.test.ts | 279 +++++++++++++++------- sdk/typescript/src/connection.ts | 78 +++++- sdk/typescript/src/msgid.property.test.ts | 2 +- sdk/typescript/src/test-helpers.ts | 8 +- specs/api-design/actions-api.md | 2 +- specs/api-design/configuration.md | 2 +- specs/api-design/connection-management.md | 8 +- specs/api-design/presence-api.md | 4 +- specs/implementation/auth-exchange.md | 2 +- specs/implementation/typescript-sdk.md | 2 +- tests/e2e/auth-store-only.json | 11 + tests/e2e/src/e2e.test.ts | 18 ++ tests/e2e/src/test-store-only.ts | 33 +++ 15 files changed, 361 insertions(+), 129 deletions(-) create mode 100644 tests/e2e/auth-store-only.json create mode 100644 tests/e2e/src/test-store-only.ts 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/client.test.ts b/sdk/typescript/src/client.test.ts index f1189128..502242c8 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 () => { @@ -463,6 +452,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 }; diff --git a/sdk/typescript/src/connection.test.ts b/sdk/typescript/src/connection.test.ts index 7e161305..64902273 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,149 @@ 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(); + }); + }); + describe("liveness", () => { test("enables liveness by default and closes when a probe times out", async () => { const { manager, mockWs } = makeManager({ @@ -256,14 +372,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 +394,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 +413,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 3, + id: 2, code: "PERMISSION_DENIED", message: "Not allowed", }), @@ -330,7 +446,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 +462,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "WriteError", - id: 3, + id: 2, code: "UNIQUE_CONSTRAINT_VIOLATED", message: "duplicate", phase: "write", @@ -369,7 +485,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 3, + id: 2, code: "PERMISSION_DENIED", message: "Not allowed", }), @@ -393,7 +509,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 +534,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 3, + id: 2, code: "RATE_LIMITED", message: "Too many requests", retryAfter: 5, @@ -427,7 +543,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 +644,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 +886,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 +1196,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 3, + id: 2, code: "RATE_LIMITED", message: "Too many requests", retryAfter: 50, @@ -1100,11 +1207,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 +1227,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 3, + id: 2, code: "SCHEMA_VALIDATION_FAILED", message: "Invalid data", }), @@ -1131,7 +1238,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 +1259,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 3, + id: 2, code: "INTERNAL_ERROR", message: "Server error", }), @@ -1165,7 +1272,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 4, + id: 3, code: "INTERNAL_ERROR", message: "Server error", }), @@ -1178,7 +1285,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 5, + id: 4, code: "INTERNAL_ERROR", message: "Server error", }), @@ -1200,7 +1307,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 3, + id: 2, code: "RATE_LIMITED", message: "Too many requests", }), @@ -1209,7 +1316,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 +1335,7 @@ describe("ConnectionManager", () => { mockWs.triggerMessage( encodeToBuffer({ type: "error", - id: 3, + id: 2, code: "RATE_LIMITED", message: "Too many requests", retryAfter: 200, @@ -1238,15 +1345,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..18da6122 100644 --- a/sdk/typescript/src/connection.ts +++ b/sdk/typescript/src/connection.ts @@ -140,6 +140,9 @@ 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 presenceScope: Promise | null = null; + private presenceScopeReady = false; private processingPromise: Promise = Promise.resolve(); @@ -200,13 +203,69 @@ export class ConnectionManager { return this.presenceNamespace; } - async setPresenceNamespace(ns: string): Promise { - const ok = await this.dispatch({ + /** + * Establish the presence scope in `ns`, or switch it there. Presence + * messages sent meanwhile wait for it. + */ + setPresenceNamespace(ns: string): Promise { + this.presenceScopeReady = false; + const scope: Promise = this.dispatch({ type: "PresenceSetNamespace", namespace: ns, - }); - this.adoptUserId(ok, "PresenceSetNamespace"); - this.presenceNamespace = ns; + }) + .then((ok) => { + this.adoptUserId(ok, "PresenceSetNamespace"); + this.presenceNamespace = ns; + if (this.presenceScope === scope) this.presenceScopeReady = true; + }) + .catch((err: unknown) => { + if (this.presenceScope === scope) this.presenceScope = null; + throw err; + }); + this.presenceScope = 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, + ): Promise { + if ( + this.presenceScopeReady || + this.currentStatus !== "connected" || + !this.needsPresenceScope(msg) + ) { + return send(); + } + const scope = + this.presenceScope ?? this.setPresenceNamespace(this.presenceNamespace); + return scope.then(send); + } + + /** 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 { + return ( + typeof id === "string" && + this.schemaDictionary.getAction(id).scope === "presence" + ); } private adoptUserId(ok: OkResponse, request: string): void { @@ -288,6 +347,8 @@ export class ConnectionManager { this.intentionalDisconnect = false; this.pendingDisconnectError = null; this.currentUserId = null; + this.presenceScope = null; + this.presenceScopeReady = false; this.stopLiveness(); this.setStatus("connecting"); this.processingPromise = Promise.resolve(); @@ -305,7 +366,6 @@ export class ConnectionManager { ws.onopen = () => { this.startLiveness(); this.setStoreNamespace(this.storeNamespace) - .then(() => this.setPresenceNamespace(this.presenceNamespace)) .then(() => { this.reconnectAttempt = 0; this.setStatus("connected"); @@ -418,7 +478,9 @@ export class ConnectionManager { msg: OutboundRequest, responseTableIndex?: number, ): Promise { - return this.dispatchWithRetry(msg, 0, responseTableIndex); + return this.withPresenceScope(msg, () => + this.dispatchWithRetry(msg, 0, responseTableIndex), + ); } /** @@ -426,7 +488,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); } /** 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/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(); + } +} From 8ab7e212616b961caa107942e6e00644f906e3fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sat, 21 Nov 2026 19:53:38 +0100 Subject: [PATCH 02/17] Add presence namespace handling and tests for same-namespace scope --- sdk/typescript/src/client.test.ts | 42 ++++++++++ sdk/typescript/src/client.ts | 5 +- sdk/typescript/src/connection.test.ts | 115 ++++++++++++++++++++++++++ sdk/typescript/src/connection.ts | 49 ++++++----- 4 files changed, 190 insertions(+), 21 deletions(-) diff --git a/sdk/typescript/src/client.test.ts b/sdk/typescript/src/client.test.ts index 502242c8..4930c0d5 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -511,6 +511,48 @@ 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("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..ee8ad3a9 100644 --- a/sdk/typescript/src/client.ts +++ b/sdk/typescript/src/client.ts @@ -225,7 +225,10 @@ export class ZyncBaseClient< /** Switch the active presence namespace. */ async setPresenceNamespace(namespace: string): Promise { const oldNs = this.conn.getPresenceNamespace(); - if (oldNs === namespace) return; + if (oldNs === namespace) { + await this.conn.setPresenceNamespace(namespace); + return; + } this.presenceImpl.invalidate(); await this.conn.setPresenceNamespace(namespace); diff --git a/sdk/typescript/src/connection.test.ts b/sdk/typescript/src/connection.test.ts index 64902273..4faddd34 100644 --- a/sdk/typescript/src/connection.test.ts +++ b/sdk/typescript/src/connection.test.ts @@ -307,6 +307,121 @@ describe("ConnectionManager", () => { again.catch(() => {}); manager.disconnect(); }); + + test("a queued presence message waits for a replacement scope", async () => { + const { manager, mockWs } = makeManager(); + await connectManager(manager, mockWs); + const presence = manager.dispatch({ type: "PresenceSet", data: {} }); + const switched = manager.setPresenceNamespace("other"); + expect(mockWs.sentMessages.map(sentType)).toEqual([ + WireMessageType.StoreSetNamespace, + WireMessageType.PresenceSetNamespace, + WireMessageType.PresenceSetNamespace, + ]); + 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, + ]); + + ack(mockWs, replacement.id); + await tick(); + const sent = 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: sent.id })); + await Promise.all([presence, switched]); + }); + + 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("a retry on a replacement socket requests the presence scope again", async () => { + const { manager, mockWs } = makeManager({ + reconnect: false, + reconnectDelay: 10, + }); + await connectManager(manager, mockWs); + const presence = manager.dispatch({ type: "PresenceSet", data: {} }); + 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; + + await new Promise((r) => setTimeout(r, 150)); + const setup = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( + WireMessageType.PresenceSetNamespace, + ); + ack(mockWs, setup.id); + await tick(); + const retried = 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: retried.id })); + await presence; + manager.disconnect(); + }); }); describe("liveness", () => { diff --git a/sdk/typescript/src/connection.ts b/sdk/typescript/src/connection.ts index 18da6122..960eaec0 100644 --- a/sdk/typescript/src/connection.ts +++ b/sdk/typescript/src/connection.ts @@ -142,6 +142,7 @@ export class ConnectionManager { private presenceNamespace: string; /** The presence scope request of this socket; null until presence is first used. */ private presenceScope: Promise | null = null; + private presenceScopeNamespace: string | null = null; private presenceScopeReady = false; private processingPromise: Promise = Promise.resolve(); @@ -208,7 +209,11 @@ export class ConnectionManager { * messages sent meanwhile wait for it. */ setPresenceNamespace(ns: string): Promise { + if (this.presenceScope !== null && this.presenceScopeNamespace === ns) { + return this.presenceScope; + } this.presenceScopeReady = false; + this.presenceScopeNamespace = ns; const scope: Promise = this.dispatch({ type: "PresenceSetNamespace", namespace: ns, @@ -219,7 +224,10 @@ export class ConnectionManager { if (this.presenceScope === scope) this.presenceScopeReady = true; }) .catch((err: unknown) => { - if (this.presenceScope === scope) this.presenceScope = null; + if (this.presenceScope === scope) { + this.presenceScope = null; + this.presenceScopeNamespace = null; + } throw err; }); this.presenceScope = scope; @@ -244,7 +252,7 @@ export class ConnectionManager { } const scope = this.presenceScope ?? this.setPresenceNamespace(this.presenceNamespace); - return scope.then(send); + return scope.then(() => this.withPresenceScope(msg, send)); } /** Presence messages, and action messages naming a presence-scoped action. */ @@ -348,6 +356,7 @@ export class ConnectionManager { this.pendingDisconnectError = null; this.currentUserId = null; this.presenceScope = null; + this.presenceScopeNamespace = null; this.presenceScopeReady = false; this.stopLiveness(); this.setStatus("connecting"); @@ -478,9 +487,7 @@ export class ConnectionManager { msg: OutboundRequest, responseTableIndex?: number, ): Promise { - return this.withPresenceScope(msg, () => - this.dispatchWithRetry(msg, 0, responseTableIndex), - ); + return this.dispatchWithRetry(msg, 0, responseTableIndex); } /** @@ -551,25 +558,27 @@ export class ConnectionManager { return { id, result, debugType: encoded.debugMessage.type }; } - private async dispatchWithRetry( + private dispatchWithRetry( msg: OutboundRequest, attempt: number, responseTableIndex?: 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, - ); - } + return this.withPresenceScope(msg, async () => { + 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, + ); + } + }); } private async handleRetryOrThrow( From a96af135cca4c5a4740d6703b8e0153288efdac2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sat, 21 Nov 2026 20:41:24 +0100 Subject: [PATCH 03/17] Implement presence scope generation and handle superseded setups in ConnectionManager --- sdk/typescript/src/connection.test.ts | 140 ++++++++++++++++++++++++++ sdk/typescript/src/connection.ts | 68 ++++++++++--- 2 files changed, 195 insertions(+), 13 deletions(-) diff --git a/sdk/typescript/src/connection.test.ts b/sdk/typescript/src/connection.test.ts index 4faddd34..5ff4354c 100644 --- a/sdk/typescript/src/connection.test.ts +++ b/sdk/typescript/src/connection.test.ts @@ -358,6 +358,146 @@ describe("ConnectionManager", () => { expect(mockWs.sentMessages).toHaveLength(2); }); + test("a late superseded setup cannot overwrite the latest scope", async () => { + const { manager, mockWs } = makeManager({ + presenceNamespace: "initial", + }); + await connectManager(manager, mockWs); + const first = manager.setPresenceNamespace("first"); + const firstOutcome = first.then( + () => null, + (err: { code?: string }) => err.code, + ); + const second = manager.setPresenceNamespace("second"); + const [firstScope, secondScope] = mockWs.sentMessages + .slice(1) + .map((bytes) => decode(bytes) as { id: number }); + + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: firstScope.id, + userId: packDocId("019c1e50-7d11-7000-8000-000000000002"), + }), + ); + await tick(); + expect(await firstOutcome).toBe("REQUEST_SUPERSEDED"); + expect(manager.getPresenceNamespace()).toBe("initial"); + expect(manager.userId).toBe(TEST_USER_ID); + + ack(mockWs, secondScope.id); + await second; + expect(manager.getPresenceNamespace()).toBe("second"); + expect(manager.userId).toBe(TEST_USER_ID); + }); + + 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 retriedScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( + WireMessageType.PresenceSetNamespace, + ); + ack(mockWs, retriedScope.id); + await tick(); + 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 superseded setup is not retried after the latest request", async () => { + const { manager, mockWs } = makeManager({ + reconnectDelay: 10, + }); + await connectManager(manager, mockWs); + const first = manager.setPresenceNamespace("first"); + const firstOutcome = first.then( + () => null, + (err: { code?: string }) => err.code, + ); + 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: 100, + }), + ); + await tick(); + + const second = manager.setPresenceNamespace("second"); + const secondOutcome = second.then( + () => null, + (err: { code?: string }) => err.code, + ); + const secondScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + const third = manager.setPresenceNamespace("first"); + const thirdScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: secondScope.id, + code: "RATE_LIMITED", + message: "Too many requests", + }), + ); + await tick(); + + await new Promise((r) => setTimeout(r, 150)); + expect(mockWs.sentMessages.map(sentType)).toEqual([ + WireMessageType.StoreSetNamespace, + WireMessageType.PresenceSetNamespace, + WireMessageType.PresenceSetNamespace, + WireMessageType.PresenceSetNamespace, + ]); + + ack(mockWs, thirdScope.id); + await third; + expect(await firstOutcome).toBe("REQUEST_SUPERSEDED"); + expect(await secondOutcome).toBe("REQUEST_SUPERSEDED"); + expect(manager.getPresenceNamespace()).toBe("first"); + }); + test("a retry on a replacement socket requests the presence scope again", async () => { const { manager, mockWs } = makeManager({ reconnect: false, diff --git a/sdk/typescript/src/connection.ts b/sdk/typescript/src/connection.ts index 960eaec0..d934a60e 100644 --- a/sdk/typescript/src/connection.ts +++ b/sdk/typescript/src/connection.ts @@ -144,6 +144,7 @@ export class ConnectionManager { private presenceScope: Promise | null = null; private presenceScopeNamespace: string | null = null; private presenceScopeReady = false; + private presenceScopeGeneration = 0; private processingPromise: Promise = Promise.resolve(); @@ -212,16 +213,22 @@ export class ConnectionManager { if (this.presenceScope !== null && this.presenceScopeNamespace === ns) { return this.presenceScope; } + const generation = ++this.presenceScopeGeneration; this.presenceScopeReady = false; this.presenceScopeNamespace = ns; - const scope: Promise = this.dispatch({ - type: "PresenceSetNamespace", - namespace: ns, - }) + const scope: Promise = this.dispatchWithRetry( + { type: "PresenceSetNamespace", namespace: ns }, + 0, + undefined, + () => this.presenceScopeGeneration === generation, + ) .then((ok) => { + if (this.presenceScope !== scope) { + throw this.supersededPresenceScopeError(); + } this.adoptUserId(ok, "PresenceSetNamespace"); this.presenceNamespace = ns; - if (this.presenceScope === scope) this.presenceScopeReady = true; + this.presenceScopeReady = true; }) .catch((err: unknown) => { if (this.presenceScope === scope) { @@ -243,16 +250,36 @@ export class ConnectionManager { msg: OutboundRequest, send: () => Promise, ): Promise { - if ( - this.presenceScopeReady || - this.currentStatus !== "connected" || - !this.needsPresenceScope(msg) - ) { + if (this.currentStatus !== "connected" || !this.needsPresenceScope(msg)) { return send(); } + if (this.presenceScopeReady) { + if (this.presenceNamespace === this.presenceScopeNamespace) return send(); + this.presenceScopeReady = false; + this.presenceScope = null; + } const scope = - this.presenceScope ?? this.setPresenceNamespace(this.presenceNamespace); - return scope.then(() => this.withPresenceScope(msg, send)); + this.presenceScope ?? + this.setPresenceNamespace( + this.presenceScopeNamespace ?? this.presenceNamespace, + ); + return scope.then( + () => this.withPresenceScope(msg, send), + (err) => { + if (this.presenceScope !== null && this.presenceScope !== scope) { + return this.withPresenceScope(msg, send); + } + throw err; + }, + ); + } + + private supersededPresenceScopeError(): ZyncBaseError { + return new ZyncBaseError("Presence namespace setup superseded", { + code: ErrorCodes.REQUEST_SUPERSEDED, + category: "state", + retryable: false, + }); } /** Presence messages, and action messages naming a presence-scoped action. */ @@ -358,6 +385,7 @@ export class ConnectionManager { this.presenceScope = null; this.presenceScopeNamespace = null; this.presenceScopeReady = false; + this.presenceScopeGeneration++; this.stopLiveness(); this.setStatus("connecting"); this.processingPromise = Promise.resolve(); @@ -562,6 +590,7 @@ export class ConnectionManager { msg: OutboundRequest, attempt: number, responseTableIndex?: number, + isCurrent?: () => boolean, ): Promise { return this.withPresenceScope(msg, async () => { const { result, debugType } = this.sendRequest(msg, responseTableIndex); @@ -576,6 +605,7 @@ export class ConnectionManager { err, debugType, responseTableIndex, + isCurrent, ); } }); @@ -587,7 +617,11 @@ export class ConnectionManager { err: unknown, debugType: string, responseTableIndex?: number, + isCurrent?: () => boolean, ): Promise { + if (isCurrent !== undefined && !isCurrent()) { + throw this.supersededPresenceScopeError(); + } if (!this.retryPolicy.shouldRetry(err, attempt)) throw err; const delay = this.retryPolicy.getDelay(err, attempt); @@ -598,7 +632,15 @@ export class ConnectionManager { } await sleep(delay); if (this.intentionalDisconnect) throw err; - return this.dispatchWithRetry(msg, attempt + 1, responseTableIndex); + if (isCurrent !== undefined && !isCurrent()) { + throw this.supersededPresenceScopeError(); + } + return this.dispatchWithRetry( + msg, + attempt + 1, + responseTableIndex, + isCurrent, + ); } authRefresh(token: string): Promise { From 9d1b165fba95bde83ce76967f3a04fdd2c044529 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sat, 21 Nov 2026 23:15:08 +0100 Subject: [PATCH 04/17] Refactor presence handling in ConnectionManager and improve error management in ZyncBaseClient --- sdk/typescript/src/actions.test.ts | 56 +++++++- sdk/typescript/src/actions.ts | 18 ++- sdk/typescript/src/client.test.ts | 191 ++++++++++++++++++++++++++ sdk/typescript/src/client.ts | 32 ++++- sdk/typescript/src/connection.test.ts | 121 +++++++++++++--- sdk/typescript/src/connection.ts | 102 +++++++++----- 6 files changed, 460 insertions(+), 60 deletions(-) diff --git a/sdk/typescript/src/actions.test.ts b/sdk/typescript/src/actions.test.ts index 3526bfec..e68d2dd0 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,56 @@ 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; + actions.replayRegistrations(); + await nextTick(); + expect(conn.dispatched).toHaveLength(2); + expect(conn.dispatched).toContainEqual({ + type: "ActionRegister", + action_ids: ["checkout"], + }); + expect(errors.some((err) => err.code === "NAMESPACE_UNAUTHORIZED")).toBe( + true, + ); + }); }); diff --git a/sdk/typescript/src/actions.ts b/sdk/typescript/src/actions.ts index 3813e42e..78806f27 100644 --- a/sdk/typescript/src/actions.ts +++ b/sdk/typescript/src/actions.ts @@ -95,17 +95,27 @@ export class ActionsImpl implements Actions { replayRegistrations(): void { if (this.handlers.size === 0 || !this.conn.isSchemaReady()) return; - 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(() => {}); + if (storeNames.length > 0) { + void this.register(storeNames).catch(() => {}); + } + if (presenceNames.length > 0) { + void this.register(presenceNames).catch(() => {}); + } } private async register(names: string[]): Promise { diff --git a/sdk/typescript/src/client.test.ts b/sdk/typescript/src/client.test.ts index 4930c0d5..b41f6ea8 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -440,6 +440,197 @@ 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 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 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 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", + }); + + 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("setStoreNamespace replays store subscriptions without touching presence", async () => { installMockWebSocket(); const client = createClient(defaultOptions); diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts index ee8ad3a9..006a8262 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"; @@ -230,8 +230,20 @@ export class ZyncBaseClient< return; } + try { + await this.conn.setPresenceNamespace(namespace); + } catch (err) { + if ( + !( + err instanceof ZyncBaseError && + err.code === ErrorCodes.NAMESPACE_SWITCH_REJECTED + ) + ) { + this.presenceImpl.invalidate(); + } + throw err; + } this.presenceImpl.invalidate(); - await this.conn.setPresenceNamespace(namespace); await this.presenceImpl.replaySubscriptions(); this.actionsImpl.replayRegistrations(); } @@ -300,9 +312,21 @@ export class ZyncBaseClient< * readiness queue. On a connection cycle this ends with `synced`. */ private async _restore(): Promise { - await this.presenceImpl.replaySubscriptions(); + const [store, presence] = await Promise.allSettled([ + this._restoreStore(), + this.presenceImpl.replaySubscriptions(), + ]); + await this.conn.awaitSchemaSync(); this.actionsImpl.replayRegistrations(); - await this._restoreStore(); + 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 5ff4354c..e836d6dc 100644 --- a/sdk/typescript/src/connection.test.ts +++ b/sdk/typescript/src/connection.test.ts @@ -308,10 +308,14 @@ describe("ConnectionManager", () => { manager.disconnect(); }); - test("a queued presence message waits for a replacement scope", async () => { + test("a queued subscription is rejected when its scope is replaced", async () => { const { manager, mockWs } = makeManager(); await connectManager(manager, mockWs); - const presence = manager.dispatch({ type: "PresenceSet", data: {} }); + const subscribe = manager.dispatch({ type: "PresenceSubscribe" }); + const outcome = subscribe.then( + () => null, + (err: { code?: string }) => err.code, + ); const switched = manager.setPresenceNamespace("other"); expect(mockWs.sentMessages.map(sentType)).toEqual([ WireMessageType.StoreSetNamespace, @@ -324,6 +328,7 @@ describe("ConnectionManager", () => { ack(mockWs, initial.id); await tick(); + expect(await outcome).toBe("REQUEST_SUPERSEDED"); expect(mockWs.sentMessages.map(sentType)).toEqual([ WireMessageType.StoreSetNamespace, WireMessageType.PresenceSetNamespace, @@ -331,15 +336,12 @@ describe("ConnectionManager", () => { ]); ack(mockWs, replacement.id); - await tick(); - const sent = 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: sent.id })); - await Promise.all([presence, switched]); + await switched; + expect(mockWs.sentMessages.map(sentType)).toEqual([ + WireMessageType.StoreSetNamespace, + WireMessageType.PresenceSetNamespace, + WireMessageType.PresenceSetNamespace, + ]); }); test("a same-namespace call joins a pending scope request", async () => { @@ -418,14 +420,6 @@ describe("ConnectionManager", () => { expect(manager.getPresenceNamespace()).toBe("public"); const retried = manager.dispatch({ type: "PresenceSet", data: {} }); - const retriedScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { - id: number; - }; - expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( - WireMessageType.PresenceSetNamespace, - ); - ack(mockWs, retriedScope.id); - await tick(); const presence = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { id: number; }; @@ -562,6 +556,95 @@ describe("ConnectionManager", () => { await presence; manager.disconnect(); }); + + test("a presence write retry is rejected after a namespace switch", async () => { + const { manager, mockWs } = makeManager({ reconnectDelay: 10 }); + await connectManager(manager, mockWs); + const write = manager.dispatch({ type: "PresenceSet", data: {} }); + const outcome = write.then( + () => null, + (err: { code?: string }) => err.code, + ); + const scope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + ack(mockWs, scope.id); + await tick(); + const attempt = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + mockWs.triggerMessage( + encodeToBuffer({ + type: "error", + id: attempt.id, + code: "RATE_LIMITED", + message: "Too many requests", + retryAfter: 100, + }), + ); + await tick(); + + const switched = manager.setPresenceNamespace("other"); + const replacement = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + }; + ack(mockWs, replacement.id); + await switched; + await new Promise((r) => setTimeout(r, 150)); + + expect(await outcome).toBe("REQUEST_SUPERSEDED"); + expect(mockWs.sentMessages.map(sentType)).toEqual([ + WireMessageType.StoreSetNamespace, + WireMessageType.PresenceSetNamespace, + WireMessageType.PresenceSet, + WireMessageType.PresenceSetNamespace, + ]); + }); + + 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", () => { diff --git a/sdk/typescript/src/connection.ts b/sdk/typescript/src/connection.ts index d934a60e..a9623d04 100644 --- a/sdk/typescript/src/connection.ts +++ b/sdk/typescript/src/connection.ts @@ -210,9 +210,19 @@ export class ConnectionManager { * messages sent meanwhile wait for it. */ setPresenceNamespace(ns: string): Promise { - if (this.presenceScope !== null && this.presenceScopeNamespace === ns) { + if ( + this.currentStatus === "connected" && + this.presenceScope !== null && + this.presenceScopeNamespace === ns + ) { return this.presenceScope; } + const previous = { + scope: this.presenceScope, + namespace: this.presenceScopeNamespace, + ready: this.presenceScopeReady, + generation: this.presenceScopeGeneration, + }; const generation = ++this.presenceScopeGeneration; this.presenceScopeReady = false; this.presenceScopeNamespace = ns; @@ -232,8 +242,15 @@ export class ConnectionManager { }) .catch((err: unknown) => { if (this.presenceScope === scope) { - this.presenceScope = null; - this.presenceScopeNamespace = null; + if (this.isNamespaceSwitchRejected(err)) { + this.presenceScope = previous.scope; + this.presenceScopeNamespace = previous.namespace; + this.presenceScopeReady = previous.ready; + this.presenceScopeGeneration = previous.generation; + } else { + this.presenceScope = null; + this.presenceScopeNamespace = null; + } } throw err; }); @@ -249,25 +266,30 @@ export class ConnectionManager { private withPresenceScope( msg: OutboundRequest, send: () => Promise, + namespace = this.presenceScopeNamespace ?? this.presenceNamespace, ): Promise { if (this.currentStatus !== "connected" || !this.needsPresenceScope(msg)) { return send(); } + const requested = this.presenceScopeNamespace ?? this.presenceNamespace; + if (requested !== namespace) { + return Promise.reject(this.supersededPresenceScopeError()); + } if (this.presenceScopeReady) { - if (this.presenceNamespace === this.presenceScopeNamespace) return send(); + if (this.presenceNamespace === namespace) return send(); this.presenceScopeReady = false; this.presenceScope = null; } - const scope = - this.presenceScope ?? - this.setPresenceNamespace( - this.presenceScopeNamespace ?? this.presenceNamespace, - ); + const scope = this.presenceScope ?? this.setPresenceNamespace(namespace); return scope.then( - () => this.withPresenceScope(msg, send), + () => this.withPresenceScope(msg, send, namespace), (err) => { + const current = this.presenceScopeNamespace ?? this.presenceNamespace; + if (current !== namespace) { + throw this.supersededPresenceScopeError(); + } if (this.presenceScope !== null && this.presenceScope !== scope) { - return this.withPresenceScope(msg, send); + return this.withPresenceScope(msg, send, namespace); } throw err; }, @@ -282,6 +304,13 @@ export class ConnectionManager { }); } + private isNamespaceSwitchRejected(err: unknown): boolean { + return ( + err instanceof ZyncBaseError && + err.code === ErrorCodes.NAMESPACE_SWITCH_REJECTED + ); + } + /** Presence messages, and action messages naming a presence-scoped action. */ private needsPresenceScope(msg: OutboundRequest): boolean { switch (msg.type) { @@ -297,10 +326,9 @@ export class ConnectionManager { } private isPresenceAction(id: string | number): boolean { - return ( - typeof id === "string" && - this.schemaDictionary.getAction(id).scope === "presence" - ); + const name = + typeof id === "number" ? this.schemaDictionary.getActionName(id) : id; + return this.schemaDictionary.getAction(name).scope === "presence"; } private adoptUserId(ok: OkResponse, request: string): void { @@ -591,24 +619,32 @@ export class ConnectionManager { attempt: number, responseTableIndex?: number, isCurrent?: () => boolean, + namespace?: string, ): Promise { - return this.withPresenceScope(msg, async () => { - 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, - isCurrent, - ); - } - }); + const target = + namespace ?? this.presenceScopeNamespace ?? this.presenceNamespace; + return this.withPresenceScope( + msg, + async () => { + 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, + isCurrent, + target, + ); + } + }, + target, + ); } private async handleRetryOrThrow( @@ -618,6 +654,7 @@ export class ConnectionManager { debugType: string, responseTableIndex?: number, isCurrent?: () => boolean, + namespace?: string, ): Promise { if (isCurrent !== undefined && !isCurrent()) { throw this.supersededPresenceScopeError(); @@ -640,6 +677,7 @@ export class ConnectionManager { attempt + 1, responseTableIndex, isCurrent, + namespace, ); } From e4e210c4d719ab9abe439cf8f3533ee571acad75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sat, 21 Nov 2026 23:40:52 +0100 Subject: [PATCH 05/17] Enhance presence handling with namespace switch logic and improve subscription management --- sdk/typescript/src/actions.test.ts | 4 +- sdk/typescript/src/actions.ts | 23 +++-- sdk/typescript/src/client.test.ts | 83 +++++++++++++++++- sdk/typescript/src/client.ts | 60 ++++++++++--- sdk/typescript/src/connection.test.ts | 38 ++++++++ sdk/typescript/src/connection.ts | 44 +++++++--- sdk/typescript/src/presence.test.ts | 81 +++++++++++++++++ sdk/typescript/src/presence.ts | 121 +++++++++++++++++++------- 8 files changed, 387 insertions(+), 67 deletions(-) diff --git a/sdk/typescript/src/actions.test.ts b/sdk/typescript/src/actions.test.ts index e68d2dd0..18f687ae 100644 --- a/sdk/typescript/src/actions.test.ts +++ b/sdk/typescript/src/actions.test.ts @@ -393,8 +393,8 @@ describe("ActionsImpl.handle", () => { await actions.handle("player_move", () => {}); conn.dispatched.length = 0; failPresence = true; - actions.replayRegistrations(); - await nextTick(); + const replay = actions.replayRegistrations(); + await Promise.allSettled([replay.store, replay.presence]); expect(conn.dispatched).toHaveLength(2); expect(conn.dispatched).toContainEqual({ type: "ActionRegister", diff --git a/sdk/typescript/src/actions.ts b/sdk/typescript/src/actions.ts index 78806f27..eaacfecf 100644 --- a/sdk/typescript/src/actions.ts +++ b/sdk/typescript/src/actions.ts @@ -92,8 +92,13 @@ 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 storeNames: string[] = []; const presenceNames: string[] = []; @@ -110,12 +115,14 @@ export class ActionsImpl implements Actions { this.handlers.delete(name); } } - if (storeNames.length > 0) { - void this.register(storeNames).catch(() => {}); - } - if (presenceNames.length > 0) { - void this.register(presenceNames).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 { diff --git a/sdk/typescript/src/client.test.ts b/sdk/typescript/src/client.test.ts index b41f6ea8..55562b5d 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -566,7 +566,10 @@ describe("ZyncBaseClient", () => { triggerSchemaSync(mockWs); await connected; - const pendingPresence = client.presence.subscribe(() => {}); + 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; @@ -610,6 +613,15 @@ describe("ZyncBaseClient", () => { 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) => { @@ -631,6 +643,75 @@ describe("ZyncBaseClient", () => { 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("setStoreNamespace replays store subscriptions without touching presence", async () => { installMockWebSocket(); const client = createClient(defaultOptions); diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts index 006a8262..44d9dec3 100644 --- a/sdk/typescript/src/client.ts +++ b/sdk/typescript/src/client.ts @@ -48,6 +48,7 @@ export class ZyncBaseClient< >(); /** Whether a connection existed earlier in this process. */ private hasConnectedOnce = false; + private presenceSwitchGeneration = 0; /** Backoff state for retrying a failed restore. */ private restoreAttempt = 0; private restoreTimer: ReturnType | null = null; @@ -164,12 +165,15 @@ export class ZyncBaseClient< * one is surfaced to the error callbacks instead of retrying forever. */ private scheduleRestore(): void { - this._restore() + const generation = this.conn.getConnectionGeneration(); + this._restore(generation) .then(() => { + if (this.conn.getConnectionGeneration() !== generation) return; this.restoreAttempt = 0; this.emitLocal("synced"); }) .catch((err: unknown) => { + if (this.conn.getConnectionGeneration() !== generation) return; if (err instanceof ZyncBaseError && err.retryable) { this.retryRestoreLater(); return; @@ -225,27 +229,42 @@ export class ZyncBaseClient< /** Switch the active presence namespace. */ async setPresenceNamespace(namespace: string): Promise { const oldNs = this.conn.getPresenceNamespace(); - if (oldNs === namespace) { + if ( + oldNs === namespace && + this.conn.getPresenceScopeTarget() === namespace + ) { await this.conn.setPresenceNamespace(namespace); return; } + this.presenceImpl.beginNamespaceSwitch(); + const switchGeneration = ++this.presenceSwitchGeneration; try { await this.conn.setPresenceNamespace(namespace); } catch (err) { - if ( - !( + if (this.presenceSwitchGeneration === switchGeneration) { + if ( + err instanceof ZyncBaseError && + err.code === ErrorCodes.REQUEST_SUPERSEDED + ) { + // A newer switch owns the presence transaction. + } else if ( err instanceof ZyncBaseError && err.code === ErrorCodes.NAMESPACE_SWITCH_REJECTED - ) - ) { - this.presenceImpl.invalidate(); + ) { + this.presenceImpl.rollbackNamespaceSwitch(); + } else { + this.presenceImpl.invalidate(); + } } throw err; } - this.presenceImpl.invalidate(); + if (this.presenceSwitchGeneration !== switchGeneration) return; + this.presenceImpl.commitNamespaceSwitch(); await this.presenceImpl.replaySubscriptions(); - this.actionsImpl.replayRegistrations(); + const replay = this.actionsImpl.replayRegistrations(); + replay.store.catch(() => {}); + replay.presence.catch(() => {}); } /** @@ -311,13 +330,16 @@ export class ZyncBaseClient< * Replay everything after a connect or reconnect, then release the * readiness queue. On a connection cycle this ends with `synced`. */ - private async _restore(): Promise { + private async _restore(generation: number): Promise { const [store, presence] = await Promise.allSettled([ - this._restoreStore(), + this._restoreStore(generation), this.presenceImpl.replaySubscriptions(), ]); await this.conn.awaitSchemaSync(); - this.actionsImpl.replayRegistrations(); + if (this.conn.getConnectionGeneration() !== generation) return; + const actions = this.actionsImpl.replayRegistrations(); + await Promise.allSettled([actions.store, actions.presence]); + if (this.conn.getConnectionGeneration() !== generation) return; if (presence.status === "rejected") { const error = toZyncError(presence.reason, "Restore failed", false); if (!error.retryable || store.status === "rejected") { @@ -334,7 +356,7 @@ export class ZyncBaseClient< * the readiness queue. Runs on connect/reconnect and on a store namespace * switch — the flows that invalidate store subscriptions. */ - private async _restoreStore(): Promise { + private async _restoreStore(generation?: number): Promise { const oldToNew = new Map(); const replaySnapshots = new Map< number, @@ -345,6 +367,12 @@ export class ZyncBaseClient< await this._replaySubscription(params, oldId, oldToNew, replaySnapshots); }); + if ( + generation !== undefined && + this.conn.getConnectionGeneration() !== generation + ) { + return; + } // Always reconnect: with no subscriptions this still re-enables delta // delivery after an explicit disconnect(). this.tracker.reconnect(oldToNew, () => { @@ -354,6 +382,12 @@ export class ZyncBaseClient< }); await this.conn.awaitSchemaSync(); + if ( + generation !== undefined && + this.conn.getConnectionGeneration() !== generation + ) { + return; + } await this.storeImpl.markSessionReady(); } diff --git a/sdk/typescript/src/connection.test.ts b/sdk/typescript/src/connection.test.ts index e836d6dc..b7debb04 100644 --- a/sdk/typescript/src/connection.test.ts +++ b/sdk/typescript/src/connection.test.ts @@ -431,6 +431,44 @@ describe("ConnectionManager", () => { expect(manager.getPresenceNamespace()).toBe("public"); }); + test("a rejected switch restores the confirmed scope, not a pending one", async () => { + const { manager, mockWs } = makeManager(); + await connectManager(manager, mockWs); + const confirmed = manager.setPresenceNamespace("public"); + ack(mockWs, 2); + await confirmed; + + const pending = manager.setPresenceNamespace("other"); + pending.catch(() => {}); + const rejected = manager.setPresenceNamespace("third"); + 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 presence = manager.dispatch({ type: "PresenceSet", data: {} }); + const sent = 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: sent.id })); + await presence; + manager.disconnect(); + }); + test("a superseded setup is not retried after the latest request", async () => { const { manager, mockWs } = makeManager({ reconnectDelay: 10, diff --git a/sdk/typescript/src/connection.ts b/sdk/typescript/src/connection.ts index a9623d04..ec9f1b8b 100644 --- a/sdk/typescript/src/connection.ts +++ b/sdk/typescript/src/connection.ts @@ -145,6 +145,10 @@ export class ConnectionManager { private presenceScopeNamespace: string | null = null; private presenceScopeReady = false; private presenceScopeGeneration = 0; + private presenceConfirmedScope: Promise | null = null; + private presenceConfirmedNamespace: string | null = null; + private presenceConfirmedGeneration = 0; + private connectionGeneration = 0; private processingPromise: Promise = Promise.resolve(); @@ -204,6 +208,15 @@ export class ConnectionManager { getPresenceNamespace(): string { return this.presenceNamespace; } + getPresenceScopeTarget(): string { + return this.presenceScopeNamespace ?? this.presenceNamespace; + } + getPresenceScopeGeneration(): number { + return this.presenceScopeGeneration; + } + getConnectionGeneration(): number { + return this.connectionGeneration; + } /** * Establish the presence scope in `ns`, or switch it there. Presence @@ -217,12 +230,6 @@ export class ConnectionManager { ) { return this.presenceScope; } - const previous = { - scope: this.presenceScope, - namespace: this.presenceScopeNamespace, - ready: this.presenceScopeReady, - generation: this.presenceScopeGeneration, - }; const generation = ++this.presenceScopeGeneration; this.presenceScopeReady = false; this.presenceScopeNamespace = ns; @@ -239,17 +246,29 @@ export class ConnectionManager { this.adoptUserId(ok, "PresenceSetNamespace"); this.presenceNamespace = ns; this.presenceScopeReady = true; + this.presenceConfirmedScope = scope; + this.presenceConfirmedNamespace = ns; + this.presenceConfirmedGeneration = generation; }) .catch((err: unknown) => { if (this.presenceScope === scope) { if (this.isNamespaceSwitchRejected(err)) { - this.presenceScope = previous.scope; - this.presenceScopeNamespace = previous.namespace; - this.presenceScopeReady = previous.ready; - this.presenceScopeGeneration = previous.generation; + this.presenceScope = this.presenceConfirmedScope; + this.presenceScopeNamespace = this.presenceConfirmedNamespace; + this.presenceScopeReady = + this.presenceConfirmedScope !== null && + this.presenceConfirmedNamespace !== null; + this.presenceScopeGeneration = + this.presenceConfirmedNamespace !== null + ? this.presenceConfirmedGeneration + : generation; } else { this.presenceScope = null; this.presenceScopeNamespace = null; + this.presenceScopeReady = false; + this.presenceConfirmedScope = null; + this.presenceConfirmedNamespace = null; + this.presenceConfirmedGeneration = 0; } } throw err; @@ -414,6 +433,10 @@ export class ConnectionManager { this.presenceScopeNamespace = null; this.presenceScopeReady = false; this.presenceScopeGeneration++; + this.presenceConfirmedScope = null; + this.presenceConfirmedNamespace = null; + this.presenceConfirmedGeneration = 0; + this.connectionGeneration++; this.stopLiveness(); this.setStatus("connecting"); this.processingPromise = Promise.resolve(); @@ -701,6 +724,7 @@ export class ConnectionManager { disconnect(): void { this.intentionalDisconnect = true; + this.connectionGeneration++; this.currentUserId = null; this.stopLiveness(); if (this.reconnectTimer !== null) { diff --git a/sdk/typescript/src/presence.test.ts b/sdk/typescript/src/presence.test.ts index 5a50ae44..16128bed 100644 --- a/sdk/typescript/src/presence.test.ts +++ b/sdk/typescript/src/presence.test.ts @@ -46,6 +46,14 @@ function createMockConnection() { on: () => {}, schemaDictionary: schema, userId: null as string | null, + presenceScopeTarget: "public", + presenceScopeGeneration: 0, + getPresenceScopeTarget() { + return this.presenceScopeTarget; + }, + getPresenceScopeGeneration() { + return this.presenceScopeGeneration; + }, dispatched, schema, fireBroadcast: (msg: PresenceBroadcast | SharedStateBroadcast) => { @@ -117,6 +125,50 @@ describe("PresenceImpl", () => { } }); + test("a namespace switch pauses queued sets and rejects old-namespace data", async () => { + const conn = createMockConnection(); + await setupSchema(conn.schema); + const presence = new PresenceImpl(conn); + presence.set({ status: "active" }); + const queued = presence.set({ status: "away" }); + const outcome = queued.then( + () => null, + (err: { code?: string }) => err.code, + ); + presence.beginNamespaceSwitch(); + conn.presenceScopeTarget = "other"; + conn.presenceScopeGeneration++; + await new Promise((resolve) => setTimeout(resolve, 20)); + expect( + conn.dispatched.filter((msg) => msg.type === "PresenceSet"), + ).toHaveLength(1); + presence.commitNamespaceSwitch(); + expect(await outcome).toBe("REQUEST_SUPERSEDED"); + expect( + conn.dispatched.filter((msg) => msg.type === "PresenceSet"), + ).toHaveLength(1); + }); + + test("a rejected namespace switch resumes queued sets in the old namespace", async () => { + const conn = createMockConnection(); + await setupSchema(conn.schema); + const presence = new PresenceImpl(conn); + presence.set({ status: "active" }); + const queued = presence.set({ status: "away" }); + presence.beginNamespaceSwitch(); + conn.presenceScopeTarget = "other"; + await new Promise((resolve) => setTimeout(resolve, 20)); + expect( + conn.dispatched.filter((msg) => msg.type === "PresenceSet"), + ).toHaveLength(1); + conn.presenceScopeTarget = "public"; + presence.rollbackNamespaceSwitch(); + await queued; + expect( + conn.dispatched.filter((msg) => msg.type === "PresenceSet"), + ).toHaveLength(2); + }); + test("setShared() dispatches PresenceSetShared with encoded data", async () => { const conn = createMockConnection(); await setupSchema(conn.schema); @@ -680,6 +732,35 @@ describe("PresenceImpl", () => { expect(presence.get(staleUserId)).toBeUndefined(); }); + test("stale subscription completion after a scope change skips unscoped unsubscribe", 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 unsubscribes = 0; + conn.dispatch = (msg: Record) => { + if (msg.type === "PresenceSubscribe") return stalePromise; + if (msg.type === "PresenceUnsubscribe") { + unsubscribes++; + } + return Promise.resolve({ type: "ok", id: 0 } as OkResponse); + }; + presence.subscribe(() => {}); + conn.presenceScopeGeneration++; + presence.invalidate(); + resolveStale({ + type: "ok", + id: 0, + subId: 100, + users: [], + } 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..2b41ed52 100644 --- a/sdk/typescript/src/presence.ts +++ b/sdk/typescript/src/presence.ts @@ -17,6 +17,10 @@ interface SetWaiter { resolve: () => void; reject: (reason?: unknown) => void; } +interface PendingSetBatch { + data: Record; + waiters: SetWaiter[]; +} export interface PresenceConnection { dispatch(msg: Record): Promise; @@ -26,6 +30,8 @@ export interface PresenceConnection { on(event: LifecycleEvent, handler: (...args: unknown[]) => void): void; schemaDictionary: SchemaDictionary; readonly userId: string | null; + getPresenceScopeTarget(): string; + getPresenceScopeGeneration(): number; } export class PresenceImpl implements Presence { @@ -43,8 +49,8 @@ export class PresenceImpl implements Presence { (shared: Record | null) => void >(); private lastSetTime = 0; - private pendingSetData: Record | null = null; - private pendingSetWaiters: SetWaiter[] = []; + private pendingSets = new Map(); + private switchPending = false; private throttleTimer: ReturnType | null = null; private conn: PresenceConnection; private readonly emitError: (err: ZyncBaseError) => void; @@ -72,7 +78,15 @@ export class PresenceImpl implements Presence { reject = rej; }); accepted.catch(() => {}); - this.pendingSetWaiters.push({ resolve, reject }); + const namespace = this.conn.getPresenceScopeTarget(); + const batch = this.pendingSets.get(namespace) ?? { + data: {}, + waiters: [], + }; + batch.data = { ...batch.data, ...data }; + batch.waiters.push({ resolve, reject }); + this.pendingSets.set(namespace, batch); + if (this.switchPending) return accepted; const now = performance.now(); const elapsed = now - this.lastSetTime; @@ -82,25 +96,12 @@ export class PresenceImpl implements Presence { clearTimeout(this.throttleTimer); this.throttleTimer = null; } - const pending = this.pendingSetData; - this.pendingSetData = null; - this.lastSetTime = now; - this.sendSet( - pending ? { ...pending, ...data } : data, - this.pendingSetWaiters.splice(0), - ); - } else { - this.pendingSetData = { ...(this.pendingSetData ?? {}), ...data }; - if (this.throttleTimer === null) { - this.throttleTimer = setTimeout(() => { - this.throttleTimer = null; - if (this.pendingSetData) { - this.lastSetTime = performance.now(); - this.sendSet(this.pendingSetData, this.pendingSetWaiters.splice(0)); - this.pendingSetData = null; - } - }, THROTTLE_INTERVAL_MS - elapsed); - } + this.flushPendingSets(); + } else if (this.throttleTimer === null) { + this.throttleTimer = setTimeout(() => { + this.throttleTimer = null; + this.flushPendingSets(); + }, THROTTLE_INTERVAL_MS - elapsed); } return accepted; } @@ -111,6 +112,45 @@ export class PresenceImpl implements Presence { "Presence setShared failed", ); } + beginNamespaceSwitch(): void { + this.switchPending = true; + if (this.throttleTimer !== null) { + clearTimeout(this.throttleTimer); + this.throttleTimer = null; + } + } + commitNamespaceSwitch(): void { + this.switchPending = false; + this.invalidate(); + } + rollbackNamespaceSwitch(): void { + this.switchPending = false; + const target = this.conn.getPresenceScopeTarget(); + const superseded = new ZyncBaseError( + "Presence set superseded by scope change", + { + code: ErrorCodes.REQUEST_SUPERSEDED, + category: "state", + retryable: false, + }, + ); + for (const [namespace, batch] of this.pendingSets) { + if (namespace === target) continue; + this.pendingSets.delete(namespace); + for (const waiter of batch.waiters) waiter.reject(superseded); + } + this.flushPendingSets(); + } + private flushPendingSets(): void { + if (this.switchPending || this.pendingSets.size === 0) return; + const target = this.conn.getPresenceScopeTarget(); + for (const [namespace, batch] of [...this.pendingSets]) { + if (namespace !== target) continue; + this.pendingSets.delete(namespace); + this.sendSet(batch.data, batch.waiters); + } + this.lastSetTime = performance.now(); + } private hasUserSubscribers(): boolean { return this.userCallbacks.size > 0; @@ -141,6 +181,7 @@ export class PresenceImpl implements Presence { private async establishUserSubscription(gen: number): Promise { while (gen === this.userSubGen) { + const epoch = this.conn.getPresenceScopeGeneration(); const ok = await this.conn.dispatch({ type: "PresenceSubscribe" }); if (ok.subId === undefined) { throw new ZyncBaseError("PresenceSubscribe response missing subId", { @@ -150,10 +191,15 @@ export class PresenceImpl implements Presence { }); } if (gen !== this.userSubGen || !this.hasUserSubscribers()) { - await this.dispatchAccepted( - { type: "PresenceUnsubscribe", subId: ok.subId }, - "Presence unsubscribe failed", - ); + if ( + this.conn.getPresenceScopeGeneration() === epoch && + this.userSubId === null + ) { + await this.dispatchAccepted( + { type: "PresenceUnsubscribe", subId: ok.subId }, + "Presence unsubscribe failed", + ); + } if (gen !== this.userSubGen || !this.hasUserSubscribers()) return; continue; } @@ -213,6 +259,7 @@ export class PresenceImpl implements Presence { private async establishSharedSubscription(gen: number): Promise { while (gen === this.sharedSubGen) { + const epoch = this.conn.getPresenceScopeGeneration(); const ok = await this.conn.dispatch({ type: "PresenceSubscribeShared" }); if (ok.subId === undefined) { throw new ZyncBaseError( @@ -225,10 +272,15 @@ export class PresenceImpl implements Presence { ); } if (!this.hasCurrentSharedSubscribers(gen)) { - await this.dispatchAccepted( - { type: "PresenceUnsubscribeShared", subId: ok.subId }, - "Presence unsubscribeShared failed", - ); + if ( + this.conn.getPresenceScopeGeneration() === epoch && + this.sharedSubId === null + ) { + await this.dispatchAccepted( + { type: "PresenceUnsubscribeShared", subId: ok.subId }, + "Presence unsubscribeShared failed", + ); + } if (!this.hasCurrentSharedSubscribers(gen)) return; continue; } @@ -409,6 +461,7 @@ export class PresenceImpl implements Presence { ): void { this.userSubGen++; this.sharedSubGen++; + this.switchPending = false; this.clearUserCache(); this.sharedCache = null; this.userSubId = null; @@ -615,11 +668,13 @@ export class PresenceImpl implements Presence { clearTimeout(this.throttleTimer); this.throttleTimer = null; } - this.pendingSetData = null; + const batches = [...this.pendingSets.values()]; + this.pendingSets.clear(); if (reason) { - for (const waiter of this.pendingSetWaiters) waiter.reject(reason); + for (const batch of batches) { + for (const waiter of batch.waiters) waiter.reject(reason); + } } - this.pendingSetWaiters = []; this.lastSetTime = 0; } } From 241ce40a71e15a7b526ccd45cd959b97861781ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sun, 22 Nov 2026 00:03:19 +0100 Subject: [PATCH 06/17] Implement ensurePresenceScope method and update PresenceImpl for namespace handling --- sdk/typescript/src/connection.ts | 13 +++++ sdk/typescript/src/presence.test.ts | 77 ++++++++++++++++++++++++++++- sdk/typescript/src/presence.ts | 10 ++++ 3 files changed, 98 insertions(+), 2 deletions(-) diff --git a/sdk/typescript/src/connection.ts b/sdk/typescript/src/connection.ts index ec9f1b8b..92083945 100644 --- a/sdk/typescript/src/connection.ts +++ b/sdk/typescript/src/connection.ts @@ -217,6 +217,19 @@ export class ConnectionManager { getConnectionGeneration(): number { return this.connectionGeneration; } + async ensurePresenceScope(): Promise { + if (this.currentStatus !== "connected") return; + const namespace = this.presenceScopeNamespace ?? this.presenceNamespace; + if (this.presenceScopeReady) { + if (this.presenceNamespace === namespace) return; + this.presenceScopeReady = false; + this.presenceScope = null; + } + const scope = this.presenceScope ?? this.setPresenceNamespace(namespace); + await scope; + const current = this.presenceScopeNamespace ?? this.presenceNamespace; + if (current !== namespace) return this.ensurePresenceScope(); + } /** * Establish the presence scope in `ns`, or switch it there. Presence diff --git a/sdk/typescript/src/presence.test.ts b/sdk/typescript/src/presence.test.ts index 16128bed..d05c1c73 100644 --- a/sdk/typescript/src/presence.test.ts +++ b/sdk/typescript/src/presence.test.ts @@ -54,6 +54,7 @@ function createMockConnection() { getPresenceScopeGeneration() { return this.presenceScopeGeneration; }, + ensurePresenceScope: () => Promise.resolve(), dispatched, schema, fireBroadcast: (msg: PresenceBroadcast | SharedStateBroadcast) => { @@ -169,6 +170,32 @@ describe("PresenceImpl", () => { ).toHaveLength(2); }); + test("commit flushes batches queued for the acknowledged target", async () => { + const conn = createMockConnection(); + await setupSchema(conn.schema); + const presence = new PresenceImpl(conn); + presence.set({ status: "active" }); + const oldBatch = presence.set({ status: "old" }); + const oldOutcome = oldBatch.then( + () => null, + (err: { code?: string }) => err.code, + ); + presence.beginNamespaceSwitch(); + conn.presenceScopeTarget = "other"; + conn.presenceScopeGeneration++; + const newBatch = presence.set({ status: "new" }); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect( + conn.dispatched.filter((msg) => msg.type === "PresenceSet"), + ).toHaveLength(1); + presence.commitNamespaceSwitch(); + await newBatch; + expect(await oldOutcome).toBe("REQUEST_SUPERSEDED"); + const sets = conn.dispatched.filter((msg) => msg.type === "PresenceSet"); + expect(sets).toHaveLength(2); + expect(sets.at(-1)?.data).toEqual([2, "new"]); + }); + test("setShared() dispatches PresenceSetShared with encoded data", async () => { const conn = createMockConnection(); await setupSchema(conn.schema); @@ -742,14 +769,17 @@ describe("PresenceImpl", () => { }); let unsubscribes = 0; conn.dispatch = (msg: Record) => { - if (msg.type === "PresenceSubscribe") return stalePromise; + if (msg.type === "PresenceSubscribe") { + conn.presenceScopeGeneration++; + return stalePromise; + } if (msg.type === "PresenceUnsubscribe") { unsubscribes++; } return Promise.resolve({ type: "ok", id: 0 } as OkResponse); }; presence.subscribe(() => {}); - conn.presenceScopeGeneration++; + await new Promise((resolve) => setTimeout(resolve, 0)); presence.invalidate(); resolveStale({ type: "ok", @@ -778,6 +808,49 @@ describe("PresenceImpl", () => { expect(conn.dispatched.length).toBe(2); }); + test("subscription cleanup captures the epoch after the lazy scope setup", async () => { + const conn = createMockConnection(); + await setupSchema(conn.schema); + const presence = new PresenceImpl(conn); + let resolveReplay: (value: OkResponse) => void = () => {}; + const replayPromise = new Promise((resolve) => { + resolveReplay = resolve; + }); + let subscribeCall = 0; + let unsubscribes = 0; + conn.dispatch = (msg: Record) => { + if (msg.type === "PresenceSubscribe") { + subscribeCall++; + if (subscribeCall === 1) { + return Promise.resolve({ + type: "ok", + id: 0, + subId: 100, + users: [], + } as OkResponse); + } + return replayPromise; + } + if (msg.type === "PresenceUnsubscribe") unsubscribes++; + return Promise.resolve({ type: "ok", id: 0 } as OkResponse); + }; + const unsubscribe = await presence.subscribe(() => {}); + presence.invalidate(); + conn.ensurePresenceScope = async () => { + conn.presenceScopeGeneration++; + }; + const replaying = presence.replaySubscriptions(); + const closing = unsubscribe(); + resolveReplay({ + type: "ok", + id: 0, + subId: 200, + users: [], + } as OkResponse); + await replaying; + await closing; + expect(unsubscribes).toBe(1); + }); test("replaySubscriptions unsubscribes user if client unsubscribed before promise resolves", async () => { const conn = createMockConnection(); await setupSchema(conn.schema); diff --git a/sdk/typescript/src/presence.ts b/sdk/typescript/src/presence.ts index 2b41ed52..1eae504f 100644 --- a/sdk/typescript/src/presence.ts +++ b/sdk/typescript/src/presence.ts @@ -32,6 +32,7 @@ export interface PresenceConnection { readonly userId: string | null; getPresenceScopeTarget(): string; getPresenceScopeGeneration(): number; + ensurePresenceScope(): Promise; } export class PresenceImpl implements Presence { @@ -121,7 +122,14 @@ export class PresenceImpl implements Presence { } commitNamespaceSwitch(): void { this.switchPending = false; + const target = this.conn.getPresenceScopeTarget(); + const targetBatch = this.pendingSets.get(target); + if (targetBatch) this.pendingSets.delete(target); this.invalidate(); + if (targetBatch) { + this.pendingSets.set(target, targetBatch); + this.flushPendingSets(); + } } rollbackNamespaceSwitch(): void { this.switchPending = false; @@ -181,6 +189,7 @@ export class PresenceImpl implements Presence { private async establishUserSubscription(gen: number): Promise { while (gen === this.userSubGen) { + await this.conn.ensurePresenceScope(); const epoch = this.conn.getPresenceScopeGeneration(); const ok = await this.conn.dispatch({ type: "PresenceSubscribe" }); if (ok.subId === undefined) { @@ -259,6 +268,7 @@ export class PresenceImpl implements Presence { private async establishSharedSubscription(gen: number): Promise { while (gen === this.sharedSubGen) { + await this.conn.ensurePresenceScope(); const epoch = this.conn.getPresenceScopeGeneration(); const ok = await this.conn.dispatch({ type: "PresenceSubscribeShared" }); if (ok.subId === undefined) { From 679459671884da6b57cddd51c7c8f8e5f6e39c82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sun, 22 Nov 2026 00:25:40 +0100 Subject: [PATCH 07/17] Refactor presence scope management in ConnectionManager to remove confirmed generation and streamline scope handling --- sdk/typescript/src/connection.test.ts | 6 ++++++ sdk/typescript/src/connection.ts | 11 +++-------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/sdk/typescript/src/connection.test.ts b/sdk/typescript/src/connection.test.ts index b7debb04..1fd27d51 100644 --- a/sdk/typescript/src/connection.test.ts +++ b/sdk/typescript/src/connection.test.ts @@ -437,10 +437,12 @@ describe("ConnectionManager", () => { const confirmed = manager.setPresenceNamespace("public"); ack(mockWs, 2); await confirmed; + const confirmedGeneration = manager.getPresenceScopeGeneration(); const pending = manager.setPresenceNamespace("other"); pending.catch(() => {}); const rejected = manager.setPresenceNamespace("third"); + const rejectedGeneration = manager.getPresenceScopeGeneration(); const rejectedScope = decode( mockWs.sentMessages.at(-1) as Uint8Array, ) as { id: number }; @@ -456,6 +458,10 @@ describe("ConnectionManager", () => { code: "NAMESPACE_SWITCH_REJECTED", }); expect(manager.getPresenceNamespace()).toBe("public"); + expect(manager.getPresenceScopeGeneration()).toBe(rejectedGeneration); + expect(manager.getPresenceScopeGeneration()).toBeGreaterThan( + confirmedGeneration, + ); const presence = manager.dispatch({ type: "PresenceSet", data: {} }); const sent = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { diff --git a/sdk/typescript/src/connection.ts b/sdk/typescript/src/connection.ts index 92083945..0f8d8303 100644 --- a/sdk/typescript/src/connection.ts +++ b/sdk/typescript/src/connection.ts @@ -147,7 +147,6 @@ export class ConnectionManager { private presenceScopeGeneration = 0; private presenceConfirmedScope: Promise | null = null; private presenceConfirmedNamespace: string | null = null; - private presenceConfirmedGeneration = 0; private connectionGeneration = 0; private processingPromise: Promise = Promise.resolve(); @@ -261,7 +260,6 @@ export class ConnectionManager { this.presenceScopeReady = true; this.presenceConfirmedScope = scope; this.presenceConfirmedNamespace = ns; - this.presenceConfirmedGeneration = generation; }) .catch((err: unknown) => { if (this.presenceScope === scope) { @@ -271,17 +269,12 @@ export class ConnectionManager { this.presenceScopeReady = this.presenceConfirmedScope !== null && this.presenceConfirmedNamespace !== null; - this.presenceScopeGeneration = - this.presenceConfirmedNamespace !== null - ? this.presenceConfirmedGeneration - : generation; } else { this.presenceScope = null; this.presenceScopeNamespace = null; this.presenceScopeReady = false; this.presenceConfirmedScope = null; this.presenceConfirmedNamespace = null; - this.presenceConfirmedGeneration = 0; } } throw err; @@ -448,7 +441,6 @@ export class ConnectionManager { this.presenceScopeGeneration++; this.presenceConfirmedScope = null; this.presenceConfirmedNamespace = null; - this.presenceConfirmedGeneration = 0; this.connectionGeneration++; this.stopLiveness(); this.setStatus("connecting"); @@ -662,6 +654,9 @@ export class ConnectionManager { return this.withPresenceScope( msg, async () => { + if (isCurrent !== undefined && !isCurrent()) { + throw this.supersededPresenceScopeError(); + } const { result, debugType } = this.sendRequest(msg, responseTableIndex); try { From aefab7c1ab1befe406f87fa58470c200e2c7dedb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sun, 22 Nov 2026 00:51:50 +0100 Subject: [PATCH 08/17] Refactor presence handling in ConnectionManager and PresenceImpl to streamline scope management and remove unnecessary complexity --- sdk/typescript/src/client.ts | 60 +------ sdk/typescript/src/connection.test.ts | 218 -------------------------- sdk/typescript/src/connection.ts | 211 +++++++++---------------- sdk/typescript/src/presence.test.ts | 154 ------------------ sdk/typescript/src/presence.ts | 132 ++++------------ 5 files changed, 111 insertions(+), 664 deletions(-) diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts index 44d9dec3..be4c9f9c 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 { ErrorCodes, toZyncError, ZyncBaseError } from "./errors.js"; +import { toZyncError, ZyncBaseError } from "./errors.js"; import { PresenceImpl } from "./presence.js"; import { backoffDelay } from "./retry_policy.js"; import { StoreImpl } from "./store.js"; @@ -48,7 +48,6 @@ export class ZyncBaseClient< >(); /** Whether a connection existed earlier in this process. */ private hasConnectedOnce = false; - private presenceSwitchGeneration = 0; /** Backoff state for retrying a failed restore. */ private restoreAttempt = 0; private restoreTimer: ReturnType | null = null; @@ -165,15 +164,12 @@ export class ZyncBaseClient< * one is surfaced to the error callbacks instead of retrying forever. */ private scheduleRestore(): void { - const generation = this.conn.getConnectionGeneration(); - this._restore(generation) + this._restore() .then(() => { - if (this.conn.getConnectionGeneration() !== generation) return; this.restoreAttempt = 0; this.emitLocal("synced"); }) .catch((err: unknown) => { - if (this.conn.getConnectionGeneration() !== generation) return; if (err instanceof ZyncBaseError && err.retryable) { this.retryRestoreLater(); return; @@ -229,38 +225,12 @@ export class ZyncBaseClient< /** Switch the active presence namespace. */ async setPresenceNamespace(namespace: string): Promise { const oldNs = this.conn.getPresenceNamespace(); - if ( - oldNs === namespace && - this.conn.getPresenceScopeTarget() === namespace - ) { - await this.conn.setPresenceNamespace(namespace); + if (oldNs === namespace && this.conn.isPresenceScopeReady()) { return; } - this.presenceImpl.beginNamespaceSwitch(); - const switchGeneration = ++this.presenceSwitchGeneration; - try { - await this.conn.setPresenceNamespace(namespace); - } catch (err) { - if (this.presenceSwitchGeneration === switchGeneration) { - if ( - err instanceof ZyncBaseError && - err.code === ErrorCodes.REQUEST_SUPERSEDED - ) { - // A newer switch owns the presence transaction. - } else if ( - err instanceof ZyncBaseError && - err.code === ErrorCodes.NAMESPACE_SWITCH_REJECTED - ) { - this.presenceImpl.rollbackNamespaceSwitch(); - } else { - this.presenceImpl.invalidate(); - } - } - throw err; - } - if (this.presenceSwitchGeneration !== switchGeneration) return; - this.presenceImpl.commitNamespaceSwitch(); + await this.conn.setPresenceNamespace(namespace); + this.presenceImpl.invalidate(); await this.presenceImpl.replaySubscriptions(); const replay = this.actionsImpl.replayRegistrations(); replay.store.catch(() => {}); @@ -330,16 +300,14 @@ export class ZyncBaseClient< * Replay everything after a connect or reconnect, then release the * readiness queue. On a connection cycle this ends with `synced`. */ - private async _restore(generation: number): Promise { + private async _restore(): Promise { const [store, presence] = await Promise.allSettled([ - this._restoreStore(generation), + this._restoreStore(), this.presenceImpl.replaySubscriptions(), ]); await this.conn.awaitSchemaSync(); - if (this.conn.getConnectionGeneration() !== generation) return; const actions = this.actionsImpl.replayRegistrations(); await Promise.allSettled([actions.store, actions.presence]); - if (this.conn.getConnectionGeneration() !== generation) return; if (presence.status === "rejected") { const error = toZyncError(presence.reason, "Restore failed", false); if (!error.retryable || store.status === "rejected") { @@ -356,7 +324,7 @@ export class ZyncBaseClient< * the readiness queue. Runs on connect/reconnect and on a store namespace * switch — the flows that invalidate store subscriptions. */ - private async _restoreStore(generation?: number): Promise { + private async _restoreStore(): Promise { const oldToNew = new Map(); const replaySnapshots = new Map< number, @@ -367,12 +335,6 @@ export class ZyncBaseClient< await this._replaySubscription(params, oldId, oldToNew, replaySnapshots); }); - if ( - generation !== undefined && - this.conn.getConnectionGeneration() !== generation - ) { - return; - } // Always reconnect: with no subscriptions this still re-enables delta // delivery after an explicit disconnect(). this.tracker.reconnect(oldToNew, () => { @@ -382,12 +344,6 @@ export class ZyncBaseClient< }); await this.conn.awaitSchemaSync(); - if ( - generation !== undefined && - this.conn.getConnectionGeneration() !== generation - ) { - return; - } await this.storeImpl.markSessionReady(); } diff --git a/sdk/typescript/src/connection.test.ts b/sdk/typescript/src/connection.test.ts index 1fd27d51..7b1f4b8c 100644 --- a/sdk/typescript/src/connection.test.ts +++ b/sdk/typescript/src/connection.test.ts @@ -308,42 +308,6 @@ describe("ConnectionManager", () => { 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"); - expect(mockWs.sentMessages.map(sentType)).toEqual([ - WireMessageType.StoreSetNamespace, - WireMessageType.PresenceSetNamespace, - WireMessageType.PresenceSetNamespace, - ]); - const [initial, replacement] = mockWs.sentMessages - .slice(1) - .map((bytes) => decode(bytes) as { id: number }); - - ack(mockWs, initial.id); - await tick(); - expect(await outcome).toBe("REQUEST_SUPERSEDED"); - expect(mockWs.sentMessages.map(sentType)).toEqual([ - WireMessageType.StoreSetNamespace, - WireMessageType.PresenceSetNamespace, - WireMessageType.PresenceSetNamespace, - ]); - - ack(mockWs, replacement.id); - await switched; - expect(mockWs.sentMessages.map(sentType)).toEqual([ - WireMessageType.StoreSetNamespace, - WireMessageType.PresenceSetNamespace, - WireMessageType.PresenceSetNamespace, - ]); - }); - test("a same-namespace call joins a pending scope request", async () => { const { manager, mockWs } = makeManager(); await connectManager(manager, mockWs); @@ -360,39 +324,6 @@ describe("ConnectionManager", () => { expect(mockWs.sentMessages).toHaveLength(2); }); - test("a late superseded setup cannot overwrite the latest scope", async () => { - const { manager, mockWs } = makeManager({ - presenceNamespace: "initial", - }); - await connectManager(manager, mockWs); - const first = manager.setPresenceNamespace("first"); - const firstOutcome = first.then( - () => null, - (err: { code?: string }) => err.code, - ); - const second = manager.setPresenceNamespace("second"); - const [firstScope, secondScope] = mockWs.sentMessages - .slice(1) - .map((bytes) => decode(bytes) as { id: number }); - - mockWs.triggerMessage( - encodeToBuffer({ - type: "ok", - id: firstScope.id, - userId: packDocId("019c1e50-7d11-7000-8000-000000000002"), - }), - ); - await tick(); - expect(await firstOutcome).toBe("REQUEST_SUPERSEDED"); - expect(manager.getPresenceNamespace()).toBe("initial"); - expect(manager.userId).toBe(TEST_USER_ID); - - ack(mockWs, secondScope.id); - await second; - expect(manager.getPresenceNamespace()).toBe("second"); - expect(manager.userId).toBe(TEST_USER_ID); - }); - test("a rejected presence switch keeps the previous namespace usable", async () => { const { manager, mockWs } = makeManager(); await connectManager(manager, mockWs); @@ -431,111 +362,6 @@ describe("ConnectionManager", () => { expect(manager.getPresenceNamespace()).toBe("public"); }); - test("a rejected switch restores the confirmed scope, not a pending one", async () => { - const { manager, mockWs } = makeManager(); - await connectManager(manager, mockWs); - const confirmed = manager.setPresenceNamespace("public"); - ack(mockWs, 2); - await confirmed; - const confirmedGeneration = manager.getPresenceScopeGeneration(); - - const pending = manager.setPresenceNamespace("other"); - pending.catch(() => {}); - const rejected = manager.setPresenceNamespace("third"); - const rejectedGeneration = manager.getPresenceScopeGeneration(); - 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"); - expect(manager.getPresenceScopeGeneration()).toBe(rejectedGeneration); - expect(manager.getPresenceScopeGeneration()).toBeGreaterThan( - confirmedGeneration, - ); - - const presence = manager.dispatch({ type: "PresenceSet", data: {} }); - const sent = 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: sent.id })); - await presence; - manager.disconnect(); - }); - - test("a superseded setup is not retried after the latest request", async () => { - const { manager, mockWs } = makeManager({ - reconnectDelay: 10, - }); - await connectManager(manager, mockWs); - const first = manager.setPresenceNamespace("first"); - const firstOutcome = first.then( - () => null, - (err: { code?: string }) => err.code, - ); - 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: 100, - }), - ); - await tick(); - - const second = manager.setPresenceNamespace("second"); - const secondOutcome = second.then( - () => null, - (err: { code?: string }) => err.code, - ); - const secondScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { - id: number; - }; - const third = manager.setPresenceNamespace("first"); - const thirdScope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { - id: number; - }; - mockWs.triggerMessage( - encodeToBuffer({ - type: "error", - id: secondScope.id, - code: "RATE_LIMITED", - message: "Too many requests", - }), - ); - await tick(); - - await new Promise((r) => setTimeout(r, 150)); - expect(mockWs.sentMessages.map(sentType)).toEqual([ - WireMessageType.StoreSetNamespace, - WireMessageType.PresenceSetNamespace, - WireMessageType.PresenceSetNamespace, - WireMessageType.PresenceSetNamespace, - ]); - - ack(mockWs, thirdScope.id); - await third; - expect(await firstOutcome).toBe("REQUEST_SUPERSEDED"); - expect(await secondOutcome).toBe("REQUEST_SUPERSEDED"); - expect(manager.getPresenceNamespace()).toBe("first"); - }); - test("a retry on a replacement socket requests the presence scope again", async () => { const { manager, mockWs } = makeManager({ reconnect: false, @@ -601,50 +427,6 @@ describe("ConnectionManager", () => { manager.disconnect(); }); - test("a presence write retry is rejected after a namespace switch", async () => { - const { manager, mockWs } = makeManager({ reconnectDelay: 10 }); - await connectManager(manager, mockWs); - const write = manager.dispatch({ type: "PresenceSet", data: {} }); - const outcome = write.then( - () => null, - (err: { code?: string }) => err.code, - ); - const scope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { - id: number; - }; - ack(mockWs, scope.id); - await tick(); - const attempt = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { - id: number; - }; - mockWs.triggerMessage( - encodeToBuffer({ - type: "error", - id: attempt.id, - code: "RATE_LIMITED", - message: "Too many requests", - retryAfter: 100, - }), - ); - await tick(); - - const switched = manager.setPresenceNamespace("other"); - const replacement = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { - id: number; - }; - ack(mockWs, replacement.id); - await switched; - await new Promise((r) => setTimeout(r, 150)); - - expect(await outcome).toBe("REQUEST_SUPERSEDED"); - expect(mockWs.sentMessages.map(sentType)).toEqual([ - WireMessageType.StoreSetNamespace, - WireMessageType.PresenceSetNamespace, - WireMessageType.PresenceSet, - WireMessageType.PresenceSetNamespace, - ]); - }); - test("a same-namespace call after disconnect fails with CONNECTION_FAILED", async () => { const { manager, mockWs } = makeManager(); await connectManager(manager, mockWs); diff --git a/sdk/typescript/src/connection.ts b/sdk/typescript/src/connection.ts index 0f8d8303..f7c003f8 100644 --- a/sdk/typescript/src/connection.ts +++ b/sdk/typescript/src/connection.ts @@ -141,13 +141,8 @@ export class ConnectionManager { private currentUserId: string | null = null; private presenceNamespace: string; /** The presence scope request of this socket; null until presence is first used. */ - private presenceScope: Promise | null = null; - private presenceScopeNamespace: string | null = null; + private presenceScopePromise: Promise | null = null; private presenceScopeReady = false; - private presenceScopeGeneration = 0; - private presenceConfirmedScope: Promise | null = null; - private presenceConfirmedNamespace: string | null = null; - private connectionGeneration = 0; private processingPromise: Promise = Promise.resolve(); @@ -207,27 +202,29 @@ export class ConnectionManager { getPresenceNamespace(): string { return this.presenceNamespace; } - getPresenceScopeTarget(): string { - return this.presenceScopeNamespace ?? this.presenceNamespace; - } - getPresenceScopeGeneration(): number { - return this.presenceScopeGeneration; - } - getConnectionGeneration(): number { - return this.connectionGeneration; + + isPresenceScopeReady(): boolean { + return this.presenceScopeReady; } - async ensurePresenceScope(): Promise { - if (this.currentStatus !== "connected") return; - const namespace = this.presenceScopeNamespace ?? this.presenceNamespace; - if (this.presenceScopeReady) { - if (this.presenceNamespace === namespace) return; - this.presenceScopeReady = false; - this.presenceScope = null; + + async ensurePresenceScope( + ns: string = this.presenceNamespace, + ): Promise { + if (this.currentStatus !== "connected") { + throw new ZyncBaseError("Connection is not ready", { + code: ErrorCodes.CONNECTION_FAILED, + category: "network", + retryable: true, + }); + } + if (this.presenceScopeReady && this.presenceNamespace === ns) { + return; + } + if (this.presenceScopePromise && this.presenceNamespace === ns) { + return this.presenceScopePromise; } - const scope = this.presenceScope ?? this.setPresenceNamespace(namespace); - await scope; - const current = this.presenceScopeNamespace ?? this.presenceNamespace; - if (current !== namespace) return this.ensurePresenceScope(); + + return this.setPresenceNamespace(ns); } /** @@ -237,49 +234,47 @@ export class ConnectionManager { setPresenceNamespace(ns: string): Promise { if ( this.currentStatus === "connected" && - this.presenceScope !== null && - this.presenceScopeNamespace === ns + this.presenceScopeReady && + this.presenceNamespace === ns ) { - return this.presenceScope; + return Promise.resolve(); + } + if (this.presenceScopePromise && this.presenceNamespace === ns) { + return this.presenceScopePromise; } - const generation = ++this.presenceScopeGeneration; + + const previousNs = this.presenceNamespace; + const previousReady = this.presenceScopeReady; this.presenceScopeReady = false; - this.presenceScopeNamespace = ns; + this.presenceNamespace = ns; + const scope: Promise = this.dispatchWithRetry( { type: "PresenceSetNamespace", namespace: ns }, 0, - undefined, - () => this.presenceScopeGeneration === generation, ) .then((ok) => { - if (this.presenceScope !== scope) { - throw this.supersededPresenceScopeError(); - } this.adoptUserId(ok, "PresenceSetNamespace"); - this.presenceNamespace = ns; this.presenceScopeReady = true; - this.presenceConfirmedScope = scope; - this.presenceConfirmedNamespace = ns; }) .catch((err: unknown) => { - if (this.presenceScope === scope) { - if (this.isNamespaceSwitchRejected(err)) { - this.presenceScope = this.presenceConfirmedScope; - this.presenceScopeNamespace = this.presenceConfirmedNamespace; - this.presenceScopeReady = - this.presenceConfirmedScope !== null && - this.presenceConfirmedNamespace !== null; - } else { - this.presenceScope = null; - this.presenceScopeNamespace = null; - this.presenceScopeReady = false; - this.presenceConfirmedScope = null; - this.presenceConfirmedNamespace = null; - } + 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.presenceScope = scope; + + this.presenceScopePromise = scope; return scope; } @@ -291,49 +286,14 @@ export class ConnectionManager { private withPresenceScope( msg: OutboundRequest, send: () => Promise, - namespace = this.presenceScopeNamespace ?? this.presenceNamespace, ): Promise { if (this.currentStatus !== "connected" || !this.needsPresenceScope(msg)) { return send(); } - const requested = this.presenceScopeNamespace ?? this.presenceNamespace; - if (requested !== namespace) { - return Promise.reject(this.supersededPresenceScopeError()); - } if (this.presenceScopeReady) { - if (this.presenceNamespace === namespace) return send(); - this.presenceScopeReady = false; - this.presenceScope = null; + return send(); } - const scope = this.presenceScope ?? this.setPresenceNamespace(namespace); - return scope.then( - () => this.withPresenceScope(msg, send, namespace), - (err) => { - const current = this.presenceScopeNamespace ?? this.presenceNamespace; - if (current !== namespace) { - throw this.supersededPresenceScopeError(); - } - if (this.presenceScope !== null && this.presenceScope !== scope) { - return this.withPresenceScope(msg, send, namespace); - } - throw err; - }, - ); - } - - private supersededPresenceScopeError(): ZyncBaseError { - return new ZyncBaseError("Presence namespace setup superseded", { - code: ErrorCodes.REQUEST_SUPERSEDED, - category: "state", - retryable: false, - }); - } - - private isNamespaceSwitchRejected(err: unknown): boolean { - return ( - err instanceof ZyncBaseError && - err.code === ErrorCodes.NAMESPACE_SWITCH_REJECTED - ); + return this.ensurePresenceScope().then(() => send()); } /** Presence messages, and action messages naming a presence-scoped action. */ @@ -435,13 +395,8 @@ export class ConnectionManager { this.intentionalDisconnect = false; this.pendingDisconnectError = null; this.currentUserId = null; - this.presenceScope = null; - this.presenceScopeNamespace = null; + this.presenceScopePromise = null; this.presenceScopeReady = false; - this.presenceScopeGeneration++; - this.presenceConfirmedScope = null; - this.presenceConfirmedNamespace = null; - this.connectionGeneration++; this.stopLiveness(); this.setStatus("connecting"); this.processingPromise = Promise.resolve(); @@ -646,36 +601,23 @@ export class ConnectionManager { msg: OutboundRequest, attempt: number, responseTableIndex?: number, - isCurrent?: () => boolean, - namespace?: string, ): Promise { - const target = - namespace ?? this.presenceScopeNamespace ?? this.presenceNamespace; - return this.withPresenceScope( - msg, - async () => { - if (isCurrent !== undefined && !isCurrent()) { - throw this.supersededPresenceScopeError(); - } - 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, - isCurrent, - target, - ); - } - }, - target, - ); + return this.withPresenceScope(msg, async () => { + 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, + ); + } + }); } private async handleRetryOrThrow( @@ -684,12 +626,7 @@ export class ConnectionManager { err: unknown, debugType: string, responseTableIndex?: number, - isCurrent?: () => boolean, - namespace?: string, ): Promise { - if (isCurrent !== undefined && !isCurrent()) { - throw this.supersededPresenceScopeError(); - } if (!this.retryPolicy.shouldRetry(err, attempt)) throw err; const delay = this.retryPolicy.getDelay(err, attempt); @@ -700,16 +637,7 @@ export class ConnectionManager { } await sleep(delay); if (this.intentionalDisconnect) throw err; - if (isCurrent !== undefined && !isCurrent()) { - throw this.supersededPresenceScopeError(); - } - return this.dispatchWithRetry( - msg, - attempt + 1, - responseTableIndex, - isCurrent, - namespace, - ); + return this.dispatchWithRetry(msg, attempt + 1, responseTableIndex); } authRefresh(token: string): Promise { @@ -732,7 +660,8 @@ export class ConnectionManager { disconnect(): void { this.intentionalDisconnect = true; - this.connectionGeneration++; + this.presenceScopePromise = null; + this.presenceScopeReady = false; this.currentUserId = null; this.stopLiveness(); if (this.reconnectTimer !== null) { diff --git a/sdk/typescript/src/presence.test.ts b/sdk/typescript/src/presence.test.ts index d05c1c73..5a50ae44 100644 --- a/sdk/typescript/src/presence.test.ts +++ b/sdk/typescript/src/presence.test.ts @@ -46,15 +46,6 @@ function createMockConnection() { on: () => {}, schemaDictionary: schema, userId: null as string | null, - presenceScopeTarget: "public", - presenceScopeGeneration: 0, - getPresenceScopeTarget() { - return this.presenceScopeTarget; - }, - getPresenceScopeGeneration() { - return this.presenceScopeGeneration; - }, - ensurePresenceScope: () => Promise.resolve(), dispatched, schema, fireBroadcast: (msg: PresenceBroadcast | SharedStateBroadcast) => { @@ -126,76 +117,6 @@ describe("PresenceImpl", () => { } }); - test("a namespace switch pauses queued sets and rejects old-namespace data", async () => { - const conn = createMockConnection(); - await setupSchema(conn.schema); - const presence = new PresenceImpl(conn); - presence.set({ status: "active" }); - const queued = presence.set({ status: "away" }); - const outcome = queued.then( - () => null, - (err: { code?: string }) => err.code, - ); - presence.beginNamespaceSwitch(); - conn.presenceScopeTarget = "other"; - conn.presenceScopeGeneration++; - await new Promise((resolve) => setTimeout(resolve, 20)); - expect( - conn.dispatched.filter((msg) => msg.type === "PresenceSet"), - ).toHaveLength(1); - presence.commitNamespaceSwitch(); - expect(await outcome).toBe("REQUEST_SUPERSEDED"); - expect( - conn.dispatched.filter((msg) => msg.type === "PresenceSet"), - ).toHaveLength(1); - }); - - test("a rejected namespace switch resumes queued sets in the old namespace", async () => { - const conn = createMockConnection(); - await setupSchema(conn.schema); - const presence = new PresenceImpl(conn); - presence.set({ status: "active" }); - const queued = presence.set({ status: "away" }); - presence.beginNamespaceSwitch(); - conn.presenceScopeTarget = "other"; - await new Promise((resolve) => setTimeout(resolve, 20)); - expect( - conn.dispatched.filter((msg) => msg.type === "PresenceSet"), - ).toHaveLength(1); - conn.presenceScopeTarget = "public"; - presence.rollbackNamespaceSwitch(); - await queued; - expect( - conn.dispatched.filter((msg) => msg.type === "PresenceSet"), - ).toHaveLength(2); - }); - - test("commit flushes batches queued for the acknowledged target", async () => { - const conn = createMockConnection(); - await setupSchema(conn.schema); - const presence = new PresenceImpl(conn); - presence.set({ status: "active" }); - const oldBatch = presence.set({ status: "old" }); - const oldOutcome = oldBatch.then( - () => null, - (err: { code?: string }) => err.code, - ); - presence.beginNamespaceSwitch(); - conn.presenceScopeTarget = "other"; - conn.presenceScopeGeneration++; - const newBatch = presence.set({ status: "new" }); - await new Promise((resolve) => setTimeout(resolve, 20)); - expect( - conn.dispatched.filter((msg) => msg.type === "PresenceSet"), - ).toHaveLength(1); - presence.commitNamespaceSwitch(); - await newBatch; - expect(await oldOutcome).toBe("REQUEST_SUPERSEDED"); - const sets = conn.dispatched.filter((msg) => msg.type === "PresenceSet"); - expect(sets).toHaveLength(2); - expect(sets.at(-1)?.data).toEqual([2, "new"]); - }); - test("setShared() dispatches PresenceSetShared with encoded data", async () => { const conn = createMockConnection(); await setupSchema(conn.schema); @@ -759,38 +680,6 @@ describe("PresenceImpl", () => { expect(presence.get(staleUserId)).toBeUndefined(); }); - test("stale subscription completion after a scope change skips unscoped unsubscribe", 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 unsubscribes = 0; - conn.dispatch = (msg: Record) => { - if (msg.type === "PresenceSubscribe") { - conn.presenceScopeGeneration++; - return stalePromise; - } - if (msg.type === "PresenceUnsubscribe") { - unsubscribes++; - } - return Promise.resolve({ type: "ok", id: 0 } as OkResponse); - }; - presence.subscribe(() => {}); - await new Promise((resolve) => setTimeout(resolve, 0)); - presence.invalidate(); - resolveStale({ - type: "ok", - id: 0, - subId: 100, - users: [], - } 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); @@ -808,49 +697,6 @@ describe("PresenceImpl", () => { expect(conn.dispatched.length).toBe(2); }); - test("subscription cleanup captures the epoch after the lazy scope setup", async () => { - const conn = createMockConnection(); - await setupSchema(conn.schema); - const presence = new PresenceImpl(conn); - let resolveReplay: (value: OkResponse) => void = () => {}; - const replayPromise = new Promise((resolve) => { - resolveReplay = resolve; - }); - let subscribeCall = 0; - let unsubscribes = 0; - conn.dispatch = (msg: Record) => { - if (msg.type === "PresenceSubscribe") { - subscribeCall++; - if (subscribeCall === 1) { - return Promise.resolve({ - type: "ok", - id: 0, - subId: 100, - users: [], - } as OkResponse); - } - return replayPromise; - } - if (msg.type === "PresenceUnsubscribe") unsubscribes++; - return Promise.resolve({ type: "ok", id: 0 } as OkResponse); - }; - const unsubscribe = await presence.subscribe(() => {}); - presence.invalidate(); - conn.ensurePresenceScope = async () => { - conn.presenceScopeGeneration++; - }; - const replaying = presence.replaySubscriptions(); - const closing = unsubscribe(); - resolveReplay({ - type: "ok", - id: 0, - subId: 200, - users: [], - } as OkResponse); - await replaying; - await closing; - expect(unsubscribes).toBe(1); - }); test("replaySubscriptions unsubscribes user if client unsubscribed before promise resolves", async () => { const conn = createMockConnection(); await setupSchema(conn.schema); diff --git a/sdk/typescript/src/presence.ts b/sdk/typescript/src/presence.ts index 1eae504f..c016c20a 100644 --- a/sdk/typescript/src/presence.ts +++ b/sdk/typescript/src/presence.ts @@ -17,11 +17,6 @@ interface SetWaiter { resolve: () => void; reject: (reason?: unknown) => void; } -interface PendingSetBatch { - data: Record; - waiters: SetWaiter[]; -} - export interface PresenceConnection { dispatch(msg: Record): Promise; onPresenceBroadcast( @@ -30,9 +25,6 @@ export interface PresenceConnection { on(event: LifecycleEvent, handler: (...args: unknown[]) => void): void; schemaDictionary: SchemaDictionary; readonly userId: string | null; - getPresenceScopeTarget(): string; - getPresenceScopeGeneration(): number; - ensurePresenceScope(): Promise; } export class PresenceImpl implements Presence { @@ -50,8 +42,8 @@ export class PresenceImpl implements Presence { (shared: Record | null) => void >(); private lastSetTime = 0; - private pendingSets = new Map(); - private switchPending = false; + private pendingSetData: Record | null = null; + private pendingSetWaiters: SetWaiter[] = []; private throttleTimer: ReturnType | null = null; private conn: PresenceConnection; private readonly emitError: (err: ZyncBaseError) => void; @@ -79,15 +71,7 @@ export class PresenceImpl implements Presence { reject = rej; }); accepted.catch(() => {}); - const namespace = this.conn.getPresenceScopeTarget(); - const batch = this.pendingSets.get(namespace) ?? { - data: {}, - waiters: [], - }; - batch.data = { ...batch.data, ...data }; - batch.waiters.push({ resolve, reject }); - this.pendingSets.set(namespace, batch); - if (this.switchPending) return accepted; + this.pendingSetWaiters.push({ resolve, reject }); const now = performance.now(); const elapsed = now - this.lastSetTime; @@ -97,12 +81,25 @@ export class PresenceImpl implements Presence { clearTimeout(this.throttleTimer); this.throttleTimer = null; } - this.flushPendingSets(); - } else if (this.throttleTimer === null) { - this.throttleTimer = setTimeout(() => { - this.throttleTimer = null; - this.flushPendingSets(); - }, THROTTLE_INTERVAL_MS - elapsed); + const pending = this.pendingSetData; + this.pendingSetData = null; + this.lastSetTime = now; + this.sendSet( + pending ? { ...pending, ...data } : data, + this.pendingSetWaiters.splice(0), + ); + } else { + this.pendingSetData = { ...(this.pendingSetData ?? {}), ...data }; + if (this.throttleTimer === null) { + this.throttleTimer = setTimeout(() => { + this.throttleTimer = null; + if (this.pendingSetData) { + this.lastSetTime = performance.now(); + this.sendSet(this.pendingSetData, this.pendingSetWaiters.splice(0)); + this.pendingSetData = null; + } + }, THROTTLE_INTERVAL_MS - elapsed); + } } return accepted; } @@ -113,52 +110,6 @@ export class PresenceImpl implements Presence { "Presence setShared failed", ); } - beginNamespaceSwitch(): void { - this.switchPending = true; - if (this.throttleTimer !== null) { - clearTimeout(this.throttleTimer); - this.throttleTimer = null; - } - } - commitNamespaceSwitch(): void { - this.switchPending = false; - const target = this.conn.getPresenceScopeTarget(); - const targetBatch = this.pendingSets.get(target); - if (targetBatch) this.pendingSets.delete(target); - this.invalidate(); - if (targetBatch) { - this.pendingSets.set(target, targetBatch); - this.flushPendingSets(); - } - } - rollbackNamespaceSwitch(): void { - this.switchPending = false; - const target = this.conn.getPresenceScopeTarget(); - const superseded = new ZyncBaseError( - "Presence set superseded by scope change", - { - code: ErrorCodes.REQUEST_SUPERSEDED, - category: "state", - retryable: false, - }, - ); - for (const [namespace, batch] of this.pendingSets) { - if (namespace === target) continue; - this.pendingSets.delete(namespace); - for (const waiter of batch.waiters) waiter.reject(superseded); - } - this.flushPendingSets(); - } - private flushPendingSets(): void { - if (this.switchPending || this.pendingSets.size === 0) return; - const target = this.conn.getPresenceScopeTarget(); - for (const [namespace, batch] of [...this.pendingSets]) { - if (namespace !== target) continue; - this.pendingSets.delete(namespace); - this.sendSet(batch.data, batch.waiters); - } - this.lastSetTime = performance.now(); - } private hasUserSubscribers(): boolean { return this.userCallbacks.size > 0; @@ -189,8 +140,6 @@ export class PresenceImpl implements Presence { private async establishUserSubscription(gen: number): Promise { while (gen === this.userSubGen) { - await this.conn.ensurePresenceScope(); - const epoch = this.conn.getPresenceScopeGeneration(); const ok = await this.conn.dispatch({ type: "PresenceSubscribe" }); if (ok.subId === undefined) { throw new ZyncBaseError("PresenceSubscribe response missing subId", { @@ -200,15 +149,10 @@ export class PresenceImpl implements Presence { }); } if (gen !== this.userSubGen || !this.hasUserSubscribers()) { - if ( - this.conn.getPresenceScopeGeneration() === epoch && - this.userSubId === null - ) { - await this.dispatchAccepted( - { type: "PresenceUnsubscribe", subId: ok.subId }, - "Presence unsubscribe failed", - ); - } + await this.dispatchAccepted( + { type: "PresenceUnsubscribe", subId: ok.subId }, + "Presence unsubscribe failed", + ); if (gen !== this.userSubGen || !this.hasUserSubscribers()) return; continue; } @@ -268,8 +212,6 @@ export class PresenceImpl implements Presence { private async establishSharedSubscription(gen: number): Promise { while (gen === this.sharedSubGen) { - await this.conn.ensurePresenceScope(); - const epoch = this.conn.getPresenceScopeGeneration(); const ok = await this.conn.dispatch({ type: "PresenceSubscribeShared" }); if (ok.subId === undefined) { throw new ZyncBaseError( @@ -282,15 +224,10 @@ export class PresenceImpl implements Presence { ); } if (!this.hasCurrentSharedSubscribers(gen)) { - if ( - this.conn.getPresenceScopeGeneration() === epoch && - this.sharedSubId === null - ) { - await this.dispatchAccepted( - { type: "PresenceUnsubscribeShared", subId: ok.subId }, - "Presence unsubscribeShared failed", - ); - } + await this.dispatchAccepted( + { type: "PresenceUnsubscribeShared", subId: ok.subId }, + "Presence unsubscribeShared failed", + ); if (!this.hasCurrentSharedSubscribers(gen)) return; continue; } @@ -471,7 +408,6 @@ export class PresenceImpl implements Presence { ): void { this.userSubGen++; this.sharedSubGen++; - this.switchPending = false; this.clearUserCache(); this.sharedCache = null; this.userSubId = null; @@ -678,13 +614,11 @@ export class PresenceImpl implements Presence { clearTimeout(this.throttleTimer); this.throttleTimer = null; } - const batches = [...this.pendingSets.values()]; - this.pendingSets.clear(); + this.pendingSetData = null; if (reason) { - for (const batch of batches) { - for (const waiter of batch.waiters) waiter.reject(reason); - } + for (const waiter of this.pendingSetWaiters) waiter.reject(reason); } + this.pendingSetWaiters = []; this.lastSetTime = 0; } } From a3618be992ab3dec8cc6827b020d95640058e2ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sun, 22 Nov 2026 00:59:55 +0100 Subject: [PATCH 09/17] Refactor presence namespace handling in ConnectionManager to ensure state consistency during rapid switches --- sdk/typescript/src/connection.test.ts | 44 +++++++++++++++++++++++++++ sdk/typescript/src/connection.ts | 24 +++++++++------ 2 files changed, 58 insertions(+), 10 deletions(-) diff --git a/sdk/typescript/src/connection.test.ts b/sdk/typescript/src/connection.test.ts index 7b1f4b8c..1809b95c 100644 --- a/sdk/typescript/src/connection.test.ts +++ b/sdk/typescript/src/connection.test.ts @@ -324,6 +324,50 @@ describe("ConnectionManager", () => { 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 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 Promise.all([first, second]); + + expect(manager.getPresenceNamespace()).toBe("room2"); + expect(manager.userId).toBe("019c1e50-7d11-7000-8000-000000000003"); + }); + test("a rejected presence switch keeps the previous namespace usable", async () => { const { manager, mockWs } = makeManager(); await connectManager(manager, mockWs); diff --git a/sdk/typescript/src/connection.ts b/sdk/typescript/src/connection.ts index f7c003f8..7dd81edf 100644 --- a/sdk/typescript/src/connection.ts +++ b/sdk/typescript/src/connection.ts @@ -253,18 +253,22 @@ export class ConnectionManager { 0, ) .then((ok) => { - this.adoptUserId(ok, "PresenceSetNamespace"); - this.presenceScopeReady = true; + if (this.presenceNamespace === ns) { + this.adoptUserId(ok, "PresenceSetNamespace"); + this.presenceScopeReady = true; + } }) .catch((err: unknown) => { - if ( - err instanceof ZyncBaseError && - err.code === ErrorCodes.NAMESPACE_SWITCH_REJECTED - ) { - this.presenceNamespace = previousNs; - this.presenceScopeReady = previousReady; - } else { - this.presenceScopeReady = false; + if (this.presenceNamespace === ns) { + if ( + err instanceof ZyncBaseError && + err.code === ErrorCodes.NAMESPACE_SWITCH_REJECTED + ) { + this.presenceNamespace = previousNs; + this.presenceScopeReady = previousReady; + } else { + this.presenceScopeReady = false; + } } throw err; }) From bf95e72cf8a1ca5080d2f2cb4ec1e35714b57b92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sun, 22 Nov 2026 01:20:07 +0100 Subject: [PATCH 10/17] Add tests for presence namespace switching and handle request superseding in ConnectionManager --- sdk/typescript/src/client.test.ts | 218 ++++++++++++++++++++++++++ sdk/typescript/src/client.ts | 39 ++++- sdk/typescript/src/connection.test.ts | 58 +++++++ sdk/typescript/src/connection.ts | 32 +++- sdk/typescript/src/presence.test.ts | 41 +++++ sdk/typescript/src/presence.ts | 10 +- 6 files changed, 386 insertions(+), 12 deletions(-) diff --git a/sdk/typescript/src/client.test.ts b/sdk/typescript/src/client.test.ts index 55562b5d..c4fd4b13 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -712,6 +712,224 @@ describe("ZyncBaseClient", () => { 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 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); diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts index be4c9f9c..824c376b 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"; @@ -229,12 +229,37 @@ export class ZyncBaseClient< return; } - await this.conn.setPresenceNamespace(namespace); - this.presenceImpl.invalidate(); - await this.presenceImpl.replaySubscriptions(); - const replay = this.actionsImpl.replayRegistrations(); - replay.store.catch(() => {}); - replay.presence.catch(() => {}); + this.presenceImpl.clearThrottle( + new ZyncBaseError("Presence set superseded by namespace switch", { + code: ErrorCodes.REQUEST_SUPERSEDED, + category: "state", + retryable: false, + }), + ); + + try { + await this.conn.setPresenceNamespace(namespace); + if (this.conn.getPresenceNamespace() !== namespace) { + return; + } + this.presenceImpl.invalidate(); + await this.presenceImpl.replaySubscriptions(); + const replay = this.actionsImpl.replayRegistrations(); + replay.store.catch(() => {}); + replay.presence.catch(() => {}); + } catch (err) { + 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; + } } /** diff --git a/sdk/typescript/src/connection.test.ts b/sdk/typescript/src/connection.test.ts index 1809b95c..f6bde04b 100644 --- a/sdk/typescript/src/connection.test.ts +++ b/sdk/typescript/src/connection.test.ts @@ -368,6 +368,64 @@ describe("ConnectionManager", () => { 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("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); diff --git a/sdk/typescript/src/connection.ts b/sdk/typescript/src/connection.ts index 7dd81edf..b63ee354 100644 --- a/sdk/typescript/src/connection.ts +++ b/sdk/typescript/src/connection.ts @@ -297,7 +297,17 @@ export class ConnectionManager { if (this.presenceScopeReady) { return send(); } - return this.ensurePresenceScope().then(() => send()); + const expectedNs = this.presenceNamespace; + return this.ensurePresenceScope().then(() => { + if (this.presenceNamespace !== expectedNs) { + throw new ZyncBaseError("Request was superseded by a newer operation", { + code: ErrorCodes.REQUEST_SUPERSEDED, + category: "state", + retryable: false, + }); + } + return send(); + }); } /** Presence messages, and action messages naming a presence-scoped action. */ @@ -631,6 +641,16 @@ export class ConnectionManager { debugType: string, responseTableIndex?: number, ): Promise { + if ( + msg.type === "PresenceSetNamespace" && + msg.namespace !== this.presenceNamespace + ) { + throw new ZyncBaseError("Request was superseded by a newer operation", { + code: ErrorCodes.REQUEST_SUPERSEDED, + category: "state", + retryable: false, + }); + } if (!this.retryPolicy.shouldRetry(err, attempt)) throw err; const delay = this.retryPolicy.getDelay(err, attempt); @@ -641,6 +661,16 @@ export class ConnectionManager { } await sleep(delay); if (this.intentionalDisconnect) throw err; + if ( + msg.type === "PresenceSetNamespace" && + msg.namespace !== this.presenceNamespace + ) { + throw new ZyncBaseError("Request was superseded by a newer operation", { + code: ErrorCodes.REQUEST_SUPERSEDED, + category: "state", + retryable: false, + }); + } return this.dispatchWithRetry(msg, attempt + 1, responseTableIndex); } diff --git a/sdk/typescript/src/presence.test.ts b/sdk/typescript/src/presence.test.ts index 5a50ae44..4f64a9ec 100644 --- a/sdk/typescript/src/presence.test.ts +++ b/sdk/typescript/src/presence.test.ts @@ -680,6 +680,47 @@ describe("PresenceImpl", () => { expect(presence.get(staleUserId)).toBeUndefined(); }); + 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("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 c016c20a..b8438695 100644 --- a/sdk/typescript/src/presence.ts +++ b/sdk/typescript/src/presence.ts @@ -148,13 +148,15 @@ export class PresenceImpl implements Presence { retryable: false, }); } - if (gen !== this.userSubGen || !this.hasUserSubscribers()) { + if (gen !== this.userSubGen) { + return; + } + if (!this.hasUserSubscribers()) { await this.dispatchAccepted( { type: "PresenceUnsubscribe", subId: ok.subId }, "Presence unsubscribe failed", ); - if (gen !== this.userSubGen || !this.hasUserSubscribers()) return; - continue; + return; } this.userSubId = ok.subId; this.populateUserCacheFromSnapshot(ok); @@ -609,7 +611,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; From 464208d1f1dd6ccd8b8d10c01e7d214837072ac7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sun, 22 Nov 2026 01:36:24 +0100 Subject: [PATCH 11/17] Add tests for handling namespace switch rejection and ensure queued presence sets are resumed --- sdk/typescript/src/client.test.ts | 117 ++++++++++++++++++++++++++ sdk/typescript/src/client.ts | 8 -- sdk/typescript/src/connection.test.ts | 57 ++++++++++++- sdk/typescript/src/connection.ts | 59 ++++++++++--- sdk/typescript/src/presence.test.ts | 39 +++++++++ sdk/typescript/src/presence.ts | 20 +++-- 6 files changed, 270 insertions(+), 30 deletions(-) diff --git a/sdk/typescript/src/client.test.ts b/sdk/typescript/src/client.test.ts index c4fd4b13..d72e3a2f 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -787,6 +787,123 @@ describe("ZyncBaseClient", () => { } }); + 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 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); diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts index 824c376b..1442aed1 100644 --- a/sdk/typescript/src/client.ts +++ b/sdk/typescript/src/client.ts @@ -229,14 +229,6 @@ export class ZyncBaseClient< return; } - this.presenceImpl.clearThrottle( - new ZyncBaseError("Presence set superseded by namespace switch", { - code: ErrorCodes.REQUEST_SUPERSEDED, - category: "state", - retryable: false, - }), - ); - try { await this.conn.setPresenceNamespace(namespace); if (this.conn.getPresenceNamespace() !== namespace) { diff --git a/sdk/typescript/src/connection.test.ts b/sdk/typescript/src/connection.test.ts index f6bde04b..a218dd7a 100644 --- a/sdk/typescript/src/connection.test.ts +++ b/sdk/typescript/src/connection.test.ts @@ -328,6 +328,7 @@ describe("ConnectionManager", () => { 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([ @@ -362,7 +363,8 @@ describe("ConnectionManager", () => { userId: packDocId("019c1e50-7d11-7000-8000-000000000003"), }), ); - await Promise.all([first, second]); + await second; + expect(await firstOutcome).toBe("REQUEST_SUPERSEDED"); expect(manager.getPresenceNamespace()).toBe("room2"); expect(manager.userId).toBe("019c1e50-7d11-7000-8000-000000000003"); @@ -396,12 +398,61 @@ describe("ConnectionManager", () => { 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) => 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 queued subscription is rejected when its scope is replaced", async () => { const { manager, mockWs } = makeManager(); await connectManager(manager, mockWs); diff --git a/sdk/typescript/src/connection.ts b/sdk/typescript/src/connection.ts index b63ee354..119f5f25 100644 --- a/sdk/typescript/src/connection.ts +++ b/sdk/typescript/src/connection.ts @@ -143,6 +143,7 @@ export class ConnectionManager { /** 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 processingPromise: Promise = Promise.resolve(); @@ -243,6 +244,7 @@ export class ConnectionManager { return this.presenceScopePromise; } + const gen = ++this.presenceScopeGen; const previousNs = this.presenceNamespace; const previousReady = this.presenceScopeReady; this.presenceScopeReady = false; @@ -251,15 +253,25 @@ export class ConnectionManager { const scope: Promise = this.dispatchWithRetry( { type: "PresenceSetNamespace", namespace: ns }, 0, + undefined, + gen, ) .then((ok) => { - if (this.presenceNamespace === ns) { - this.adoptUserId(ok, "PresenceSetNamespace"); - this.presenceScopeReady = true; + 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 (this.presenceNamespace === ns) { + if (gen === this.presenceScopeGen) { if ( err instanceof ZyncBaseError && err.code === ErrorCodes.NAMESPACE_SWITCH_REJECTED @@ -294,10 +306,13 @@ export class ConnectionManager { if (this.currentStatus !== "connected" || !this.needsPresenceScope(msg)) { return send(); } - if (this.presenceScopeReady) { + const expectedNs = + "targetNamespace" in msg && typeof msg.targetNamespace === "string" + ? msg.targetNamespace + : this.presenceNamespace; + if (this.presenceScopeReady && this.presenceNamespace === expectedNs) { return send(); } - const expectedNs = this.presenceNamespace; return this.ensurePresenceScope().then(() => { if (this.presenceNamespace !== expectedNs) { throw new ZyncBaseError("Request was superseded by a newer operation", { @@ -615,8 +630,19 @@ export class ConnectionManager { msg: OutboundRequest, attempt: number, responseTableIndex?: number, + expectedScopeGen?: number, ): Promise { return this.withPresenceScope(msg, async () => { + if ( + expectedScopeGen !== undefined && + expectedScopeGen !== this.presenceScopeGen + ) { + throw new ZyncBaseError("Request was superseded by a newer operation", { + code: ErrorCodes.REQUEST_SUPERSEDED, + category: "state", + retryable: false, + }); + } const { result, debugType } = this.sendRequest(msg, responseTableIndex); try { @@ -629,6 +655,7 @@ export class ConnectionManager { err, debugType, responseTableIndex, + expectedScopeGen, ); } }); @@ -640,10 +667,13 @@ export class ConnectionManager { err: unknown, debugType: string, responseTableIndex?: number, + expectedScopeGen?: number, ): Promise { if ( - msg.type === "PresenceSetNamespace" && - msg.namespace !== this.presenceNamespace + (expectedScopeGen !== undefined && + expectedScopeGen !== this.presenceScopeGen) || + (msg.type === "PresenceSetNamespace" && + msg.namespace !== this.presenceNamespace) ) { throw new ZyncBaseError("Request was superseded by a newer operation", { code: ErrorCodes.REQUEST_SUPERSEDED, @@ -662,8 +692,10 @@ export class ConnectionManager { await sleep(delay); if (this.intentionalDisconnect) throw err; if ( - msg.type === "PresenceSetNamespace" && - msg.namespace !== this.presenceNamespace + (expectedScopeGen !== undefined && + expectedScopeGen !== this.presenceScopeGen) || + (msg.type === "PresenceSetNamespace" && + msg.namespace !== this.presenceNamespace) ) { throw new ZyncBaseError("Request was superseded by a newer operation", { code: ErrorCodes.REQUEST_SUPERSEDED, @@ -671,7 +703,12 @@ export class ConnectionManager { retryable: false, }); } - return this.dispatchWithRetry(msg, attempt + 1, responseTableIndex); + return this.dispatchWithRetry( + msg, + attempt + 1, + responseTableIndex, + expectedScopeGen, + ); } authRefresh(token: string): Promise { diff --git a/sdk/typescript/src/presence.test.ts b/sdk/typescript/src/presence.test.ts index 4f64a9ec..5cd5190a 100644 --- a/sdk/typescript/src/presence.test.ts +++ b/sdk/typescript/src/presence.test.ts @@ -721,6 +721,45 @@ describe("PresenceImpl", () => { 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 b8438695..edefb197 100644 --- a/sdk/typescript/src/presence.ts +++ b/sdk/typescript/src/presence.ts @@ -25,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 { @@ -63,7 +64,10 @@ export class PresenceImpl implements Presence { return this.conn.userId; } + private pendingSetTargetNs: string | null = null; + set(data: Record): Promise { + this.pendingSetTargetNs = this.conn.getPresenceNamespace?.() ?? null; let resolve!: () => void; let reject!: (reason?: unknown) => void; const accepted = new Promise((res, rej) => { @@ -225,13 +229,15 @@ export class PresenceImpl implements Presence { }, ); } - if (!this.hasCurrentSharedSubscribers(gen)) { + if (gen !== this.sharedSubGen) { + return; + } + if (this.sharedCallbacks.size === 0) { await this.dispatchAccepted( { type: "PresenceUnsubscribeShared", subId: ok.subId }, "Presence unsubscribeShared failed", ); - if (!this.hasCurrentSharedSubscribers(gen)) return; - continue; + return; } this.sharedSubId = ok.subId; this.sharedCache = @@ -246,10 +252,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 && @@ -432,8 +434,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( () => { From 16490171984f7a4d70bd91c9b90f573412403aa8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sun, 22 Nov 2026 01:52:13 +0100 Subject: [PATCH 12/17] Enhance presence management by adding support for queued presence sets and handling namespace switch rejections --- sdk/typescript/src/client.test.ts | 102 +++++++++++++++++++-- sdk/typescript/src/connection.ts | 62 +++++++++---- sdk/typescript/src/connection_wire.test.ts | 15 +++ sdk/typescript/src/connection_wire.ts | 2 + sdk/typescript/src/presence.test.ts | 18 ++++ sdk/typescript/src/presence.ts | 19 +++- 6 files changed, 188 insertions(+), 30 deletions(-) diff --git a/sdk/typescript/src/client.test.ts b/sdk/typescript/src/client.test.ts index d72e3a2f..037220b5 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -761,9 +761,10 @@ describe("ZyncBaseClient", () => { ); 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 }; + const replacement = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; expect(replacement.type).toBe(WireMessageType.PresenceSetNamespace); mockWs.triggerMessage( encodeToBuffer({ @@ -867,6 +868,87 @@ describe("ZyncBaseClient", () => { } }); + 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); @@ -929,9 +1011,10 @@ describe("ZyncBaseClient", () => { }), ); await new Promise((r) => setTimeout(r, 0)); - const presenceSub = decode( - mockWs.sentMessages.at(-1) as Uint8Array, - ) as { id: number; type: number }; + const presenceSub = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; mockWs.triggerMessage( encodeToBuffer({ type: "ok", @@ -1002,9 +1085,10 @@ describe("ZyncBaseClient", () => { }), ); await new Promise((r) => setTimeout(r, 0)); - const presenceSub = decode( - mockWs.sentMessages.at(-1) as Uint8Array, - ) as { id: number; type: number }; + const presenceSub = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { + id: number; + type: number; + }; mockWs.triggerMessage( encodeToBuffer({ type: "ok", diff --git a/sdk/typescript/src/connection.ts b/sdk/typescript/src/connection.ts index 119f5f25..a44b0183 100644 --- a/sdk/typescript/src/connection.ts +++ b/sdk/typescript/src/connection.ts @@ -142,6 +142,7 @@ export class ConnectionManager { private presenceNamespace: string; /** The presence scope request of this socket; null until presence is first used. */ private presenceScopePromise: Promise | null = null; + private presenceScopeActivePromise: Promise | null = null; private presenceScopeReady = false; private presenceScopeGen = 0; @@ -208,24 +209,25 @@ export class ConnectionManager { return this.presenceScopeReady; } - async ensurePresenceScope( - ns: string = this.presenceNamespace, - ): Promise { + ensurePresenceScope(): Promise { if (this.currentStatus !== "connected") { - throw new ZyncBaseError("Connection is not ready", { - code: ErrorCodes.CONNECTION_FAILED, - category: "network", - retryable: true, - }); + return Promise.reject( + new ZyncBaseError("Connection is not ready", { + code: ErrorCodes.CONNECTION_FAILED, + category: "network", + retryable: true, + }), + ); } - if (this.presenceScopeReady && this.presenceNamespace === ns) { - return; + if (this.presenceScopeReady) { + return Promise.resolve(); } - if (this.presenceScopePromise && this.presenceNamespace === ns) { + if (this.presenceScopePromise) { return this.presenceScopePromise; } - return this.setPresenceNamespace(ns); + this.setPresenceNamespace(this.presenceNamespace); + return this.presenceScopePromise ?? Promise.resolve(); } /** @@ -240,8 +242,8 @@ export class ConnectionManager { ) { return Promise.resolve(); } - if (this.presenceScopePromise && this.presenceNamespace === ns) { - return this.presenceScopePromise; + if (this.presenceScopeActivePromise && this.presenceNamespace === ns) { + return this.presenceScopeActivePromise; } const gen = ++this.presenceScopeGen; @@ -283,14 +285,32 @@ export class ConnectionManager { } } throw err; - }) - .finally(() => { - if (this.presenceScopePromise === scope) { - this.presenceScopePromise = null; - } }); - this.presenceScopePromise = scope; + const scopeWaiter = scope.catch((err: unknown) => { + if ( + err instanceof ZyncBaseError && + err.code === ErrorCodes.NAMESPACE_SWITCH_REJECTED && + this.presenceScopeReady + ) { + return; + } + throw err; + }); + scopeWaiter.catch(() => {}); + + const cleanup = () => { + if (this.presenceScopeActivePromise === scope) { + this.presenceScopeActivePromise = null; + } + if (this.presenceScopePromise === scopeWaiter) { + this.presenceScopePromise = null; + } + }; + scope.then(cleanup, cleanup); + + this.presenceScopeActivePromise = scope; + this.presenceScopePromise = scopeWaiter; return scope; } @@ -425,6 +445,7 @@ export class ConnectionManager { this.pendingDisconnectError = null; this.currentUserId = null; this.presenceScopePromise = null; + this.presenceScopeActivePromise = null; this.presenceScopeReady = false; this.stopLiveness(); this.setStatus("connecting"); @@ -732,6 +753,7 @@ export class ConnectionManager { disconnect(): void { this.intentionalDisconnect = true; this.presenceScopePromise = null; + this.presenceScopeActivePromise = null; this.presenceScopeReady = false; this.currentUserId = null; this.stopLiveness(); 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/presence.test.ts b/sdk/typescript/src/presence.test.ts index 5cd5190a..ee213a9f 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); diff --git a/sdk/typescript/src/presence.ts b/sdk/typescript/src/presence.ts index edefb197..92d84a02 100644 --- a/sdk/typescript/src/presence.ts +++ b/sdk/typescript/src/presence.ts @@ -67,7 +67,24 @@ export class PresenceImpl implements Presence { private pendingSetTargetNs: string | null = null; set(data: Record): Promise { - this.pendingSetTargetNs = this.conn.getPresenceNamespace?.() ?? null; + 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) => { From 60186644af2d3883cc0b484c0180bb99577843e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sun, 22 Nov 2026 01:58:11 +0100 Subject: [PATCH 13/17] Add tests for concurrent presence namespace switches and ensure old setups do not survive reconnects --- sdk/typescript/src/client.test.ts | 80 +++++++++++++++++++++++++++ sdk/typescript/src/client.ts | 23 +++++--- sdk/typescript/src/connection.test.ts | 42 ++++++++++++++ sdk/typescript/src/connection.ts | 2 + 4 files changed, 138 insertions(+), 9 deletions(-) diff --git a/sdk/typescript/src/client.test.ts b/sdk/typescript/src/client.test.ts index 037220b5..b2b44856 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -1244,6 +1244,86 @@ describe("ZyncBaseClient", () => { 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; + const first = client.setPresenceNamespace("room"); + first.catch(() => {}); + const second = client.setPresenceNamespace("room"); + second.catch(() => {}); + 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); + mockWs.triggerMessage( + encodeToBuffer({ + type: "ok", + id: replays[0].id, + subId: 31, + users: [], + }), + ); + await Promise.all([first, second]); + } 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 1442aed1..55779f31 100644 --- a/sdk/typescript/src/client.ts +++ b/sdk/typescript/src/client.ts @@ -48,6 +48,7 @@ export class ZyncBaseClient< >(); /** Whether a connection existed earlier in this process. */ private hasConnectedOnce = false; + private presenceSwitchGeneration = 0; /** Backoff state for retrying a failed restore. */ private restoreAttempt = 0; private restoreTimer: ReturnType | null = null; @@ -229,8 +230,10 @@ export class ZyncBaseClient< return; } + const switchGeneration = ++this.presenceSwitchGeneration; try { await this.conn.setPresenceNamespace(namespace); + if (this.presenceSwitchGeneration !== switchGeneration) return; if (this.conn.getPresenceNamespace() !== namespace) { return; } @@ -240,15 +243,17 @@ export class ZyncBaseClient< replay.store.catch(() => {}); replay.presence.catch(() => {}); } catch (err) { - 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(); + 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; } diff --git a/sdk/typescript/src/connection.test.ts b/sdk/typescript/src/connection.test.ts index a218dd7a..9e21f816 100644 --- a/sdk/typescript/src/connection.test.ts +++ b/sdk/typescript/src/connection.test.ts @@ -308,6 +308,48 @@ describe("ConnectionManager", () => { 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"); + first.catch(() => {}); + 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; + }; + 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.PresenceSetNamespace, + ), + ).toBe(false); + manager.disconnect(); + }); + test("a same-namespace call joins a pending scope request", async () => { const { manager, mockWs } = makeManager(); await connectManager(manager, mockWs); diff --git a/sdk/typescript/src/connection.ts b/sdk/typescript/src/connection.ts index a44b0183..1af40d53 100644 --- a/sdk/typescript/src/connection.ts +++ b/sdk/typescript/src/connection.ts @@ -447,6 +447,7 @@ export class ConnectionManager { this.presenceScopePromise = null; this.presenceScopeActivePromise = null; this.presenceScopeReady = false; + this.presenceScopeGen++; this.stopLiveness(); this.setStatus("connecting"); this.processingPromise = Promise.resolve(); @@ -755,6 +756,7 @@ export class ConnectionManager { this.presenceScopePromise = null; this.presenceScopeActivePromise = null; this.presenceScopeReady = false; + this.presenceScopeGen++; this.currentUserId = null; this.stopLiveness(); if (this.reconnectTimer !== null) { From 7a08f6c0128dd89e115a43146ad8f631bdceb6d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sun, 22 Nov 2026 02:28:22 +0100 Subject: [PATCH 14/17] Enhance presence management by adding automatic retry for dispatch requests and improving user subscription handling --- sdk/typescript/src/actions.ts | 7 +- sdk/typescript/src/client.test.ts | 95 ++++++++++++++ sdk/typescript/src/client.ts | 27 +++- sdk/typescript/src/connection.test.ts | 46 +++++++ sdk/typescript/src/connection.ts | 178 +++++++++++--------------- sdk/typescript/src/presence.test.ts | 62 +++++++++ sdk/typescript/src/presence.ts | 31 ++++- 7 files changed, 337 insertions(+), 109 deletions(-) diff --git a/sdk/typescript/src/actions.ts b/sdk/typescript/src/actions.ts index eaacfecf..c86092c7 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). */ @@ -127,7 +129,10 @@ export class ActionsImpl implements Actions { 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, }); diff --git a/sdk/typescript/src/client.test.ts b/sdk/typescript/src/client.test.ts index b2b44856..ae5bb79c 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -553,6 +553,101 @@ describe("ZyncBaseClient", () => { restoreWebSocket(); }); + test("a retryable store action replay blocks synced until it recovers", async () => { + installMockWebSocket(); + const client = createClient(defaultOptions); + 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, + ), + 1_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, + 1_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 rejected presence switch preserves active presence consumers", async () => { installMockWebSocket(); const client = createClient({ diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts index 55779f31..5575092c 100644 --- a/sdk/typescript/src/client.ts +++ b/sdk/typescript/src/client.ts @@ -329,7 +329,32 @@ export class ZyncBaseClient< ]); await this.conn.awaitSchemaSync(); const actions = this.actionsImpl.replayRegistrations(); - await Promise.allSettled([actions.store, actions.presence]); + 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" && + storeActions.status !== "rejected" + ) { + throw error; + } + } if (presence.status === "rejected") { const error = toZyncError(presence.reason, "Restore failed", false); if (!error.retryable || store.status === "rejected") { diff --git a/sdk/typescript/src/connection.test.ts b/sdk/typescript/src/connection.test.ts index 9e21f816..928d544a 100644 --- a/sdk/typescript/src/connection.test.ts +++ b/sdk/typescript/src/connection.test.ts @@ -495,6 +495,52 @@ describe("ConnectionManager", () => { 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); diff --git a/sdk/typescript/src/connection.ts b/sdk/typescript/src/connection.ts index 1af40d53..ec6c18c1 100644 --- a/sdk/typescript/src/connection.ts +++ b/sdk/typescript/src/connection.ts @@ -142,7 +142,6 @@ export class ConnectionManager { private presenceNamespace: string; /** The presence scope request of this socket; null until presence is first used. */ private presenceScopePromise: Promise | null = null; - private presenceScopeActivePromise: Promise | null = null; private presenceScopeReady = false; private presenceScopeGen = 0; @@ -209,27 +208,6 @@ export class ConnectionManager { return this.presenceScopeReady; } - ensurePresenceScope(): Promise { - if (this.currentStatus !== "connected") { - return Promise.reject( - new ZyncBaseError("Connection is not ready", { - code: ErrorCodes.CONNECTION_FAILED, - category: "network", - retryable: true, - }), - ); - } - if (this.presenceScopeReady) { - return Promise.resolve(); - } - if (this.presenceScopePromise) { - return this.presenceScopePromise; - } - - this.setPresenceNamespace(this.presenceNamespace); - return this.presenceScopePromise ?? Promise.resolve(); - } - /** * Establish the presence scope in `ns`, or switch it there. Presence * messages sent meanwhile wait for it. @@ -242,8 +220,8 @@ export class ConnectionManager { ) { return Promise.resolve(); } - if (this.presenceScopeActivePromise && this.presenceNamespace === ns) { - return this.presenceScopeActivePromise; + if (this.presenceScopePromise && this.presenceNamespace === ns) { + return this.presenceScopePromise; } const gen = ++this.presenceScopeGen; @@ -285,32 +263,13 @@ export class ConnectionManager { } } throw err; + }) + .finally(() => { + if (this.presenceScopePromise === scope) { + this.presenceScopePromise = null; + } }); - - const scopeWaiter = scope.catch((err: unknown) => { - if ( - err instanceof ZyncBaseError && - err.code === ErrorCodes.NAMESPACE_SWITCH_REJECTED && - this.presenceScopeReady - ) { - return; - } - throw err; - }); - scopeWaiter.catch(() => {}); - - const cleanup = () => { - if (this.presenceScopeActivePromise === scope) { - this.presenceScopeActivePromise = null; - } - if (this.presenceScopePromise === scopeWaiter) { - this.presenceScopePromise = null; - } - }; - scope.then(cleanup, cleanup); - - this.presenceScopeActivePromise = scope; - this.presenceScopePromise = scopeWaiter; + this.presenceScopePromise = scope; return scope; } @@ -322,26 +281,38 @@ export class ConnectionManager { 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 expectedNs = - "targetNamespace" in msg && typeof msg.targetNamespace === "string" - ? msg.targetNamespace - : this.presenceNamespace; - if (this.presenceScopeReady && this.presenceNamespace === expectedNs) { - 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; + }, + ); } - return this.ensurePresenceScope().then(() => { - if (this.presenceNamespace !== expectedNs) { - throw new ZyncBaseError("Request was superseded by a newer operation", { - code: ErrorCodes.REQUEST_SUPERSEDED, - category: "state", - retryable: false, - }); - } - return send(); + 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, }); } @@ -445,7 +416,6 @@ export class ConnectionManager { this.pendingDisconnectError = null; this.currentUserId = null; this.presenceScopePromise = null; - this.presenceScopeActivePromise = null; this.presenceScopeReady = false; this.presenceScopeGen++; this.stopLiveness(); @@ -653,34 +623,43 @@ export class ConnectionManager { attempt: number, responseTableIndex?: number, expectedScopeGen?: number, + targetNamespace?: string, ): Promise { - return this.withPresenceScope(msg, async () => { - if ( - expectedScopeGen !== undefined && - expectedScopeGen !== this.presenceScopeGen - ) { - throw new ZyncBaseError("Request was superseded by a newer operation", { - code: ErrorCodes.REQUEST_SUPERSEDED, - category: "state", - retryable: false, - }); - } - 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, - expectedScopeGen, - ); - } - }); + const target = + targetNamespace ?? + ("targetNamespace" in msg && typeof msg.targetNamespace === "string" + ? msg.targetNamespace + : this.presenceNamespace); + return this.withPresenceScope( + msg, + async () => { + 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, + ); + } + }, + target, + ); } private async handleRetryOrThrow( @@ -690,6 +669,7 @@ export class ConnectionManager { debugType: string, responseTableIndex?: number, expectedScopeGen?: number, + targetNamespace?: string, ): Promise { if ( (expectedScopeGen !== undefined && @@ -697,11 +677,7 @@ export class ConnectionManager { (msg.type === "PresenceSetNamespace" && msg.namespace !== this.presenceNamespace) ) { - throw new ZyncBaseError("Request was superseded by a newer operation", { - code: ErrorCodes.REQUEST_SUPERSEDED, - category: "state", - retryable: false, - }); + throw this.supersededError(); } if (!this.retryPolicy.shouldRetry(err, attempt)) throw err; @@ -719,17 +695,14 @@ export class ConnectionManager { (msg.type === "PresenceSetNamespace" && msg.namespace !== this.presenceNamespace) ) { - throw new ZyncBaseError("Request was superseded by a newer operation", { - code: ErrorCodes.REQUEST_SUPERSEDED, - category: "state", - retryable: false, - }); + throw this.supersededError(); } return this.dispatchWithRetry( msg, attempt + 1, responseTableIndex, expectedScopeGen, + targetNamespace, ); } @@ -754,7 +727,6 @@ export class ConnectionManager { disconnect(): void { this.intentionalDisconnect = true; this.presenceScopePromise = null; - this.presenceScopeActivePromise = null; this.presenceScopeReady = false; this.presenceScopeGen++; this.currentUserId = null; diff --git a/sdk/typescript/src/presence.test.ts b/sdk/typescript/src/presence.test.ts index ee213a9f..6b8f6f61 100644 --- a/sdk/typescript/src/presence.test.ts +++ b/sdk/typescript/src/presence.test.ts @@ -698,6 +698,68 @@ 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(() => {}); + resolveUnsubscribe({ type: "ok", id: 0 } as OkResponse); + await replaying; + await next; + + expect(subscribeCalls).toBe(3); + }); test("a stale subscription completion does not unsubscribe a replacement", async () => { const conn = createMockConnection(); await setupSchema(conn.schema); diff --git a/sdk/typescript/src/presence.ts b/sdk/typescript/src/presence.ts index 92d84a02..616432ce 100644 --- a/sdk/typescript/src/presence.ts +++ b/sdk/typescript/src/presence.ts @@ -35,6 +35,7 @@ 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 userSubGen = 0; private sharedSubGen = 0; @@ -126,8 +127,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", ); } @@ -138,7 +140,16 @@ 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) { + return this.userSubPromise.then(() => { + if (this.userSubId === null && this.hasUserSubscribers()) { + return this.ensureUserSubscription(); + } + }); + } + if (this.userCleanupPromise !== null) { + return this.userCleanupPromise.then(() => this.ensureUserSubscription()); + } const gen = this.userSubGen; const pending = this.establishUserSubscription(gen).catch((err) => { const error = toZyncError(err, "Presence subscribe failed"); @@ -173,10 +184,16 @@ export class PresenceImpl implements Presence { return; } if (!this.hasUserSubscribers()) { - await this.dispatchAccepted( + const unsub = this.dispatchAccepted( { type: "PresenceUnsubscribe", subId: ok.subId }, "Presence unsubscribe failed", ); + this.userCleanupPromise = unsub; + const clear = () => { + if (this.userCleanupPromise === unsub) this.userCleanupPromise = null; + }; + unsub.then(clear, clear); + await unsub; return; } this.userSubId = ok.subId; @@ -200,10 +217,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; } From 45d4b7cfe5a1116f1533fa798dd852d07f55401e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sun, 22 Nov 2026 02:31:07 +0100 Subject: [PATCH 15/17] Refactor presence management to ensure shared subscription cleanup and improve subscription handling during stale unsubscribe scenarios --- sdk/typescript/src/client.ts | 16 ++++----- sdk/typescript/src/presence.test.ts | 55 +++++++++++++++++++++++++++++ sdk/typescript/src/presence.ts | 34 ++++++++++++++++-- 3 files changed, 93 insertions(+), 12 deletions(-) diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts index 5575092c..6f785ed5 100644 --- a/sdk/typescript/src/client.ts +++ b/sdk/typescript/src/client.ts @@ -233,15 +233,6 @@ export class ZyncBaseClient< const switchGeneration = ++this.presenceSwitchGeneration; try { await this.conn.setPresenceNamespace(namespace); - if (this.presenceSwitchGeneration !== switchGeneration) return; - if (this.conn.getPresenceNamespace() !== namespace) { - return; - } - this.presenceImpl.invalidate(); - await this.presenceImpl.replaySubscriptions(); - const replay = this.actionsImpl.replayRegistrations(); - replay.store.catch(() => {}); - replay.presence.catch(() => {}); } catch (err) { if (this.presenceSwitchGeneration === switchGeneration) { if ( @@ -257,6 +248,13 @@ export class ZyncBaseClient< } throw err; } + if (this.presenceSwitchGeneration !== switchGeneration) return; + if (this.conn.getPresenceNamespace() !== namespace) return; + this.presenceImpl.invalidate(); + await this.presenceImpl.replaySubscriptions(); + const replay = this.actionsImpl.replayRegistrations(); + replay.store.catch(() => {}); + replay.presence.catch(() => {}); } /** diff --git a/sdk/typescript/src/presence.test.ts b/sdk/typescript/src/presence.test.ts index 6b8f6f61..83e46c23 100644 --- a/sdk/typescript/src/presence.test.ts +++ b/sdk/typescript/src/presence.test.ts @@ -760,6 +760,61 @@ describe("PresenceImpl", () => { 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(() => {}); + resolveUnsubscribe({ type: "ok", id: 0 } as OkResponse); + await replaying; + await next; + + expect(subscribeCalls).toBe(3); + }); test("a stale subscription completion does not unsubscribe a replacement", async () => { const conn = createMockConnection(); await setupSchema(conn.schema); diff --git a/sdk/typescript/src/presence.ts b/sdk/typescript/src/presence.ts index 616432ce..1a501bba 100644 --- a/sdk/typescript/src/presence.ts +++ b/sdk/typescript/src/presence.ts @@ -37,6 +37,7 @@ export class PresenceImpl implements Presence { 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>(); @@ -235,7 +236,18 @@ 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) { + return this.sharedSubPromise.then(() => { + if (this.sharedSubId === null && this.sharedCallbacks.size > 0) { + return this.ensureSharedSubscription(); + } + }); + } + if (this.sharedCleanupPromise !== null) { + return this.sharedCleanupPromise.then(() => + this.ensureSharedSubscription(), + ); + } const gen = this.sharedSubGen; const pending = this.establishSharedSubscription(gen).catch((err) => { const error = toZyncError(err, "Presence subscribeShared failed"); @@ -273,10 +285,18 @@ export class PresenceImpl implements Presence { return; } if (this.sharedCallbacks.size === 0) { - await this.dispatchAccepted( + const unsub = this.dispatchAccepted( { type: "PresenceUnsubscribeShared", subId: ok.subId }, "Presence unsubscribeShared failed", ); + this.sharedCleanupPromise = unsub; + const clear = () => { + if (this.sharedCleanupPromise === unsub) { + this.sharedCleanupPromise = null; + } + }; + unsub.then(clear, clear); + await unsub; return; } this.sharedSubId = ok.subId; @@ -301,10 +321,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; } From 1480b7f4c34456d257332941ff5734b6974db53d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sun, 22 Nov 2026 02:36:16 +0100 Subject: [PATCH 16/17] Adjust retryable store action test to disable retry rate limits and extend timeout durations --- sdk/typescript/src/client.test.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/sdk/typescript/src/client.test.ts b/sdk/typescript/src/client.test.ts index ae5bb79c..46d618ce 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -555,7 +555,10 @@ describe("ZyncBaseClient", () => { test("a retryable store action replay blocks synced until it recovers", async () => { installMockWebSocket(); - const client = createClient(defaultOptions); + const client = createClient({ + ...defaultOptions, + retryRateLimits: false, + }); try { const synced: string[] = []; client.on("synced", () => synced.push("synced")); @@ -610,7 +613,7 @@ describe("ZyncBaseClient", () => { (decode(message) as { type: number }).type === WireMessageType.ActionRegister, ), - 1_000, + 2_000, ); const failed = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { id: number; @@ -635,7 +638,7 @@ describe("ZyncBaseClient", () => { (decode(message) as { type: number }).type === WireMessageType.ActionRegister, ).length >= 2, - 1_000, + 2_000, ); const retried = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { id: number; From 3614da81842ed2a4bcc532e7f17d081066f25420 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Dokumac=C4=B1?= Date: Sun, 22 Nov 2026 02:51:48 +0100 Subject: [PATCH 17/17] Enhance presence management and error handling for retryable actions, including tests for subscription behavior during failures --- sdk/typescript/src/actions.test.ts | 22 +++ sdk/typescript/src/actions.ts | 5 +- sdk/typescript/src/client.test.ts | 193 +++++++++++++++++++++++++- sdk/typescript/src/client.ts | 28 +++- sdk/typescript/src/connection.test.ts | 44 +++--- sdk/typescript/src/connection.ts | 24 ++++ sdk/typescript/src/presence.test.ts | 143 +++++++++++++++++++ sdk/typescript/src/presence.ts | 20 ++- 8 files changed, 442 insertions(+), 37 deletions(-) diff --git a/sdk/typescript/src/actions.test.ts b/sdk/typescript/src/actions.test.ts index 18f687ae..4bfe6430 100644 --- a/sdk/typescript/src/actions.test.ts +++ b/sdk/typescript/src/actions.test.ts @@ -404,4 +404,26 @@ describe("ActionsImpl.handle", () => { 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 c86092c7..7a4ee5bc 100644 --- a/sdk/typescript/src/actions.ts +++ b/sdk/typescript/src/actions.ts @@ -137,7 +137,10 @@ export class ActionsImpl implements Actions { 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 46d618ce..9ddbad22 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -651,6 +651,175 @@ describe("ZyncBaseClient", () => { 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({ @@ -1381,10 +1550,26 @@ describe("ZyncBaseClient", () => { await pendingPresence; const marker = mockWs.sentMessages.length; + let firstSettled = false; + let secondSettled = false; const first = client.setPresenceNamespace("room"); - first.catch(() => {}); + first.then( + () => { + firstSettled = true; + }, + () => { + firstSettled = true; + }, + ); const second = client.setPresenceNamespace("room"); - second.catch(() => {}); + 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; @@ -1407,6 +1592,8 @@ describe("ZyncBaseClient", () => { (message) => message.type === WireMessageType.PresenceSubscribe, ); expect(replays).toHaveLength(1); + expect(firstSettled).toBe(false); + expect(secondSettled).toBe(false); mockWs.triggerMessage( encodeToBuffer({ type: "ok", @@ -1416,6 +1603,8 @@ describe("ZyncBaseClient", () => { }), ); await Promise.all([first, second]); + expect(firstSettled).toBe(true); + expect(secondSettled).toBe(true); } finally { client.disconnect(); restoreWebSocket(); diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts index 6f785ed5..82735ea0 100644 --- a/sdk/typescript/src/client.ts +++ b/sdk/typescript/src/client.ts @@ -49,6 +49,10 @@ 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; @@ -224,12 +228,26 @@ 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 && this.conn.isPresenceScopeReady()) { - return; + 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); @@ -345,11 +363,7 @@ export class ZyncBaseClient< "Presence action registration failed", false, ); - if ( - error.retryable && - store.status !== "rejected" && - storeActions.status !== "rejected" - ) { + if (error.retryable && store.status !== "rejected") { throw error; } } diff --git a/sdk/typescript/src/connection.test.ts b/sdk/typescript/src/connection.test.ts index 928d544a..bdc4c991 100644 --- a/sdk/typescript/src/connection.test.ts +++ b/sdk/typescript/src/connection.test.ts @@ -312,7 +312,10 @@ describe("ConnectionManager", () => { const { manager, mockWs } = makeManager(); await connectManager(manager, mockWs); const first = manager.setPresenceNamespace("public"); - first.catch(() => {}); + const outcome = first.then( + () => null, + (err: { code?: string }) => err.code, + ); const scope = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { id: number; }; @@ -334,8 +337,6 @@ describe("ConnectionManager", () => { const store = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { id: number; }; - ack(mockWs, store.id); - await reconnected; const marker = mockWs.sentMessages.length; await new Promise((r) => setTimeout(r, 150)); @@ -347,6 +348,9 @@ describe("ConnectionManager", () => { (message) => message.type === WireMessageType.PresenceSetNamespace, ), ).toBe(false); + expect(await outcome).toBe("REQUEST_SUPERSEDED"); + ack(mockWs, store.id); + await reconnected; manager.disconnect(); }); @@ -603,13 +607,17 @@ describe("ConnectionManager", () => { expect(manager.getPresenceNamespace()).toBe("public"); }); - test("a retry on a replacement socket requests the presence scope again", async () => { + 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; }; @@ -647,24 +655,20 @@ describe("ConnectionManager", () => { ); ack(mockWs, store.id); await reconnected; + const marker = mockWs.sentMessages.length; await new Promise((r) => setTimeout(r, 150)); - const setup = decode(mockWs.sentMessages.at(-1) as Uint8Array) as { - id: number; - }; - expect(sentType(mockWs.sentMessages.at(-1) as Uint8Array)).toBe( - WireMessageType.PresenceSetNamespace, - ); - ack(mockWs, setup.id); - await tick(); - const retried = 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: retried.id })); - await presence; + 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(); }); diff --git a/sdk/typescript/src/connection.ts b/sdk/typescript/src/connection.ts index ec6c18c1..b9304fa3 100644 --- a/sdk/typescript/src/connection.ts +++ b/sdk/typescript/src/connection.ts @@ -144,6 +144,7 @@ export class ConnectionManager { private presenceScopePromise: Promise | null = null; private presenceScopeReady = false; private presenceScopeGen = 0; + private connectionGeneration = 0; private processingPromise: Promise = Promise.resolve(); @@ -369,6 +370,7 @@ export class ConnectionManager { } private teardownSocket(): void { + this.connectionGeneration++; this.currentUserId = null; if (this.ws) { const ws = this.ws; @@ -418,6 +420,7 @@ export class ConnectionManager { this.presenceScopePromise = null; this.presenceScopeReady = false; this.presenceScopeGen++; + this.connectionGeneration++; this.stopLiveness(); this.setStatus("connecting"); this.processingPromise = Promise.resolve(); @@ -624,15 +627,27 @@ export class ConnectionManager { responseTableIndex?: number, expectedScopeGen?: number, targetNamespace?: string, + sessionGeneration?: number, ): Promise { 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" @@ -655,6 +670,7 @@ export class ConnectionManager { responseTableIndex, scopeGen, target, + session, ); } }, @@ -670,10 +686,13 @@ export class ConnectionManager { 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) ) { @@ -692,6 +711,8 @@ export class ConnectionManager { if ( (expectedScopeGen !== undefined && expectedScopeGen !== this.presenceScopeGen) || + (sessionGeneration !== undefined && + sessionGeneration !== this.connectionGeneration) || (msg.type === "PresenceSetNamespace" && msg.namespace !== this.presenceNamespace) ) { @@ -703,6 +724,7 @@ export class ConnectionManager { responseTableIndex, expectedScopeGen, targetNamespace, + sessionGeneration, ); } @@ -729,6 +751,7 @@ export class ConnectionManager { this.presenceScopePromise = null; this.presenceScopeReady = false; this.presenceScopeGen++; + this.connectionGeneration++; this.currentUserId = null; this.stopLiveness(); if (this.reconnectTimer !== null) { @@ -793,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/presence.test.ts b/sdk/typescript/src/presence.test.ts index 83e46c23..edf7b359 100644 --- a/sdk/typescript/src/presence.test.ts +++ b/sdk/typescript/src/presence.test.ts @@ -754,6 +754,7 @@ describe("PresenceImpl", () => { const next = presence.subscribe(() => {}); next.catch(() => {}); + expect(subscribeCalls).toBe(2); resolveUnsubscribe({ type: "ok", id: 0 } as OkResponse); await replaying; await next; @@ -809,12 +810,154 @@ describe("PresenceImpl", () => { 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); diff --git a/sdk/typescript/src/presence.ts b/sdk/typescript/src/presence.ts index 1a501bba..29724a81 100644 --- a/sdk/typescript/src/presence.ts +++ b/sdk/typescript/src/presence.ts @@ -142,14 +142,18 @@ export class PresenceImpl implements Presence { private ensureUserSubscription(): Promise { if (this.userSubId !== null) return Promise.resolve(); if (this.userSubPromise !== null) { - return this.userSubPromise.then(() => { + 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()); + return this.userCleanupPromise.then( + () => this.ensureUserSubscription(), + () => this.ensureUserSubscription(), + ); } const gen = this.userSubGen; const pending = this.establishUserSubscription(gen).catch((err) => { @@ -237,15 +241,17 @@ export class PresenceImpl implements Presence { private ensureSharedSubscription(): Promise { if (this.sharedSubId !== null) return Promise.resolve(); if (this.sharedSubPromise !== null) { - return this.sharedSubPromise.then(() => { + 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(), + return this.sharedCleanupPromise.then( + () => this.ensureSharedSubscription(), + () => this.ensureSharedSubscription(), ); } const gen = this.sharedSubGen;