@syncular/server 0.0.1-60

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 (211) hide show
  1. package/dist/blobs/adapters/database.d.ts +83 -0
  2. package/dist/blobs/adapters/database.d.ts.map +1 -0
  3. package/dist/blobs/adapters/database.js +180 -0
  4. package/dist/blobs/adapters/database.js.map +1 -0
  5. package/dist/blobs/adapters/s3.d.ts +82 -0
  6. package/dist/blobs/adapters/s3.d.ts.map +1 -0
  7. package/dist/blobs/adapters/s3.js +170 -0
  8. package/dist/blobs/adapters/s3.js.map +1 -0
  9. package/dist/blobs/index.d.ts +9 -0
  10. package/dist/blobs/index.d.ts.map +1 -0
  11. package/dist/blobs/index.js +9 -0
  12. package/dist/blobs/index.js.map +1 -0
  13. package/dist/blobs/manager.d.ts +195 -0
  14. package/dist/blobs/manager.d.ts.map +1 -0
  15. package/dist/blobs/manager.js +440 -0
  16. package/dist/blobs/manager.js.map +1 -0
  17. package/dist/blobs/migrate.d.ts +27 -0
  18. package/dist/blobs/migrate.d.ts.map +1 -0
  19. package/dist/blobs/migrate.js +119 -0
  20. package/dist/blobs/migrate.js.map +1 -0
  21. package/dist/blobs/types.d.ts +54 -0
  22. package/dist/blobs/types.d.ts.map +1 -0
  23. package/dist/blobs/types.js +5 -0
  24. package/dist/blobs/types.js.map +1 -0
  25. package/dist/clients.d.ts +14 -0
  26. package/dist/clients.d.ts.map +1 -0
  27. package/dist/clients.js +7 -0
  28. package/dist/clients.js.map +1 -0
  29. package/dist/compaction.d.ts +27 -0
  30. package/dist/compaction.d.ts.map +1 -0
  31. package/dist/compaction.js +49 -0
  32. package/dist/compaction.js.map +1 -0
  33. package/dist/dialect/index.d.ts +5 -0
  34. package/dist/dialect/index.d.ts.map +1 -0
  35. package/dist/dialect/index.js +5 -0
  36. package/dist/dialect/index.js.map +1 -0
  37. package/dist/dialect/types.d.ts +170 -0
  38. package/dist/dialect/types.d.ts.map +1 -0
  39. package/dist/dialect/types.js +8 -0
  40. package/dist/dialect/types.js.map +1 -0
  41. package/dist/helpers/conflict.d.ts +52 -0
  42. package/dist/helpers/conflict.d.ts.map +1 -0
  43. package/dist/helpers/conflict.js +49 -0
  44. package/dist/helpers/conflict.js.map +1 -0
  45. package/dist/helpers/emitted-change.d.ts +56 -0
  46. package/dist/helpers/emitted-change.d.ts.map +1 -0
  47. package/dist/helpers/emitted-change.js +46 -0
  48. package/dist/helpers/emitted-change.js.map +1 -0
  49. package/dist/helpers/index.d.ts +10 -0
  50. package/dist/helpers/index.d.ts.map +1 -0
  51. package/dist/helpers/index.js +10 -0
  52. package/dist/helpers/index.js.map +1 -0
  53. package/dist/helpers/paginate.d.ts +49 -0
  54. package/dist/helpers/paginate.d.ts.map +1 -0
  55. package/dist/helpers/paginate.js +54 -0
  56. package/dist/helpers/paginate.js.map +1 -0
  57. package/dist/helpers/scope-strings.d.ts +74 -0
  58. package/dist/helpers/scope-strings.d.ts.map +1 -0
  59. package/dist/helpers/scope-strings.js +82 -0
  60. package/dist/helpers/scope-strings.js.map +1 -0
  61. package/dist/index.d.ts +28 -0
  62. package/dist/index.d.ts.map +1 -0
  63. package/dist/index.js +27 -0
  64. package/dist/index.js.map +1 -0
  65. package/dist/migrate.d.ts +14 -0
  66. package/dist/migrate.d.ts.map +1 -0
  67. package/dist/migrate.js +13 -0
  68. package/dist/migrate.js.map +1 -0
  69. package/dist/proxy/handler.d.ts +42 -0
  70. package/dist/proxy/handler.d.ts.map +1 -0
  71. package/dist/proxy/handler.js +99 -0
  72. package/dist/proxy/handler.js.map +1 -0
  73. package/dist/proxy/index.d.ts +9 -0
  74. package/dist/proxy/index.d.ts.map +1 -0
  75. package/dist/proxy/index.js +14 -0
  76. package/dist/proxy/index.js.map +1 -0
  77. package/dist/proxy/mutation-detector.d.ts +31 -0
  78. package/dist/proxy/mutation-detector.d.ts.map +1 -0
  79. package/dist/proxy/mutation-detector.js +61 -0
  80. package/dist/proxy/mutation-detector.js.map +1 -0
  81. package/dist/proxy/oplog.d.ts +30 -0
  82. package/dist/proxy/oplog.d.ts.map +1 -0
  83. package/dist/proxy/oplog.js +110 -0
  84. package/dist/proxy/oplog.js.map +1 -0
  85. package/dist/proxy/registry.d.ts +35 -0
  86. package/dist/proxy/registry.d.ts.map +1 -0
  87. package/dist/proxy/registry.js +49 -0
  88. package/dist/proxy/registry.js.map +1 -0
  89. package/dist/proxy/types.d.ts +44 -0
  90. package/dist/proxy/types.d.ts.map +1 -0
  91. package/dist/proxy/types.js +7 -0
  92. package/dist/proxy/types.js.map +1 -0
  93. package/dist/prune.d.ts +37 -0
  94. package/dist/prune.d.ts.map +1 -0
  95. package/dist/prune.js +112 -0
  96. package/dist/prune.js.map +1 -0
  97. package/dist/pull.d.ts +31 -0
  98. package/dist/pull.d.ts.map +1 -0
  99. package/dist/pull.js +414 -0
  100. package/dist/pull.js.map +1 -0
  101. package/dist/push.d.ts +33 -0
  102. package/dist/push.d.ts.map +1 -0
  103. package/dist/push.js +329 -0
  104. package/dist/push.js.map +1 -0
  105. package/dist/realtime/in-memory.d.ts +13 -0
  106. package/dist/realtime/in-memory.d.ts.map +1 -0
  107. package/dist/realtime/in-memory.js +28 -0
  108. package/dist/realtime/in-memory.js.map +1 -0
  109. package/dist/realtime/index.d.ts +3 -0
  110. package/dist/realtime/index.d.ts.map +1 -0
  111. package/dist/realtime/index.js +2 -0
  112. package/dist/realtime/index.js.map +1 -0
  113. package/dist/realtime/types.d.ts +50 -0
  114. package/dist/realtime/types.d.ts.map +1 -0
  115. package/dist/realtime/types.js +7 -0
  116. package/dist/realtime/types.js.map +1 -0
  117. package/dist/schema.d.ts +164 -0
  118. package/dist/schema.d.ts.map +1 -0
  119. package/dist/schema.js +10 -0
  120. package/dist/schema.js.map +1 -0
  121. package/dist/shapes/create-handler.d.ts +119 -0
  122. package/dist/shapes/create-handler.d.ts.map +1 -0
  123. package/dist/shapes/create-handler.js +327 -0
  124. package/dist/shapes/create-handler.js.map +1 -0
  125. package/dist/shapes/index.d.ts +4 -0
  126. package/dist/shapes/index.d.ts.map +1 -0
  127. package/dist/shapes/index.js +4 -0
  128. package/dist/shapes/index.js.map +1 -0
  129. package/dist/shapes/registry.d.ts +20 -0
  130. package/dist/shapes/registry.d.ts.map +1 -0
  131. package/dist/shapes/registry.js +88 -0
  132. package/dist/shapes/registry.js.map +1 -0
  133. package/dist/shapes/types.d.ts +204 -0
  134. package/dist/shapes/types.d.ts.map +1 -0
  135. package/dist/shapes/types.js +2 -0
  136. package/dist/shapes/types.js.map +1 -0
  137. package/dist/snapshot-chunks/adapters/s3.d.ts +63 -0
  138. package/dist/snapshot-chunks/adapters/s3.d.ts.map +1 -0
  139. package/dist/snapshot-chunks/adapters/s3.js +50 -0
  140. package/dist/snapshot-chunks/adapters/s3.js.map +1 -0
  141. package/dist/snapshot-chunks/db-metadata.d.ts +33 -0
  142. package/dist/snapshot-chunks/db-metadata.d.ts.map +1 -0
  143. package/dist/snapshot-chunks/db-metadata.js +169 -0
  144. package/dist/snapshot-chunks/db-metadata.js.map +1 -0
  145. package/dist/snapshot-chunks/index.d.ts +9 -0
  146. package/dist/snapshot-chunks/index.d.ts.map +1 -0
  147. package/dist/snapshot-chunks/index.js +9 -0
  148. package/dist/snapshot-chunks/index.js.map +1 -0
  149. package/dist/snapshot-chunks/types.d.ts +65 -0
  150. package/dist/snapshot-chunks/types.d.ts.map +1 -0
  151. package/dist/snapshot-chunks/types.js +8 -0
  152. package/dist/snapshot-chunks/types.js.map +1 -0
  153. package/dist/snapshot-chunks.d.ts +59 -0
  154. package/dist/snapshot-chunks.d.ts.map +1 -0
  155. package/dist/snapshot-chunks.js +202 -0
  156. package/dist/snapshot-chunks.js.map +1 -0
  157. package/dist/stats.d.ts +19 -0
  158. package/dist/stats.d.ts.map +1 -0
  159. package/dist/stats.js +57 -0
  160. package/dist/stats.js.map +1 -0
  161. package/dist/subscriptions/index.d.ts +2 -0
  162. package/dist/subscriptions/index.d.ts.map +1 -0
  163. package/dist/subscriptions/index.js +2 -0
  164. package/dist/subscriptions/index.js.map +1 -0
  165. package/dist/subscriptions/resolve.d.ts +35 -0
  166. package/dist/subscriptions/resolve.d.ts.map +1 -0
  167. package/dist/subscriptions/resolve.js +134 -0
  168. package/dist/subscriptions/resolve.js.map +1 -0
  169. package/package.json +80 -0
  170. package/src/blobs/adapters/database.ts +290 -0
  171. package/src/blobs/adapters/s3.ts +271 -0
  172. package/src/blobs/index.ts +9 -0
  173. package/src/blobs/manager.ts +600 -0
  174. package/src/blobs/migrate.ts +150 -0
  175. package/src/blobs/types.ts +70 -0
  176. package/src/clients.ts +21 -0
  177. package/src/compaction.ts +77 -0
  178. package/src/dialect/index.ts +5 -0
  179. package/src/dialect/types.ts +222 -0
  180. package/src/helpers/conflict.ts +64 -0
  181. package/src/helpers/emitted-change.ts +69 -0
  182. package/src/helpers/index.ts +10 -0
  183. package/src/helpers/paginate.ts +82 -0
  184. package/src/helpers/scope-strings.ts +101 -0
  185. package/src/index.ts +28 -0
  186. package/src/migrate.ts +20 -0
  187. package/src/proxy/handler.ts +152 -0
  188. package/src/proxy/index.ts +18 -0
  189. package/src/proxy/mutation-detector.ts +83 -0
  190. package/src/proxy/oplog.ts +144 -0
  191. package/src/proxy/registry.ts +56 -0
  192. package/src/proxy/types.ts +46 -0
  193. package/src/prune.ts +200 -0
  194. package/src/pull.ts +551 -0
  195. package/src/push.ts +457 -0
  196. package/src/realtime/in-memory.ts +33 -0
  197. package/src/realtime/index.ts +5 -0
  198. package/src/realtime/types.ts +55 -0
  199. package/src/schema.ts +172 -0
  200. package/src/shapes/create-handler.ts +590 -0
  201. package/src/shapes/index.ts +3 -0
  202. package/src/shapes/registry.ts +109 -0
  203. package/src/shapes/types.ts +267 -0
  204. package/src/snapshot-chunks/adapters/s3.ts +68 -0
  205. package/src/snapshot-chunks/db-metadata.ts +238 -0
  206. package/src/snapshot-chunks/index.ts +9 -0
  207. package/src/snapshot-chunks/types.ts +79 -0
  208. package/src/snapshot-chunks.ts +301 -0
  209. package/src/stats.ts +104 -0
  210. package/src/subscriptions/index.ts +1 -0
  211. package/src/subscriptions/resolve.ts +185 -0
package/src/pull.ts ADDED
@@ -0,0 +1,551 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { promisify } from 'node:util';
3
+ import { gzip, gzipSync } from 'node:zlib';
4
+ import type {
5
+ ScopeValues,
6
+ SyncBootstrapState,
7
+ SyncChange,
8
+ SyncCommit,
9
+ SyncPullRequest,
10
+ SyncPullResponse,
11
+ SyncPullSubscriptionResponse,
12
+ SyncSnapshot,
13
+ } from '@syncular/core';
14
+ import type { Kysely } from 'kysely';
15
+ import type { ServerSyncDialect } from './dialect/types';
16
+ import type { SyncCoreDb } from './schema';
17
+ import type { TableRegistry } from './shapes/registry';
18
+ import {
19
+ insertSnapshotChunk,
20
+ readSnapshotChunkRefByPageKey,
21
+ } from './snapshot-chunks';
22
+ import type { SnapshotChunkStorage } from './snapshot-chunks/types';
23
+ import { resolveEffectiveScopesForSubscriptions } from './subscriptions/resolve';
24
+
25
+ const gzipAsync = promisify(gzip);
26
+ const ASYNC_GZIP_MIN_BYTES = 64 * 1024;
27
+
28
+ async function compressSnapshotNdjson(ndjson: string): Promise<Uint8Array> {
29
+ if (Buffer.byteLength(ndjson) < ASYNC_GZIP_MIN_BYTES) {
30
+ return new Uint8Array(gzipSync(ndjson));
31
+ }
32
+ const compressed = await gzipAsync(ndjson);
33
+ return new Uint8Array(compressed);
34
+ }
35
+
36
+ export interface PullResult {
37
+ response: SyncPullResponse;
38
+ /**
39
+ * Effective scopes for all active subscriptions (for cursor tracking).
40
+ * Maps subscription ID to effective scopes.
41
+ */
42
+ effectiveScopes: ScopeValues;
43
+ /** Minimum nextCursor across active subscriptions (for pruning cursor tracking). */
44
+ clientCursor: number;
45
+ }
46
+
47
+ /**
48
+ * Generate a stable cache key for snapshot chunks.
49
+ */
50
+ function scopesToCacheKey(scopes: ScopeValues): string {
51
+ const sorted = Object.entries(scopes)
52
+ .sort(([a], [b]) => a.localeCompare(b))
53
+ .map(([k, v]) => {
54
+ const arr = Array.isArray(v) ? [...v].sort() : [v];
55
+ return `${k}:${arr.join(',')}`;
56
+ })
57
+ .join('|');
58
+ return createHash('sha256').update(sorted).digest('hex');
59
+ }
60
+
61
+ /**
62
+ * Sanitize a numeric limit parameter with bounds checking.
63
+ * Handles NaN, negative values, and undefined.
64
+ */
65
+ function sanitizeLimit(
66
+ value: number | undefined,
67
+ defaultValue: number,
68
+ min: number,
69
+ max: number
70
+ ): number {
71
+ if (value === undefined || value === null) return defaultValue;
72
+ if (Number.isNaN(value)) return defaultValue;
73
+ return Math.max(min, Math.min(max, value));
74
+ }
75
+
76
+ /**
77
+ * Merge all scope values into a flat ScopeValues for cursor tracking.
78
+ */
79
+ function mergeScopes(subscriptions: { scopes: ScopeValues }[]): ScopeValues {
80
+ const result: Record<string, Set<string>> = {};
81
+
82
+ for (const sub of subscriptions) {
83
+ for (const [key, value] of Object.entries(sub.scopes)) {
84
+ if (!result[key]) result[key] = new Set();
85
+ const arr = Array.isArray(value) ? value : [value];
86
+ for (const v of arr) result[key].add(v);
87
+ }
88
+ }
89
+
90
+ const merged: ScopeValues = {};
91
+ for (const [key, set] of Object.entries(result)) {
92
+ const arr = Array.from(set);
93
+ if (arr.length === 0) continue;
94
+ merged[key] = arr.length === 1 ? arr[0]! : arr;
95
+ }
96
+ return merged;
97
+ }
98
+
99
+ export async function pull<DB extends SyncCoreDb>(args: {
100
+ db: Kysely<DB>;
101
+ dialect: ServerSyncDialect;
102
+ shapes: TableRegistry<DB>;
103
+ actorId: string;
104
+ partitionId?: string;
105
+ request: SyncPullRequest;
106
+ /**
107
+ * Optional snapshot chunk storage adapter.
108
+ * When provided, stores chunk bodies in external storage (S3, etc.)
109
+ * instead of inline in the database.
110
+ */
111
+ chunkStorage?: SnapshotChunkStorage;
112
+ }): Promise<PullResult> {
113
+ const { request, dialect } = args;
114
+ const db = args.db;
115
+ const partitionId = args.partitionId ?? 'default';
116
+
117
+ // Validate and sanitize request limits
118
+ const limitCommits = sanitizeLimit(request.limitCommits, 50, 1, 500);
119
+ const limitSnapshotRows = sanitizeLimit(
120
+ request.limitSnapshotRows,
121
+ 1000,
122
+ 1,
123
+ 5000
124
+ );
125
+ const maxSnapshotPages = sanitizeLimit(request.maxSnapshotPages, 1, 1, 50);
126
+ const dedupeRows = request.dedupeRows === true;
127
+
128
+ // Resolve effective scopes for each subscription
129
+ const resolved = await resolveEffectiveScopesForSubscriptions({
130
+ db,
131
+ actorId: args.actorId,
132
+ subscriptions: request.subscriptions ?? [],
133
+ shapes: args.shapes,
134
+ });
135
+
136
+ return dialect.executeInTransaction(db, async (trx) => {
137
+ await dialect.setRepeatableRead(trx);
138
+
139
+ const maxCommitSeq = await dialect.readMaxCommitSeq(trx, { partitionId });
140
+ const minCommitSeq = await dialect.readMinCommitSeq(trx, { partitionId });
141
+
142
+ const subResponses: SyncPullSubscriptionResponse[] = [];
143
+ const activeSubscriptions: { scopes: ScopeValues }[] = [];
144
+ const nextCursors: number[] = [];
145
+
146
+ for (const sub of resolved) {
147
+ const cursor = Math.max(-1, sub.cursor ?? -1);
148
+ // Validate shape exists (throws if not registered)
149
+ args.shapes.getOrThrow(sub.shape);
150
+
151
+ if (sub.status === 'revoked' || Object.keys(sub.scopes).length === 0) {
152
+ subResponses.push({
153
+ id: sub.id,
154
+ status: 'revoked',
155
+ scopes: {},
156
+ bootstrap: false,
157
+ nextCursor: cursor,
158
+ commits: [],
159
+ });
160
+ continue;
161
+ }
162
+
163
+ const effectiveScopes = sub.scopes;
164
+ activeSubscriptions.push({ scopes: effectiveScopes });
165
+
166
+ const needsBootstrap =
167
+ sub.bootstrapState != null ||
168
+ cursor < 0 ||
169
+ cursor > maxCommitSeq ||
170
+ (minCommitSeq > 0 && cursor < minCommitSeq - 1);
171
+
172
+ if (needsBootstrap) {
173
+ const tables = args.shapes
174
+ .getBootstrapOrderFor(sub.shape)
175
+ .map((handler) => handler.table);
176
+
177
+ const initState: SyncBootstrapState = {
178
+ asOfCommitSeq: maxCommitSeq,
179
+ tables,
180
+ tableIndex: 0,
181
+ rowCursor: null,
182
+ };
183
+
184
+ const requestedState = sub.bootstrapState ?? null;
185
+ const state =
186
+ requestedState &&
187
+ typeof requestedState.asOfCommitSeq === 'number' &&
188
+ Array.isArray(requestedState.tables) &&
189
+ typeof requestedState.tableIndex === 'number'
190
+ ? (requestedState as SyncBootstrapState)
191
+ : initState;
192
+
193
+ // If the bootstrap state's asOfCommitSeq is no longer catch-up-able, restart bootstrap.
194
+ const effectiveState =
195
+ state.asOfCommitSeq < minCommitSeq - 1 ? initState : state;
196
+
197
+ const tableName = effectiveState.tables[effectiveState.tableIndex];
198
+
199
+ // No tables (or ran past the end): treat bootstrap as complete.
200
+ if (!tableName) {
201
+ subResponses.push({
202
+ id: sub.id,
203
+ status: 'active',
204
+ scopes: effectiveScopes,
205
+ bootstrap: true,
206
+ bootstrapState: null,
207
+ nextCursor: effectiveState.asOfCommitSeq,
208
+ commits: [],
209
+ snapshots: [],
210
+ });
211
+ nextCursors.push(effectiveState.asOfCommitSeq);
212
+ continue;
213
+ }
214
+
215
+ const snapshots: SyncSnapshot[] = [];
216
+ let nextState: SyncBootstrapState | null = effectiveState;
217
+
218
+ for (let pageIndex = 0; pageIndex < maxSnapshotPages; pageIndex++) {
219
+ if (!nextState) break;
220
+
221
+ const nextTableName = nextState.tables[nextState.tableIndex];
222
+ if (!nextTableName) {
223
+ nextState = null;
224
+ break;
225
+ }
226
+
227
+ const tableHandler = args.shapes.getOrThrow(nextTableName);
228
+ const isFirstPage = nextState.rowCursor == null;
229
+
230
+ const page = await tableHandler.snapshot(
231
+ {
232
+ db: trx,
233
+ actorId: args.actorId,
234
+ scopeValues: effectiveScopes,
235
+ cursor: nextState.rowCursor,
236
+ limit: limitSnapshotRows,
237
+ },
238
+ sub.params
239
+ );
240
+
241
+ const isLastPage = page.nextCursor == null;
242
+
243
+ // Always use NDJSON+gzip for bootstrap snapshots
244
+ const ttlMs = tableHandler.snapshotChunkTtlMs ?? 24 * 60 * 60 * 1000; // 24h
245
+ const nowIso = new Date().toISOString();
246
+
247
+ // Use scope hash for caching
248
+ const cacheKey = `${partitionId}:${scopesToCacheKey(effectiveScopes)}`;
249
+ const cached = await readSnapshotChunkRefByPageKey(trx, {
250
+ partitionId,
251
+ scopeKey: cacheKey,
252
+ scope: nextTableName,
253
+ asOfCommitSeq: effectiveState.asOfCommitSeq,
254
+ rowCursor: nextState.rowCursor,
255
+ rowLimit: limitSnapshotRows,
256
+ encoding: 'ndjson',
257
+ compression: 'gzip',
258
+ nowIso,
259
+ });
260
+
261
+ let chunkRef = cached;
262
+
263
+ if (!chunkRef) {
264
+ const lines: string[] = [];
265
+ for (const r of page.rows ?? []) {
266
+ const s = JSON.stringify(r);
267
+ lines.push(s === undefined ? 'null' : s);
268
+ }
269
+ const ndjson = lines.length > 0 ? `${lines.join('\n')}\n` : '';
270
+ const gz = await compressSnapshotNdjson(ndjson);
271
+ const sha256 = createHash('sha256').update(ndjson).digest('hex');
272
+ const expiresAt = new Date(
273
+ Date.now() + Math.max(1000, ttlMs)
274
+ ).toISOString();
275
+
276
+ // Use external chunk storage if available, otherwise fall back to inline
277
+ if (args.chunkStorage) {
278
+ chunkRef = await args.chunkStorage.storeChunk({
279
+ partitionId,
280
+ scopeKey: cacheKey,
281
+ scope: nextTableName,
282
+ asOfCommitSeq: effectiveState.asOfCommitSeq,
283
+ rowCursor: nextState.rowCursor ?? null,
284
+ rowLimit: limitSnapshotRows,
285
+ encoding: 'ndjson',
286
+ compression: 'gzip',
287
+ sha256,
288
+ body: gz,
289
+ expiresAt,
290
+ });
291
+ } else {
292
+ const chunkId = randomUUID();
293
+ chunkRef = await insertSnapshotChunk(trx, {
294
+ chunkId,
295
+ partitionId,
296
+ scopeKey: cacheKey,
297
+ scope: nextTableName,
298
+ asOfCommitSeq: effectiveState.asOfCommitSeq,
299
+ rowCursor: nextState.rowCursor,
300
+ rowLimit: limitSnapshotRows,
301
+ encoding: 'ndjson',
302
+ compression: 'gzip',
303
+ sha256,
304
+ body: gz,
305
+ expiresAt,
306
+ });
307
+ }
308
+ }
309
+
310
+ snapshots.push({
311
+ table: nextTableName,
312
+ rows: [],
313
+ chunks: [chunkRef],
314
+ isFirstPage,
315
+ isLastPage,
316
+ });
317
+
318
+ if (page.nextCursor != null) {
319
+ nextState = { ...nextState, rowCursor: page.nextCursor };
320
+ continue;
321
+ }
322
+
323
+ if (nextState.tableIndex + 1 < nextState.tables.length) {
324
+ nextState = {
325
+ ...nextState,
326
+ tableIndex: nextState.tableIndex + 1,
327
+ rowCursor: null,
328
+ };
329
+ continue;
330
+ }
331
+
332
+ nextState = null;
333
+ break;
334
+ }
335
+
336
+ subResponses.push({
337
+ id: sub.id,
338
+ status: 'active',
339
+ scopes: effectiveScopes,
340
+ bootstrap: true,
341
+ bootstrapState: nextState,
342
+ nextCursor: effectiveState.asOfCommitSeq,
343
+ commits: [],
344
+ snapshots,
345
+ });
346
+ nextCursors.push(effectiveState.asOfCommitSeq);
347
+ continue;
348
+ }
349
+
350
+ // Incremental pull for this subscription
351
+ // Read the commit window for this table up-front so the subscription cursor
352
+ // can advance past commits that don't match the requested scopes.
353
+ const scannedCommitSeqs = await dialect.readCommitSeqsForPull(trx, {
354
+ partitionId,
355
+ cursor,
356
+ limitCommits,
357
+ tables: [sub.shape],
358
+ });
359
+ const maxScannedCommitSeq =
360
+ scannedCommitSeqs.length > 0
361
+ ? scannedCommitSeqs[scannedCommitSeqs.length - 1]!
362
+ : cursor;
363
+
364
+ // Use streaming when available to reduce memory pressure for large pulls
365
+ const pullRowStream = dialect.streamIncrementalPullRows
366
+ ? dialect.streamIncrementalPullRows(trx, {
367
+ partitionId,
368
+ table: sub.shape,
369
+ scopes: effectiveScopes,
370
+ cursor,
371
+ limitCommits,
372
+ })
373
+ : null;
374
+
375
+ // Collect rows and compute nextCursor in a single pass
376
+ const incrementalRows: Array<{
377
+ commit_seq: number;
378
+ actor_id: string;
379
+ created_at: string;
380
+ change_id: number;
381
+ table: string;
382
+ row_id: string;
383
+ op: 'upsert' | 'delete';
384
+ row_json: unknown | null;
385
+ row_version: number | null;
386
+ scopes: Record<string, string | string[]>;
387
+ }> = [];
388
+
389
+ let nextCursor = cursor;
390
+
391
+ if (pullRowStream) {
392
+ // Streaming path: process rows as they arrive
393
+ for await (const row of pullRowStream) {
394
+ incrementalRows.push(row);
395
+ nextCursor = Math.max(nextCursor, row.commit_seq);
396
+ }
397
+ } else {
398
+ // Non-streaming fallback: load all rows at once
399
+ const rows = await dialect.readIncrementalPullRows(trx, {
400
+ partitionId,
401
+ table: sub.shape,
402
+ scopes: effectiveScopes,
403
+ cursor,
404
+ limitCommits,
405
+ });
406
+ incrementalRows.push(...rows);
407
+ for (const r of incrementalRows) {
408
+ nextCursor = Math.max(nextCursor, r.commit_seq);
409
+ }
410
+ }
411
+
412
+ nextCursor = Math.max(nextCursor, maxScannedCommitSeq);
413
+
414
+ if (incrementalRows.length === 0) {
415
+ subResponses.push({
416
+ id: sub.id,
417
+ status: 'active',
418
+ scopes: effectiveScopes,
419
+ bootstrap: false,
420
+ nextCursor,
421
+ commits: [],
422
+ });
423
+ nextCursors.push(nextCursor);
424
+ continue;
425
+ }
426
+
427
+ if (dedupeRows) {
428
+ const latestByRowKey = new Map<
429
+ string,
430
+ {
431
+ commitSeq: number;
432
+ createdAt: string;
433
+ actorId: string;
434
+ changeId: number;
435
+ change: SyncChange;
436
+ }
437
+ >();
438
+
439
+ for (const r of incrementalRows) {
440
+ const rowKey = `${r.table}\u0000${r.row_id}`;
441
+ const change: SyncChange = {
442
+ table: r.table,
443
+ row_id: r.row_id,
444
+ op: r.op,
445
+ row_json: r.row_json,
446
+ row_version: r.row_version,
447
+ scopes: dialect.dbToScopes(r.scopes),
448
+ };
449
+
450
+ latestByRowKey.set(rowKey, {
451
+ commitSeq: r.commit_seq,
452
+ createdAt: r.created_at,
453
+ actorId: r.actor_id,
454
+ changeId: r.change_id,
455
+ change,
456
+ });
457
+ }
458
+
459
+ const latest = Array.from(latestByRowKey.values()).sort(
460
+ (a, b) => a.commitSeq - b.commitSeq || a.changeId - b.changeId
461
+ );
462
+
463
+ const commitsBySeq = new Map<number, SyncCommit>();
464
+ for (const item of latest) {
465
+ let commit = commitsBySeq.get(item.commitSeq);
466
+ if (!commit) {
467
+ commit = {
468
+ commitSeq: item.commitSeq,
469
+ createdAt: item.createdAt,
470
+ actorId: item.actorId,
471
+ changes: [],
472
+ };
473
+ commitsBySeq.set(item.commitSeq, commit);
474
+ }
475
+ commit.changes.push(item.change);
476
+ }
477
+
478
+ const commits = Array.from(commitsBySeq.values()).sort(
479
+ (a, b) => a.commitSeq - b.commitSeq
480
+ );
481
+
482
+ subResponses.push({
483
+ id: sub.id,
484
+ status: 'active',
485
+ scopes: effectiveScopes,
486
+ bootstrap: false,
487
+ nextCursor,
488
+ commits,
489
+ });
490
+ nextCursors.push(nextCursor);
491
+ continue;
492
+ }
493
+
494
+ const commitsBySeq = new Map<number, SyncCommit>();
495
+ const commitSeqs: number[] = [];
496
+
497
+ for (const r of incrementalRows) {
498
+ const seq = r.commit_seq;
499
+ let commit = commitsBySeq.get(seq);
500
+ if (!commit) {
501
+ commit = {
502
+ commitSeq: seq,
503
+ createdAt: r.created_at,
504
+ actorId: r.actor_id,
505
+ changes: [],
506
+ };
507
+ commitsBySeq.set(seq, commit);
508
+ commitSeqs.push(seq);
509
+ }
510
+
511
+ const change: SyncChange = {
512
+ table: r.table,
513
+ row_id: r.row_id,
514
+ op: r.op,
515
+ row_json: r.row_json,
516
+ row_version: r.row_version,
517
+ scopes: dialect.dbToScopes(r.scopes),
518
+ };
519
+ commit.changes.push(change);
520
+ }
521
+
522
+ const commits: SyncCommit[] = commitSeqs
523
+ .map((seq) => commitsBySeq.get(seq))
524
+ .filter((c): c is SyncCommit => !!c)
525
+ .filter((c) => c.changes.length > 0);
526
+
527
+ subResponses.push({
528
+ id: sub.id,
529
+ status: 'active',
530
+ scopes: effectiveScopes,
531
+ bootstrap: false,
532
+ nextCursor,
533
+ commits,
534
+ });
535
+ nextCursors.push(nextCursor);
536
+ }
537
+
538
+ const effectiveScopes = mergeScopes(activeSubscriptions);
539
+ const clientCursor =
540
+ nextCursors.length > 0 ? Math.min(...nextCursors) : maxCommitSeq;
541
+
542
+ return {
543
+ response: {
544
+ ok: true as const,
545
+ subscriptions: subResponses,
546
+ },
547
+ effectiveScopes,
548
+ clientCursor,
549
+ };
550
+ });
551
+ }