@indigoai-us/hq-cloud 6.14.49 → 6.15.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 (126) hide show
  1. package/.github/workflows/unreleased-commits-nag.yml +256 -0
  2. package/dist/bin/sync-runner-watch-loop.d.ts +12 -0
  3. package/dist/bin/sync-runner-watch-loop.d.ts.map +1 -1
  4. package/dist/bin/sync-runner-watch-loop.js +153 -25
  5. package/dist/bin/sync-runner-watch-loop.js.map +1 -1
  6. package/dist/bin/sync-runner-watch-routes.d.ts +17 -0
  7. package/dist/bin/sync-runner-watch-routes.d.ts.map +1 -1
  8. package/dist/bin/sync-runner-watch-routes.js +11 -0
  9. package/dist/bin/sync-runner-watch-routes.js.map +1 -1
  10. package/dist/bin/sync-runner-watch-routes.test.d.ts +2 -0
  11. package/dist/bin/sync-runner-watch-routes.test.d.ts.map +1 -0
  12. package/dist/bin/sync-runner-watch-routes.test.js +51 -0
  13. package/dist/bin/sync-runner-watch-routes.test.js.map +1 -0
  14. package/dist/bin/sync-runner.d.ts +11 -12
  15. package/dist/bin/sync-runner.d.ts.map +1 -1
  16. package/dist/bin/sync-runner.js.map +1 -1
  17. package/dist/bin/sync-runner.test.js +173 -52
  18. package/dist/bin/sync-runner.test.js.map +1 -1
  19. package/dist/cli/reindex-knowledge.d.ts +7 -0
  20. package/dist/cli/reindex-knowledge.d.ts.map +1 -0
  21. package/dist/cli/reindex-knowledge.js +389 -0
  22. package/dist/cli/reindex-knowledge.js.map +1 -0
  23. package/dist/cli/reindex-knowledge.test.d.ts +12 -0
  24. package/dist/cli/reindex-knowledge.test.d.ts.map +1 -0
  25. package/dist/cli/reindex-knowledge.test.js +260 -0
  26. package/dist/cli/reindex-knowledge.test.js.map +1 -0
  27. package/dist/cli/reindex.d.ts.map +1 -1
  28. package/dist/cli/reindex.js +8 -0
  29. package/dist/cli/reindex.js.map +1 -1
  30. package/dist/cli/rescue-classify-ordering.test.js +8 -2
  31. package/dist/cli/rescue-classify-ordering.test.js.map +1 -1
  32. package/dist/cli/rescue-core.d.ts +85 -0
  33. package/dist/cli/rescue-core.d.ts.map +1 -1
  34. package/dist/cli/rescue-core.js +390 -1
  35. package/dist/cli/rescue-core.js.map +1 -1
  36. package/dist/cli/rescue-settings-reconcile.test.d.ts +2 -0
  37. package/dist/cli/rescue-settings-reconcile.test.d.ts.map +1 -0
  38. package/dist/cli/rescue-settings-reconcile.test.js +523 -0
  39. package/dist/cli/rescue-settings-reconcile.test.js.map +1 -0
  40. package/dist/index.d.ts +1 -1
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +1 -1
  43. package/dist/index.js.map +1 -1
  44. package/dist/journal.d.ts.map +1 -1
  45. package/dist/journal.js +81 -51
  46. package/dist/journal.js.map +1 -1
  47. package/dist/journal.test.js +11 -19
  48. package/dist/journal.test.js.map +1 -1
  49. package/dist/sync/event-sync.d.ts +8 -25
  50. package/dist/sync/event-sync.d.ts.map +1 -1
  51. package/dist/sync/event-sync.js +23 -48
  52. package/dist/sync/event-sync.js.map +1 -1
  53. package/dist/sync/event-sync.test.js +6 -32
  54. package/dist/sync/event-sync.test.js.map +1 -1
  55. package/dist/sync/feature-flags.d.ts +20 -117
  56. package/dist/sync/feature-flags.d.ts.map +1 -1
  57. package/dist/sync/feature-flags.js +24 -147
  58. package/dist/sync/feature-flags.js.map +1 -1
  59. package/dist/sync/feature-flags.test.js +15 -61
  60. package/dist/sync/feature-flags.test.js.map +1 -1
  61. package/dist/sync/index.d.ts +1 -1
  62. package/dist/sync/index.d.ts.map +1 -1
  63. package/dist/sync/index.js +1 -1
  64. package/dist/sync/index.js.map +1 -1
  65. package/dist/sync/lease-client.d.ts +67 -0
  66. package/dist/sync/lease-client.d.ts.map +1 -0
  67. package/dist/sync/lease-client.js +158 -0
  68. package/dist/sync/lease-client.js.map +1 -0
  69. package/dist/sync/lease-client.test.d.ts +2 -0
  70. package/dist/sync/lease-client.test.d.ts.map +1 -0
  71. package/dist/sync/lease-client.test.js +119 -0
  72. package/dist/sync/lease-client.test.js.map +1 -0
  73. package/dist/sync/push-receiver.d.ts +8 -19
  74. package/dist/sync/push-receiver.d.ts.map +1 -1
  75. package/dist/sync/push-receiver.js +6 -50
  76. package/dist/sync/push-receiver.js.map +1 -1
  77. package/dist/sync/push-receiver.test.js +6 -57
  78. package/dist/sync/push-receiver.test.js.map +1 -1
  79. package/dist/sync/realtime-rollout.d.ts +85 -0
  80. package/dist/sync/realtime-rollout.d.ts.map +1 -0
  81. package/dist/sync/realtime-rollout.js +206 -0
  82. package/dist/sync/realtime-rollout.js.map +1 -0
  83. package/dist/sync/realtime-rollout.test.d.ts +2 -0
  84. package/dist/sync/realtime-rollout.test.d.ts.map +1 -0
  85. package/dist/sync/realtime-rollout.test.js +71 -0
  86. package/dist/sync/realtime-rollout.test.js.map +1 -0
  87. package/dist/sync/state-store.d.ts +40 -0
  88. package/dist/sync/state-store.d.ts.map +1 -0
  89. package/dist/sync/state-store.js +680 -0
  90. package/dist/sync/state-store.js.map +1 -0
  91. package/dist/sync/state-store.test.d.ts +2 -0
  92. package/dist/sync/state-store.test.d.ts.map +1 -0
  93. package/dist/sync/state-store.test.js +159 -0
  94. package/dist/sync/state-store.test.js.map +1 -0
  95. package/dist/types.d.ts +12 -0
  96. package/dist/types.d.ts.map +1 -1
  97. package/package.json +1 -1
  98. package/src/bin/sync-runner-watch-loop.ts +176 -32
  99. package/src/bin/sync-runner-watch-routes.test.ts +71 -0
  100. package/src/bin/sync-runner-watch-routes.ts +27 -0
  101. package/src/bin/sync-runner.test.ts +188 -53
  102. package/src/bin/sync-runner.ts +11 -12
  103. package/src/cli/reindex-knowledge.test.ts +307 -0
  104. package/src/cli/reindex-knowledge.ts +450 -0
  105. package/src/cli/reindex.ts +9 -0
  106. package/src/cli/rescue-classify-ordering.test.ts +9 -3
  107. package/src/cli/rescue-core.ts +459 -1
  108. package/src/cli/rescue-settings-reconcile.test.ts +637 -0
  109. package/src/index.ts +2 -4
  110. package/src/journal.test.ts +19 -21
  111. package/src/journal.ts +87 -54
  112. package/src/sync/event-sync.test.ts +9 -44
  113. package/src/sync/event-sync.ts +26 -52
  114. package/src/sync/feature-flags.test.ts +22 -72
  115. package/src/sync/feature-flags.ts +32 -199
  116. package/src/sync/index.ts +2 -4
  117. package/src/sync/lease-client.test.ts +128 -0
  118. package/src/sync/lease-client.ts +207 -0
  119. package/src/sync/push-receiver.test.ts +6 -58
  120. package/src/sync/push-receiver.ts +9 -74
  121. package/src/sync/realtime-rollout.test.ts +86 -0
  122. package/src/sync/realtime-rollout.ts +262 -0
  123. package/src/sync/state-store.test.ts +194 -0
  124. package/src/sync/state-store.ts +727 -0
  125. package/src/types.ts +14 -0
  126. package/test/e2e/sync/transient-company-leg.test.ts +8 -4
@@ -0,0 +1,727 @@
1
+ /**
2
+ * Durable per-scope state store for the realtime-sync v2 protocol.
3
+ *
4
+ * The store intentionally has no knowledge of journal or sync domain records.
5
+ * Callers supply a reducer; this keeps the on-disk framing/recovery boundary
6
+ * small while allowing later protocol units to append their own typed records.
7
+ */
8
+ import * as crypto from "node:crypto";
9
+ import * as fs from "node:fs";
10
+ import * as path from "node:path";
11
+
12
+ const SNAPSHOT_MAGIC = Buffer.from("HQSNAP3\0", "ascii");
13
+ const WAL_MAGIC = Buffer.from("HQWAL3\0\0", "ascii");
14
+ const FRAME_MAGIC = 0x48515733;
15
+ const SNAPSHOT_HEADER_BYTES = 8 + 8 + 4 + 32 + 32;
16
+ const WAL_HEADER_BYTES = 8 + 8 + 32 + 32;
17
+ const FRAME_PREFIX_BYTES = 4 + 4;
18
+ const FRAME_FIXED_BODY_BYTES = 8 + 2 + 2 + 4 + 4 + 32;
19
+ const MAX_FRAME_BYTES = 64 * 1024 * 1024;
20
+ const LOCK_RETRY_MS = 10;
21
+ const LOCK_TIMEOUT_MS = 5_000;
22
+
23
+ export interface StateStoreRecord<T = unknown> {
24
+ sequence: number;
25
+ type: number;
26
+ flags: number;
27
+ payload: T;
28
+ }
29
+
30
+ export interface StateStoreOptions<T> {
31
+ rootDir: string;
32
+ scopeId: string;
33
+ initialState: T;
34
+ reduce: (state: T, record: StateStoreRecord) => T;
35
+ /** Compact after this many WAL records. Defaults to 256. */
36
+ maxRecordsBeforeCompaction?: number;
37
+ }
38
+
39
+ interface SnapshotPayload<T> {
40
+ lastRecordSequence: number;
41
+ state: T;
42
+ }
43
+
44
+ interface Generation<T> {
45
+ generation: number;
46
+ state: T;
47
+ lastRecordSequence: number;
48
+ recordCount: number;
49
+ }
50
+
51
+ export class StateStoreCorruptionError extends Error {
52
+ constructor(message: string, options?: ErrorOptions) {
53
+ super(`state-store corruption: ${message}`, options);
54
+ this.name = "StateStoreCorruptionError";
55
+ }
56
+ }
57
+
58
+ class StateStoreLockError extends Error {
59
+ constructor(message: string, options?: ErrorOptions) {
60
+ super(`state-store lock: ${message}`, options);
61
+ this.name = "StateStoreLockError";
62
+ }
63
+ }
64
+
65
+ /** A recovered v3 store. `append` is the ordinary hot path. */
66
+ export class StateStore<T> {
67
+ readonly stateDir: string;
68
+ readonly scopeDigest: Buffer;
69
+ readonly wasCreated: boolean;
70
+ private generation: number;
71
+ private state: T;
72
+ private lastRecordSequence: number;
73
+ private recordCount: number;
74
+
75
+ private constructor(
76
+ private readonly options: StateStoreOptions<T> & { maxRecordsBeforeCompaction: number },
77
+ recovered: Generation<T>,
78
+ wasCreated: boolean,
79
+ ) {
80
+ this.scopeDigest = digestScope(options.scopeId);
81
+ this.stateDir = stateDirectory(options.rootDir, this.scopeDigest);
82
+ this.generation = recovered.generation;
83
+ this.state = recovered.state;
84
+ this.lastRecordSequence = recovered.lastRecordSequence;
85
+ this.recordCount = recovered.recordCount;
86
+ this.wasCreated = wasCreated;
87
+ }
88
+
89
+ static exists(rootDir: string, scopeId: string): boolean {
90
+ const dir = stateDirectory(rootDir, digestScope(scopeId));
91
+ try {
92
+ return fs.readdirSync(dir).some((name) => /^snapshot-\d+\.bin$/.test(name));
93
+ } catch (error) {
94
+ if (isMissing(error)) return false;
95
+ throw new Error(`state-store: cannot inspect ${dir}`, { cause: error });
96
+ }
97
+ }
98
+
99
+ static open<T>(options: StateStoreOptions<T>): StateStore<T> {
100
+ if (!options.scopeId) throw new Error("state-store: scopeId is required");
101
+ const normalized: StateStoreOptions<T> & { maxRecordsBeforeCompaction: number } = {
102
+ ...options,
103
+ maxRecordsBeforeCompaction: options.maxRecordsBeforeCompaction ?? 256,
104
+ };
105
+ if (normalized.maxRecordsBeforeCompaction < 1) {
106
+ throw new Error("state-store: maxRecordsBeforeCompaction must be positive");
107
+ }
108
+ const scopeDigest = digestScope(normalized.scopeId);
109
+ const dir = stateDirectory(normalized.rootDir, scopeDigest);
110
+ fs.mkdirSync(dir, { recursive: true });
111
+ cleanupUnpublishedInitialGeneration(dir);
112
+ const generations = readGenerations(dir, scopeDigest, normalized.reduce);
113
+ if (generations.length > 0) {
114
+ return new StateStore(normalized, generations[0]!, false);
115
+ }
116
+
117
+ const initial: Generation<T> = {
118
+ generation: 1,
119
+ state: normalized.initialState,
120
+ lastRecordSequence: 0,
121
+ recordCount: 0,
122
+ };
123
+ writeGeneration(dir, scopeDigest, initial);
124
+ writeCurrentPointer(dir, initial.generation);
125
+ return new StateStore(normalized, initial, true);
126
+ }
127
+
128
+ getState(): T {
129
+ return this.state;
130
+ }
131
+
132
+ getGeneration(): number {
133
+ return this.generation;
134
+ }
135
+
136
+ getLastRecordSequence(): number {
137
+ return this.lastRecordSequence;
138
+ }
139
+
140
+ append(type: number, payload: unknown, flags = 0): StateStoreRecord {
141
+ assertUint16(type, "record type");
142
+ assertUint16(flags, "record flags");
143
+ return withScopeLock(this.stateDir, () => {
144
+ this.refreshFromDisk();
145
+ const record: StateStoreRecord = {
146
+ sequence: this.lastRecordSequence + 1,
147
+ type,
148
+ flags,
149
+ payload,
150
+ };
151
+ if (!Number.isSafeInteger(record.sequence)) {
152
+ throw new Error("state-store: record sequence exceeds safe integer range");
153
+ }
154
+ // Validate reducer acceptance before making this frame durable.
155
+ const nextState = this.options.reduce(this.state, record);
156
+ appendDurably(walPath(this.stateDir, this.generation), encodeFrame(record));
157
+ this.state = nextState;
158
+ this.lastRecordSequence = record.sequence;
159
+ this.recordCount++;
160
+ if (this.recordCount >= this.options.maxRecordsBeforeCompaction) this.compactUnlocked();
161
+ return record;
162
+ });
163
+ }
164
+
165
+ /** Create G+1 without ever merging two generations during recovery. */
166
+ compact(): void {
167
+ withScopeLock(this.stateDir, () => {
168
+ this.refreshFromDisk();
169
+ this.compactUnlocked();
170
+ });
171
+ }
172
+
173
+ private refreshFromDisk(): void {
174
+ const recovered = readGenerations(this.stateDir, this.scopeDigest, this.options.reduce);
175
+ if (recovered.length === 0) {
176
+ throw new StateStoreCorruptionError("no valid generation remains while appending");
177
+ }
178
+ const current = recovered[0]!;
179
+ this.generation = current.generation;
180
+ this.state = current.state;
181
+ this.lastRecordSequence = current.lastRecordSequence;
182
+ this.recordCount = current.recordCount;
183
+ }
184
+
185
+ private compactUnlocked(): void {
186
+ const next: Generation<T> = {
187
+ generation: highestGenerationOnDisk(this.stateDir) + 1,
188
+ state: this.state,
189
+ lastRecordSequence: this.lastRecordSequence,
190
+ recordCount: 0,
191
+ };
192
+ writeGeneration(this.stateDir, this.scopeDigest, next);
193
+ writeCurrentPointer(this.stateDir, next.generation);
194
+ pruneGenerations(this.stateDir, [this.generation, next.generation]);
195
+ this.generation = next.generation;
196
+ this.recordCount = 0;
197
+ }
198
+ }
199
+
200
+ function readGenerations<T>(
201
+ dir: string,
202
+ scopeDigest: Buffer,
203
+ reduce: StateStoreOptions<T>["reduce"],
204
+ ): Generation<T>[] {
205
+ const names = fs.readdirSync(dir);
206
+ const generations = names
207
+ .map((name) => /^snapshot-(\d+)\.bin$/.exec(name)?.[1])
208
+ .filter((value): value is string => value !== undefined)
209
+ .map(Number)
210
+ .filter(Number.isSafeInteger)
211
+ .sort((a, b) => b - a);
212
+ const recovered: Generation<T>[] = [];
213
+ const errors: Error[] = [];
214
+ for (const generation of generations) {
215
+ try {
216
+ recovered.push(readGeneration(dir, scopeDigest, generation!, reduce));
217
+ } catch (error) {
218
+ if (!(error instanceof StateStoreCorruptionError)) {
219
+ throw new Error(`state-store: reducer rejected generation ${generation}`, { cause: error });
220
+ }
221
+ errors.push(error);
222
+ }
223
+ }
224
+ if (recovered.length === 0 && generations.length > 0) {
225
+ throw new StateStoreCorruptionError("no valid snapshot/WAL generation remains", {
226
+ cause: errors[0],
227
+ });
228
+ }
229
+ return recovered;
230
+ }
231
+
232
+ function readGeneration<T>(
233
+ dir: string,
234
+ scopeDigest: Buffer,
235
+ generation: number,
236
+ reduce: StateStoreOptions<T>["reduce"],
237
+ ): Generation<T> {
238
+ const snapshot = readSnapshot<T>(snapshotPath(dir, generation), scopeDigest, generation);
239
+ const parsed = readWal(
240
+ walPath(dir, generation),
241
+ scopeDigest,
242
+ generation,
243
+ snapshot.lastRecordSequence,
244
+ );
245
+ let state = snapshot.state;
246
+ for (const record of parsed.records) state = reduce(state, record);
247
+ return {
248
+ generation,
249
+ state,
250
+ lastRecordSequence: parsed.lastRecordSequence,
251
+ recordCount: parsed.records.length,
252
+ };
253
+ }
254
+
255
+ function writeGeneration<T>(dir: string, scopeDigest: Buffer, generation: Generation<T>): void {
256
+ const snapshot = encodeSnapshot(generation.generation, scopeDigest, {
257
+ lastRecordSequence: generation.lastRecordSequence,
258
+ state: generation.state,
259
+ });
260
+ const destination = snapshotPath(dir, generation.generation);
261
+ writeDurableTempThenRename(dir, destination, snapshot);
262
+ const header = encodeWalHeader(generation.generation, scopeDigest);
263
+ writeNewDurably(walPath(dir, generation.generation), header);
264
+ }
265
+
266
+ function readSnapshot<T>(filePath: string, scopeDigest: Buffer, generation: number): SnapshotPayload<T> {
267
+ let bytes: Buffer;
268
+ try {
269
+ bytes = fs.readFileSync(filePath);
270
+ } catch (error) {
271
+ throw new StateStoreCorruptionError(`cannot read snapshot generation ${generation}`, { cause: error });
272
+ }
273
+ if (bytes.length < SNAPSHOT_HEADER_BYTES) {
274
+ throw new StateStoreCorruptionError(`snapshot generation ${generation} has a torn header`);
275
+ }
276
+ if (!bytes.subarray(0, 8).equals(SNAPSHOT_MAGIC)) {
277
+ throw new StateStoreCorruptionError(`snapshot generation ${generation} has an invalid magic`);
278
+ }
279
+ if (readU64(bytes, 8) !== generation) {
280
+ throw new StateStoreCorruptionError(`snapshot generation ${generation} has a generation mismatch`);
281
+ }
282
+ const payloadLength = bytes.readUInt32BE(16);
283
+ if (bytes.length !== SNAPSHOT_HEADER_BYTES + payloadLength) {
284
+ throw new StateStoreCorruptionError(`snapshot generation ${generation} has an invalid payload length`);
285
+ }
286
+ if (!bytes.subarray(20, 52).equals(scopeDigest)) {
287
+ throw new StateStoreCorruptionError(`snapshot generation ${generation} has a scope digest mismatch`);
288
+ }
289
+ const expected = sha256(bytes.subarray(0, 52 + payloadLength));
290
+ if (!expected.equals(bytes.subarray(52 + payloadLength))) {
291
+ throw new StateStoreCorruptionError(`snapshot generation ${generation} has a bad checksum`);
292
+ }
293
+ let decoded: unknown;
294
+ try {
295
+ decoded = JSON.parse(bytes.subarray(52, 52 + payloadLength).toString("utf8"));
296
+ } catch (error) {
297
+ throw new StateStoreCorruptionError(`snapshot generation ${generation} has invalid JSON`, { cause: error });
298
+ }
299
+ if (!isSnapshotPayload(decoded)) {
300
+ throw new StateStoreCorruptionError(`snapshot generation ${generation} has an invalid state payload`);
301
+ }
302
+ return decoded as SnapshotPayload<T>;
303
+ }
304
+
305
+ function readWal(
306
+ filePath: string,
307
+ scopeDigest: Buffer,
308
+ generation: number,
309
+ snapshotSequence: number,
310
+ ): { records: StateStoreRecord[]; lastRecordSequence: number } {
311
+ let bytes: Buffer;
312
+ try {
313
+ bytes = fs.readFileSync(filePath);
314
+ } catch (error) {
315
+ throw new StateStoreCorruptionError(`cannot read WAL generation ${generation}`, { cause: error });
316
+ }
317
+ verifyWalHeader(bytes, scopeDigest, generation);
318
+ const records: StateStoreRecord[] = [];
319
+ let offset = WAL_HEADER_BYTES;
320
+ let sequence = snapshotSequence;
321
+ while (offset < bytes.length) {
322
+ const parsed = decodeFrame(bytes, offset);
323
+ if (parsed.kind === "torn") {
324
+ truncateWal(filePath, offset);
325
+ break;
326
+ }
327
+ if (parsed.record.sequence !== sequence + 1) {
328
+ throw new StateStoreCorruptionError(`WAL generation ${generation} has non-contiguous record sequence`);
329
+ }
330
+ records.push(parsed.record);
331
+ sequence = parsed.record.sequence;
332
+ offset = parsed.nextOffset;
333
+ }
334
+ return { records, lastRecordSequence: sequence };
335
+ }
336
+
337
+ function verifyWalHeader(bytes: Buffer, scopeDigest: Buffer, generation: number): void {
338
+ if (bytes.length < WAL_HEADER_BYTES) {
339
+ throw new StateStoreCorruptionError(`WAL generation ${generation} has a torn header`);
340
+ }
341
+ if (!bytes.subarray(0, 8).equals(WAL_MAGIC)) {
342
+ throw new StateStoreCorruptionError(`WAL generation ${generation} has an invalid magic`);
343
+ }
344
+ if (readU64(bytes, 8) !== generation) {
345
+ throw new StateStoreCorruptionError(`WAL generation ${generation} has a generation mismatch`);
346
+ }
347
+ if (!bytes.subarray(16, 48).equals(scopeDigest)) {
348
+ throw new StateStoreCorruptionError(`WAL generation ${generation} has a scope digest mismatch`);
349
+ }
350
+ if (!sha256(bytes.subarray(0, 48)).equals(bytes.subarray(48, 80))) {
351
+ throw new StateStoreCorruptionError(`WAL generation ${generation} has a bad header checksum`);
352
+ }
353
+ }
354
+
355
+ type DecodedFrame = { kind: "frame"; record: StateStoreRecord; nextOffset: number } | { kind: "torn" };
356
+
357
+ function decodeFrame(bytes: Buffer, offset: number): DecodedFrame {
358
+ if (bytes.length - offset < FRAME_PREFIX_BYTES) return { kind: "torn" };
359
+ if (bytes.readUInt32BE(offset) !== FRAME_MAGIC) {
360
+ throw new StateStoreCorruptionError("WAL has an invalid frame magic");
361
+ }
362
+ const frameLength = bytes.readUInt32BE(offset + 4);
363
+ if (frameLength < FRAME_FIXED_BODY_BYTES || frameLength > MAX_FRAME_BYTES) {
364
+ throw new StateStoreCorruptionError("WAL has an invalid frame length");
365
+ }
366
+ const available = bytes.length - offset - FRAME_PREFIX_BYTES;
367
+ if (available < frameLength) {
368
+ // A torn write cannot supply the complete declared payload. If it does,
369
+ // but the outer length disagrees, the length prefix was corrupted rather
370
+ // than the writer being interrupted.
371
+ if (available >= 16) {
372
+ const declaredPayloadLength = bytes.readUInt32BE(offset + FRAME_PREFIX_BYTES + 12);
373
+ const declaredFrameLength = FRAME_FIXED_BODY_BYTES + declaredPayloadLength;
374
+ if (declaredFrameLength <= available && declaredFrameLength !== frameLength) {
375
+ throw new StateStoreCorruptionError("WAL frame length prefix is corrupt");
376
+ }
377
+ }
378
+ return { kind: "torn" };
379
+ }
380
+ const body = bytes.subarray(offset + FRAME_PREFIX_BYTES, offset + FRAME_PREFIX_BYTES + frameLength);
381
+ const payloadLength = body.readUInt32BE(12);
382
+ if (frameLength !== FRAME_FIXED_BODY_BYTES + payloadLength) {
383
+ throw new StateStoreCorruptionError("WAL frame length does not match payload length");
384
+ }
385
+ const payload = body.subarray(16, 16 + payloadLength);
386
+ const storedCrc = body.readUInt32BE(16 + payloadLength);
387
+ const crcBytes = body.subarray(0, 16 + payloadLength);
388
+ if (crc32c(crcBytes) !== storedCrc) {
389
+ throw new StateStoreCorruptionError("WAL frame has a bad CRC32C");
390
+ }
391
+ const checksumInput = body.subarray(0, 20 + payloadLength);
392
+ if (!sha256(checksumInput).equals(body.subarray(20 + payloadLength))) {
393
+ throw new StateStoreCorruptionError("WAL frame has a bad SHA-256 checksum");
394
+ }
395
+ let value: unknown;
396
+ try {
397
+ value = JSON.parse(payload.toString("utf8"));
398
+ } catch (error) {
399
+ throw new StateStoreCorruptionError("WAL frame has invalid JSON", { cause: error });
400
+ }
401
+ return {
402
+ kind: "frame",
403
+ record: { sequence: readU64(body, 0), type: body.readUInt16BE(8), flags: body.readUInt16BE(10), payload: value },
404
+ nextOffset: offset + FRAME_PREFIX_BYTES + frameLength,
405
+ };
406
+ }
407
+
408
+ function encodeSnapshot<T>(generation: number, scopeDigest: Buffer, payload: SnapshotPayload<T>): Buffer {
409
+ const data = Buffer.from(canonicalJson(payload), "utf8");
410
+ const header = Buffer.alloc(52);
411
+ SNAPSHOT_MAGIC.copy(header, 0);
412
+ writeU64(header, generation, 8);
413
+ header.writeUInt32BE(data.length, 16);
414
+ scopeDigest.copy(header, 20);
415
+ return Buffer.concat([header, data, sha256(Buffer.concat([header, data]))]);
416
+ }
417
+
418
+ function encodeWalHeader(generation: number, scopeDigest: Buffer): Buffer {
419
+ const header = Buffer.alloc(48);
420
+ WAL_MAGIC.copy(header, 0);
421
+ writeU64(header, generation, 8);
422
+ scopeDigest.copy(header, 16);
423
+ return Buffer.concat([header, sha256(header)]);
424
+ }
425
+
426
+ function encodeFrame(record: StateStoreRecord): Buffer {
427
+ const payload = Buffer.from(canonicalJson(record.payload), "utf8");
428
+ if (payload.length > MAX_FRAME_BYTES - FRAME_FIXED_BODY_BYTES) {
429
+ throw new Error("state-store: record payload exceeds WAL frame limit");
430
+ }
431
+ const withoutChecksums = Buffer.alloc(16 + payload.length);
432
+ writeU64(withoutChecksums, record.sequence, 0);
433
+ withoutChecksums.writeUInt16BE(record.type, 8);
434
+ withoutChecksums.writeUInt16BE(record.flags, 10);
435
+ withoutChecksums.writeUInt32BE(payload.length, 12);
436
+ payload.copy(withoutChecksums, 16);
437
+ const crc = Buffer.alloc(4);
438
+ crc.writeUInt32BE(crc32c(withoutChecksums), 0);
439
+ const checksum = sha256(Buffer.concat([withoutChecksums, crc]));
440
+ const prefix = Buffer.alloc(FRAME_PREFIX_BYTES);
441
+ prefix.writeUInt32BE(FRAME_MAGIC, 0);
442
+ prefix.writeUInt32BE(withoutChecksums.length + crc.length + checksum.length, 4);
443
+ return Buffer.concat([prefix, withoutChecksums, crc, checksum]);
444
+ }
445
+
446
+ function appendDurably(filePath: string, bytes: Buffer): void {
447
+ let fd: number | undefined;
448
+ try {
449
+ fd = fs.openSync(filePath, "a");
450
+ writeAllSync(fd, bytes);
451
+ fs.fdatasyncSync(fd);
452
+ } catch (error) {
453
+ throw new Error(`state-store: append and fdatasync failed for ${filePath}`, { cause: error });
454
+ } finally {
455
+ if (fd !== undefined) fs.closeSync(fd);
456
+ }
457
+ }
458
+
459
+ function writeNewDurably(filePath: string, bytes: Buffer): void {
460
+ let fd: number | undefined;
461
+ try {
462
+ fd = fs.openSync(filePath, "wx");
463
+ writeAllSync(fd, bytes);
464
+ fs.fdatasyncSync(fd);
465
+ } catch (error) {
466
+ throw new Error(`state-store: durable create failed for ${filePath}`, { cause: error });
467
+ } finally {
468
+ if (fd !== undefined) fs.closeSync(fd);
469
+ }
470
+ }
471
+
472
+ function writeDurableTempThenRename(dir: string, destination: string, bytes: Buffer): void {
473
+ const temporary = path.join(dir, `.${path.basename(destination)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
474
+ let fd: number | undefined;
475
+ try {
476
+ fd = fs.openSync(temporary, "wx");
477
+ writeAllSync(fd, bytes);
478
+ fs.fdatasyncSync(fd);
479
+ fs.closeSync(fd);
480
+ fd = undefined;
481
+ fs.renameSync(temporary, destination);
482
+ fsyncDirectory(dir);
483
+ } catch (error) {
484
+ if (fd !== undefined) fs.closeSync(fd);
485
+ try { fs.rmSync(temporary, { force: true }); } catch { /* preserve the primary durable-write error */ }
486
+ throw new Error(`state-store: snapshot write/rename failed for ${destination}`, { cause: error });
487
+ }
488
+ }
489
+
490
+ function writeCurrentPointer(dir: string, generation: number): void {
491
+ const pointer = path.join(dir, "current");
492
+ writeDurableTempThenRename(dir, pointer, Buffer.from(`${generation}\n`, "ascii"));
493
+ }
494
+
495
+ function writeAllSync(fd: number, bytes: Buffer): void {
496
+ let offset = 0;
497
+ while (offset < bytes.length) {
498
+ const written = fs.writeSync(fd, bytes, offset, bytes.length - offset);
499
+ if (written <= 0) throw new Error("state-store: short write made no progress");
500
+ offset += written;
501
+ }
502
+ }
503
+
504
+ function withScopeLock<T>(dir: string, action: () => T): T {
505
+ const lockPath = path.join(dir, "append.lock");
506
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
507
+ let fd: number | undefined;
508
+ while (fd === undefined) {
509
+ try {
510
+ fd = fs.openSync(lockPath, "wx");
511
+ fs.writeFileSync(fd, String(process.pid));
512
+ fs.fdatasyncSync(fd);
513
+ } catch (error) {
514
+ if (!isAlreadyExists(error)) {
515
+ throw new StateStoreLockError(`cannot acquire ${lockPath}`, { cause: error });
516
+ }
517
+ if (removeDeadLock(lockPath)) continue;
518
+ if (Date.now() >= deadline) {
519
+ throw new StateStoreLockError(`timed out acquiring ${lockPath}`);
520
+ }
521
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, LOCK_RETRY_MS);
522
+ }
523
+ }
524
+ let result: T | undefined;
525
+ let actionError: unknown;
526
+ try {
527
+ result = action();
528
+ } catch (error) {
529
+ actionError = error;
530
+ } finally {
531
+ fs.closeSync(fd);
532
+ }
533
+ try {
534
+ fs.unlinkSync(lockPath);
535
+ } catch (error) {
536
+ throw new StateStoreLockError(`cannot release ${lockPath}`, { cause: error });
537
+ }
538
+ if (actionError !== undefined) throw actionError;
539
+ return result as T;
540
+ }
541
+
542
+ function removeDeadLock(lockPath: string): boolean {
543
+ let pid: number;
544
+ try {
545
+ pid = Number(fs.readFileSync(lockPath, "utf8"));
546
+ } catch (error) {
547
+ return isMissing(error);
548
+ }
549
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
550
+ try {
551
+ process.kill(pid, 0);
552
+ return false;
553
+ } catch (error) {
554
+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") return false;
555
+ }
556
+ try {
557
+ fs.unlinkSync(lockPath);
558
+ return true;
559
+ } catch (error) {
560
+ return isMissing(error);
561
+ }
562
+ }
563
+
564
+ function truncateWal(filePath: string, boundary: number): void {
565
+ let fd: number | undefined;
566
+ try {
567
+ fd = fs.openSync(filePath, "r+");
568
+ fs.ftruncateSync(fd, boundary);
569
+ fs.fdatasyncSync(fd);
570
+ } catch (error) {
571
+ throw new Error(`state-store: failed to truncate torn WAL tail at ${filePath}`, { cause: error });
572
+ } finally {
573
+ if (fd !== undefined) fs.closeSync(fd);
574
+ }
575
+ }
576
+
577
+ function fsyncDirectory(dir: string): void {
578
+ let fd: number | undefined;
579
+ try {
580
+ fd = fs.openSync(dir, "r");
581
+ fs.fsyncSync(fd);
582
+ } catch (error) {
583
+ if (isUnsupportedDirectoryFsync(error)) return;
584
+ throw new Error(`state-store: directory fsync failed for ${dir}`, { cause: error });
585
+ } finally {
586
+ if (fd !== undefined) fs.closeSync(fd);
587
+ }
588
+ }
589
+
590
+ function stateDirectory(rootDir: string, scopeDigest: Buffer): string {
591
+ return path.join(rootDir, "sync-state-v3", scopeDigest.toString("hex"));
592
+ }
593
+
594
+ function snapshotPath(dir: string, generation: number): string {
595
+ return path.join(dir, `snapshot-${generation}.bin`);
596
+ }
597
+
598
+ function walPath(dir: string, generation: number): string {
599
+ return path.join(dir, `wal-${generation}.bin`);
600
+ }
601
+
602
+ function highestGenerationOnDisk(dir: string): number {
603
+ return fs.readdirSync(dir)
604
+ .map((name) => /^(?:snapshot|wal)-(\d+)\.bin$/.exec(name)?.[1])
605
+ .filter((value): value is string => value !== undefined)
606
+ .map(Number)
607
+ .filter(Number.isSafeInteger)
608
+ .reduce((highest, generation) => Math.max(highest, generation), 0);
609
+ }
610
+
611
+ function pruneGenerations(dir: string, retain: number[]): void {
612
+ const retained = new Set(retain);
613
+ for (const name of fs.readdirSync(dir)) {
614
+ const match = /^(?:snapshot|wal)-(\d+)\.bin$/.exec(name);
615
+ if (!match) continue;
616
+ const generation = Number(match[1]);
617
+ if (!retained.has(generation)) {
618
+ try {
619
+ fs.unlinkSync(path.join(dir, name));
620
+ } catch (error) {
621
+ throw new Error(`state-store: failed to prune obsolete generation ${generation}`, { cause: error });
622
+ }
623
+ }
624
+ }
625
+ fsyncDirectory(dir);
626
+ }
627
+
628
+ function cleanupUnpublishedInitialGeneration(dir: string): void {
629
+ if (fs.existsSync(path.join(dir, "current"))) return;
630
+ const initialSnapshot = snapshotPath(dir, 1);
631
+ const initialWal = walPath(dir, 1);
632
+ if (fs.existsSync(initialSnapshot) && !fs.existsSync(initialWal)) {
633
+ try {
634
+ fs.unlinkSync(initialSnapshot);
635
+ fsyncDirectory(dir);
636
+ } catch (error) {
637
+ throw new Error("state-store: failed to clean unpublished initial snapshot", { cause: error });
638
+ }
639
+ }
640
+ if (!fs.existsSync(initialSnapshot) && fs.existsSync(initialWal)) {
641
+ try {
642
+ fs.unlinkSync(initialWal);
643
+ fsyncDirectory(dir);
644
+ } catch (error) {
645
+ throw new Error("state-store: failed to clean unpublished initial WAL", { cause: error });
646
+ }
647
+ }
648
+ }
649
+
650
+ function digestScope(scopeId: string): Buffer {
651
+ return sha256(Buffer.from(scopeId, "utf8"));
652
+ }
653
+
654
+ function sha256(value: Buffer): Buffer {
655
+ return crypto.createHash("sha256").update(value).digest();
656
+ }
657
+
658
+ function writeU64(target: Buffer, value: number, offset: number): void {
659
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error("state-store: invalid u64 value");
660
+ target.writeBigUInt64BE(BigInt(value), offset);
661
+ }
662
+
663
+ function readU64(source: Buffer, offset: number): number {
664
+ const value = source.readBigUInt64BE(offset);
665
+ if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw new StateStoreCorruptionError("u64 exceeds JavaScript safe integer range");
666
+ return Number(value);
667
+ }
668
+
669
+ function assertUint16(value: number, name: string): void {
670
+ if (!Number.isInteger(value) || value < 0 || value > 0xffff) throw new Error(`state-store: ${name} must be a u16`);
671
+ }
672
+
673
+ function isSnapshotPayload(value: unknown): value is SnapshotPayload<unknown> {
674
+ return typeof value === "object" && value !== null &&
675
+ Number.isSafeInteger((value as { lastRecordSequence?: unknown }).lastRecordSequence) &&
676
+ (value as { lastRecordSequence: number }).lastRecordSequence >= 0 &&
677
+ Object.hasOwn(value, "state");
678
+ }
679
+
680
+ function isMissing(error: unknown): boolean {
681
+ return typeof error === "object" && error !== null && (error as NodeJS.ErrnoException).code === "ENOENT";
682
+ }
683
+
684
+ function isAlreadyExists(error: unknown): boolean {
685
+ return typeof error === "object" && error !== null && (error as NodeJS.ErrnoException).code === "EEXIST";
686
+ }
687
+
688
+ function isUnsupportedDirectoryFsync(error: unknown): boolean {
689
+ const code = typeof error === "object" && error !== null
690
+ ? (error as NodeJS.ErrnoException).code
691
+ : undefined;
692
+ return code === "EINVAL" || code === "ENOTSUP" || code === "EOPNOTSUPP" || code === "EPERM";
693
+ }
694
+
695
+ /** RFC 8785-compatible JSON for the plain JSON values persisted by this store. */
696
+ function canonicalJson(value: unknown): string {
697
+ if (value === null || typeof value === "boolean" || typeof value === "string") return JSON.stringify(value);
698
+ if (typeof value === "number") {
699
+ if (!Number.isFinite(value)) throw new Error("state-store: JSON numbers must be finite");
700
+ return Object.is(value, -0) ? "0" : JSON.stringify(value);
701
+ }
702
+ if (Array.isArray(value)) {
703
+ return `[${value.map((item, index) => {
704
+ if (!(index in value) || item === undefined) throw new Error("state-store: JSON arrays cannot be sparse or undefined");
705
+ return canonicalJson(item);
706
+ }).join(",")}]`;
707
+ }
708
+ if (typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype) {
709
+ const object = value as Record<string, unknown>;
710
+ return `{${Object.keys(object).sort().map((key) => {
711
+ const item = object[key];
712
+ if (item === undefined) throw new Error(`state-store: JSON property ${key} is undefined`);
713
+ return `${JSON.stringify(key)}:${canonicalJson(item)}`;
714
+ }).join(",")}}`;
715
+ }
716
+ throw new Error("state-store: payload must be a plain JSON value");
717
+ }
718
+
719
+ // Castagnoli CRC32C, tableless to avoid a new dependency in the hot path.
720
+ function crc32c(bytes: Buffer): number {
721
+ let crc = 0xffffffff;
722
+ for (const byte of bytes) {
723
+ crc ^= byte;
724
+ for (let bit = 0; bit < 8; bit++) crc = (crc >>> 1) ^ (0x82f63b78 & -(crc & 1));
725
+ }
726
+ return (crc ^ 0xffffffff) >>> 0;
727
+ }