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