@syncular/server 0.58.0 → 0.60.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 (103) hide show
  1. package/README.md +49 -36
  2. package/dist/admin.d.ts +32 -20
  3. package/dist/admin.js +46 -40
  4. package/dist/blob-handlers.d.ts +25 -31
  5. package/dist/blob-handlers.js +63 -41
  6. package/dist/blob-store.d.ts +42 -24
  7. package/dist/blob-store.js +0 -0
  8. package/dist/bucket-blob-store.d.ts +12 -8
  9. package/dist/bucket-blob-store.js +54 -45
  10. package/dist/bucket-segment-store.js +18 -16
  11. package/dist/content-encoding.d.ts +5 -2
  12. package/dist/content-encoding.js +42 -13
  13. package/dist/context.d.ts +19 -5
  14. package/dist/context.js +19 -1
  15. package/dist/d1-storage.d.ts +14 -98
  16. package/dist/d1-storage.js +249 -1119
  17. package/dist/errors.js +16 -0
  18. package/dist/events.d.ts +36 -18
  19. package/dist/frame-bytes.js +24 -6
  20. package/dist/handler.js +503 -208
  21. package/dist/local-authority.d.ts +2 -0
  22. package/dist/local-authority.js +24 -12
  23. package/dist/object-bucket.d.ts +2 -0
  24. package/dist/operations-realtime.js +69 -50
  25. package/dist/operations.d.ts +5 -2
  26. package/dist/operations.js +20 -29
  27. package/dist/pg-executor-pglite.d.ts +5 -6
  28. package/dist/pg-executor-pglite.js +22 -14
  29. package/dist/pg-executor.d.ts +4 -1
  30. package/dist/postgres-storage.d.ts +24 -19
  31. package/dist/postgres-storage.js +420 -262
  32. package/dist/pull.d.ts +70 -47
  33. package/dist/pull.js +270 -301
  34. package/dist/push.d.ts +12 -3
  35. package/dist/push.js +361 -173
  36. package/dist/realtime.d.ts +85 -39
  37. package/dist/realtime.js +355 -219
  38. package/dist/relational-rows.d.ts +21 -66
  39. package/dist/relational-rows.js +28 -109
  40. package/dist/s3-blob-store.d.ts +11 -12
  41. package/dist/s3-blob-store.js +20 -13
  42. package/dist/s3-object-bucket.d.ts +8 -1
  43. package/dist/s3-object-bucket.js +16 -3
  44. package/dist/schema.d.ts +14 -0
  45. package/dist/schema.js +23 -0
  46. package/dist/scopes.d.ts +6 -2
  47. package/dist/scopes.js +22 -4
  48. package/dist/seed.js +10 -16
  49. package/dist/segment-download.d.ts +4 -1
  50. package/dist/segment-download.js +22 -6
  51. package/dist/signed-url.d.ts +2 -2
  52. package/dist/signed-url.js +9 -2
  53. package/dist/sigv4.d.ts +8 -2
  54. package/dist/sigv4.js +8 -4
  55. package/dist/sqlite-blob-store.d.ts +1 -1
  56. package/dist/sqlite-blob-store.js +23 -22
  57. package/dist/sqlite-dialect.d.ts +164 -84
  58. package/dist/sqlite-dialect.js +1145 -150
  59. package/dist/sqlite-lease-store.js +13 -18
  60. package/dist/sqlite-storage.d.ts +9 -62
  61. package/dist/sqlite-storage.js +303 -1123
  62. package/dist/storage-query.d.ts +30 -1
  63. package/dist/storage-query.js +68 -0
  64. package/dist/storage.d.ts +185 -63
  65. package/dist/storage.js +15 -0
  66. package/package.json +2 -2
  67. package/src/admin.ts +99 -57
  68. package/src/blob-handlers.ts +91 -72
  69. package/src/blob-store.ts +0 -0
  70. package/src/bucket-blob-store.ts +75 -48
  71. package/src/bucket-segment-store.ts +20 -15
  72. package/src/content-encoding.ts +48 -16
  73. package/src/context.ts +33 -6
  74. package/src/d1-storage.ts +350 -1700
  75. package/src/errors.ts +16 -0
  76. package/src/events.ts +37 -18
  77. package/src/frame-bytes.ts +26 -6
  78. package/src/handler.ts +654 -261
  79. package/src/local-authority.ts +27 -14
  80. package/src/object-bucket.ts +2 -0
  81. package/src/operations-realtime.ts +85 -61
  82. package/src/operations.ts +44 -42
  83. package/src/pg-executor-pglite.ts +27 -23
  84. package/src/pg-executor.ts +5 -1
  85. package/src/postgres-storage.ts +557 -354
  86. package/src/pull.ts +406 -440
  87. package/src/push.ts +466 -220
  88. package/src/realtime.ts +447 -290
  89. package/src/relational-rows.ts +43 -121
  90. package/src/s3-blob-store.ts +23 -13
  91. package/src/s3-object-bucket.ts +20 -2
  92. package/src/schema.ts +31 -0
  93. package/src/scopes.ts +23 -3
  94. package/src/seed.ts +13 -20
  95. package/src/segment-download.ts +33 -7
  96. package/src/signed-url.ts +10 -4
  97. package/src/sigv4.ts +17 -4
  98. package/src/sqlite-blob-store.ts +27 -26
  99. package/src/sqlite-dialect.ts +1851 -199
  100. package/src/sqlite-lease-store.ts +12 -23
  101. package/src/sqlite-storage.ts +390 -1821
  102. package/src/storage-query.ts +102 -0
  103. package/src/storage.ts +215 -67
@@ -1,4 +1,11 @@
1
+ import { bindAuthoritativePartition, prepareAuthoritativeQuery, } from './authoritative-query.js';
2
+ import { syncError } from './errors.js';
3
+ import { validateCommitPruneQuery } from './prune.js';
4
+ import { StorageQueryError } from './storage-errors.js';
5
+ import { deleteRowSql, deleteSqliteRowScopesSql, indexRowPageStatement, quoteIdent, scanRowPageSql, rowsReferencingBlobSql, selectRowSql, SYNC_COLUMN_VERSIONS_COLUMN, SYNC_PARTITION_COLUMN, SYNC_PAYLOAD_COLUMN, SYNC_ROW_ID_COLUMN, SYNC_SCOPES_COLUMN, SYNC_VERSION_COLUMN, upsertSql, upsertValues, } from './relational-rows.js';
1
6
  import { matchesEffective } from './scopes.js';
7
+ import { clientRoundState, PARTITION_TOUCH_INTERVAL_MS, rowsLiveAfterDelete, } from './storage.js';
8
+ import { assertScopeIndexedScan, readLiveWindowPages, resolveIndexRowScan, } from './storage-query.js';
2
9
  /**
3
10
  * Schema DDL, one statement per `;`-delimited chunk. Native SQLite applies
4
11
  * the whole string via `db.exec(SQLITE_DDL)`; D1 applies each statement
@@ -12,17 +19,15 @@ import { matchesEffective } from './scopes.js';
12
19
  * the Postgres storage documents (§3.1, performance-by-
13
20
  * construction).
14
21
  *
15
- * `sync_row_scopes_by_row` is the one secondary scope index: a per-row
16
- * scope replacement predicates on `(partition, tbl, row_id)`, and `row_id`
17
- * is the LAST PRIMARY KEY column, so that predicate cannot narrow the
18
- * inverted index. Declared here so every SQLite-family storage (and D1,
19
- * which applies this same DDL) keeps the same plan shape as Postgres.
22
+ * Changes to the core tables of an existing database (added and dropped
23
+ * columns and indexes) live in `sqliteUpgradeDdl`, which runs after this DDL.
20
24
  */
21
25
  export const SQLITE_DDL = `
22
26
  CREATE TABLE IF NOT EXISTS sync_partitions(
23
27
  partition TEXT PRIMARY KEY,
24
28
  max_commit_seq INTEGER NOT NULL DEFAULT 0,
25
- horizon_seq INTEGER NOT NULL DEFAULT 0
29
+ horizon_seq INTEGER NOT NULL DEFAULT 0,
30
+ delete_floor INTEGER NOT NULL DEFAULT 0
26
31
  );
27
32
  CREATE TABLE IF NOT EXISTS sync_partition_registry(
28
33
  partition TEXT PRIMARY KEY,
@@ -35,8 +40,6 @@ CREATE TABLE IF NOT EXISTS sync_row_scopes(
35
40
  var TEXT NOT NULL, value TEXT NOT NULL, row_id TEXT NOT NULL,
36
41
  PRIMARY KEY(partition, tbl, var, value, row_id)
37
42
  );
38
- CREATE INDEX IF NOT EXISTS sync_row_scopes_by_row
39
- ON sync_row_scopes(partition, tbl, row_id);
40
43
  CREATE TABLE IF NOT EXISTS sync_commits(
41
44
  partition TEXT NOT NULL, commit_seq INTEGER NOT NULL,
42
45
  client_id TEXT NOT NULL, client_commit_id TEXT NOT NULL,
@@ -62,8 +65,14 @@ CREATE TABLE IF NOT EXISTS sync_change_scopes(
62
65
  CREATE TABLE IF NOT EXISTS sync_push_results(
63
66
  partition TEXT NOT NULL, client_id TEXT NOT NULL,
64
67
  client_commit_id TEXT NOT NULL, result TEXT NOT NULL,
68
+ outbox_id TEXT, client_seq INTEGER,
65
69
  PRIMARY KEY(partition, client_id, client_commit_id)
66
70
  );
71
+ CREATE TABLE IF NOT EXISTS sync_push_watermarks(
72
+ partition TEXT NOT NULL, client_id TEXT NOT NULL, outbox_id TEXT NOT NULL,
73
+ through_seq INTEGER NOT NULL,
74
+ PRIMARY KEY(partition, client_id, outbox_id)
75
+ );
67
76
  CREATE TABLE IF NOT EXISTS sync_reactions(
68
77
  partition TEXT NOT NULL, idempotency_key TEXT NOT NULL,
69
78
  type TEXT NOT NULL, version INTEGER NOT NULL, payload TEXT NOT NULL,
@@ -87,10 +96,12 @@ CREATE INDEX IF NOT EXISTS sync_reactions_dead_letter
87
96
  CREATE TABLE IF NOT EXISTS sync_clients(
88
97
  partition TEXT NOT NULL, client_id TEXT NOT NULL, actor_id TEXT NOT NULL,
89
98
  wire_version INTEGER NOT NULL DEFAULT 1,
90
- cursor INTEGER NOT NULL, subscriptions TEXT NOT NULL,
99
+ cursor INTEGER NOT NULL,
91
100
  updated_at_ms INTEGER NOT NULL,
92
101
  last_round_at_ms INTEGER, last_error_code TEXT,
93
102
  consecutive_failures INTEGER NOT NULL DEFAULT 0,
103
+ schema_version INTEGER, units TEXT, registration_digest BLOB,
104
+ catching_up TEXT NOT NULL DEFAULT '[]',
94
105
  PRIMARY KEY(partition, client_id)
95
106
  );
96
107
  CREATE TABLE IF NOT EXISTS sync_blob_refs(
@@ -102,7 +113,7 @@ CREATE INDEX IF NOT EXISTS sync_blob_refs_by_blob
102
113
  ON sync_blob_refs(partition, blob_id);
103
114
  CREATE TABLE IF NOT EXISTS sync_tombstones(
104
115
  partition TEXT NOT NULL, tbl TEXT NOT NULL, row_id TEXT NOT NULL,
105
- commit_seq INTEGER NOT NULL,
116
+ commit_seq INTEGER NOT NULL, server_version INTEGER, scopes TEXT,
106
117
  PRIMARY KEY(partition, tbl, row_id)
107
118
  );
108
119
  CREATE TABLE IF NOT EXISTS sync_backfill_checkpoints(
@@ -120,53 +131,103 @@ CREATE TABLE IF NOT EXISTS sync_writer_fence(
120
131
  required_writer_version INTEGER NOT NULL
121
132
  );
122
133
  `;
123
- /** Columns added to `sync_clients` after its first release, by column name. */
124
- export const SYNC_CLIENT_ROUND_COLUMNS = {
125
- last_round_at_ms: 'INTEGER',
126
- last_error_code: 'TEXT',
127
- consecutive_failures: 'INTEGER NOT NULL DEFAULT 0',
134
+ /**
135
+ * Columns added to core tables after their first release: table, column,
136
+ * type. A client record from before wire version 4 gains NULL `units` and
137
+ * `registration_digest`, so it holds no registration list (§9), and a push
138
+ * result gains NULL `outbox_id` and `client_seq`: it is a result stored
139
+ * before the upgrade, settled by the client's next push (§9). The
140
+ * watermark delete and the settlement range over the `(partition,
141
+ * client_id)` prefix of the primary key, which the watermark keeps to one
142
+ * request's results per outbox.
143
+ */
144
+ const SQLITE_ADDED_COLUMNS = [
145
+ ['sync_clients', 'wire_version', 'INTEGER NOT NULL DEFAULT 1'],
146
+ ['sync_clients', 'last_round_at_ms', 'INTEGER'],
147
+ ['sync_clients', 'last_error_code', 'TEXT'],
148
+ ['sync_clients', 'consecutive_failures', 'INTEGER NOT NULL DEFAULT 0'],
149
+ ['sync_clients', 'schema_version', 'INTEGER'],
150
+ ['sync_clients', 'units', 'TEXT'],
151
+ ['sync_clients', 'registration_digest', 'BLOB'],
152
+ ['sync_clients', 'catching_up', "TEXT NOT NULL DEFAULT '[]'"],
153
+ ['sync_tombstones', 'server_version', 'INTEGER'],
154
+ ['sync_tombstones', 'scopes', 'TEXT'],
155
+ ['sync_push_results', 'outbox_id', 'TEXT'],
156
+ ['sync_push_results', 'client_seq', 'INTEGER'],
157
+ ['sync_partitions', 'delete_floor', 'INTEGER NOT NULL DEFAULT 0'],
158
+ ];
159
+ /** Core-table columns wire version 4 deleted: the version 3 subscription list. */
160
+ const SQLITE_DROPPED_COLUMNS = [['sync_clients', 'subscriptions']];
161
+ /**
162
+ * Indexes that `sqliteUpgradeDdl` creates, on a fresh database and an
163
+ * upgraded one alike. `sync_change_scopes_by_key` serves the §4.5 live
164
+ * scan: one range per (variable, value) across tables.
165
+ */
166
+ const SQLITE_ADDED_INDEXES = [
167
+ [
168
+ 'sync_change_scopes_by_key',
169
+ 'CREATE INDEX IF NOT EXISTS sync_change_scopes_by_key ON sync_change_scopes(partition, var, value, commit_seq)',
170
+ ],
171
+ ];
172
+ /**
173
+ * Indexes that `sqliteUpgradeDdl` drops. With `sync_row_scopes_by_row`
174
+ * present the planner answered a scope scan of two or more values by walking
175
+ * it in `row_id` order and filtering, instead of seeking the PRIMARY KEY once
176
+ * per value; the per-row scope replacement (`deleteSqliteRowScopesSql`)
177
+ * binds the full key and needs no secondary index.
178
+ */
179
+ const SQLITE_DROPPED_INDEXES = ['sync_row_scopes_by_row'];
180
+ /**
181
+ * One statement that reads what `sqliteUpgradeDdl` needs: the columns of
182
+ * every table with added or dropped columns, and which added indexes exist.
183
+ */
184
+ export const SQLITE_UPGRADE_PROBE = {
185
+ sql: `SELECT t.value AS tbl, c.name AS name
186
+ FROM json_each(?) AS t, pragma_table_info(t.value) AS c
187
+ UNION ALL
188
+ SELECT '' AS tbl, name FROM sqlite_master
189
+ WHERE type='index' AND name IN (SELECT value FROM json_each(?))`,
190
+ params: [
191
+ JSON.stringify([
192
+ ...new Set([...SQLITE_ADDED_COLUMNS, ...SQLITE_DROPPED_COLUMNS].map(([table]) => table)),
193
+ ]),
194
+ JSON.stringify([
195
+ ...SQLITE_ADDED_INDEXES.map(([name]) => name),
196
+ ...SQLITE_DROPPED_INDEXES,
197
+ ]),
198
+ ],
128
199
  };
200
+ /**
201
+ * The statements that bring the core tables of a database from an earlier
202
+ * release to the current DDL, given the `SQLITE_UPGRADE_PROBE` rows: missing
203
+ * columns, dropped columns, dropped indexes, then missing indexes. Empty for
204
+ * a current database. Run after `SQLITE_DDL`: on every `SqliteServerStorage`
205
+ * construction, and on D1 in `migrate()`, the core phase of `migrateSchema`
206
+ * and the first open of a database at the current schema version.
207
+ */
208
+ export function sqliteUpgradeDdl(present) {
209
+ const has = (table, name) => present.some((row) => row.tbl === table && row.name === name);
210
+ return [
211
+ ...SQLITE_ADDED_COLUMNS.filter(([table, name]) => !has(table, name)).map(([table, name, definition]) => `ALTER TABLE ${table} ADD COLUMN ${name} ${definition}`),
212
+ // A database from before wire version 4 (and the delete floor) starts
213
+ // the delete floor at the highest version its tombstones recorded
214
+ // (§2.2) and the horizon at its last commit (§9).
215
+ ...(has('sync_partitions', 'delete_floor')
216
+ ? []
217
+ : [
218
+ `UPDATE sync_partitions SET horizon_seq=max_commit_seq, delete_floor=coalesce((SELECT max(server_version) FROM sync_tombstones t WHERE t.partition=sync_partitions.partition),0)`,
219
+ ]),
220
+ ...SQLITE_DROPPED_COLUMNS.filter(([table, name]) => has(table, name)).map(([table, name]) => `ALTER TABLE ${table} DROP COLUMN ${name}`),
221
+ ...SQLITE_DROPPED_INDEXES.filter((name) => has('', name)).map((name) => `DROP INDEX IF EXISTS ${name}`),
222
+ ...SQLITE_ADDED_INDEXES.filter(([name]) => !has('', name)).map(([, ddl]) => ddl),
223
+ ];
224
+ }
129
225
  /** Split the DDL into individual statements (D1 applies them one by one). */
130
226
  export function sqliteDdlStatements() {
131
227
  return SQLITE_DDL.split(';')
132
228
  .map((statement) => statement.trim())
133
229
  .filter((statement) => statement.length > 0);
134
230
  }
135
- /** §4.6.1: rowIds of one table bound to one scope value, budgeted. */
136
- export const LIST_SCOPE_VALUE_ROWS_SQLITE_SQL = 'SELECT row_id FROM sync_row_scopes WHERE partition=? AND tbl=? AND var=? AND value=? ORDER BY row_id LIMIT ?';
137
- /**
138
- * §4.6.1 history scrub, bound by `eraseScopeValueHistoryParams`: upsert change
139
- * records of the binding first, then the change scope entries whose commit
140
- * no longer holds a change of the binding. Each returns one row per removed
141
- * record (D1 batch results carry no reliable change count).
142
- */
143
- export const ERASE_SCOPE_VALUE_HISTORY_SQLITE_SQL = [
144
- `DELETE FROM sync_changes WHERE rowid IN (
145
- SELECT c.rowid FROM sync_change_scopes s JOIN sync_changes c
146
- ON c.partition=s.partition AND c.commit_seq=s.commit_seq AND c.tbl=s.tbl
147
- WHERE s.partition=?1 AND s.tbl=?2 AND s.var=?3 AND s.value=?4
148
- AND s.commit_seq<=?5 AND c.op=1 AND json_extract(c.scopes, ?6)=s.value
149
- LIMIT ?7) RETURNING 1 AS removed`,
150
- `DELETE FROM sync_change_scopes WHERE rowid IN (
151
- SELECT s.rowid FROM sync_change_scopes s
152
- WHERE s.partition=?1 AND s.tbl=?2 AND s.var=?3 AND s.value=?4
153
- AND s.commit_seq<=?5 AND NOT EXISTS (
154
- SELECT 1 FROM sync_changes c
155
- WHERE c.partition=s.partition AND c.commit_seq=s.commit_seq
156
- AND c.tbl=s.tbl AND json_extract(c.scopes, ?6)=s.value)
157
- LIMIT ?7) RETURNING 1 AS removed`,
158
- ];
159
- export function eraseScopeValueHistoryParams(partition, query) {
160
- return [
161
- partition,
162
- query.table,
163
- query.variable,
164
- query.value,
165
- query.throughSeq,
166
- `$.${JSON.stringify(query.variable)}`,
167
- query.limit,
168
- ];
169
- }
170
231
  /** `?,?,…` for an `IN (…)` clause of `count` positional parameters. */
171
232
  export function placeholders(count) {
172
233
  return new Array(count).fill('?').join(',');
@@ -226,46 +287,54 @@ export function serializePushResult(result) {
226
287
  }),
227
288
  });
228
289
  }
290
+ /** Parse a stored push result; an unreadable record is a §6.3 cache miss. */
229
291
  export function deserializePushResult(text) {
230
- const parsed = JSON.parse(text);
231
- const results = parsed.results.map((record) => {
232
- if (record.status === 'conflict') {
233
- return {
234
- opIndex: record.opIndex,
235
- status: 'conflict',
236
- code: record.code ?? '',
237
- message: record.message ?? '',
238
- serverVersion: record.serverVersion ?? 0,
239
- serverRow: base64ToBytes(record.serverRow ?? ''),
240
- conflictColumns: base64ToBytes(record.conflictColumns ?? ''),
241
- };
242
- }
243
- if (record.status === 'error') {
244
- return {
245
- opIndex: record.opIndex,
246
- status: 'error',
247
- code: record.code ?? '',
248
- message: record.message ?? '',
249
- retryable: record.retryable ?? false,
250
- ...(record.details !== undefined ? { details: record.details } : {}),
251
- };
252
- }
253
- return { opIndex: record.opIndex, status: 'applied' };
254
- });
255
- return {
256
- status: parsed.status,
257
- ...(parsed.commitSeq !== undefined ? { commitSeq: parsed.commitSeq } : {}),
258
- ...(parsed.recordedAtMs !== undefined
259
- ? { recordedAtMs: parsed.recordedAtMs }
260
- : {}),
261
- ...(parsed.cacheIdentity !== undefined
262
- ? { cacheIdentity: parsed.cacheIdentity }
263
- : {}),
264
- ...(parsed.conflictAuthorization !== undefined
265
- ? { conflictAuthorization: parsed.conflictAuthorization }
266
- : {}),
267
- results,
268
- };
292
+ try {
293
+ const parsed = JSON.parse(text);
294
+ const results = parsed.results.map((record) => {
295
+ if (record.status === 'conflict') {
296
+ return {
297
+ opIndex: record.opIndex,
298
+ status: 'conflict',
299
+ code: record.code ?? '',
300
+ message: record.message ?? '',
301
+ serverVersion: record.serverVersion ?? 0,
302
+ serverRow: base64ToBytes(record.serverRow ?? ''),
303
+ conflictColumns: base64ToBytes(record.conflictColumns ?? ''),
304
+ };
305
+ }
306
+ if (record.status === 'error') {
307
+ return {
308
+ opIndex: record.opIndex,
309
+ status: 'error',
310
+ code: record.code ?? '',
311
+ message: record.message ?? '',
312
+ retryable: record.retryable ?? false,
313
+ ...(record.details !== undefined ? { details: record.details } : {}),
314
+ };
315
+ }
316
+ return { opIndex: record.opIndex, status: 'applied' };
317
+ });
318
+ return {
319
+ status: parsed.status,
320
+ ...(parsed.commitSeq !== undefined
321
+ ? { commitSeq: parsed.commitSeq }
322
+ : {}),
323
+ ...(parsed.recordedAtMs !== undefined
324
+ ? { recordedAtMs: parsed.recordedAtMs }
325
+ : {}),
326
+ ...(parsed.cacheIdentity !== undefined
327
+ ? { cacheIdentity: parsed.cacheIdentity }
328
+ : {}),
329
+ ...(parsed.conflictAuthorization !== undefined
330
+ ? { conflictAuthorization: parsed.conflictAuthorization }
331
+ : {}),
332
+ results,
333
+ };
334
+ }
335
+ catch {
336
+ throw syncError('sync.idempotency_cache_miss', 'persisted push result unreadable (§6.3)');
337
+ }
269
338
  }
270
339
  /** Native SQLite returns `Uint8Array`; D1 returns `ArrayBuffer` for BLOBs. */
271
340
  export function asUint8Array(value) {
@@ -288,6 +357,17 @@ export function toStoredRow(record) {
288
357
  : {}),
289
358
  };
290
359
  }
360
+ export function toTombstone(record) {
361
+ return {
362
+ commitSeq: record.commit_seq,
363
+ ...(record.server_version !== null
364
+ ? { serverVersion: record.server_version }
365
+ : {}),
366
+ ...(record.scopes !== null
367
+ ? { scopes: JSON.parse(record.scopes) }
368
+ : {}),
369
+ };
370
+ }
291
371
  export function toStoredChange(record) {
292
372
  return {
293
373
  table: record.tbl,
@@ -300,74 +380,989 @@ export function toStoredChange(record) {
300
380
  : {}),
301
381
  };
302
382
  }
383
+ function toStoredReaction(record) {
384
+ return {
385
+ idempotencyKey: record.idempotency_key,
386
+ type: record.type,
387
+ version: record.version,
388
+ payload: JSON.parse(record.payload),
389
+ sourceClientId: record.source_client_id,
390
+ sourceClientCommitId: record.source_client_commit_id,
391
+ sourceCommitSeq: record.source_commit_seq,
392
+ createdAtMs: record.created_at_ms,
393
+ maxAttempts: record.max_attempts,
394
+ status: record.status,
395
+ attempts: record.attempts,
396
+ availableAtMs: record.available_at_ms,
397
+ ...(record.lease_owner !== null ? { leaseOwner: record.lease_owner } : {}),
398
+ ...(record.lease_expires_at_ms !== null
399
+ ? { leaseExpiresAtMs: record.lease_expires_at_ms }
400
+ : {}),
401
+ ...(record.completed_at_ms !== null
402
+ ? { completedAtMs: record.completed_at_ms }
403
+ : {}),
404
+ ...(record.last_failure !== null
405
+ ? { lastFailure: JSON.parse(record.last_failure) }
406
+ : {}),
407
+ };
408
+ }
409
+ const CLIENT_RECORD_COLUMNS = 'client_id, actor_id, wire_version, cursor, updated_at_ms, schema_version, units, registration_digest, catching_up, last_round_at_ms, last_error_code, consecutive_failures';
410
+ function toClientRecord(record) {
411
+ return {
412
+ clientId: record.client_id,
413
+ actorId: record.actor_id,
414
+ wireVersion: record.wire_version,
415
+ cursor: record.cursor,
416
+ updatedAtMs: record.updated_at_ms,
417
+ ...(record.schema_version !== null
418
+ ? { schemaVersion: record.schema_version }
419
+ : {}),
420
+ ...(record.units !== null && record.registration_digest !== null
421
+ ? {
422
+ registration: {
423
+ units: JSON.parse(record.units),
424
+ digest: asUint8Array(record.registration_digest),
425
+ },
426
+ }
427
+ : {}),
428
+ catchingUp: JSON.parse(record.catching_up),
429
+ ...clientRoundState(record.last_round_at_ms, record.last_error_code, record.consecutive_failures),
430
+ };
431
+ }
432
+ function toPartitionRegistryEntry(row) {
433
+ return {
434
+ partition: row.partition,
435
+ logEpoch: row.log_epoch,
436
+ epochRequired: row.epoch_required === 1,
437
+ lastAuthenticatedAtMs: row.last_authenticated_at_ms,
438
+ };
439
+ }
303
440
  /**
304
- * Fold one `commitWindowPageSql` page into commits, preserving the exact
305
- * semantics of the old per-candidate loop:
306
- *
307
- * - rows arrive ordered (commit_seq, idx); consecutive rows with the same
308
- * `commit_seq` are one candidate commit;
309
- * - every candidate advances the cursor (`lastSeq`) — including vanished
310
- * commits (NULL meta) and commits whose changes all fail the exact
311
- * multi-variable scope verification (`matchesEffective`);
312
- * - a commit is emitted only with its matching changes, in `idx` order;
313
- * - stops after the commit that accumulates at least `remaining` matching
314
- * changes (never splitting a commit).
315
- *
316
- * `candidateCount` counts the processed candidates so the caller can detect
317
- * a short page (window exhausted) exactly as it did with the old candidate
318
- * query.
441
+ * The `ServerStorage` methods SQLite and D1 share. A subclass supplies the
442
+ * execution seam and implements the rest of the interface: schema migration,
443
+ * `begin`, registered queries, the serve gate and checkpoints.
319
444
  */
320
- export function collectCommitWindowPage(records, scopeFilter, remaining) {
321
- const commits = [];
322
- let delivered = 0;
323
- let lastSeq = 0;
324
- let candidateCount = 0;
325
- let i = 0;
326
- while (i < records.length) {
327
- const head = records[i];
328
- if (head === undefined)
329
- break;
330
- const seq = head.commit_seq;
331
- candidateCount += 1;
332
- lastSeq = seq;
333
- const changes = [];
334
- for (; i < records.length; i++) {
335
- const record = records[i];
336
- if (record === undefined || record.commit_seq !== seq)
445
+ export class SqliteFamilyStorage {
446
+ /** Set by `ensureSchema`: app-table lookup for the relational row store. */
447
+ tables;
448
+ schemaVersion;
449
+ /** Resolve a table's compiled schema; row operations require `ensureSchema`. */
450
+ table(name) {
451
+ const table = this.tables?.get(name);
452
+ if (table === undefined) {
453
+ throw new Error(`unknown table ${JSON.stringify(name)} — ensureSchema(schema) must run before row operations`);
454
+ }
455
+ return table;
456
+ }
457
+ prepareAuthoritativeQuery(partition, query) {
458
+ if (this.tables === undefined) {
459
+ throw new Error('ensureSchema(schema) must run before registered queries');
460
+ }
461
+ return bindAuthoritativePartition(prepareAuthoritativeQuery(query.plan, query.params, query.tables, this.tables), partition);
462
+ }
463
+ async touchPartition(partition, authenticatedAtMs, initialLogEpoch) {
464
+ if (initialLogEpoch.length === 0) {
465
+ throw new Error('initial log epoch must be non-empty');
466
+ }
467
+ // One atomic unit, so an idle SQLite connection runs both statements at
468
+ // call time, before a `close()` in the same tick. The upsert writes only
469
+ // a new partition or one whose last authentication is a full interval old.
470
+ const [, rows] = await this.atomic([
471
+ {
472
+ sql: `INSERT INTO sync_partition_registry(
473
+ partition, log_epoch, last_authenticated_at_ms
474
+ ) VALUES (?,?,?)
475
+ ON CONFLICT(partition) DO UPDATE SET
476
+ last_authenticated_at_ms=excluded.last_authenticated_at_ms
477
+ WHERE excluded.last_authenticated_at_ms - last_authenticated_at_ms >= ?`,
478
+ params: [
479
+ partition,
480
+ initialLogEpoch,
481
+ authenticatedAtMs,
482
+ PARTITION_TOUCH_INTERVAL_MS,
483
+ ],
484
+ },
485
+ {
486
+ sql: `SELECT partition, log_epoch, epoch_required, last_authenticated_at_ms
487
+ FROM sync_partition_registry WHERE partition=?`,
488
+ params: [partition],
489
+ },
490
+ ]);
491
+ const row = rows?.[0];
492
+ if (row === undefined)
493
+ throw new Error('partition registry write did not persist');
494
+ return toPartitionRegistryEntry(row);
495
+ }
496
+ async rotatePartitionLogEpoch(partition, logEpoch, authenticatedAtMs) {
497
+ if (logEpoch.length === 0)
498
+ throw new Error('log epoch must be non-empty');
499
+ await this.atomic([
500
+ {
501
+ sql: `INSERT INTO sync_partition_registry(
502
+ partition, log_epoch, epoch_required, last_authenticated_at_ms
503
+ ) VALUES (?,?,1,?)
504
+ ON CONFLICT(partition) DO UPDATE SET
505
+ log_epoch=excluded.log_epoch,
506
+ epoch_required=1,
507
+ last_authenticated_at_ms=excluded.last_authenticated_at_ms`,
508
+ params: [partition, logEpoch, authenticatedAtMs],
509
+ },
510
+ {
511
+ sql: 'DELETE FROM sync_clients WHERE partition=?',
512
+ params: [partition],
513
+ },
514
+ ]);
515
+ return {
516
+ partition,
517
+ logEpoch,
518
+ epochRequired: true,
519
+ lastAuthenticatedAtMs: authenticatedAtMs,
520
+ };
521
+ }
522
+ async listPartitionRegistry() {
523
+ return (await this.all(`SELECT partition, log_epoch, epoch_required, last_authenticated_at_ms
524
+ FROM sync_partition_registry ORDER BY partition`, [])).map(toPartitionRegistryEntry);
525
+ }
526
+ async getMaxCommitSeq(partition) {
527
+ const [row] = await this.all('SELECT max_commit_seq FROM sync_partitions WHERE partition=?', [partition]);
528
+ return row?.max_commit_seq ?? 0;
529
+ }
530
+ async getPartitionLogEpoch(partition) {
531
+ const [row] = await this.all('SELECT log_epoch FROM sync_partition_registry WHERE partition=?', [partition]);
532
+ return row?.log_epoch;
533
+ }
534
+ async getHorizonSeq(partition) {
535
+ const [row] = await this.all('SELECT horizon_seq FROM sync_partitions WHERE partition=?', [partition]);
536
+ return row?.horizon_seq ?? 0;
537
+ }
538
+ async setHorizonSeq(partition, seq) {
539
+ await this.all(`INSERT INTO sync_partitions(partition, horizon_seq) VALUES (?,?)
540
+ ON CONFLICT(partition) DO UPDATE SET horizon_seq=max(horizon_seq,excluded.horizon_seq)`, [partition, seq]);
541
+ }
542
+ async pruneCommitsThrough(partition, query) {
543
+ validateCommitPruneQuery(query);
544
+ // Every write re-checks the epoch, so the unit needs no read before its
545
+ // writes: on a mismatch it changes nothing and the first row reports it.
546
+ const epochGuard = 'EXISTS (SELECT 1 FROM sync_partition_registry WHERE partition=? AND log_epoch=?)';
547
+ const horizon = '(SELECT horizon_seq FROM sync_partitions WHERE partition=?)';
548
+ const results = await this.atomic([
549
+ {
550
+ sql: `SELECT log_epoch, coalesce(${horizon},0) AS previous_horizon_seq FROM sync_partition_registry WHERE partition=?`,
551
+ params: [partition, partition],
552
+ },
553
+ {
554
+ sql: `INSERT INTO sync_partitions(partition,horizon_seq) SELECT ?,? WHERE ${epochGuard}
555
+ ON CONFLICT(partition) DO UPDATE SET horizon_seq=max(horizon_seq,excluded.horizon_seq)`,
556
+ params: [partition, query.throughSeq, partition, query.logEpoch],
557
+ },
558
+ {
559
+ sql: `SELECT horizon_seq, (SELECT count(*) FROM sync_commits WHERE partition=? AND commit_seq<=${horizon}) AS removed_commits FROM sync_partitions WHERE partition=?`,
560
+ params: [partition, partition, partition],
561
+ },
562
+ // Change-scope entries go first, by the keys of the changes being
563
+ // pruned: a predicate on `commit_seq` alone would scan the partition's
564
+ // whole scope index, because `commit_seq` is its last key column.
565
+ {
566
+ sql: `DELETE FROM sync_change_scopes WHERE (partition, tbl, var, value, commit_seq) IN (
567
+ SELECT c.partition, c.tbl, j.key, j.value, c.commit_seq
568
+ FROM sync_changes c, json_each(c.scopes) j
569
+ WHERE c.partition=? AND c.commit_seq<=${horizon})
570
+ AND ${epochGuard}`,
571
+ params: [partition, partition, partition, query.logEpoch],
572
+ },
573
+ // §4.6: tombstones prune in the same pass as the commit log.
574
+ ...['sync_commits', 'sync_changes', 'sync_tombstones'].map((table) => ({
575
+ sql: `DELETE FROM ${table} WHERE partition=? AND commit_seq<=${horizon} AND ${epochGuard}`,
576
+ params: [partition, partition, partition, query.logEpoch],
577
+ })),
578
+ ]);
579
+ const [before, after] = [results[0], results[2]].map((rows) => {
580
+ const row = rows?.[0];
581
+ return typeof row === 'object' && row !== null
582
+ ? row
583
+ : undefined;
584
+ });
585
+ if (before?.log_epoch !== query.logEpoch)
586
+ throw new StorageQueryError('sync.storage.prune_epoch_mismatch');
587
+ if (typeof before.previous_horizon_seq !== 'number' ||
588
+ typeof after?.horizon_seq !== 'number' ||
589
+ typeof after.removed_commits !== 'number') {
590
+ throw new Error('pruning returned invalid horizon metadata');
591
+ }
592
+ return {
593
+ previousHorizonSeq: before.previous_horizon_seq,
594
+ horizonSeq: after.horizon_seq,
595
+ removedCommits: after.removed_commits,
596
+ };
597
+ }
598
+ async getCommitSeqBefore(partition, createdBeforeMs) {
599
+ const [row] = await this.all('SELECT max(commit_seq) AS seq FROM sync_commits WHERE partition=? AND created_at_ms<?', [partition, createdBeforeMs]);
600
+ return row?.seq ?? 0;
601
+ }
602
+ async sourceCoverageSeq(partition, tables) {
603
+ if (tables.length === 0)
604
+ return 0;
605
+ const [row] = await this.all(`SELECT max(commit_seq) AS seq FROM sync_changes
606
+ WHERE partition=? AND tbl IN (${placeholders(tables.length)})`, [partition, ...tables]);
607
+ return row?.seq ?? 0;
608
+ }
609
+ async hasSourceChangesAbove(partition, tables, seq) {
610
+ // Read the horizon before the window scan: a horizon past `seq` means the
611
+ // history that would answer the question is gone, so an empty scan proves
612
+ // nothing and must not be reported as `clean`.
613
+ const horizon = await this.getHorizonSeq(partition);
614
+ if (tables.length === 0)
615
+ return 'clean';
616
+ const hit = await this.all(`SELECT 1 AS hit FROM sync_changes
617
+ WHERE partition=? AND tbl IN (${placeholders(tables.length)})
618
+ AND commit_seq>? LIMIT 1`, [partition, ...tables, seq]);
619
+ if (hit.length > 0)
620
+ return 'changed';
621
+ return horizon > seq ? 'unverifiable' : 'clean';
622
+ }
623
+ async getRow(partition, table, rowId) {
624
+ const [record] = await this.guardedAll(selectRowSql(this.table(table), 'sqlite'), [partition, rowId]);
625
+ return record === undefined ? undefined : toStoredRow(record);
626
+ }
627
+ async getPushResult(partition, clientId, clientCommitId) {
628
+ const [record] = await this.guardedAll('SELECT result FROM sync_push_results WHERE partition=? AND client_id=? AND client_commit_id=?', [partition, clientId, clientCommitId]);
629
+ return record === undefined
630
+ ? undefined
631
+ : deserializePushResult(record.result);
632
+ }
633
+ async claimReactions(partition, query) {
634
+ if (query.types.length === 0 || query.limit <= 0)
635
+ return [];
636
+ if (query.types.length + 7 > this.maxBindParams) {
637
+ throw new Error('D1 reaction claim exceeds the bound-parameter limit');
638
+ }
639
+ const records = await this.all(`UPDATE sync_reactions
640
+ SET status='leased', attempts=attempts+1,
641
+ lease_owner=?, lease_expires_at_ms=?, completed_at_ms=NULL
642
+ WHERE (partition, idempotency_key) IN (
643
+ SELECT partition, idempotency_key
644
+ FROM sync_reactions
645
+ WHERE partition=? AND type IN (${placeholders(query.types.length)})
646
+ AND ((status='pending' AND available_at_ms<=?)
647
+ OR (status='leased' AND lease_expires_at_ms<=?))
648
+ ORDER BY CASE WHEN status='leased' THEN lease_expires_at_ms
649
+ ELSE available_at_ms END,
650
+ created_at_ms, idempotency_key
651
+ LIMIT ?
652
+ )
653
+ RETURNING *`, [
654
+ query.leaseOwner,
655
+ Math.min(Number.MAX_SAFE_INTEGER, query.nowMs + query.leaseDurationMs),
656
+ partition,
657
+ ...query.types,
658
+ query.nowMs,
659
+ query.nowMs,
660
+ query.limit,
661
+ ]);
662
+ return records
663
+ .map(toStoredReaction)
664
+ .sort((a, b) => a.createdAtMs - b.createdAtMs ||
665
+ a.idempotencyKey.localeCompare(b.idempotencyKey));
666
+ }
667
+ async completeReaction(partition, idempotencyKey, leaseOwner, completedAtMs) {
668
+ const updated = await this.all(`UPDATE sync_reactions
669
+ SET status='completed', completed_at_ms=?,
670
+ lease_owner=NULL, lease_expires_at_ms=NULL
671
+ WHERE partition=? AND idempotency_key=?
672
+ AND status='leased' AND lease_owner=?
673
+ RETURNING idempotency_key`, [completedAtMs, partition, idempotencyKey, leaseOwner]);
674
+ return updated.length === 1;
675
+ }
676
+ async extendReactionLease(partition, idempotencyKey, leaseOwner, leaseExpiresAtMs) {
677
+ const updated = await this.all(`UPDATE sync_reactions SET lease_expires_at_ms=?
678
+ WHERE partition=? AND idempotency_key=?
679
+ AND status='leased' AND lease_owner=?
680
+ RETURNING idempotency_key`, [leaseExpiresAtMs, partition, idempotencyKey, leaseOwner]);
681
+ return updated.length === 1;
682
+ }
683
+ async failReaction(partition, idempotencyKey, update) {
684
+ const updated = await this.all(`UPDATE sync_reactions
685
+ SET status=?, available_at_ms=?, last_failure=?,
686
+ lease_owner=NULL, lease_expires_at_ms=NULL
687
+ WHERE partition=? AND idempotency_key=?
688
+ AND status='leased' AND lease_owner=?
689
+ RETURNING idempotency_key`, [
690
+ update.retryAtMs === undefined ? 'dead-letter' : 'pending',
691
+ update.retryAtMs ?? update.failure.atMs,
692
+ JSON.stringify(update.failure),
693
+ partition,
694
+ idempotencyKey,
695
+ update.leaseOwner,
696
+ ]);
697
+ return updated.length === 1;
698
+ }
699
+ async retryReaction(partition, idempotencyKey, nowMs) {
700
+ const updated = await this.all(`UPDATE sync_reactions
701
+ SET status='pending', attempts=0, available_at_ms=?,
702
+ last_failure=NULL, lease_owner=NULL, lease_expires_at_ms=NULL,
703
+ completed_at_ms=NULL
704
+ WHERE partition=? AND idempotency_key=? AND status='dead-letter'
705
+ RETURNING idempotency_key`, [nowMs, partition, idempotencyKey]);
706
+ return updated.length === 1;
707
+ }
708
+ async getReaction(partition, idempotencyKey) {
709
+ const [record] = await this.all('SELECT * FROM sync_reactions WHERE partition=? AND idempotency_key=?', [partition, idempotencyKey]);
710
+ return record === undefined ? undefined : toStoredReaction(record);
711
+ }
712
+ async listReactions(partition, query) {
713
+ const where = ['partition=?'];
714
+ const params = [partition];
715
+ if (query.statuses !== undefined && query.statuses.length > 0) {
716
+ where.push(`status IN (${placeholders(query.statuses.length)})`);
717
+ params.push(...query.statuses);
718
+ }
719
+ if (query.types !== undefined && query.types.length > 0) {
720
+ where.push(`type IN (${placeholders(query.types.length)})`);
721
+ params.push(...query.types);
722
+ }
723
+ if (params.length + 1 > this.maxBindParams) {
724
+ throw new Error('D1 reaction list exceeds the bound-parameter limit');
725
+ }
726
+ params.push(query.limit);
727
+ const records = await this.all(`SELECT * FROM sync_reactions WHERE ${where.join(' AND ')}
728
+ ORDER BY created_at_ms DESC, idempotency_key DESC LIMIT ?`, params);
729
+ return records.map(toStoredReaction);
730
+ }
731
+ async pruneReactions(partition, query) {
732
+ if (query.limit <= 0)
733
+ return { completed: 0, deadLetter: 0 };
734
+ const records = await this.all(`DELETE FROM sync_reactions
735
+ WHERE partition=? AND idempotency_key IN (
736
+ SELECT idempotency_key FROM sync_reactions
737
+ WHERE partition=?
738
+ AND ((status='completed' AND completed_at_ms IS NOT NULL
739
+ AND completed_at_ms<?)
740
+ OR (status='dead-letter' AND available_at_ms<?))
741
+ ORDER BY CASE WHEN status='completed' THEN completed_at_ms
742
+ ELSE available_at_ms END,
743
+ idempotency_key
744
+ LIMIT ?
745
+ )
746
+ AND ((status='completed' AND completed_at_ms IS NOT NULL
747
+ AND completed_at_ms<?)
748
+ OR (status='dead-letter' AND available_at_ms<?))
749
+ RETURNING status`, [
750
+ partition,
751
+ partition,
752
+ query.completedBeforeMs,
753
+ query.deadLetterBeforeMs,
754
+ query.limit,
755
+ query.completedBeforeMs,
756
+ query.deadLetterBeforeMs,
757
+ ]);
758
+ return {
759
+ completed: records.filter((record) => record.status === 'completed')
760
+ .length,
761
+ deadLetter: records.filter((record) => record.status === 'dead-letter')
762
+ .length,
763
+ };
764
+ }
765
+ async latestScopedChangeSeq(partition, query) {
766
+ const variable = Object.keys(query.scopes).sort()[0];
767
+ const value = variable === undefined ? undefined : query.scopes[variable];
768
+ if (variable === undefined || value === undefined)
769
+ return 0;
770
+ // One index-only max over the (partition, tbl, var, value) prefix.
771
+ const [row] = await this.guardedAll('SELECT max(commit_seq) AS seq FROM sync_change_scopes WHERE partition=? AND tbl=? AND var=? AND value=?', [partition, query.table, variable, value]);
772
+ return row?.seq ?? 0;
773
+ }
774
+ readLiveWindow(partition, query) {
775
+ // One statement per page: the unit keys bind as one JSON array, and the
776
+ // CROSS JOIN keeps them the outer loop, so each key seeks one range of
777
+ // `sync_change_scopes_by_key` (INDEXED BY fails loudly when the index is
778
+ // missing). The candidates LEFT JOIN the commit meta and every change of
779
+ // the commit; a candidate whose commit vanished comes back with NULL
780
+ // meta and still advances the scan.
781
+ return readLiveWindowPages(query, async (keys, limit) => (await this.guardedAll(`SELECT c.commit_seq AS commit_seq, m.actor_id AS actor_id, m.created_at_ms AS created_at_ms,
782
+ ch.tbl AS tbl, ch.row_id AS row_id, ch.op AS op, ch.row_version AS row_version, ch.scopes AS scopes, ch.payload AS payload
783
+ FROM (SELECT DISTINCT s.commit_seq AS commit_seq
784
+ FROM json_each(?2) AS k
785
+ CROSS JOIN sync_change_scopes AS s INDEXED BY sync_change_scopes_by_key
786
+ ON s.partition=?1 AND s.var=json_extract(k.value, '$.var')
787
+ AND s.value=json_extract(k.value, '$.value')
788
+ AND s.commit_seq>json_extract(k.value, '$.after') AND s.commit_seq<=?3
789
+ ORDER BY s.commit_seq LIMIT ?4) AS c
790
+ LEFT JOIN sync_commits AS m ON m.partition=?1 AND m.commit_seq=c.commit_seq
791
+ LEFT JOIN sync_changes AS ch ON ch.partition=?1 AND ch.commit_seq=c.commit_seq
792
+ ORDER BY c.commit_seq, ch.idx`, [partition, JSON.stringify(keys), query.throughSeq, limit])).map((record) => ({
793
+ commitSeq: record.commit_seq,
794
+ ...(record.actor_id !== null && record.created_at_ms !== null
795
+ ? {
796
+ meta: {
797
+ actorId: record.actor_id,
798
+ createdAtMs: record.created_at_ms,
799
+ },
800
+ }
801
+ : {}),
802
+ ...(record.tbl !== null
803
+ ? { change: toStoredChange({ ...record, tbl: record.tbl }) }
804
+ : {}),
805
+ })));
806
+ }
807
+ async scanRows(partition, query) {
808
+ const firstVariable = assertScopeIndexedScan(query);
809
+ const firstValues = query.scopeFilter[firstVariable] ?? [];
810
+ if (firstValues.length === 0)
811
+ return [];
812
+ // Candidates via the inverted index LEFT JOINed to the row table — one
813
+ // statement per page, never one per row (see `scanRowPageSql`). Exact
814
+ // multi-variable verification against the stored scope map below.
815
+ const sql = scanRowPageSql(this.table(query.table), firstValues.length, 'sqlite');
816
+ const rows = [];
817
+ let afterRowId = query.afterRowId ?? '';
818
+ const batchSize = Math.max(64, query.limit);
819
+ while (rows.length < query.limit) {
820
+ const records = await this.guardedAll(sql, [
821
+ partition,
822
+ query.table,
823
+ firstVariable,
824
+ JSON.stringify(firstValues),
825
+ afterRowId,
826
+ batchSize,
827
+ partition,
828
+ ]);
829
+ if (records.length === 0)
337
830
  break;
338
- // NULL tbl: a candidate with no change rows for the table (LEFT JOIN
339
- // contract) — it still advanced the cursor above.
340
- if (record.tbl === null ||
341
- record.row_id === null ||
342
- record.op === null ||
343
- record.scopes === null) {
344
- continue;
831
+ for (const record of records) {
832
+ afterRowId = record.row_id;
833
+ // NULL payload: an index candidate whose row vanished — it still
834
+ // advances the keyset cursor (LEFT JOIN contract) but yields no row.
835
+ if (record.payload === null)
836
+ continue;
837
+ const stored = toStoredRow(record);
838
+ if (!matchesEffective(stored.scopes, query.scopeFilter))
839
+ continue;
840
+ rows.push(stored);
841
+ if (rows.length >= query.limit)
842
+ break;
345
843
  }
346
- const change = toStoredChange({
347
- tbl: record.tbl,
348
- row_id: record.row_id,
349
- op: record.op,
350
- row_version: record.row_version,
351
- scopes: record.scopes,
352
- payload: record.payload,
844
+ if (records.length < batchSize)
845
+ break;
846
+ }
847
+ return rows;
848
+ }
849
+ async scanRowsByIndex(partition, query) {
850
+ const table = this.table(query.table);
851
+ const statement = indexRowPageStatement(table, resolveIndexRowScan(table, query), query.values, partition, query.afterRowId, query.limit, 'sqlite');
852
+ return (await this.guardedAll(statement.sql, statement.params)).map(toStoredRow);
853
+ }
854
+ async getClientRecord(partition, clientId) {
855
+ const [record] = await this.all(`SELECT ${CLIENT_RECORD_COLUMNS} FROM sync_clients WHERE partition=? AND client_id=?`, [partition, clientId]);
856
+ return record === undefined ? undefined : toClientRecord(record);
857
+ }
858
+ async putClientRecord(partition, record, options) {
859
+ // One row per (partition, client_id): every non-key field is written
860
+ // from the new record, except the registration list and digest, which
861
+ // only a traveling list replaces (§4.5). `keepRoundOutcome` leaves the
862
+ // round-state columns alone (§1.5, §4.5).
863
+ const registration = record.registration;
864
+ await this.all(`INSERT INTO sync_clients(partition, client_id, actor_id, wire_version, cursor, updated_at_ms, last_round_at_ms, schema_version, units, registration_digest, catching_up) VALUES (?,?,?,?,?,?,?,?,?,?,?)
865
+ ON CONFLICT(partition, client_id) DO UPDATE SET
866
+ actor_id=excluded.actor_id,
867
+ wire_version=excluded.wire_version,
868
+ cursor=excluded.cursor,
869
+ updated_at_ms=excluded.updated_at_ms,
870
+ last_round_at_ms=excluded.last_round_at_ms,
871
+ schema_version=excluded.schema_version,${registration === undefined
872
+ ? ''
873
+ : `
874
+ units=excluded.units,
875
+ registration_digest=excluded.registration_digest,`}
876
+ catching_up=excluded.catching_up${options?.keepRoundOutcome === true
877
+ ? ''
878
+ : `,
879
+ last_error_code=NULL,
880
+ consecutive_failures=0`}`, [
881
+ partition,
882
+ record.clientId,
883
+ record.actorId,
884
+ record.wireVersion,
885
+ record.cursor,
886
+ record.updatedAtMs,
887
+ record.lastRoundAtMs ?? record.updatedAtMs,
888
+ record.schemaVersion ?? null,
889
+ registration === undefined ? null : JSON.stringify(registration.units),
890
+ registration?.digest ?? null,
891
+ JSON.stringify(record.catchingUp),
892
+ ]);
893
+ }
894
+ async recordClientRoundFailure(partition, clientId, actorId, errorCode, atMs) {
895
+ await this.all(`UPDATE sync_clients
896
+ SET last_round_at_ms=?, last_error_code=?,
897
+ consecutive_failures=consecutive_failures+1
898
+ WHERE partition=? AND client_id=? AND actor_id=?`, [atMs, errorCode, partition, clientId, actorId]);
899
+ }
900
+ async advanceClientCursor(partition, clientId, actorId, logEpoch, cursor, updatedAtMs) {
901
+ // §8.2: the ack never raises the record cursor above a catching-up
902
+ // unit's cursor, so pruning keeps that unit's history (§4.6).
903
+ await this.all(`UPDATE sync_clients
904
+ SET cursor=MAX(cursor, MIN(?, coalesce((
905
+ SELECT min(json_extract(u.value, '$.cursor'))
906
+ FROM json_each(sync_clients.catching_up) AS u
907
+ WHERE json_extract(u.value, '$.cursor')>=0), ?))),
908
+ updated_at_ms=MAX(updated_at_ms, ?)
909
+ WHERE partition=? AND client_id=? AND actor_id=?
910
+ AND EXISTS (SELECT 1 FROM sync_partition_registry
911
+ WHERE partition=sync_clients.partition AND log_epoch=?)`, [cursor, cursor, updatedAtMs, partition, clientId, actorId, logEpoch]);
912
+ }
913
+ async getActiveClientCursorFloor(partition, cutoffMs) {
914
+ const [row] = await this.all('SELECT MIN(cursor) AS cursor FROM sync_clients WHERE partition=? AND updated_at_ms>=? AND cursor>=0', [partition, cutoffMs]);
915
+ return row.cursor;
916
+ }
917
+ async listClientCursors(partition) {
918
+ const records = await this.all('SELECT client_id, cursor, updated_at_ms FROM sync_clients WHERE partition=?', [partition]);
919
+ return records.map((r) => ({
920
+ clientId: r.client_id,
921
+ cursor: r.cursor,
922
+ updatedAtMs: r.updated_at_ms,
923
+ }));
924
+ }
925
+ async listRowsReferencingBlob(partition, blobId) {
926
+ // One statement: the by-blob index (§5.9.4/§5.9.5) supplies the candidate
927
+ // rows and each row's stored scopes come from its row table for the §3.4
928
+ // authorization test (see `rowsReferencingBlobSql`).
929
+ if (this.tables === undefined || this.tables.size === 0)
930
+ return [];
931
+ return (await this.guardedAll(rowsReferencingBlobSql(this.tables.values(), 'sqlite'), [
932
+ partition,
933
+ blobId,
934
+ ])).flatMap((row) => row.scopes === null
935
+ ? []
936
+ : [
937
+ {
938
+ table: row.tbl,
939
+ rowId: row.row_id,
940
+ scopes: JSON.parse(row.scopes),
941
+ },
942
+ ]);
943
+ }
944
+ async listReferencedBlobIds(partition) {
945
+ const rows = await this.all('SELECT DISTINCT blob_id FROM sync_blob_refs WHERE partition=?', [partition]);
946
+ return rows.map((r) => r.blob_id);
947
+ }
948
+ async listScopeValueRows(partition, query) {
949
+ // §4.6.1: rowIds of one table bound to one scope value, budgeted.
950
+ const rows = await this.all('SELECT row_id FROM sync_row_scopes WHERE partition=? AND tbl=? AND var=? AND value=? ORDER BY row_id LIMIT ?', [partition, query.table, query.variable, query.value, query.limit]);
951
+ return rows.map((row) => row.row_id);
952
+ }
953
+ async eraseScopeValueHistory(partition, query) {
954
+ const params = [
955
+ partition,
956
+ query.table,
957
+ query.variable,
958
+ query.value,
959
+ query.throughSeq,
960
+ `$.${JSON.stringify(query.variable)}`,
961
+ query.limit,
962
+ ];
963
+ // §4.6.1 history scrub: upsert change records of the binding first, then
964
+ // the change scope entries whose commit no longer holds a change of the
965
+ // binding, then `serverRow` of stored conflict results whose conflict
966
+ // authorization scopes carry the binding. Each statement returns one row
967
+ // per changed record (D1 batch results carry no reliable change count).
968
+ const results = await this.atomic([
969
+ `DELETE FROM sync_changes WHERE rowid IN (
970
+ SELECT c.rowid FROM sync_change_scopes s JOIN sync_changes c
971
+ ON c.partition=s.partition AND c.commit_seq=s.commit_seq AND c.tbl=s.tbl
972
+ WHERE s.partition=?1 AND s.tbl=?2 AND s.var=?3 AND s.value=?4
973
+ AND s.commit_seq<=?5 AND c.op=1 AND json_extract(c.scopes, ?6)=s.value
974
+ LIMIT ?7) RETURNING 1 AS removed`,
975
+ `DELETE FROM sync_change_scopes WHERE rowid IN (
976
+ SELECT s.rowid FROM sync_change_scopes s
977
+ WHERE s.partition=?1 AND s.tbl=?2 AND s.var=?3 AND s.value=?4
978
+ AND s.commit_seq<=?5 AND NOT EXISTS (
979
+ SELECT 1 FROM sync_changes c
980
+ WHERE c.partition=s.partition AND c.commit_seq=s.commit_seq
981
+ AND c.tbl=s.tbl AND json_extract(c.scopes, ?6)=s.value)
982
+ LIMIT ?7) RETURNING 1 AS removed`,
983
+ `UPDATE sync_push_results SET result=json_set(result, '$.results', json((
984
+ SELECT json_group_array(json(json_remove(e.value, '$.serverRow')))
985
+ FROM (SELECT value FROM json_each(sync_push_results.result, '$.results')
986
+ ORDER BY key) e)))
987
+ WHERE rowid IN (
988
+ SELECT rowid FROM sync_push_results
989
+ WHERE partition=?1
990
+ AND json_extract(result, '$.conflictAuthorization.table')=?2
991
+ AND json_extract(result,
992
+ '$.conflictAuthorization.scopes' || substr(?6, 2))=?4
993
+ AND EXISTS (SELECT 1 FROM json_each(result, '$.results') r
994
+ WHERE json_type(r.value, '$.serverRow') IS NOT NULL)
995
+ LIMIT ?7) RETURNING 1 AS removed`,
996
+ ].map((sql) => ({ sql, params })));
997
+ return results.reduce((removed, rows) => removed + rows.length, 0);
998
+ }
999
+ // -- admin/console read surface --------------------------------------------
1000
+ async listClientRecords(partition) {
1001
+ return (await this.all(`SELECT ${CLIENT_RECORD_COLUMNS} FROM sync_clients WHERE partition=? ORDER BY updated_at_ms DESC`, [partition])).map(toClientRecord);
1002
+ }
1003
+ async listCommitMetadata(partition, query) {
1004
+ // Newest-first window, resumed by `afterSeq` (exclusive lower bound) and
1005
+ // ended by `beforeSeq` (exclusive upper bound) when paging older. An
1006
+ // omitted bound is the largest safe commitSeq, so one statement serves
1007
+ // both the bounded and unbounded read.
1008
+ const beforeSeq = query.beforeSeq ?? Number.MAX_SAFE_INTEGER;
1009
+ const rows = await this.all(query.table
1010
+ ? `SELECT c.commit_seq, c.client_id, c.client_commit_id, c.actor_id, c.created_at_ms
1011
+ FROM sync_commits c
1012
+ WHERE c.partition=? AND c.commit_seq>? AND c.commit_seq<?
1013
+ AND EXISTS (SELECT 1 FROM sync_changes ch
1014
+ WHERE ch.partition=c.partition AND ch.commit_seq=c.commit_seq AND ch.tbl=?)
1015
+ ORDER BY c.commit_seq DESC LIMIT ?`
1016
+ : `SELECT commit_seq, client_id, client_commit_id, actor_id, created_at_ms
1017
+ FROM sync_commits
1018
+ WHERE partition=? AND commit_seq>? AND commit_seq<?
1019
+ ORDER BY commit_seq DESC LIMIT ?`, query.table
1020
+ ? [partition, query.afterSeq, beforeSeq, query.table, query.limit]
1021
+ : [partition, query.afterSeq, beforeSeq, query.limit]);
1022
+ // One grouped statement for the page's per-table change counts and, with
1023
+ // `changeSample`, one for the first `sample` changes (change-index order)
1024
+ // of every listed commit. The commit ids bind as one JSON array, so the
1025
+ // statement count does not grow with the page.
1026
+ const sampleCount = query.changeSample !== undefined &&
1027
+ Number.isInteger(query.changeSample) &&
1028
+ query.changeSample > 0
1029
+ ? query.changeSample
1030
+ : 0;
1031
+ const seqs = JSON.stringify(rows.map((row) => row.commit_seq));
1032
+ const counts = new Map();
1033
+ for (const count of rows.length === 0
1034
+ ? []
1035
+ : await this.all(`SELECT commit_seq, tbl, count(*) AS n FROM sync_changes
1036
+ WHERE partition=? AND commit_seq IN (SELECT value FROM json_each(?))
1037
+ GROUP BY commit_seq, tbl ORDER BY commit_seq, tbl`, [partition, seqs])) {
1038
+ counts.set(count.commit_seq, [
1039
+ ...(counts.get(count.commit_seq) ?? []),
1040
+ count,
1041
+ ]);
1042
+ }
1043
+ const samples = new Map();
1044
+ for (const change of sampleCount === 0 || rows.length === 0
1045
+ ? []
1046
+ : await this.all(`SELECT commit_seq, tbl, row_id, op FROM sync_changes
1047
+ WHERE partition=? AND commit_seq IN (SELECT value FROM json_each(?)) AND idx<?
1048
+ ORDER BY commit_seq, idx`, [partition, seqs, sampleCount])) {
1049
+ samples.set(change.commit_seq, [
1050
+ ...(samples.get(change.commit_seq) ?? []),
1051
+ {
1052
+ table: change.tbl,
1053
+ rowId: change.row_id,
1054
+ op: change.op === 1 ? 'upsert' : 'delete',
1055
+ },
1056
+ ]);
1057
+ }
1058
+ const out = [];
1059
+ for (const row of rows) {
1060
+ const changes = counts.get(row.commit_seq) ?? [];
1061
+ out.push({
1062
+ commitSeq: row.commit_seq,
1063
+ clientId: row.client_id,
1064
+ clientCommitId: row.client_commit_id,
1065
+ actorId: row.actor_id,
1066
+ createdAtMs: row.created_at_ms,
1067
+ changeCount: changes.reduce((sum, c) => sum + c.n, 0),
1068
+ tables: changes.map((c) => c.tbl),
1069
+ ...(sampleCount > 0
1070
+ ? { sample: samples.get(row.commit_seq) ?? [] }
1071
+ : {}),
353
1072
  });
354
- if (matchesEffective(change.scopes, scopeFilter))
355
- changes.push(change);
356
1073
  }
357
- // NULL meta: the commit vanished — cursor advanced, nothing emitted.
358
- if (head.actor_id === null || head.created_at_ms === null)
359
- continue;
360
- if (changes.length === 0)
361
- continue;
362
- commits.push({
363
- commitSeq: seq,
364
- createdAtMs: head.created_at_ms,
365
- actorId: head.actor_id,
1074
+ return out;
1075
+ }
1076
+ async getCommit(partition, commitSeq) {
1077
+ const [meta] = await this.all('SELECT client_id, client_commit_id, actor_id, created_at_ms FROM sync_commits WHERE partition=? AND commit_seq=?', [partition, commitSeq]);
1078
+ if (meta === undefined)
1079
+ return undefined;
1080
+ const changes = (await this.all('SELECT tbl, row_id, op, row_version, scopes, payload FROM sync_changes WHERE partition=? AND commit_seq=? ORDER BY idx', [partition, commitSeq])).map(toStoredChange);
1081
+ return {
1082
+ commitSeq,
1083
+ clientId: meta.client_id,
1084
+ clientCommitId: meta.client_commit_id,
1085
+ actorId: meta.actor_id,
1086
+ createdAtMs: meta.created_at_ms,
1087
+ changeCount: changes.length,
1088
+ tables: [...new Set(changes.map((change) => change.table))].sort(),
366
1089
  changes,
1090
+ };
1091
+ }
1092
+ async listRowChanges(partition, query) {
1093
+ // Retained-log read for one row: no dedicated index (the write path pays
1094
+ // nothing for it), bounded by retention (§4.6).
1095
+ const rows = await this.all(`SELECT ch.commit_seq, ch.op, ch.row_version, c.actor_id, c.client_id, c.created_at_ms
1096
+ FROM sync_changes ch
1097
+ JOIN sync_commits c
1098
+ ON c.partition=ch.partition AND c.commit_seq=ch.commit_seq
1099
+ WHERE ch.partition=? AND ch.tbl=? AND ch.row_id=?
1100
+ ORDER BY ch.commit_seq DESC, ch.idx DESC LIMIT ?`, [partition, query.table, query.rowId, query.limit]);
1101
+ return rows.map((row) => ({
1102
+ commitSeq: row.commit_seq,
1103
+ op: row.op === 1 ? 'upsert' : 'delete',
1104
+ ...(row.row_version !== null ? { rowVersion: row.row_version } : {}),
1105
+ actorId: row.actor_id,
1106
+ clientId: row.client_id,
1107
+ createdAtMs: row.created_at_ms,
1108
+ }));
1109
+ }
1110
+ async listRows(partition, query) {
1111
+ // Keyset page over the row table's (partition, rowId) primary key: an
1112
+ // index range read, no scope filter, no per-row lookup.
1113
+ return (await this.guardedAll(`SELECT ${quoteIdent(SYNC_ROW_ID_COLUMN)} AS row_id, ${quoteIdent(SYNC_VERSION_COLUMN)} AS server_version, ${quoteIdent(SYNC_SCOPES_COLUMN)} AS scopes, ${quoteIdent(SYNC_PAYLOAD_COLUMN)} AS payload, ${quoteIdent(SYNC_COLUMN_VERSIONS_COLUMN)} AS column_versions
1114
+ FROM ${quoteIdent(this.table(query.table).name)}
1115
+ WHERE ${quoteIdent(SYNC_PARTITION_COLUMN)}=? AND ${quoteIdent(SYNC_ROW_ID_COLUMN)}>?
1116
+ ORDER BY ${quoteIdent(SYNC_ROW_ID_COLUMN)} LIMIT ?`, [partition, query.afterRowId ?? '', query.limit])).map(toStoredRow);
1117
+ }
1118
+ async countRows(partition, table) {
1119
+ const [record] = await this.guardedAll(`SELECT count(*) AS n FROM ${quoteIdent(this.table(table).name)} WHERE ${quoteIdent(SYNC_PARTITION_COLUMN)}=?`, [partition]);
1120
+ return record?.n ?? 0;
1121
+ }
1122
+ async listPushResults(partition, clientCommitId) {
1123
+ // Retained outcomes for one clientCommitId: no dedicated index, ordered
1124
+ // by client so the read is deterministic.
1125
+ const records = await this.guardedAll('SELECT client_id, result FROM sync_push_results WHERE partition=? AND client_commit_id=? ORDER BY client_id', [partition, clientCommitId]);
1126
+ return records.map((record) => ({
1127
+ clientId: record.client_id,
1128
+ result: deserializePushResult(record.result),
1129
+ }));
1130
+ }
1131
+ async listPushWatermarks(partition, clientCommitId) {
1132
+ // The clients come from the retained commit log, which has no index on
1133
+ // `client_commit_id`; the read is bounded by retention (§4.6).
1134
+ return (await this.all(`SELECT client_id, outbox_id, through_seq FROM sync_push_watermarks
1135
+ WHERE partition=? AND client_id IN (
1136
+ SELECT client_id FROM sync_commits WHERE partition=? AND client_commit_id=?)
1137
+ ORDER BY client_id, outbox_id`, [partition, partition, clientCommitId])).map((row) => ({
1138
+ clientId: row.client_id,
1139
+ outboxId: row.outbox_id,
1140
+ throughSeq: row.through_seq,
1141
+ }));
1142
+ }
1143
+ async scopeActivity(partition, query) {
1144
+ // One statement for the page: candidate (commit, table) pairs from the
1145
+ // `sync_change_scopes_by_key` range of the key, newest first, joined to
1146
+ // the commit metadata with the table's change count. A candidate whose
1147
+ // commit was pruned has no metadata and is skipped.
1148
+ return (await this.all(`SELECT s.commit_seq, s.tbl, m.actor_id, m.created_at_ms,
1149
+ (SELECT count(*) FROM sync_changes ch
1150
+ WHERE ch.partition=? AND ch.commit_seq=s.commit_seq AND ch.tbl=s.tbl) AS n
1151
+ FROM (SELECT DISTINCT commit_seq, tbl FROM sync_change_scopes
1152
+ WHERE partition=? AND var=? AND value=?
1153
+ ORDER BY commit_seq DESC LIMIT ?) s
1154
+ JOIN sync_commits m ON m.partition=? AND m.commit_seq=s.commit_seq
1155
+ ORDER BY s.commit_seq DESC`, [
1156
+ partition,
1157
+ partition,
1158
+ query.variable,
1159
+ query.value,
1160
+ query.limit,
1161
+ partition,
1162
+ ])).map((row) => ({
1163
+ commitSeq: row.commit_seq,
1164
+ table: row.tbl,
1165
+ createdAtMs: row.created_at_ms,
1166
+ actorId: row.actor_id,
1167
+ changeCount: row.n,
1168
+ }));
1169
+ }
1170
+ async listPartitions() {
1171
+ return (await this.listPartitionRegistry()).map((entry) => entry.partition);
1172
+ }
1173
+ }
1174
+ /**
1175
+ * The `StorageTransaction` writes SQLite and D1 share. `run` executes a write
1176
+ * at call time on SQLite, inside its `BEGIN IMMEDIATE`; D1 buffers it for the
1177
+ * one `db.batch` at `commit()`.
1178
+ */
1179
+ export class SqliteFamilyTransaction {
1180
+ partition;
1181
+ open = true;
1182
+ constructor(partition) {
1183
+ this.partition = partition;
1184
+ }
1185
+ assertOpen() {
1186
+ if (!this.open)
1187
+ throw new Error('transaction already finished');
1188
+ }
1189
+ async getRows(table, rowIds) {
1190
+ this.assertOpen();
1191
+ // One indexed lookup per id: SQLite is in-process, and on D1 `getRow`
1192
+ // owns the buffered-write overlay.
1193
+ const rows = new Map();
1194
+ for (const rowId of new Set(rowIds)) {
1195
+ const row = await this.getRow(table, rowId);
1196
+ if (row !== undefined)
1197
+ rows.set(rowId, row);
1198
+ }
1199
+ return rows;
1200
+ }
1201
+ async getTombstone(table, rowId) {
1202
+ this.assertOpen();
1203
+ const [row] = await this.all('SELECT commit_seq, server_version, scopes FROM sync_tombstones WHERE partition=? AND tbl=? AND row_id=?', [this.partition, table, rowId]);
1204
+ return row === undefined ? undefined : toTombstone(row);
1205
+ }
1206
+ async clearTombstone(table, rowId) {
1207
+ this.assertOpen();
1208
+ this.run('DELETE FROM sync_tombstones WHERE partition=? AND tbl=? AND row_id=?', [this.partition, table, rowId]);
1209
+ }
1210
+ /**
1211
+ * Write a row and refresh its scope-index entries. The DELETE drops only
1212
+ * the keys the new scope map no longer carries and runs before the upsert,
1213
+ * so its subquery reads the pre-upsert scope map; keys present in both
1214
+ * maps are left alone and the `INSERT OR IGNORE` writes nothing for them.
1215
+ */
1216
+ writeRow(table, row) {
1217
+ const p = this.partition;
1218
+ const compiled = this.table(table);
1219
+ this.run(`${deleteSqliteRowScopesSql(compiled)}
1220
+ AND (var, value) NOT IN (SELECT key, value FROM json_each(?))`, [p, table, row.rowId, p, row.rowId, JSON.stringify(row.scopes)]);
1221
+ this.run(upsertSql(compiled, 'sqlite'), upsertValues(compiled, p, row, 'sqlite'));
1222
+ for (const [variable, value] of Object.entries(row.scopes)) {
1223
+ this.run('INSERT OR IGNORE INTO sync_row_scopes(partition, tbl, var, value, row_id) VALUES (?,?,?,?,?)', [p, table, variable, value, row.rowId]);
1224
+ }
1225
+ }
1226
+ async deleteRow(table, rowId) {
1227
+ this.assertOpen();
1228
+ const p = this.partition;
1229
+ const compiled = this.table(table);
1230
+ this.run(deleteSqliteRowScopesSql(compiled), [p, table, rowId, p, rowId]);
1231
+ this.run(deleteRowSql(compiled, 'sqlite'), [p, rowId]);
1232
+ // §5.9.4: a deleted row references no blobs.
1233
+ this.run('DELETE FROM sync_blob_refs WHERE partition=? AND tbl=? AND row_id=?', [p, table, rowId]);
1234
+ }
1235
+ async setBlobRefs(table, rowId, blobIds) {
1236
+ this.assertOpen();
1237
+ const p = this.partition;
1238
+ // Replace the row's reference set atomically (§5.9.4).
1239
+ this.run('DELETE FROM sync_blob_refs WHERE partition=? AND tbl=? AND row_id=?', [p, table, rowId]);
1240
+ for (const blobId of blobIds) {
1241
+ this.run('INSERT OR IGNORE INTO sync_blob_refs(partition, tbl, row_id, blob_id) VALUES (?,?,?,?)', [p, table, rowId, blobId]);
1242
+ }
1243
+ }
1244
+ async appendCommit(commit) {
1245
+ this.assertOpen();
1246
+ const p = this.partition;
1247
+ const commitSeq = await this.appendCommitRow(commit);
1248
+ const liveAfterDelete = rowsLiveAfterDelete(commit.changes);
1249
+ commit.changes.forEach((change, idx) => {
1250
+ this.run('INSERT INTO sync_changes(partition, commit_seq, idx, tbl, row_id, op, row_version, scopes, payload) VALUES (?,?,?,?,?,?,?,?,?)', [
1251
+ p,
1252
+ commitSeq,
1253
+ idx,
1254
+ change.table,
1255
+ change.rowId,
1256
+ change.op === 'upsert' ? 1 : 2,
1257
+ change.rowVersion,
1258
+ JSON.stringify(change.scopes),
1259
+ change.payload ?? null,
1260
+ ]);
1261
+ if (change.op === 'delete' &&
1262
+ !liveAfterDelete.has(`${change.table}\u0000${change.rowId}`)) {
1263
+ // §5 delete precedence: every applied delete leaves a tombstone,
1264
+ // pruned with the commit log (§4.6). A delete that the same commit
1265
+ // follows with an upsert is a §2.2 scope move, not a deletion.
1266
+ this.run(`INSERT INTO sync_tombstones(partition, tbl, row_id, commit_seq, server_version, scopes) VALUES (?,?,?,?,?,?)
1267
+ ON CONFLICT(partition, tbl, row_id) DO UPDATE SET commit_seq=excluded.commit_seq, server_version=excluded.server_version, scopes=excluded.scopes`, [
1268
+ p,
1269
+ change.table,
1270
+ change.rowId,
1271
+ commitSeq,
1272
+ change.rowVersion,
1273
+ JSON.stringify(change.scopes),
1274
+ ]);
1275
+ }
1276
+ for (const [variable, value] of Object.entries(change.scopes)) {
1277
+ this.run('INSERT OR IGNORE INTO sync_change_scopes(partition, tbl, var, value, commit_seq) VALUES (?,?,?,?,?)', [p, change.table, variable, value, commitSeq]);
1278
+ }
367
1279
  });
368
- delivered += changes.length;
369
- if (delivered >= remaining)
370
- break;
1280
+ return commitSeq;
1281
+ }
1282
+ async putPushResult(clientId, clientCommitId, result, sequence) {
1283
+ this.assertOpen();
1284
+ this.run('INSERT OR IGNORE INTO sync_push_results(partition, client_id, client_commit_id, result, outbox_id, client_seq) VALUES (?,?,?,?,?,?)', [
1285
+ this.partition,
1286
+ clientId,
1287
+ clientCommitId,
1288
+ serializePushResult(result),
1289
+ sequence?.outboxId ?? null,
1290
+ sequence?.clientSeq ?? null,
1291
+ ]);
1292
+ }
1293
+ /**
1294
+ * The §9 settlement and §6.3.2 steps 1 and 2 for one request, then the
1295
+ * idempotency read of its first commit. The reads run before the writes,
1296
+ * so D1, which buffers the writes until commit, answers exactly as SQLite:
1297
+ * the first commit's result counts as deleted when the writes delete it.
1298
+ */
1299
+ async settleOutbox(clientId, clientCommitId, outbox) {
1300
+ const first = outbox.commits[0];
1301
+ const last = outbox.commits.at(-1);
1302
+ if (first === undefined ||
1303
+ last === undefined ||
1304
+ first.clientCommitId !== clientCommitId) {
1305
+ throw new Error("outbox settlement rides the request's first commit");
1306
+ }
1307
+ const p = this.partition;
1308
+ const [state] = await this.all(`SELECT (SELECT through_seq FROM sync_push_watermarks
1309
+ WHERE partition=?1 AND client_id=?2 AND outbox_id=?3) AS stored,
1310
+ EXISTS (SELECT 1 FROM sync_push_results WHERE partition=?1
1311
+ AND client_id=?2 AND client_commit_id=?5 AND outbox_id IS NULL) AS last_sequenceless,
1312
+ r.result AS result, r.outbox_id AS outbox_id, r.client_seq AS client_seq
1313
+ FROM (SELECT 1) LEFT JOIN sync_push_results AS r
1314
+ ON r.partition=?1 AND r.client_id=?2 AND r.client_commit_id=?4`, [p, clientId, outbox.outboxId, first.clientCommitId, last.clientCommitId]);
1315
+ const watermark = Math.max(state?.stored ?? 0, first.clientSeq);
1316
+ const commits = JSON.stringify(outbox.commits.map((commit) => [commit.clientCommitId, commit.clientSeq]));
1317
+ // §9 (b), then (a): with no pre-upgrade result on the request's last
1318
+ // commit, every remaining one outside the request left the outbox.
1319
+ if (state?.last_sequenceless !== 1) {
1320
+ this.run(`DELETE FROM sync_push_results
1321
+ WHERE partition=? AND client_id=? AND outbox_id IS NULL
1322
+ AND client_commit_id NOT IN (SELECT json_extract(value, '$[0]') FROM json_each(?))`, [p, clientId, commits]);
1323
+ }
1324
+ this.run(`UPDATE sync_push_results SET outbox_id=?3, client_seq=(
1325
+ SELECT json_extract(c.value, '$[1]') FROM json_each(?4) AS c
1326
+ WHERE json_extract(c.value, '$[0]')=sync_push_results.client_commit_id)
1327
+ WHERE partition=?1 AND client_id=?2 AND outbox_id IS NULL
1328
+ AND client_commit_id IN (SELECT json_extract(value, '$[0]') FROM json_each(?4))`, [p, clientId, outbox.outboxId, commits]);
1329
+ // §6.3.2 steps 1 and 2.
1330
+ this.run(`INSERT INTO sync_push_watermarks(partition, client_id, outbox_id, through_seq) VALUES (?,?,?,?)
1331
+ ON CONFLICT(partition, client_id, outbox_id) DO UPDATE SET through_seq=max(through_seq, excluded.through_seq)`, [p, clientId, outbox.outboxId, watermark]);
1332
+ this.run('DELETE FROM sync_push_results WHERE partition=? AND client_id=? AND outbox_id=? AND client_seq<?', [p, clientId, outbox.outboxId, watermark]);
1333
+ // The sequence step 2 sees: (a) gives a pre-upgrade result the first
1334
+ // commit's sequence; a result of this outbox keeps its stored one.
1335
+ const deleted = state?.outbox_id === null
1336
+ ? first.clientSeq < watermark
1337
+ : state?.outbox_id === outbox.outboxId &&
1338
+ (state.client_seq ?? 0) < watermark;
1339
+ return {
1340
+ watermark,
1341
+ persisted: state?.result === null || state?.result === undefined || deleted
1342
+ ? undefined
1343
+ : deserializePushResult(state.result),
1344
+ };
1345
+ }
1346
+ async enqueueReactions(reactions) {
1347
+ this.assertOpen();
1348
+ for (const reaction of reactions) {
1349
+ this.run(`INSERT INTO sync_reactions(
1350
+ partition, idempotency_key, type, version, payload,
1351
+ source_client_id, source_client_commit_id, source_commit_seq,
1352
+ created_at_ms, available_at_ms, status, attempts, max_attempts
1353
+ ) VALUES (?,?,?,?,?,?,?,?,?,?,'pending',0,?)`, [
1354
+ this.partition,
1355
+ reaction.idempotencyKey,
1356
+ reaction.type,
1357
+ reaction.version,
1358
+ JSON.stringify(reaction.payload),
1359
+ reaction.sourceClientId,
1360
+ reaction.sourceClientCommitId,
1361
+ reaction.sourceCommitSeq,
1362
+ reaction.createdAtMs,
1363
+ reaction.createdAtMs,
1364
+ reaction.maxAttempts,
1365
+ ]);
1366
+ }
371
1367
  }
372
- return { commits, delivered, lastSeq, candidateCount };
373
1368
  }