@syncular/server 0.15.45 → 0.15.47

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 (88) hide show
  1. package/README.md +144 -7
  2. package/dist/admin.d.ts +10 -4
  3. package/dist/admin.js +10 -0
  4. package/dist/authoritative-query.d.ts +20 -0
  5. package/dist/authoritative-query.js +184 -0
  6. package/dist/context.d.ts +11 -1
  7. package/dist/context.js +2 -0
  8. package/dist/d1-storage.d.ts +10 -1
  9. package/dist/d1-storage.js +216 -0
  10. package/dist/errors.d.ts +1 -1
  11. package/dist/errors.js +43 -1
  12. package/dist/events.d.ts +52 -3
  13. package/dist/handler.js +4 -1
  14. package/dist/index-bun.d.ts +2 -0
  15. package/dist/index-bun.js +2 -0
  16. package/dist/index-node.d.ts +2 -0
  17. package/dist/index-node.js +2 -0
  18. package/dist/index.d.ts +7 -2
  19. package/dist/index.js +7 -6
  20. package/dist/operations-realtime.d.ts +16 -0
  21. package/dist/operations-realtime.js +196 -0
  22. package/dist/operations.d.ts +97 -0
  23. package/dist/operations.js +392 -0
  24. package/dist/postgres-storage.d.ts +11 -2
  25. package/dist/postgres-storage.js +220 -0
  26. package/dist/pull.js +1 -1
  27. package/dist/push.d.ts +8 -2
  28. package/dist/push.js +75 -21
  29. package/dist/reactions.d.ts +167 -0
  30. package/dist/reactions.js +442 -0
  31. package/dist/realtime.js +4 -1
  32. package/dist/sqlite-blob-store.d.ts +4 -9
  33. package/dist/sqlite-blob-store.js +5 -10
  34. package/dist/sqlite-bun-driver.d.ts +11 -0
  35. package/dist/sqlite-bun-driver.js +27 -0
  36. package/dist/sqlite-bun.d.ts +24 -0
  37. package/dist/sqlite-bun.js +40 -0
  38. package/dist/sqlite-dialect.d.ts +8 -8
  39. package/dist/sqlite-dialect.js +22 -2
  40. package/dist/sqlite-driver.d.ts +26 -0
  41. package/dist/sqlite-driver.js +8 -0
  42. package/dist/sqlite-image.d.ts +7 -9
  43. package/dist/sqlite-image.js +26 -28
  44. package/dist/sqlite-lease-store.d.ts +4 -9
  45. package/dist/sqlite-lease-store.js +5 -10
  46. package/dist/sqlite-node-driver.d.ts +10 -0
  47. package/dist/sqlite-node-driver.js +30 -0
  48. package/dist/sqlite-node.d.ts +24 -0
  49. package/dist/sqlite-node.js +50 -0
  50. package/dist/sqlite-segment-store.d.ts +4 -10
  51. package/dist/sqlite-segment-store.js +6 -9
  52. package/dist/sqlite-storage.d.ts +13 -12
  53. package/dist/sqlite-storage.js +223 -5
  54. package/dist/storage-errors.js +4 -1
  55. package/dist/storage.d.ts +109 -0
  56. package/dist/validate.js +1 -0
  57. package/package.json +18 -3
  58. package/src/admin.ts +27 -3
  59. package/src/authoritative-query.ts +218 -0
  60. package/src/context.ts +12 -1
  61. package/src/d1-storage.ts +352 -0
  62. package/src/errors.ts +43 -1
  63. package/src/events.ts +64 -2
  64. package/src/handler.ts +13 -1
  65. package/src/index-bun.ts +9 -0
  66. package/src/index-node.ts +9 -0
  67. package/src/index.ts +40 -6
  68. package/src/operations-realtime.ts +272 -0
  69. package/src/operations.ts +720 -0
  70. package/src/postgres-storage.ts +351 -0
  71. package/src/pull.ts +1 -1
  72. package/src/push.ts +97 -29
  73. package/src/reactions.ts +741 -0
  74. package/src/realtime.ts +7 -1
  75. package/src/sqlite-blob-store.ts +11 -10
  76. package/src/sqlite-bun-driver.ts +42 -0
  77. package/src/sqlite-bun.ts +53 -0
  78. package/src/sqlite-dialect.ts +27 -7
  79. package/src/sqlite-driver.ts +44 -0
  80. package/src/sqlite-image.ts +44 -49
  81. package/src/sqlite-lease-store.ts +11 -10
  82. package/src/sqlite-node-driver.ts +46 -0
  83. package/src/sqlite-node.ts +62 -0
  84. package/src/sqlite-segment-store.ts +11 -11
  85. package/src/sqlite-storage.ts +378 -7
  86. package/src/storage-errors.ts +4 -1
  87. package/src/storage.ts +165 -0
  88. package/src/validate.ts +1 -0
@@ -1,12 +1,15 @@
1
1
  /**
2
- * SQLite storage via `bun:sqlite` (dev-speed, dependency-free).
2
+ * SQLite server storage over the shared synchronous driver.
3
3
  *
4
4
  * Scope fanout is index-first: both the commit log and the
5
5
  * current-row table carry a (table, variable, value) inverted index; reads
6
6
  * select candidates from the index and verify the full multi-variable
7
7
  * match against the stored scope map — never a log scan.
8
8
  */
9
- import { Database } from 'bun:sqlite';
9
+ import {
10
+ bindAuthoritativePartition,
11
+ prepareAuthoritativeQuery,
12
+ } from './authoritative-query';
10
13
  import { syncError } from './errors';
11
14
  import {
12
15
  commitWindowPageSql,
@@ -41,15 +44,30 @@ import {
41
44
  serializePushResult,
42
45
  toStoredRow,
43
46
  } from './sqlite-dialect';
47
+ import {
48
+ SqliteAdapterRequiredError,
49
+ type SqliteDatabase,
50
+ } from './sqlite-driver';
44
51
  import type {
52
+ AuthoritativeQueryRequest,
53
+ AuthoritativeQueryResult,
54
+ AuthoritativeQueryValue,
45
55
  ClientCursorInfo,
46
56
  ClientRecord,
47
57
  ClientSubscription,
48
58
  CommitMetadata,
49
59
  CommitMetadataQuery,
50
60
  CommitWindowQuery,
61
+ DurableJsonValue,
51
62
  IndexRowScanQuery,
52
63
  NewCommit,
64
+ NewReaction,
65
+ PrunedReactionCounts,
66
+ ReactionClaimQuery,
67
+ ReactionFailure,
68
+ ReactionFailureUpdate,
69
+ ReactionListQuery,
70
+ ReactionPruneQuery,
53
71
  RowScanQuery,
54
72
  ScopeActivityQuery,
55
73
  ScopeCommitActivity,
@@ -57,6 +75,7 @@ import type {
57
75
  StorageTransaction,
58
76
  StoredCommit,
59
77
  StoredPushResult,
78
+ StoredReaction,
60
79
  StoredRow,
61
80
  } from './storage';
62
81
  import {
@@ -65,6 +84,53 @@ import {
65
84
  } from './storage-errors';
66
85
  import { assertScopeIndexedScan, resolveIndexRowScan } from './storage-query';
67
86
 
87
+ interface SqliteReactionRecord {
88
+ partition: string;
89
+ idempotency_key: string;
90
+ type: string;
91
+ version: number;
92
+ payload: string;
93
+ source_client_id: string;
94
+ source_client_commit_id: string;
95
+ source_commit_seq: number;
96
+ created_at_ms: number;
97
+ available_at_ms: number;
98
+ status: StoredReaction['status'];
99
+ attempts: number;
100
+ max_attempts: number;
101
+ lease_owner: string | null;
102
+ lease_expires_at_ms: number | null;
103
+ completed_at_ms: number | null;
104
+ last_failure: string | null;
105
+ }
106
+
107
+ function toStoredReaction(record: SqliteReactionRecord): StoredReaction {
108
+ return {
109
+ idempotencyKey: record.idempotency_key,
110
+ type: record.type,
111
+ version: record.version,
112
+ payload: JSON.parse(record.payload) as DurableJsonValue,
113
+ sourceClientId: record.source_client_id,
114
+ sourceClientCommitId: record.source_client_commit_id,
115
+ sourceCommitSeq: record.source_commit_seq,
116
+ createdAtMs: record.created_at_ms,
117
+ maxAttempts: record.max_attempts,
118
+ status: record.status,
119
+ attempts: record.attempts,
120
+ availableAtMs: record.available_at_ms,
121
+ ...(record.lease_owner !== null ? { leaseOwner: record.lease_owner } : {}),
122
+ ...(record.lease_expires_at_ms !== null
123
+ ? { leaseExpiresAtMs: record.lease_expires_at_ms }
124
+ : {}),
125
+ ...(record.completed_at_ms !== null
126
+ ? { completedAtMs: record.completed_at_ms }
127
+ : {}),
128
+ ...(record.last_failure !== null
129
+ ? { lastFailure: JSON.parse(record.last_failure) as ReactionFailure }
130
+ : {}),
131
+ };
132
+ }
133
+
68
134
  class SqliteTransaction implements StorageTransaction {
69
135
  #storage: SqliteServerStorage;
70
136
  #partition: string;
@@ -97,7 +163,7 @@ class SqliteTransaction implements StorageTransaction {
97
163
  clientCommitId: string,
98
164
  ): Promise<StoredPushResult | undefined> {
99
165
  this.#assertOpen();
100
- // One shared bun:sqlite connection this read runs inside this
166
+ // One shared SQLite connection: this read runs inside this
101
167
  // transaction's BEGIN IMMEDIATE.
102
168
  return this.#storage.getPushResult(
103
169
  this.#partition,
@@ -256,6 +322,32 @@ class SqliteTransaction implements StorageTransaction {
256
322
  );
257
323
  }
258
324
 
325
+ async enqueueReactions(reactions: readonly NewReaction[]): Promise<void> {
326
+ this.#assertOpen();
327
+ const statement = this.#storage.db.query(
328
+ `INSERT INTO sync_reactions(
329
+ partition, idempotency_key, type, version, payload,
330
+ source_client_id, source_client_commit_id, source_commit_seq,
331
+ created_at_ms, available_at_ms, status, attempts, max_attempts
332
+ ) VALUES (?,?,?,?,?,?,?,?,?,?,'pending',0,?)`,
333
+ );
334
+ for (const reaction of reactions) {
335
+ statement.run(
336
+ this.#partition,
337
+ reaction.idempotencyKey,
338
+ reaction.type,
339
+ reaction.version,
340
+ JSON.stringify(reaction.payload),
341
+ reaction.sourceClientId,
342
+ reaction.sourceClientCommitId,
343
+ reaction.sourceCommitSeq,
344
+ reaction.createdAtMs,
345
+ reaction.createdAtMs,
346
+ reaction.maxAttempts,
347
+ );
348
+ }
349
+ }
350
+
259
351
  async commit(): Promise<void> {
260
352
  this.#assertOpen();
261
353
  try {
@@ -290,15 +382,32 @@ class SqliteTransaction implements StorageTransaction {
290
382
  }
291
383
 
292
384
  export class SqliteServerStorage implements ServerStorage {
293
- readonly db: Database;
294
- /** One bun:sqlite connection can own only one transaction at a time. */
385
+ readonly db: SqliteDatabase;
386
+ /** One SQLite connection can own only one transaction at a time. */
295
387
  #transactionTail: Promise<void> = Promise.resolve();
296
388
  /** Set by `ensureSchema`: app-table lookup for the relational row store. */
297
389
  #tables: ReadonlyMap<string, CompiledTable> | undefined;
298
390
  #schemaVersion: number | undefined;
299
391
 
300
- constructor(db: Database | string = ':memory:') {
301
- this.db = typeof db === 'string' ? new Database(db) : db;
392
+ async #serializeReactionWrite<T>(operation: () => T): Promise<T> {
393
+ const previous = this.#transactionTail;
394
+ let release!: () => void;
395
+ this.#transactionTail = new Promise<void>((resolve) => {
396
+ release = resolve;
397
+ });
398
+ await previous;
399
+ try {
400
+ return operation();
401
+ } finally {
402
+ release();
403
+ }
404
+ }
405
+
406
+ constructor(db: SqliteDatabase | string = ':memory:') {
407
+ if (typeof db === 'string') {
408
+ throw new SqliteAdapterRequiredError();
409
+ }
410
+ this.db = db;
302
411
  this.db.exec(SQLITE_DDL);
303
412
  }
304
413
 
@@ -496,6 +605,55 @@ export class SqliteServerStorage implements ServerStorage {
496
605
  return row?.max_commit_seq ?? 0;
497
606
  }
498
607
 
608
+ async queryAuthoritative(
609
+ partition: string,
610
+ query: AuthoritativeQueryRequest,
611
+ ): Promise<AuthoritativeQueryResult> {
612
+ if (this.#tables === undefined) {
613
+ throw new Error(
614
+ 'ensureSchema(schema) must run before registered queries',
615
+ );
616
+ }
617
+ const prepared = bindAuthoritativePartition(
618
+ prepareAuthoritativeQuery(
619
+ query.sql,
620
+ query.params,
621
+ query.tables,
622
+ this.#tables,
623
+ ),
624
+ partition,
625
+ );
626
+ const previous = this.#transactionTail;
627
+ let release!: () => void;
628
+ this.#transactionTail = new Promise<void>((resolve) => {
629
+ release = resolve;
630
+ });
631
+ await previous;
632
+ let open = false;
633
+ try {
634
+ this.db.exec('BEGIN');
635
+ open = true;
636
+ const rows = this.db
637
+ .query<Readonly<Record<string, unknown>>, AuthoritativeQueryValue[]>(
638
+ prepared.sql,
639
+ )
640
+ .all(...prepared.params);
641
+ const cursor = this.db
642
+ .query<{ max_commit_seq: number }, [string]>(
643
+ 'SELECT max_commit_seq FROM sync_partitions WHERE partition=?',
644
+ )
645
+ .get(partition);
646
+ this.db.exec('COMMIT');
647
+ open = false;
648
+ return { rows, maxCommitSeq: cursor?.max_commit_seq ?? 0 };
649
+ } catch (error) {
650
+ if (open) this.db.exec('ROLLBACK');
651
+ throw error;
652
+ } finally {
653
+ release();
654
+ }
655
+ }
656
+
499
657
  async getHorizonSeq(partition: string): Promise<number> {
500
658
  const row = this.db
501
659
  .query<{ horizon_seq: number }, [string]>(
@@ -575,6 +733,219 @@ export class SqliteServerStorage implements ServerStorage {
575
733
  }
576
734
  }
577
735
 
736
+ async claimReactions(
737
+ partition: string,
738
+ query: ReactionClaimQuery,
739
+ ): Promise<StoredReaction[]> {
740
+ if (query.types.length === 0 || query.limit <= 0) return [];
741
+ return this.#serializeReactionWrite(() => {
742
+ const typeParams = query.types.map(() => '?').join(',');
743
+ const records = this.db
744
+ .query<SqliteReactionRecord, (string | number)[]>(
745
+ `UPDATE sync_reactions
746
+ SET status='leased', attempts=attempts+1,
747
+ lease_owner=?, lease_expires_at_ms=?, completed_at_ms=NULL
748
+ WHERE (partition, idempotency_key) IN (
749
+ SELECT partition, idempotency_key
750
+ FROM sync_reactions
751
+ WHERE partition=? AND type IN (${typeParams})
752
+ AND ((status='pending' AND available_at_ms<=?)
753
+ OR (status='leased' AND lease_expires_at_ms<=?))
754
+ ORDER BY CASE WHEN status='leased' THEN lease_expires_at_ms
755
+ ELSE available_at_ms END,
756
+ created_at_ms, idempotency_key
757
+ LIMIT ?
758
+ )
759
+ RETURNING *`,
760
+ )
761
+ .all(
762
+ query.leaseOwner,
763
+ Math.min(
764
+ Number.MAX_SAFE_INTEGER,
765
+ query.nowMs + query.leaseDurationMs,
766
+ ),
767
+ partition,
768
+ ...query.types,
769
+ query.nowMs,
770
+ query.nowMs,
771
+ query.limit,
772
+ );
773
+ return records
774
+ .map(toStoredReaction)
775
+ .sort(
776
+ (a, b) =>
777
+ a.createdAtMs - b.createdAtMs ||
778
+ a.idempotencyKey.localeCompare(b.idempotencyKey),
779
+ );
780
+ });
781
+ }
782
+
783
+ async completeReaction(
784
+ partition: string,
785
+ idempotencyKey: string,
786
+ leaseOwner: string,
787
+ completedAtMs: number,
788
+ ): Promise<boolean> {
789
+ return this.#serializeReactionWrite(() => {
790
+ const result = this.db
791
+ .query(
792
+ `UPDATE sync_reactions
793
+ SET status='completed', completed_at_ms=?,
794
+ lease_owner=NULL, lease_expires_at_ms=NULL
795
+ WHERE partition=? AND idempotency_key=?
796
+ AND status='leased' AND lease_owner=?`,
797
+ )
798
+ .run(completedAtMs, partition, idempotencyKey, leaseOwner);
799
+ return Number(result.changes) === 1;
800
+ });
801
+ }
802
+
803
+ async extendReactionLease(
804
+ partition: string,
805
+ idempotencyKey: string,
806
+ leaseOwner: string,
807
+ leaseExpiresAtMs: number,
808
+ ): Promise<boolean> {
809
+ return this.#serializeReactionWrite(() => {
810
+ const result = this.db
811
+ .query(
812
+ `UPDATE sync_reactions SET lease_expires_at_ms=?
813
+ WHERE partition=? AND idempotency_key=?
814
+ AND status='leased' AND lease_owner=?`,
815
+ )
816
+ .run(leaseExpiresAtMs, partition, idempotencyKey, leaseOwner);
817
+ return Number(result.changes) === 1;
818
+ });
819
+ }
820
+
821
+ async failReaction(
822
+ partition: string,
823
+ idempotencyKey: string,
824
+ update: ReactionFailureUpdate,
825
+ ): Promise<boolean> {
826
+ const retry = update.retryAtMs !== undefined;
827
+ return this.#serializeReactionWrite(() => {
828
+ const result = this.db
829
+ .query(
830
+ `UPDATE sync_reactions
831
+ SET status=?, available_at_ms=?, last_failure=?,
832
+ lease_owner=NULL, lease_expires_at_ms=NULL
833
+ WHERE partition=? AND idempotency_key=?
834
+ AND status='leased' AND lease_owner=?`,
835
+ )
836
+ .run(
837
+ retry ? 'pending' : 'dead-letter',
838
+ update.retryAtMs ?? update.failure.atMs,
839
+ JSON.stringify(update.failure),
840
+ partition,
841
+ idempotencyKey,
842
+ update.leaseOwner,
843
+ );
844
+ return Number(result.changes) === 1;
845
+ });
846
+ }
847
+
848
+ async retryReaction(
849
+ partition: string,
850
+ idempotencyKey: string,
851
+ nowMs: number,
852
+ ): Promise<boolean> {
853
+ return this.#serializeReactionWrite(() => {
854
+ const result = this.db
855
+ .query(
856
+ `UPDATE sync_reactions
857
+ SET status='pending', attempts=0, available_at_ms=?,
858
+ last_failure=NULL, lease_owner=NULL, lease_expires_at_ms=NULL,
859
+ completed_at_ms=NULL
860
+ WHERE partition=? AND idempotency_key=? AND status='dead-letter'`,
861
+ )
862
+ .run(nowMs, partition, idempotencyKey);
863
+ return Number(result.changes) === 1;
864
+ });
865
+ }
866
+
867
+ async getReaction(
868
+ partition: string,
869
+ idempotencyKey: string,
870
+ ): Promise<StoredReaction | undefined> {
871
+ const record = this.db
872
+ .query<SqliteReactionRecord, [string, string]>(
873
+ 'SELECT * FROM sync_reactions WHERE partition=? AND idempotency_key=?',
874
+ )
875
+ .get(partition, idempotencyKey);
876
+ return record === null ? undefined : toStoredReaction(record);
877
+ }
878
+
879
+ async listReactions(
880
+ partition: string,
881
+ query: ReactionListQuery,
882
+ ): Promise<StoredReaction[]> {
883
+ const where = ['partition=?'];
884
+ const params: (string | number)[] = [partition];
885
+ if (query.statuses !== undefined && query.statuses.length > 0) {
886
+ where.push(`status IN (${query.statuses.map(() => '?').join(',')})`);
887
+ params.push(...query.statuses);
888
+ }
889
+ if (query.types !== undefined && query.types.length > 0) {
890
+ where.push(`type IN (${query.types.map(() => '?').join(',')})`);
891
+ params.push(...query.types);
892
+ }
893
+ params.push(query.limit);
894
+ const records = this.db
895
+ .query<SqliteReactionRecord, (string | number)[]>(
896
+ `SELECT * FROM sync_reactions WHERE ${where.join(' AND ')}
897
+ ORDER BY created_at_ms DESC, idempotency_key DESC LIMIT ?`,
898
+ )
899
+ .all(...params);
900
+ return records.map(toStoredReaction);
901
+ }
902
+
903
+ async pruneReactions(
904
+ partition: string,
905
+ query: ReactionPruneQuery,
906
+ ): Promise<PrunedReactionCounts> {
907
+ if (query.limit <= 0) return { completed: 0, deadLetter: 0 };
908
+ return this.#serializeReactionWrite(() => {
909
+ const records = this.db
910
+ .query<
911
+ { status: 'completed' | 'dead-letter' },
912
+ [string, string, number, number, number, number, number]
913
+ >(
914
+ `DELETE FROM sync_reactions
915
+ WHERE partition=? AND idempotency_key IN (
916
+ SELECT idempotency_key FROM sync_reactions
917
+ WHERE partition=?
918
+ AND ((status='completed' AND completed_at_ms IS NOT NULL
919
+ AND completed_at_ms<?)
920
+ OR (status='dead-letter' AND available_at_ms<?))
921
+ ORDER BY CASE WHEN status='completed' THEN completed_at_ms
922
+ ELSE available_at_ms END,
923
+ idempotency_key
924
+ LIMIT ?
925
+ )
926
+ AND ((status='completed' AND completed_at_ms IS NOT NULL
927
+ AND completed_at_ms<?)
928
+ OR (status='dead-letter' AND available_at_ms<?))
929
+ RETURNING status`,
930
+ )
931
+ .all(
932
+ partition,
933
+ partition,
934
+ query.completedBeforeMs,
935
+ query.deadLetterBeforeMs,
936
+ query.limit,
937
+ query.completedBeforeMs,
938
+ query.deadLetterBeforeMs,
939
+ );
940
+ return {
941
+ completed: records.filter((record) => record.status === 'completed')
942
+ .length,
943
+ deadLetter: records.filter((record) => record.status === 'dead-letter')
944
+ .length,
945
+ };
946
+ });
947
+ }
948
+
578
949
  async readCommitWindow(
579
950
  partition: string,
580
951
  query: CommitWindowQuery,
@@ -52,6 +52,7 @@ export class StorageQueryError extends Error {
52
52
  interface DriverError {
53
53
  readonly code?: unknown;
54
54
  readonly errno?: unknown;
55
+ readonly errcode?: unknown;
55
56
  readonly message?: unknown;
56
57
  }
57
58
 
@@ -72,7 +73,9 @@ export function isSqliteConstraintError(error: unknown): boolean {
72
73
  return true;
73
74
  }
74
75
  const errno = candidate?.errno;
75
- return typeof errno === 'number' && (errno & 0xff) === 19;
76
+ if (typeof errno === 'number' && (errno & 0xff) === 19) return true;
77
+ const errcode = candidate?.errcode;
78
+ return typeof errcode === 'number' && (errcode & 0xff) === 19;
76
79
  }
77
80
 
78
81
  /** PostgreSQL SQLSTATE class 23: integrity constraint violation. */
package/src/storage.ts CHANGED
@@ -65,6 +65,83 @@ export interface StoredCommit {
65
65
  readonly changes: readonly StoredChange[];
66
66
  }
67
67
 
68
+ /** JSON values accepted by the durable reaction payload/failure store. */
69
+ export type DurableJsonValue =
70
+ | null
71
+ | boolean
72
+ | number
73
+ | string
74
+ | readonly DurableJsonValue[]
75
+ | { readonly [key: string]: DurableJsonValue };
76
+
77
+ export type ReactionStatus = 'pending' | 'leased' | 'completed' | 'dead-letter';
78
+
79
+ export interface ReactionFailure {
80
+ /** Stable application or Syncular error identity. */
81
+ readonly code: string;
82
+ readonly atMs: number;
83
+ /** Bounded JSON metadata. Diagnostic exception text is never persisted. */
84
+ readonly details?: { readonly [key: string]: DurableJsonValue };
85
+ }
86
+
87
+ /** A validated reaction row written with its source commit. */
88
+ export interface NewReaction {
89
+ readonly idempotencyKey: string;
90
+ readonly type: string;
91
+ readonly version: number;
92
+ readonly payload: DurableJsonValue;
93
+ readonly sourceClientId: string;
94
+ readonly sourceClientCommitId: string;
95
+ readonly sourceCommitSeq: number;
96
+ readonly createdAtMs: number;
97
+ readonly maxAttempts: number;
98
+ }
99
+
100
+ /** Durable reaction state returned to workers and administrative readers. */
101
+ export interface StoredReaction extends NewReaction {
102
+ readonly status: ReactionStatus;
103
+ /** Incremented atomically when a worker claims the reaction. */
104
+ readonly attempts: number;
105
+ readonly availableAtMs: number;
106
+ readonly leaseOwner?: string;
107
+ readonly leaseExpiresAtMs?: number;
108
+ readonly completedAtMs?: number;
109
+ readonly lastFailure?: ReactionFailure;
110
+ }
111
+
112
+ export interface ReactionClaimQuery {
113
+ /** Opaque token unique to this claim operation. */
114
+ readonly leaseOwner: string;
115
+ readonly types: readonly string[];
116
+ readonly nowMs: number;
117
+ readonly leaseDurationMs: number;
118
+ readonly limit: number;
119
+ }
120
+
121
+ export interface ReactionListQuery {
122
+ readonly statuses?: readonly ReactionStatus[];
123
+ readonly types?: readonly string[];
124
+ readonly limit: number;
125
+ }
126
+
127
+ export interface ReactionFailureUpdate {
128
+ readonly leaseOwner: string;
129
+ readonly failure: ReactionFailure;
130
+ /** Present for retry; absent moves the row to the dead-letter state. */
131
+ readonly retryAtMs?: number;
132
+ }
133
+
134
+ export interface ReactionPruneQuery {
135
+ readonly completedBeforeMs: number;
136
+ readonly deadLetterBeforeMs: number;
137
+ readonly limit: number;
138
+ }
139
+
140
+ export interface PrunedReactionCounts {
141
+ readonly completed: number;
142
+ readonly deadLetter: number;
143
+ }
144
+
68
145
  /** Persisted push outcome for idempotent replay (§2.3, §6.3). */
69
146
  export interface StoredPushResult {
70
147
  readonly status: 'applied' | 'rejected';
@@ -183,6 +260,29 @@ export interface ScopeActivityQuery {
183
260
  readonly limit: number;
184
261
  }
185
262
 
263
+ /** A registered SELECT executed against the authoritative row projection. */
264
+ export type AuthoritativeQueryValue =
265
+ | string
266
+ | number
267
+ | bigint
268
+ | boolean
269
+ | Uint8Array
270
+ | null;
271
+
272
+ export interface AuthoritativeQueryRequest {
273
+ /** Generated, positional SQLite-family SQL. It never comes from the request. */
274
+ readonly sql: string;
275
+ readonly params: readonly AuthoritativeQueryValue[];
276
+ /** Generated dependency set, used to validate and partition every relation. */
277
+ readonly tables: readonly string[];
278
+ }
279
+
280
+ /** One transactionally consistent authoritative query snapshot. */
281
+ export interface AuthoritativeQueryResult {
282
+ readonly rows: readonly Readonly<Record<string, unknown>>[];
283
+ readonly maxCommitSeq: number;
284
+ }
285
+
186
286
  /**
187
287
  * One transaction per push commit (§6.4): all row writes, the appended
188
288
  * commit (with its scope-index entries), and the idempotency record either
@@ -248,6 +348,12 @@ export interface StorageTransaction {
248
348
  deleteRow(table: string, rowId: string): Promise<void>;
249
349
  /** Allocates the next per-partition commitSeq and appends the commit. */
250
350
  appendCommit(commit: NewCommit): Promise<number>;
351
+ /**
352
+ * Persist reaction rows in this authoritative transaction. Required when
353
+ * the host configures a reaction planner. Reactions survive commit-log
354
+ * pruning because they live outside the commit/change tables.
355
+ */
356
+ enqueueReactions?(reactions: readonly NewReaction[]): Promise<void>;
251
357
  /**
252
358
  * Persist an idempotency outcome only when the key is still absent. The
253
359
  * first writer wins; callers read the canonical value after commit.
@@ -323,6 +429,55 @@ export interface ServerStorage {
323
429
  clientCommitId: string,
324
430
  ): Promise<StoredPushResult | undefined>;
325
431
 
432
+ /**
433
+ * Atomically lease due or expired-lease reactions for one worker. Optional
434
+ * for compatibility with custom storages; reaction runners fail closed when
435
+ * any lifecycle method is absent.
436
+ */
437
+ claimReactions?(
438
+ partition: string,
439
+ query: ReactionClaimQuery,
440
+ ): Promise<StoredReaction[]>;
441
+ /** Acknowledge only while `leaseOwner` still owns the lease. */
442
+ completeReaction?(
443
+ partition: string,
444
+ idempotencyKey: string,
445
+ leaseOwner: string,
446
+ completedAtMs: number,
447
+ ): Promise<boolean>;
448
+ /** Extend only while `leaseOwner` still owns the active lease. */
449
+ extendReactionLease?(
450
+ partition: string,
451
+ idempotencyKey: string,
452
+ leaseOwner: string,
453
+ leaseExpiresAtMs: number,
454
+ ): Promise<boolean>;
455
+ /** Retry or dead-letter only while `leaseOwner` still owns the lease. */
456
+ failReaction?(
457
+ partition: string,
458
+ idempotencyKey: string,
459
+ update: ReactionFailureUpdate,
460
+ ): Promise<boolean>;
461
+ /** Reset a dead-lettered row for an explicit operator retry. */
462
+ retryReaction?(
463
+ partition: string,
464
+ idempotencyKey: string,
465
+ nowMs: number,
466
+ ): Promise<boolean>;
467
+ getReaction?(
468
+ partition: string,
469
+ idempotencyKey: string,
470
+ ): Promise<StoredReaction | undefined>;
471
+ listReactions?(
472
+ partition: string,
473
+ query: ReactionListQuery,
474
+ ): Promise<StoredReaction[]>;
475
+ /** Delete a bounded set of aged terminal rows. Never deletes active work. */
476
+ pruneReactions?(
477
+ partition: string,
478
+ query: ReactionPruneQuery,
479
+ ): Promise<PrunedReactionCounts>;
480
+
326
481
  /**
327
482
  * Matching commits in the window, oldest first, each carrying only its
328
483
  * matching changes for `table`. Stops once accumulated matching changes
@@ -336,6 +491,16 @@ export interface ServerStorage {
336
491
  /** Scope-filtered snapshot scan, ordered by rowId (bootstrap paging). */
337
492
  scanRows(partition: string, query: RowScanQuery): Promise<StoredRow[]>;
338
493
 
494
+ /**
495
+ * Optional registered-query capability. The implementation MUST replace
496
+ * every generated app-table relation with a partition-filtered relation and
497
+ * return rows plus maxCommitSeq from one consistent database snapshot.
498
+ */
499
+ queryAuthoritative?(
500
+ partition: string,
501
+ query: AuthoritativeQueryRequest,
502
+ ): Promise<AuthoritativeQueryResult>;
503
+
339
504
  /**
340
505
  * Optional trusted-host exact lookup through a declared relational index.
341
506
  * This capability is outside client scope/subscription authorization and
package/src/validate.ts CHANGED
@@ -32,6 +32,7 @@ import {
32
32
  export const RESERVED_VALIDATION_CODE_PREFIXES: readonly string[] = [
33
33
  'sync.',
34
34
  'blob.',
35
+ 'operation.',
35
36
  'presence.',
36
37
  'client.',
37
38
  ];