@indigoai-us/hq-cloud 6.14.50 → 6.15.1

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 (340) hide show
  1. package/dist/bin/sync-mutation.d.ts +14 -0
  2. package/dist/bin/sync-mutation.d.ts.map +1 -0
  3. package/dist/bin/sync-mutation.js +60 -0
  4. package/dist/bin/sync-mutation.js.map +1 -0
  5. package/dist/bin/sync-mutation.test.d.ts +2 -0
  6. package/dist/bin/sync-mutation.test.d.ts.map +1 -0
  7. package/dist/bin/sync-mutation.test.js +64 -0
  8. package/dist/bin/sync-mutation.test.js.map +1 -0
  9. package/dist/bin/sync-runner-company.d.ts +8 -0
  10. package/dist/bin/sync-runner-company.d.ts.map +1 -1
  11. package/dist/bin/sync-runner-company.js +16 -0
  12. package/dist/bin/sync-runner-company.js.map +1 -1
  13. package/dist/bin/sync-runner-company.test.d.ts +2 -0
  14. package/dist/bin/sync-runner-company.test.d.ts.map +1 -0
  15. package/dist/bin/sync-runner-company.test.js +36 -0
  16. package/dist/bin/sync-runner-company.test.js.map +1 -0
  17. package/dist/bin/sync-runner-watch-loop.d.ts.map +1 -1
  18. package/dist/bin/sync-runner-watch-loop.js +98 -8
  19. package/dist/bin/sync-runner-watch-loop.js.map +1 -1
  20. package/dist/bin/sync-runner.d.ts +17 -0
  21. package/dist/bin/sync-runner.d.ts.map +1 -1
  22. package/dist/bin/sync-runner.js.map +1 -1
  23. package/dist/bin/sync-runner.test.js +109 -0
  24. package/dist/bin/sync-runner.test.js.map +1 -1
  25. package/dist/cli/conflict-recovery.test.d.ts +2 -0
  26. package/dist/cli/conflict-recovery.test.d.ts.map +1 -0
  27. package/dist/cli/conflict-recovery.test.js +201 -0
  28. package/dist/cli/conflict-recovery.test.js.map +1 -0
  29. package/dist/cli/conflict.d.ts +60 -0
  30. package/dist/cli/conflict.d.ts.map +1 -1
  31. package/dist/cli/conflict.js +333 -0
  32. package/dist/cli/conflict.js.map +1 -1
  33. package/dist/cli/reindex-knowledge.d.ts +7 -0
  34. package/dist/cli/reindex-knowledge.d.ts.map +1 -0
  35. package/dist/cli/reindex-knowledge.js +389 -0
  36. package/dist/cli/reindex-knowledge.js.map +1 -0
  37. package/dist/cli/reindex-knowledge.test.d.ts +12 -0
  38. package/dist/cli/reindex-knowledge.test.d.ts.map +1 -0
  39. package/dist/cli/reindex-knowledge.test.js +260 -0
  40. package/dist/cli/reindex-knowledge.test.js.map +1 -0
  41. package/dist/cli/reindex.d.ts.map +1 -1
  42. package/dist/cli/reindex.js +8 -0
  43. package/dist/cli/reindex.js.map +1 -1
  44. package/dist/cli/rescue-settings-reconcile.test.js +47 -0
  45. package/dist/cli/rescue-settings-reconcile.test.js.map +1 -1
  46. package/dist/cli/sync.d.ts +27 -0
  47. package/dist/cli/sync.d.ts.map +1 -1
  48. package/dist/cli/sync.js +52 -0
  49. package/dist/cli/sync.js.map +1 -1
  50. package/dist/cli/sync.test.js +31 -1
  51. package/dist/cli/sync.test.js.map +1 -1
  52. package/dist/index.d.ts +2 -0
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +1 -0
  55. package/dist/index.js.map +1 -1
  56. package/dist/skill-telemetry.d.ts +6 -0
  57. package/dist/skill-telemetry.d.ts.map +1 -1
  58. package/dist/skill-telemetry.js +14 -2
  59. package/dist/skill-telemetry.js.map +1 -1
  60. package/dist/skill-telemetry.test.js +79 -0
  61. package/dist/skill-telemetry.test.js.map +1 -1
  62. package/dist/sync/candidate-uploader.d.ts +88 -0
  63. package/dist/sync/candidate-uploader.d.ts.map +1 -0
  64. package/dist/sync/candidate-uploader.js +212 -0
  65. package/dist/sync/candidate-uploader.js.map +1 -0
  66. package/dist/sync/candidate-uploader.test.d.ts +2 -0
  67. package/dist/sync/candidate-uploader.test.d.ts.map +1 -0
  68. package/dist/sync/candidate-uploader.test.js +132 -0
  69. package/dist/sync/candidate-uploader.test.js.map +1 -0
  70. package/dist/sync/delta-client.d.ts +73 -0
  71. package/dist/sync/delta-client.d.ts.map +1 -0
  72. package/dist/sync/delta-client.js +201 -0
  73. package/dist/sync/delta-client.js.map +1 -0
  74. package/dist/sync/delta-client.test.d.ts +2 -0
  75. package/dist/sync/delta-client.test.d.ts.map +1 -0
  76. package/dist/sync/delta-client.test.js +97 -0
  77. package/dist/sync/delta-client.test.js.map +1 -0
  78. package/dist/sync/durable-apply.d.ts +76 -0
  79. package/dist/sync/durable-apply.d.ts.map +1 -0
  80. package/dist/sync/durable-apply.js +530 -0
  81. package/dist/sync/durable-apply.js.map +1 -0
  82. package/dist/sync/durable-apply.test.d.ts +2 -0
  83. package/dist/sync/durable-apply.test.d.ts.map +1 -0
  84. package/dist/sync/durable-apply.test.js +180 -0
  85. package/dist/sync/durable-apply.test.js.map +1 -0
  86. package/dist/sync/event-sync.d.ts +33 -1
  87. package/dist/sync/event-sync.d.ts.map +1 -1
  88. package/dist/sync/event-sync.js +149 -1
  89. package/dist/sync/event-sync.js.map +1 -1
  90. package/dist/sync/event-sync.test.js +142 -1
  91. package/dist/sync/event-sync.test.js.map +1 -1
  92. package/dist/sync/index.d.ts +2 -0
  93. package/dist/sync/index.d.ts.map +1 -1
  94. package/dist/sync/index.js +1 -0
  95. package/dist/sync/index.js.map +1 -1
  96. package/dist/sync/multipart-uploader.d.ts +99 -0
  97. package/dist/sync/multipart-uploader.d.ts.map +1 -0
  98. package/dist/sync/multipart-uploader.js +447 -0
  99. package/dist/sync/multipart-uploader.js.map +1 -0
  100. package/dist/sync/multipart-uploader.test.d.ts +2 -0
  101. package/dist/sync/multipart-uploader.test.d.ts.map +1 -0
  102. package/dist/sync/multipart-uploader.test.js +119 -0
  103. package/dist/sync/multipart-uploader.test.js.map +1 -0
  104. package/dist/sync/mutation-client.d.ts +82 -0
  105. package/dist/sync/mutation-client.d.ts.map +1 -0
  106. package/dist/sync/mutation-client.js +221 -0
  107. package/dist/sync/mutation-client.js.map +1 -0
  108. package/dist/sync/mutation-client.test.d.ts +2 -0
  109. package/dist/sync/mutation-client.test.d.ts.map +1 -0
  110. package/dist/sync/mutation-client.test.js +51 -0
  111. package/dist/sync/mutation-client.test.js.map +1 -0
  112. package/dist/sync/push-receiver.d.ts +45 -0
  113. package/dist/sync/push-receiver.d.ts.map +1 -1
  114. package/dist/sync/push-receiver.js +101 -0
  115. package/dist/sync/push-receiver.js.map +1 -1
  116. package/dist/sync/push-receiver.test.js +54 -2
  117. package/dist/sync/push-receiver.test.js.map +1 -1
  118. package/dist/sync/scope-inventory-client.d.ts +69 -0
  119. package/dist/sync/scope-inventory-client.d.ts.map +1 -0
  120. package/dist/sync/scope-inventory-client.js +210 -0
  121. package/dist/sync/scope-inventory-client.js.map +1 -0
  122. package/dist/sync/scope-inventory-client.test.d.ts +2 -0
  123. package/dist/sync/scope-inventory-client.test.d.ts.map +1 -0
  124. package/dist/sync/scope-inventory-client.test.js +94 -0
  125. package/dist/sync/scope-inventory-client.test.js.map +1 -0
  126. package/dist/sync/snapshot-client.d.ts +98 -0
  127. package/dist/sync/snapshot-client.d.ts.map +1 -0
  128. package/dist/sync/snapshot-client.js +402 -0
  129. package/dist/sync/snapshot-client.js.map +1 -0
  130. package/dist/sync/snapshot-client.test.d.ts +2 -0
  131. package/dist/sync/snapshot-client.test.d.ts.map +1 -0
  132. package/dist/sync/snapshot-client.test.js +169 -0
  133. package/dist/sync/snapshot-client.test.js.map +1 -0
  134. package/dist/sync/uploader-finalization.d.ts +97 -0
  135. package/dist/sync/uploader-finalization.d.ts.map +1 -0
  136. package/dist/sync/uploader-finalization.js +273 -0
  137. package/dist/sync/uploader-finalization.js.map +1 -0
  138. package/dist/sync/uploader-finalization.test.d.ts +2 -0
  139. package/dist/sync/uploader-finalization.test.d.ts.map +1 -0
  140. package/dist/sync/uploader-finalization.test.js +92 -0
  141. package/dist/sync/uploader-finalization.test.js.map +1 -0
  142. package/dist/telemetry.d.ts +11 -1
  143. package/dist/telemetry.d.ts.map +1 -1
  144. package/dist/telemetry.js +21 -2
  145. package/dist/telemetry.js.map +1 -1
  146. package/dist/telemetry.test.js +80 -0
  147. package/dist/telemetry.test.js.map +1 -1
  148. package/package.json +6 -1
  149. package/.claude/policies/hq-cloud-esm-cannot-spy-fs-builtins.md +0 -30
  150. package/.claude/policies/hq-cloud-strip-types-no-parameter-properties.md +0 -22
  151. package/.github/workflows/ci.yml +0 -84
  152. package/.github/workflows/publish.yml +0 -56
  153. package/.github/workflows/unreleased-commits-nag.yml +0 -256
  154. package/eslint.config.js +0 -67
  155. package/pnpm-workspace.yaml +0 -2
  156. package/scripts/presign-transport-e2e.mjs +0 -250
  157. package/scripts/vault-rebaseline.sh +0 -323
  158. package/scripts/vault-rescue.sh +0 -332
  159. package/src/active-company.test.ts +0 -188
  160. package/src/active-company.ts +0 -168
  161. package/src/agent-codex-instructions.test.ts +0 -332
  162. package/src/agent-codex-instructions.ts +0 -309
  163. package/src/auth.ts +0 -146
  164. package/src/backup-prune.test.ts +0 -98
  165. package/src/backup-prune.ts +0 -182
  166. package/src/bin/backup-prune-runner.ts +0 -33
  167. package/src/bin/rescue-runner.ts +0 -25
  168. package/src/bin/sync-runner-company.ts +0 -695
  169. package/src/bin/sync-runner-events.test.ts +0 -143
  170. package/src/bin/sync-runner-events.ts +0 -55
  171. package/src/bin/sync-runner-planning.test.ts +0 -311
  172. package/src/bin/sync-runner-planning.ts +0 -258
  173. package/src/bin/sync-runner-rollup.test.ts +0 -37
  174. package/src/bin/sync-runner-rollup.ts +0 -97
  175. package/src/bin/sync-runner-telemetry.ts +0 -15
  176. package/src/bin/sync-runner-watch-loop.ts +0 -1235
  177. package/src/bin/sync-runner-watch-routes.test.ts +0 -71
  178. package/src/bin/sync-runner-watch-routes.ts +0 -184
  179. package/src/bin/sync-runner.test.ts +0 -8767
  180. package/src/bin/sync-runner.ts +0 -2190
  181. package/src/cli/accept.ts +0 -124
  182. package/src/cli/conflict.ts +0 -119
  183. package/src/cli/doctor.test.ts +0 -581
  184. package/src/cli/doctor.ts +0 -642
  185. package/src/cli/index.ts +0 -49
  186. package/src/cli/invite.test.ts +0 -250
  187. package/src/cli/invite.ts +0 -214
  188. package/src/cli/promote.ts +0 -157
  189. package/src/cli/reindex.test.ts +0 -957
  190. package/src/cli/reindex.ts +0 -970
  191. package/src/cli/rescue-classify-ordering.test.ts +0 -548
  192. package/src/cli/rescue-clone-diagnostics.test.ts +0 -120
  193. package/src/cli/rescue-core.ts +0 -3011
  194. package/src/cli/rescue-drift-reconcile.test.ts +0 -179
  195. package/src/cli/rescue-drop-dir-symlink.test.ts +0 -224
  196. package/src/cli/rescue-exec-bit-preserve.test.ts +0 -187
  197. package/src/cli/rescue-hq-root-guard.test.ts +0 -232
  198. package/src/cli/rescue-journal-reconcile.test.ts +0 -215
  199. package/src/cli/rescue-mtime-preserve.test.ts +0 -203
  200. package/src/cli/rescue-settings-reconcile.test.ts +0 -583
  201. package/src/cli/rescue-snapshot.test.ts +0 -57
  202. package/src/cli/rescue-snapshot.ts +0 -51
  203. package/src/cli/rescue.reindex.test.ts +0 -63
  204. package/src/cli/rescue.test.ts +0 -131
  205. package/src/cli/rescue.ts +0 -182
  206. package/src/cli/share.test.ts +0 -7843
  207. package/src/cli/share.ts +0 -3663
  208. package/src/cli/sync-scope.test.ts +0 -652
  209. package/src/cli/sync.test.ts +0 -5207
  210. package/src/cli/sync.ts +0 -3470
  211. package/src/cli/tombstones.ts +0 -106
  212. package/src/cli/watch-event-push-conflict.test.ts +0 -234
  213. package/src/client-info.test.ts +0 -214
  214. package/src/client-info.ts +0 -121
  215. package/src/cognito-auth.test.ts +0 -712
  216. package/src/cognito-auth.ts +0 -1422
  217. package/src/company-resolver.test.ts +0 -618
  218. package/src/company-resolver.ts +0 -521
  219. package/src/context.test.ts +0 -583
  220. package/src/context.ts +0 -378
  221. package/src/daemon-worker.ts +0 -26
  222. package/src/daemon.ts +0 -99
  223. package/src/entity-resolver.test.ts +0 -315
  224. package/src/entity-resolver.ts +0 -180
  225. package/src/ignore.test.ts +0 -466
  226. package/src/ignore.ts +0 -469
  227. package/src/index.ts +0 -439
  228. package/src/journal.test.ts +0 -968
  229. package/src/journal.ts +0 -765
  230. package/src/lib/cloud-authoritative.test.ts +0 -45
  231. package/src/lib/cloud-authoritative.ts +0 -59
  232. package/src/lib/conflict-file.ts +0 -86
  233. package/src/lib/conflict-index.ts +0 -289
  234. package/src/lib/conflict.test.ts +0 -348
  235. package/src/lib/describe-error.test.ts +0 -100
  236. package/src/lib/describe-error.ts +0 -58
  237. package/src/lib/exit-codes.ts +0 -24
  238. package/src/lib/machine-id.test.ts +0 -231
  239. package/src/lib/machine-id.ts +0 -175
  240. package/src/lib/net-errors.test.ts +0 -65
  241. package/src/lib/net-errors.ts +0 -86
  242. package/src/lib/readlink-safe.test.ts +0 -43
  243. package/src/lib/readlink-safe.ts +0 -29
  244. package/src/local-path-codec.test.ts +0 -138
  245. package/src/local-path-codec.ts +0 -161
  246. package/src/machine-auth.test.ts +0 -1323
  247. package/src/manifest-reconcile.test.ts +0 -1123
  248. package/src/manifest-reconcile.ts +0 -518
  249. package/src/object-io.test.ts +0 -1221
  250. package/src/object-io.ts +0 -1306
  251. package/src/operation-lock.test.ts +0 -484
  252. package/src/operation-lock.ts +0 -680
  253. package/src/outcome-telemetry.test.ts +0 -498
  254. package/src/outcome-telemetry.ts +0 -639
  255. package/src/personal-vault-exclusions.test.ts +0 -308
  256. package/src/personal-vault-exclusions.ts +0 -354
  257. package/src/personal-vault.test.ts +0 -756
  258. package/src/personal-vault.ts +0 -496
  259. package/src/prefix-coalesce.test.ts +0 -240
  260. package/src/prefix-coalesce.ts +0 -273
  261. package/src/public-surface.test.ts +0 -117
  262. package/src/qmd-reindex.test.ts +0 -877
  263. package/src/qmd-reindex.ts +0 -842
  264. package/src/read-only-state-dir.test.ts +0 -188
  265. package/src/remote-pull.test.ts +0 -1130
  266. package/src/remote-pull.ts +0 -618
  267. package/src/s3.symlink-materialize.test.ts +0 -492
  268. package/src/s3.test.ts +0 -1789
  269. package/src/s3.ts +0 -1532
  270. package/src/schemas/signal-types.test.ts +0 -82
  271. package/src/schemas/signal-types.ts +0 -38
  272. package/src/schemas/source-channels.test.ts +0 -82
  273. package/src/schemas/source-channels.ts +0 -53
  274. package/src/scope-shrink.test.ts +0 -633
  275. package/src/scope-shrink.ts +0 -481
  276. package/src/signals/get.test.ts +0 -310
  277. package/src/signals/get.ts +0 -75
  278. package/src/signals/internals.ts +0 -195
  279. package/src/signals/list.test.ts +0 -420
  280. package/src/signals/list.ts +0 -79
  281. package/src/signals/parse.ts +0 -8
  282. package/src/signals/types.ts +0 -91
  283. package/src/skill-telemetry.test.ts +0 -1825
  284. package/src/skill-telemetry.ts +0 -1439
  285. package/src/sources/get.test.ts +0 -293
  286. package/src/sources/get.ts +0 -66
  287. package/src/sources/internals.ts +0 -198
  288. package/src/sources/list.test.ts +0 -402
  289. package/src/sources/list.ts +0 -84
  290. package/src/sources/parse.ts +0 -43
  291. package/src/sources/types.ts +0 -84
  292. package/src/sync/event-sync.test.ts +0 -594
  293. package/src/sync/event-sync.ts +0 -545
  294. package/src/sync/feature-flags.test.ts +0 -378
  295. package/src/sync/feature-flags.ts +0 -62
  296. package/src/sync/index.ts +0 -76
  297. package/src/sync/lease-client.test.ts +0 -128
  298. package/src/sync/lease-client.ts +0 -207
  299. package/src/sync/logger.test.ts +0 -242
  300. package/src/sync/logger.ts +0 -79
  301. package/src/sync/metrics.test.ts +0 -462
  302. package/src/sync/metrics.ts +0 -213
  303. package/src/sync/pull-scope.ts +0 -265
  304. package/src/sync/push-event.test.ts +0 -266
  305. package/src/sync/push-event.ts +0 -224
  306. package/src/sync/push-receiver.test.ts +0 -566
  307. package/src/sync/push-receiver.ts +0 -1048
  308. package/src/sync/push-transport.ts +0 -231
  309. package/src/sync/realtime-rollout.test.ts +0 -86
  310. package/src/sync/realtime-rollout.ts +0 -262
  311. package/src/sync/state-store.test.ts +0 -194
  312. package/src/sync/state-store.ts +0 -727
  313. package/src/sync-core.ts +0 -58
  314. package/src/sync-progress.test.ts +0 -94
  315. package/src/sync-progress.ts +0 -140
  316. package/src/telemetry-events.test.ts +0 -88
  317. package/src/telemetry-events.ts +0 -205
  318. package/src/telemetry.test.ts +0 -1280
  319. package/src/telemetry.ts +0 -1109
  320. package/src/types.ts +0 -314
  321. package/src/vault-client.test.ts +0 -1380
  322. package/src/vault-client.ts +0 -1694
  323. package/src/version.ts +0 -24
  324. package/src/watch-roots.test.ts +0 -278
  325. package/src/watch-roots.ts +0 -162
  326. package/src/watcher-event-gate.test.ts +0 -212
  327. package/src/watcher.test.ts +0 -1079
  328. package/src/watcher.ts +0 -1741
  329. package/test/e2e/sync/cross-tenant-isolation.test.ts +0 -630
  330. package/test/e2e/sync/skill-telemetry-oversized-transcript.test.ts +0 -124
  331. package/test/e2e/sync/transient-company-leg.test.ts +0 -384
  332. package/test/e2e/sync/windows-unreadable-link-leg.test.ts +0 -191
  333. package/test/e2e/watcher-real-chokidar.test.ts +0 -165
  334. package/test/e2e/watcher-recursive-backend.test.ts +0 -181
  335. package/test/e2e/watcher-scoped-coverage.test.ts +0 -381
  336. package/test/invite-flow.integration.test.ts +0 -244
  337. package/test/joiner-manifest-reconcile.integration.test.ts +0 -322
  338. package/test/share-sync.integration.test.ts +0 -213
  339. package/tsconfig.json +0 -19
  340. package/vitest.config.ts +0 -22
@@ -1,727 +0,0 @@
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
- }