@terreno/syncdb 56.0.0-beta.2 → 57.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/README.md +33 -0
  2. package/dist/client.d.ts +5 -0
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +64 -1
  5. package/dist/client.js.map +1 -1
  6. package/dist/client.test.js +73 -1
  7. package/dist/client.test.js.map +1 -1
  8. package/dist/codegen/cli.d.ts +3 -0
  9. package/dist/codegen/cli.d.ts.map +1 -0
  10. package/dist/codegen/cli.js +47 -0
  11. package/dist/codegen/cli.js.map +1 -0
  12. package/dist/codegen/cli.test.d.ts +2 -0
  13. package/dist/codegen/cli.test.d.ts.map +1 -0
  14. package/dist/codegen/cli.test.js +54 -0
  15. package/dist/codegen/cli.test.js.map +1 -0
  16. package/dist/codegen/discoverCollections.d.ts +6 -0
  17. package/dist/codegen/discoverCollections.d.ts.map +1 -0
  18. package/dist/codegen/discoverCollections.js +111 -0
  19. package/dist/codegen/discoverCollections.js.map +1 -0
  20. package/dist/codegen/emitSdk.d.ts +12 -0
  21. package/dist/codegen/emitSdk.d.ts.map +1 -0
  22. package/dist/codegen/emitSdk.js +94 -0
  23. package/dist/codegen/emitSdk.js.map +1 -0
  24. package/dist/codegen/emitTypes.d.ts +6 -0
  25. package/dist/codegen/emitTypes.d.ts.map +1 -0
  26. package/dist/codegen/emitTypes.js +43 -0
  27. package/dist/codegen/emitTypes.js.map +1 -0
  28. package/dist/codegen/generate.d.ts +5 -0
  29. package/dist/codegen/generate.d.ts.map +1 -0
  30. package/dist/codegen/generate.js +47 -0
  31. package/dist/codegen/generate.js.map +1 -0
  32. package/dist/codegen/generate.test.d.ts +2 -0
  33. package/dist/codegen/generate.test.d.ts.map +1 -0
  34. package/dist/codegen/generate.test.js +192 -0
  35. package/dist/codegen/generate.test.js.map +1 -0
  36. package/dist/codegen/hookNames.d.ts +17 -0
  37. package/dist/codegen/hookNames.d.ts.map +1 -0
  38. package/dist/codegen/hookNames.js +27 -0
  39. package/dist/codegen/hookNames.js.map +1 -0
  40. package/dist/codegen/loadSpec.d.ts +3 -0
  41. package/dist/codegen/loadSpec.d.ts.map +1 -0
  42. package/dist/codegen/loadSpec.js +16 -0
  43. package/dist/codegen/loadSpec.js.map +1 -0
  44. package/dist/codegen/safeIdentifiers.d.ts +7 -0
  45. package/dist/codegen/safeIdentifiers.d.ts.map +1 -0
  46. package/dist/codegen/safeIdentifiers.js +15 -0
  47. package/dist/codegen/safeIdentifiers.js.map +1 -0
  48. package/dist/codegen/safeIdentifiers.test.d.ts +2 -0
  49. package/dist/codegen/safeIdentifiers.test.d.ts.map +1 -0
  50. package/dist/codegen/safeIdentifiers.test.js +25 -0
  51. package/dist/codegen/safeIdentifiers.test.js.map +1 -0
  52. package/dist/codegen/types.d.ts +69 -0
  53. package/dist/codegen/types.d.ts.map +1 -0
  54. package/dist/codegen/types.js +2 -0
  55. package/dist/codegen/types.js.map +1 -0
  56. package/dist/crypto/keyProviders.test.js +2 -2
  57. package/dist/crypto/keyProviders.test.js.map +1 -1
  58. package/dist/index.d.ts +1 -1
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js.map +1 -1
  61. package/dist/maxAttempts.d.ts +7 -0
  62. package/dist/maxAttempts.d.ts.map +1 -0
  63. package/dist/maxAttempts.js +15 -0
  64. package/dist/maxAttempts.js.map +1 -0
  65. package/dist/mutations/outbox.d.ts +5 -0
  66. package/dist/mutations/outbox.d.ts.map +1 -1
  67. package/dist/mutations/outbox.js +10 -2
  68. package/dist/mutations/outbox.js.map +1 -1
  69. package/dist/mutations/outbox.test.js +36 -0
  70. package/dist/mutations/outbox.test.js.map +1 -1
  71. package/dist/react/collectionHooks.d.ts +43 -0
  72. package/dist/react/collectionHooks.d.ts.map +1 -0
  73. package/dist/react/collectionHooks.js +51 -0
  74. package/dist/react/collectionHooks.js.map +1 -0
  75. package/dist/react/collectionHooks.test.d.ts +2 -0
  76. package/dist/react/collectionHooks.test.d.ts.map +1 -0
  77. package/dist/react/collectionHooks.test.js +150 -0
  78. package/dist/react/collectionHooks.test.js.map +1 -0
  79. package/dist/react/hooks.d.ts +4 -0
  80. package/dist/react/hooks.d.ts.map +1 -1
  81. package/dist/react/hooks.js +20 -3
  82. package/dist/react/hooks.js.map +1 -1
  83. package/dist/react/hooks.test.js +8 -4
  84. package/dist/react/hooks.test.js.map +1 -1
  85. package/dist/react/index.d.ts +1 -0
  86. package/dist/react/index.d.ts.map +1 -1
  87. package/dist/react/index.js +1 -0
  88. package/dist/react/index.js.map +1 -1
  89. package/dist/storage/idb.test.js +3 -1
  90. package/dist/storage/idb.test.js.map +1 -1
  91. package/dist/storage/schema.d.ts.map +1 -1
  92. package/dist/storage/schema.js +1 -0
  93. package/dist/storage/schema.js.map +1 -1
  94. package/dist/storage/types.d.ts +2 -0
  95. package/dist/storage/types.d.ts.map +1 -1
  96. package/dist/sync/replayCoordinator.d.ts.map +1 -1
  97. package/dist/sync/replayCoordinator.js +4 -2
  98. package/dist/sync/replayCoordinator.js.map +1 -1
  99. package/dist/sync/replayCoordinator.test.js +52 -1
  100. package/dist/sync/replayCoordinator.test.js.map +1 -1
  101. package/dist/sync/socketTransport.d.ts +9 -2
  102. package/dist/sync/socketTransport.d.ts.map +1 -1
  103. package/dist/sync/socketTransport.js +21 -3
  104. package/dist/sync/socketTransport.js.map +1 -1
  105. package/dist/sync/socketTransport.test.js +50 -2
  106. package/dist/sync/socketTransport.test.js.map +1 -1
  107. package/dist/sync/transport.d.ts +7 -1
  108. package/dist/sync/transport.d.ts.map +1 -1
  109. package/dist/sync/transport.js.map +1 -1
  110. package/dist/testing/fakeTransport.d.ts +3 -1
  111. package/dist/testing/fakeTransport.d.ts.map +1 -1
  112. package/dist/testing/fakeTransport.js +12 -0
  113. package/dist/testing/fakeTransport.js.map +1 -1
  114. package/dist/types.d.ts +17 -0
  115. package/dist/types.d.ts.map +1 -1
  116. package/package.json +8 -3
  117. package/src/client.test.ts +88 -1
  118. package/src/client.ts +74 -0
  119. package/src/codegen/cli.test.ts +61 -0
  120. package/src/codegen/cli.ts +52 -0
  121. package/src/codegen/discoverCollections.ts +159 -0
  122. package/src/codegen/emitSdk.ts +113 -0
  123. package/src/codegen/emitTypes.ts +46 -0
  124. package/src/codegen/fixtures/openapi.example.json +94 -0
  125. package/src/codegen/generate.test.ts +216 -0
  126. package/src/codegen/generate.ts +52 -0
  127. package/src/codegen/hookNames.ts +41 -0
  128. package/src/codegen/loadSpec.ts +18 -0
  129. package/src/codegen/safeIdentifiers.test.ts +32 -0
  130. package/src/codegen/safeIdentifiers.ts +17 -0
  131. package/src/codegen/types.ts +70 -0
  132. package/src/crypto/keyProviders.test.ts +2 -2
  133. package/src/index.ts +1 -0
  134. package/src/maxAttempts.ts +14 -0
  135. package/src/mutations/outbox.test.ts +39 -0
  136. package/src/mutations/outbox.ts +15 -2
  137. package/src/react/collectionHooks.test.tsx +189 -0
  138. package/src/react/collectionHooks.ts +103 -0
  139. package/src/react/hooks.test.tsx +8 -4
  140. package/src/react/hooks.ts +40 -9
  141. package/src/react/index.ts +1 -0
  142. package/src/storage/idb.test.ts +3 -1
  143. package/src/storage/schema.ts +1 -0
  144. package/src/storage/types.ts +2 -0
  145. package/src/sync/replayCoordinator.test.ts +61 -0
  146. package/src/sync/replayCoordinator.ts +4 -2
  147. package/src/sync/socketTransport.test.ts +53 -2
  148. package/src/sync/socketTransport.ts +29 -2
  149. package/src/sync/transport.ts +7 -0
  150. package/src/testing/fakeTransport.ts +15 -0
  151. package/src/types.ts +18 -0
@@ -252,11 +252,17 @@ export const useEntityIds = <TData = Record<string, unknown>>(
252
252
 
253
253
  export interface UseMutateResult {
254
254
  /** Optimistically create an entity; returns the generated ids. */
255
- create: (args: {data: Record<string, unknown>}) => {mutationId: string; id: string};
255
+ create: (args: {data: Record<string, unknown>; id?: string; maxAttempts?: number}) => {
256
+ mutationId: string;
257
+ id: string;
258
+ };
256
259
  /** Optimistically merge fields into an existing entity. */
257
- update: (args: {id: string; data: Record<string, unknown>}) => {mutationId: string; id: string};
260
+ update: (args: {id: string; data: Record<string, unknown>; maxAttempts?: number}) => {
261
+ mutationId: string;
262
+ id: string;
263
+ };
258
264
  /** Optimistically soft-delete an entity. */
259
- remove: (args: {id: string}) => {mutationId: string; id: string};
265
+ remove: (args: {id: string; maxAttempts?: number}) => {mutationId: string; id: string};
260
266
  }
261
267
 
262
268
  /**
@@ -267,20 +273,45 @@ export const useMutate = (collection: string): UseMutateResult => {
267
273
  const client = useSyncDbClient();
268
274
 
269
275
  const create = useCallback(
270
- (args: {data: Record<string, unknown>}): {mutationId: string; id: string} =>
271
- client.mutate({collection, data: args.data, operation: "create"}),
276
+ (args: {
277
+ data: Record<string, unknown>;
278
+ id?: string;
279
+ maxAttempts?: number;
280
+ }): {mutationId: string; id: string} =>
281
+ client.mutate({
282
+ collection,
283
+ data: args.data,
284
+ ...(args.id !== undefined ? {id: args.id} : {}),
285
+ ...(args.maxAttempts !== undefined ? {maxAttempts: args.maxAttempts} : {}),
286
+ operation: "create",
287
+ }),
272
288
  [client, collection]
273
289
  );
274
290
 
275
291
  const update = useCallback(
276
- (args: {id: string; data: Record<string, unknown>}): {mutationId: string; id: string} =>
277
- client.mutate({collection, data: args.data, id: args.id, operation: "update"}),
292
+ (args: {
293
+ id: string;
294
+ data: Record<string, unknown>;
295
+ maxAttempts?: number;
296
+ }): {mutationId: string; id: string} =>
297
+ client.mutate({
298
+ collection,
299
+ data: args.data,
300
+ id: args.id,
301
+ maxAttempts: args.maxAttempts,
302
+ operation: "update",
303
+ }),
278
304
  [client, collection]
279
305
  );
280
306
 
281
307
  const remove = useCallback(
282
- (args: {id: string}): {mutationId: string; id: string} =>
283
- client.mutate({collection, id: args.id, operation: "delete"}),
308
+ (args: {id: string; maxAttempts?: number}): {mutationId: string; id: string} =>
309
+ client.mutate({
310
+ collection,
311
+ id: args.id,
312
+ maxAttempts: args.maxAttempts,
313
+ operation: "delete",
314
+ }),
284
315
  [client, collection]
285
316
  );
286
317
 
@@ -7,5 +7,6 @@
7
7
  * main entry means non-React (node/backend) consumers never load React.
8
8
  */
9
9
 
10
+ export * from "./collectionHooks";
10
11
  export * from "./hooks";
11
12
  export * from "./provider";
@@ -9,12 +9,14 @@ const uniqueDbName = (): string => `idb-test-${Date.now()}-${dbCounter++}`;
9
9
 
10
10
  const withoutIndexedDb = async (run: () => Promise<void>): Promise<void> => {
11
11
  const original = globalThis.indexedDB;
12
+ // noExplicitAny: deliberately unsetting a global for the failure-path test
12
13
  // biome-ignore lint/suspicious/noExplicitAny: deliberately unsetting a global for the failure-path test
13
14
  (globalThis as any).indexedDB = undefined;
14
15
  try {
15
16
  await run();
16
17
  } finally {
17
- // biome-ignore lint/suspicious/noExplicitAny: restoring the global
18
+ // noExplicitAny: restoring the global after the failure-path test
19
+ // biome-ignore lint/suspicious/noExplicitAny: restoring the global after the failure-path test
18
20
  (globalThis as any).indexedDB = original;
19
21
  }
20
22
  };
@@ -83,6 +83,7 @@ export const buildTablesSchema = ({collections}: {collections: string[]}): Table
83
83
  enqueueOrder: {type: "number"},
84
84
  entityId: {type: "string"},
85
85
  errorNackCount: {type: "number"},
86
+ maxAttempts: {type: "number"},
86
87
  operation: {type: "string"},
87
88
  status: {type: "string"},
88
89
  userId: {type: "string"},
@@ -86,6 +86,8 @@ export interface OutboxRow {
86
86
  * (`MAX_ERROR_NACK_ATTEMPTS`) is checked against this, not `attemptCount`.
87
87
  */
88
88
  errorNackCount: number;
89
+ /** Per-mutation error-nack budget; absent cell → engine default in replay. */
90
+ maxAttempts?: number;
89
91
  /** Absent when the mutation carries no base version (e.g. creates). */
90
92
  baseVersion?: number;
91
93
  collection: string;
@@ -119,6 +119,7 @@ const enqueue = (
119
119
  mutationId,
120
120
  data = {title: entityId},
121
121
  baseVersion,
122
+ maxAttempts,
122
123
  operation = "create" as const,
123
124
  userId = USER,
124
125
  }: {
@@ -127,6 +128,7 @@ const enqueue = (
127
128
  mutationId: string;
128
129
  data?: Record<string, unknown>;
129
130
  baseVersion?: number;
131
+ maxAttempts?: number;
130
132
  operation?: "create" | "update" | "delete";
131
133
  userId?: string;
132
134
  }
@@ -143,6 +145,7 @@ const enqueue = (
143
145
  baseVersion,
144
146
  collection,
145
147
  entityId,
148
+ ...(maxAttempts !== undefined ? {maxAttempts} : {}),
146
149
  mutationId,
147
150
  operation,
148
151
  userId,
@@ -575,6 +578,35 @@ describe("createReplayCoordinator", () => {
575
578
  expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("acked");
576
579
  });
577
580
 
581
+ it("fails terminally after one error nack when maxAttempts is 1", async () => {
582
+ const harness = makeHarness();
583
+ enqueue(harness, {entityId: "t1", maxAttempts: 1, mutationId: "m1"});
584
+ harness.transport.setDefaultResponder((request) => ({
585
+ nack: {code: "error", mutationId: request.mutationId},
586
+ type: "nack",
587
+ }));
588
+
589
+ await harness.coordinator.replay({userId: USER});
590
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("failed");
591
+ expect(harness.transport.sentMutations).toHaveLength(1);
592
+ });
593
+
594
+ it("fails terminally after three error nacks when maxAttempts is 3", async () => {
595
+ const harness = makeHarness();
596
+ enqueue(harness, {entityId: "t1", maxAttempts: 3, mutationId: "m1"});
597
+ harness.transport.setDefaultResponder((request) => ({
598
+ nack: {code: "error", mutationId: request.mutationId},
599
+ type: "nack",
600
+ }));
601
+
602
+ for (let attempt = 1; attempt <= 3; attempt += 1) {
603
+ await harness.coordinator.replay({userId: USER});
604
+ harness.clock.value += ERROR_NACK_BASE_BACKOFF_MS * 2 ** attempt;
605
+ }
606
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("failed");
607
+ expect(harness.transport.sentMutations).toHaveLength(3);
608
+ });
609
+
578
610
  it(`marks failed after ${MAX_ERROR_NACK_ATTEMPTS} error-nack attempts`, async () => {
579
611
  const harness = makeHarness();
580
612
  enqueue(harness, {entityId: "t1", mutationId: "m1"});
@@ -600,6 +632,35 @@ describe("createReplayCoordinator", () => {
600
632
  expect(harness.transport.sentMutations).toHaveLength(MAX_ERROR_NACK_ATTEMPTS);
601
633
  });
602
634
 
635
+ it("marks failed after one error-nack when maxAttempts is 1", async () => {
636
+ const harness = makeHarness();
637
+ enqueue(harness, {entityId: "t1", maxAttempts: 1, mutationId: "m1"});
638
+ harness.transport.setDefaultResponder((request) => ({
639
+ nack: {code: "error", mutationId: request.mutationId},
640
+ type: "nack",
641
+ }));
642
+
643
+ await harness.coordinator.replay({userId: USER});
644
+ expect(harness.transport.sentMutations).toHaveLength(1);
645
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("failed");
646
+ });
647
+
648
+ it("marks failed after three error-nack attempts when maxAttempts is 3", async () => {
649
+ const harness = makeHarness();
650
+ enqueue(harness, {entityId: "t1", maxAttempts: 3, mutationId: "m1"});
651
+ harness.transport.setDefaultResponder((request) => ({
652
+ nack: {code: "error", mutationId: request.mutationId},
653
+ type: "nack",
654
+ }));
655
+
656
+ for (let attempt = 1; attempt <= 3; attempt += 1) {
657
+ await harness.coordinator.replay({userId: USER});
658
+ harness.clock.value += ERROR_NACK_BASE_BACKOFF_MS * 2 ** attempt;
659
+ }
660
+ expect(harness.transport.sentMutations).toHaveLength(3);
661
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("failed");
662
+ });
663
+
603
664
  it("a concurrent replay for the same user returns the in-flight promise", async () => {
604
665
  const harness = makeHarness();
605
666
  enqueue(harness, {entityId: "t1", mutationId: "m1"});
@@ -702,9 +702,11 @@ export const createReplayCoordinator = ({
702
702
  };
703
703
 
704
704
  const applyErrorNack = (mutation: OutboxMutation): OutcomeDecision => {
705
- const beforeCount = outbox.getMutation({mutationId: mutation.mutationId})?.errorNackCount ?? 0;
705
+ const stored = outbox.getMutation({mutationId: mutation.mutationId});
706
+ const maxAttempts = stored?.maxAttempts ?? MAX_ERROR_NACK_ATTEMPTS;
707
+ const beforeCount = stored?.errorNackCount ?? 0;
706
708
  const attempts = beforeCount + 1;
707
- if (attempts >= MAX_ERROR_NACK_ATTEMPTS) {
709
+ if (attempts >= maxAttempts) {
708
710
  handleTerminalFailure(mutation, "error");
709
711
  return {authPaused: false, haltDrain: false, progressed: false};
710
712
  }
@@ -74,6 +74,16 @@ const startServer = async (): Promise<TestServer> => {
74
74
  return server;
75
75
  };
76
76
 
77
+ const waitUntil = async (predicate: () => boolean, timeoutMs = 500): Promise<void> => {
78
+ const startedAt = Date.now();
79
+ while (!predicate()) {
80
+ if (Date.now() - startedAt > timeoutMs) {
81
+ throw new Error("waitUntil timed out");
82
+ }
83
+ await new Promise((resolve) => setTimeout(resolve, 10));
84
+ }
85
+ };
86
+
77
87
  describe("createSocketTransport", () => {
78
88
  let server: TestServer;
79
89
  let transport: SyncTransport | undefined;
@@ -90,6 +100,9 @@ describe("createSocketTransport", () => {
90
100
  baseUrl: server.baseUrl,
91
101
  batchUnsupportedGraceMs,
92
102
  timeoutMs,
103
+ // Websocket-only: polling→websocket upgrade emits disconnect and
104
+ // flakes the timeout test on GitHub runners.
105
+ transports: ["websocket"],
93
106
  });
94
107
  return transport;
95
108
  };
@@ -134,15 +147,53 @@ describe("createSocketTransport", () => {
134
147
  // Subscribed before connect: sent once the connection opens.
135
148
  subscriber.subscribe(["todos"]);
136
149
  await subscriber.connect();
137
- await new Promise((resolve) => setTimeout(resolve, 20));
150
+ await waitUntil(() => server.subscribes.length === 1);
138
151
  expect(server.subscribes).toEqual([{collections: ["todos"]}]);
139
152
 
140
153
  // Subscribed while connected: sent immediately.
141
154
  subscriber.subscribe(["notes"]);
142
- await new Promise((resolve) => setTimeout(resolve, 20));
155
+ await waitUntil(() => server.subscribes.length === 2);
143
156
  expect(server.subscribes).toEqual([{collections: ["todos"]}, {collections: ["notes"]}]);
144
157
  });
145
158
 
159
+ it("reports sync:subscribed confirmations to onSubscribed listeners", async () => {
160
+ server.io.removeAllListeners("connection");
161
+ server.io.on("connection", (socket) => {
162
+ socket.on("sync:subscribe", (payload: {collections: string[]}) => {
163
+ for (const collection of payload.collections) {
164
+ socket.emit("sync:subscribed", {collection, streams: [`${collection}|owner:u1`]});
165
+ }
166
+ });
167
+ });
168
+ const subscriber = makeTransport();
169
+ const confirmations: {collection: string; streams: string[]}[] = [];
170
+ subscriber.onSubscribed?.((subscribed) => confirmations.push(subscribed));
171
+ subscriber.subscribe(["todos"]);
172
+ await subscriber.connect();
173
+ await waitUntil(() => confirmations.length === 1);
174
+ expect(confirmations).toEqual([{collection: "todos", streams: ["todos|owner:u1"]}]);
175
+ });
176
+
177
+ it("ignores malformed sync:subscribed payloads", async () => {
178
+ server.io.removeAllListeners("connection");
179
+ server.io.on("connection", (socket) => {
180
+ socket.on("sync:subscribe", () => {
181
+ socket.emit("sync:subscribed", {collection: "todos"});
182
+ socket.emit("sync:subscribed", {streams: ["todos|owner:u1"]});
183
+ socket.emit("sync:subscribed", {collection: "todos", streams: [1, "todos|owner:u1"]});
184
+ });
185
+ });
186
+ const subscriber = makeTransport();
187
+ const confirmations: {collection: string; streams: string[]}[] = [];
188
+ subscriber.onSubscribed?.((subscribed) => confirmations.push(subscribed));
189
+ subscriber.subscribe(["todos"]);
190
+ await subscriber.connect();
191
+ await waitUntil(() => confirmations.length === 1);
192
+ // Only the third payload is well-formed enough to deliver, with the non-string
193
+ // stream dropped rather than passed through to the store.
194
+ expect(confirmations).toEqual([{collection: "todos", streams: ["todos|owner:u1"]}]);
195
+ });
196
+
146
197
  it("resolves sendMutation from an emitted sync:ack", async () => {
147
198
  server.mutateHandler = (request, socket) => {
148
199
  const ack: SyncAck = {id: request.id ?? "x", mutationId: request.mutationId, seq: 3};
@@ -7,6 +7,7 @@ import type {
7
7
  SyncMutateBatchRequest,
8
8
  SyncMutateRequest,
9
9
  SyncNack,
10
+ SyncSubscribed,
10
11
  } from "../types";
11
12
  import {
12
13
  DEFAULT_MUTATION_TIMEOUT_MS,
@@ -48,6 +49,11 @@ export interface SocketTransportConfig {
48
49
  timeoutMs?: number;
49
50
  /** Grace period before a batch send is treated as unsupported (default 2s). */
50
51
  batchUnsupportedGraceMs?: number;
52
+ /**
53
+ * Socket.io transports. Default polling then websocket so a restarting
54
+ * dev server does not fail the first handshake.
55
+ */
56
+ transports?: string[];
51
57
  }
52
58
 
53
59
  interface PendingMutation {
@@ -64,7 +70,9 @@ interface PendingMutation {
64
70
  * - server replies with `sync:ack` / `sync:nack` events **and** a Socket.io
65
71
  * ack callback carrying `{ack}` / `{nack}` — replies are correlated by
66
72
  * `mutationId` and the first to arrive settles the pending promise;
67
- * - server pushes `sync:delta` events for subscribed streams.
73
+ * - server replies to a subscribe with `sync:subscribed {collection, streams}` once
74
+ * the socket has actually joined the stream rooms, and pushes `sync:delta` events
75
+ * for those streams from then on.
68
76
  *
69
77
  * The handshake token is resolved via `authProvider.getToken()` inside the
70
78
  * Socket.io `auth` callback, which runs on **every** connection attempt — the
@@ -83,8 +91,10 @@ export const createSocketTransport = ({
83
91
  authProvider,
84
92
  timeoutMs = DEFAULT_MUTATION_TIMEOUT_MS,
85
93
  batchUnsupportedGraceMs = BATCH_UNSUPPORTED_GRACE_MS,
94
+ transports = ["polling", "websocket"],
86
95
  }: SocketTransportConfig): SyncTransport => {
87
96
  const deltaListeners = new Set<(delta: SyncDelta) => void>();
97
+ const subscribedListeners = new Set<(subscribed: SyncSubscribed) => void>();
88
98
  const statusListeners = new Set<(status: TransportStatus) => void>();
89
99
  const pending = new Map<string, PendingMutation>();
90
100
  const pendingBatches = new Map<
@@ -118,7 +128,7 @@ export const createSocketTransport = ({
118
128
  reconnection: true,
119
129
  // Start with polling so dev server restarts don't fail the initial
120
130
  // websocket-only handshake; Socket.io upgrades once connected.
121
- transports: ["polling", "websocket"],
131
+ transports,
122
132
  });
123
133
 
124
134
  const settle = (mutationId: string, result: SendMutationResult): void => {
@@ -167,6 +177,17 @@ export const createSocketTransport = ({
167
177
  listener(delta);
168
178
  }
169
179
  });
180
+ socket.on("sync:subscribed", (payload: {collection?: unknown; streams?: unknown}) => {
181
+ if (typeof payload?.collection !== "string" || !Array.isArray(payload.streams)) {
182
+ return;
183
+ }
184
+ const streams = payload.streams.filter(
185
+ (stream: unknown): stream is string => typeof stream === "string"
186
+ );
187
+ for (const listener of subscribedListeners) {
188
+ listener({collection: payload.collection, streams});
189
+ }
190
+ });
170
191
  socket.on("sync:ack", (ack: SyncAck) => {
171
192
  settle(ack.mutationId, {ack, type: "ack"});
172
193
  });
@@ -372,6 +393,12 @@ export const createSocketTransport = ({
372
393
  statusListeners.delete(callback);
373
394
  };
374
395
  },
396
+ onSubscribed: (callback: (subscribed: SyncSubscribed) => void): (() => void) => {
397
+ subscribedListeners.add(callback);
398
+ return () => {
399
+ subscribedListeners.delete(callback);
400
+ };
401
+ },
375
402
  sendMutation,
376
403
  sendMutationBatch,
377
404
  subscribe,
@@ -4,6 +4,7 @@ import type {
4
4
  SyncMutateBatchRequest,
5
5
  SyncMutateRequest,
6
6
  SyncNack,
7
+ SyncSubscribed,
7
8
  } from "../types";
8
9
 
9
10
  /** Default time to wait for a mutation ack/nack before rejecting. */
@@ -71,6 +72,12 @@ export interface SyncTransport {
71
72
  sendMutationBatch?: (request: SyncMutateBatchRequest) => Promise<SendMutationBatchResult>;
72
73
  /** Subscribe to inbound `sync:delta` events. Returns an unsubscribe function. */
73
74
  onDelta: (callback: (delta: SyncDelta) => void) => () => void;
75
+ /**
76
+ * Subscribe to the server's `sync:subscribed` confirmations. Returns an unsubscribe
77
+ * function. Optional so transports without a subscription handshake (HTTP-only
78
+ * doubles) satisfy the contract; callers must treat its absence as "never confirmed".
79
+ */
80
+ onSubscribed?: (callback: (subscribed: SyncSubscribed) => void) => () => void;
74
81
  /** Subscribe to connection status changes. Returns an unsubscribe function. */
75
82
  onStatusChange: (callback: (status: TransportStatus) => void) => () => void;
76
83
  }
@@ -16,6 +16,7 @@ import type {
16
16
  SyncMutateBatchRequest,
17
17
  SyncMutateRequest,
18
18
  SyncNack,
19
+ SyncSubscribed,
19
20
  } from "../types";
20
21
 
21
22
  /** Computes the reply for a sent mutation (may reject to simulate transport failure). */
@@ -38,6 +39,8 @@ export interface FakeTransport extends SyncTransport {
38
39
  readonly subscribedCollections: string[];
39
40
  /** Deliver a server delta to all onDelta listeners. */
40
41
  deliverDelta: (delta: SyncDelta) => void;
42
+ /** Deliver a `sync:subscribed` confirmation to all onSubscribed listeners. */
43
+ confirmSubscribed: (subscribed: SyncSubscribed) => void;
41
44
  /** Simulate a connect/disconnect; notifies status listeners on change. */
42
45
  setConnected: (connected: boolean) => void;
43
46
  /**
@@ -76,6 +79,7 @@ export const createFakeTransport = (): FakeTransport => {
76
79
  const sentBatches: string[][] = [];
77
80
  const subscribed = new Set<string>();
78
81
  const deltaListeners = new Set<(delta: SyncDelta) => void>();
82
+ const subscribedListeners = new Set<(subscribed: SyncSubscribed) => void>();
79
83
  const statusListeners = new Set<(status: TransportStatus) => void>();
80
84
  const responderQueue: FakeMutationResponder[] = [];
81
85
  let connected = false;
@@ -118,6 +122,11 @@ export const createFakeTransport = (): FakeTransport => {
118
122
  };
119
123
 
120
124
  return {
125
+ confirmSubscribed: (subscribed: SyncSubscribed): void => {
126
+ for (const listener of subscribedListeners) {
127
+ listener(subscribed);
128
+ }
129
+ },
121
130
  connect: async (): Promise<void> => {
122
131
  setConnected(true);
123
132
  },
@@ -147,6 +156,12 @@ export const createFakeTransport = (): FakeTransport => {
147
156
  statusListeners.delete(callback);
148
157
  };
149
158
  },
159
+ onSubscribed: (callback: (subscribed: SyncSubscribed) => void): (() => void) => {
160
+ subscribedListeners.add(callback);
161
+ return () => {
162
+ subscribedListeners.delete(callback);
163
+ };
164
+ },
150
165
  respondBatchWith: (responder: FakeBatchResponder): void => {
151
166
  batchResponderQueue.push(responder);
152
167
  },
package/src/types.ts CHANGED
@@ -31,6 +31,19 @@ export interface SyncDelta {
31
31
  deleted?: boolean;
32
32
  }
33
33
 
34
+ /**
35
+ * Server confirmation (`sync:subscribed`) that a collection's delta streams are joined.
36
+ *
37
+ * Emitted after the server has joined the socket to every `sync:{stream}` room for the
38
+ * collection, so it is the first moment live deltas are guaranteed to reach this client.
39
+ */
40
+ export interface SyncSubscribed {
41
+ /** Collection tag the confirmation is for. */
42
+ collection: string;
43
+ /** Stream keys now joined for that collection. */
44
+ streams: string[];
45
+ }
46
+
34
47
  /** A client mutation sent via `sync:mutate` or `POST /sync/mutate`. */
35
48
  export interface SyncMutateRequest {
36
49
  /** Client-generated stable id; the idempotency key. */
@@ -177,6 +190,11 @@ export interface OutboxMutation {
177
190
  attemptCount: number;
178
191
  /** Retry-budget counter incremented only on server error-nacks (see MAX_ERROR_NACK_ATTEMPTS). */
179
192
  errorNackCount: number;
193
+ /**
194
+ * Per-mutation cap on error-nack retries before terminal failure. Omitted rows use
195
+ * {@link MAX_ERROR_NACK_ATTEMPTS} in the replay coordinator.
196
+ */
197
+ maxAttempts?: number;
180
198
  /** The user this mutation belongs to; replay skips mutations from other users. */
181
199
  userId: string;
182
200
  createdAt: string;