@nifrajs/core 2.0.0 → 2.2.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 (112) hide show
  1. package/README.md +27 -0
  2. package/dist/capabilities.d.ts +54 -2
  3. package/dist/capabilities.d.ts.map +1 -1
  4. package/dist/capabilities.js +240 -5
  5. package/dist/capabilities.js.map +1 -1
  6. package/dist/durable-adapters.d.ts +241 -0
  7. package/dist/durable-adapters.d.ts.map +1 -0
  8. package/dist/durable-adapters.js +697 -0
  9. package/dist/durable-adapters.js.map +1 -0
  10. package/dist/durable-execution.d.ts +349 -0
  11. package/dist/durable-execution.d.ts.map +1 -0
  12. package/dist/durable-execution.js +1173 -0
  13. package/dist/durable-execution.js.map +1 -0
  14. package/dist/effect-lifecycle.d.ts +42 -0
  15. package/dist/effect-lifecycle.d.ts.map +1 -0
  16. package/dist/effect-lifecycle.js +66 -0
  17. package/dist/effect-lifecycle.js.map +1 -0
  18. package/dist/effect-scope.d.ts +75 -0
  19. package/dist/effect-scope.d.ts.map +1 -0
  20. package/dist/effect-scope.js +177 -0
  21. package/dist/effect-scope.js.map +1 -0
  22. package/dist/idempotency-plugin.d.ts +5 -0
  23. package/dist/idempotency-plugin.d.ts.map +1 -1
  24. package/dist/idempotency-plugin.js +8 -0
  25. package/dist/idempotency-plugin.js.map +1 -1
  26. package/dist/index.d.ts +1 -1
  27. package/dist/index.js +1 -1
  28. package/dist/internal/capability-runtime.d.ts +62 -1
  29. package/dist/internal/capability-runtime.d.ts.map +1 -1
  30. package/dist/internal/capability-runtime.js +11 -2
  31. package/dist/internal/capability-runtime.js.map +1 -1
  32. package/dist/internal/effect-execution.d.ts +16 -0
  33. package/dist/internal/effect-execution.d.ts.map +1 -0
  34. package/dist/internal/effect-execution.js +50 -0
  35. package/dist/internal/effect-execution.js.map +1 -0
  36. package/dist/internal/safe-equal.d.ts +20 -0
  37. package/dist/internal/safe-equal.d.ts.map +1 -0
  38. package/dist/internal/safe-equal.js +31 -0
  39. package/dist/internal/safe-equal.js.map +1 -0
  40. package/dist/ledger.d.ts +14 -6
  41. package/dist/ledger.d.ts.map +1 -1
  42. package/dist/ledger.js +31 -5
  43. package/dist/ledger.js.map +1 -1
  44. package/dist/reconciliation-worker.d.ts +108 -0
  45. package/dist/reconciliation-worker.d.ts.map +1 -0
  46. package/dist/reconciliation-worker.js +239 -0
  47. package/dist/reconciliation-worker.js.map +1 -0
  48. package/dist/router/pattern.d.ts +26 -1
  49. package/dist/router/pattern.d.ts.map +1 -1
  50. package/dist/router/pattern.js +164 -8
  51. package/dist/router/pattern.js.map +1 -1
  52. package/dist/router/router.d.ts.map +1 -1
  53. package/dist/router/router.js +49 -1
  54. package/dist/router/router.js.map +1 -1
  55. package/dist/server/idempotency-lane.d.ts +1 -0
  56. package/dist/server/idempotency-lane.d.ts.map +1 -1
  57. package/dist/server/idempotency-lane.js +61 -37
  58. package/dist/server/idempotency-lane.js.map +1 -1
  59. package/dist/server/respond.d.ts.map +1 -1
  60. package/dist/server/respond.js.map +1 -1
  61. package/dist/server/server.d.ts +12 -0
  62. package/dist/server/server.d.ts.map +1 -1
  63. package/dist/server/server.js +33 -2
  64. package/dist/server/server.js.map +1 -1
  65. package/dist/server/transport-lane.d.ts +28 -0
  66. package/dist/server/transport-lane.d.ts.map +1 -0
  67. package/dist/server/transport-lane.js +106 -0
  68. package/dist/server/transport-lane.js.map +1 -0
  69. package/dist/server/websocket.d.ts +6 -0
  70. package/dist/server/websocket.d.ts.map +1 -1
  71. package/dist/server/websocket.js +10 -1
  72. package/dist/server/websocket.js.map +1 -1
  73. package/dist/transport-codec-rich.d.ts +8 -0
  74. package/dist/transport-codec-rich.d.ts.map +1 -0
  75. package/dist/transport-codec-rich.js +14 -0
  76. package/dist/transport-codec-rich.js.map +1 -0
  77. package/dist/transport-codec.d.ts +31 -0
  78. package/dist/transport-codec.d.ts.map +1 -0
  79. package/dist/transport-codec.js +214 -0
  80. package/dist/transport-codec.js.map +1 -0
  81. package/dist/transport-plugin.d.ts +3 -0
  82. package/dist/transport-plugin.d.ts.map +1 -0
  83. package/dist/transport-plugin.js +3 -0
  84. package/dist/transport-plugin.js.map +1 -0
  85. package/dist/wire.d.ts +58 -0
  86. package/dist/wire.d.ts.map +1 -0
  87. package/dist/wire.js +445 -0
  88. package/dist/wire.js.map +1 -0
  89. package/package.json +46 -1
  90. package/src/capabilities.ts +306 -5
  91. package/src/durable-adapters.ts +1039 -0
  92. package/src/durable-execution.ts +1676 -0
  93. package/src/effect-lifecycle.ts +120 -0
  94. package/src/effect-scope.ts +267 -0
  95. package/src/idempotency-plugin.ts +10 -0
  96. package/src/index.ts +1 -1
  97. package/src/internal/capability-runtime.ts +87 -1
  98. package/src/internal/effect-execution.ts +70 -0
  99. package/src/internal/safe-equal.ts +27 -0
  100. package/src/ledger.ts +45 -11
  101. package/src/reconciliation-worker.ts +372 -0
  102. package/src/router/pattern.ts +179 -8
  103. package/src/router/router.ts +75 -1
  104. package/src/server/idempotency-lane.ts +68 -34
  105. package/src/server/respond.ts +1 -0
  106. package/src/server/server.ts +46 -0
  107. package/src/server/transport-lane.ts +141 -0
  108. package/src/server/websocket.ts +15 -1
  109. package/src/transport-codec-rich.ts +20 -0
  110. package/src/transport-codec.ts +284 -0
  111. package/src/transport-plugin.ts +2 -0
  112. package/src/wire.ts +474 -0
@@ -0,0 +1,1676 @@
1
+ /**
2
+ * Durable capability execution primitives. This subpath is opt-in so the bare HTTP runtime stays
3
+ * lean. Approval and journal records are token-only. Saga input, results, and compensation arguments
4
+ * intentionally live only in the caller-supplied durable saga store — never in the effect ledger or
5
+ * telemetry — and production stores should encrypt them according to the application's data policy.
6
+ */
7
+
8
+ import { type EffectLifecycleObserver, emitEffectLifecycle } from "./effect-lifecycle.ts"
9
+ import { createEffectScope } from "./effect-scope.ts"
10
+ import type {
11
+ CapabilityApprovalGate,
12
+ CapabilityExecutionIdentity,
13
+ CapabilityExecutionJournal,
14
+ } from "./internal/capability-runtime.ts"
15
+ import { validCapabilityId } from "./internal/capability-runtime.ts"
16
+ import { safeEqual } from "./internal/safe-equal.ts"
17
+
18
+ export type { CapabilityApprovalGate, CapabilityExecutionIdentity, CapabilityExecutionJournal }
19
+
20
+ const TOKEN = /^[!-~]+$/
21
+ const ERROR_CODE = /^[a-z][a-z0-9_.-]{0,63}$/
22
+ const encoder = new TextEncoder()
23
+ const decoder = new TextDecoder()
24
+
25
+ function assertToken(value: string, label: string, maxLength = 255): void {
26
+ if (
27
+ typeof value !== "string" ||
28
+ value.length === 0 ||
29
+ value.length > maxLength ||
30
+ !TOKEN.test(value)
31
+ ) {
32
+ throw new TypeError(`${label} must be a bounded printable token`)
33
+ }
34
+ }
35
+
36
+ function assertPositiveMs(value: number, label: string): void {
37
+ if (!Number.isSafeInteger(value) || value < 1)
38
+ throw new RangeError(`${label} must be a positive safe integer`)
39
+ }
40
+
41
+ function assertTimestamp(value: number, label: string): void {
42
+ if (!Number.isSafeInteger(value) || value < 0)
43
+ throw new RangeError(`${label} must be a non-negative safe integer timestamp`)
44
+ }
45
+
46
+ function readClock(clock: () => number, label: string): number {
47
+ const value = clock()
48
+ assertTimestamp(value, label)
49
+ return value
50
+ }
51
+
52
+ function addDuration(timestamp: number, duration: number, label: string): number {
53
+ const result = timestamp + duration
54
+ assertTimestamp(result, label)
55
+ return result
56
+ }
57
+
58
+ function bytesToBase64Url(bytes: Uint8Array): string {
59
+ let binary = ""
60
+ for (const byte of bytes) binary += String.fromCharCode(byte)
61
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "")
62
+ }
63
+
64
+ function base64UrlToBytes(value: string): Uint8Array {
65
+ if (!/^[A-Za-z0-9_-]+$/u.test(value)) throw new ApprovalTokenInvalidError()
66
+ const padded = value
67
+ .replaceAll("-", "+")
68
+ .replaceAll("_", "/")
69
+ .padEnd(Math.ceil(value.length / 4) * 4, "=")
70
+ let binary: string
71
+ try {
72
+ binary = atob(padded)
73
+ } catch {
74
+ throw new ApprovalTokenInvalidError()
75
+ }
76
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0))
77
+ }
78
+
79
+ async function sha256(value: string): Promise<string> {
80
+ return bytesToBase64Url(
81
+ new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(value))),
82
+ )
83
+ }
84
+
85
+ function cloneValue<T>(value: T): T {
86
+ return structuredClone(value)
87
+ }
88
+
89
+ // -------------------------------------------------------------------------------------------------
90
+ // Durable effect journal + reconciliation
91
+
92
+ export type DurableEffectState = "admission" | "executing" | "committed" | "failed" | "unknown"
93
+
94
+ export interface ReconciliationScanOptions<State extends string> {
95
+ readonly states: readonly State[]
96
+ readonly updatedBefore?: number
97
+ readonly cursor?: string
98
+ readonly limit: number
99
+ }
100
+
101
+ export interface ReconciliationScanPage<Record> {
102
+ readonly records: readonly Record[]
103
+ readonly cursor?: string
104
+ }
105
+
106
+ export interface ReconciliationPage<Finding> {
107
+ readonly findings: readonly Finding[]
108
+ readonly cursor?: string
109
+ }
110
+
111
+ export interface DurableEffectRecord {
112
+ readonly effectId: string
113
+ readonly capability: string
114
+ readonly target?: string
115
+ readonly digest?: string
116
+ readonly tenantId?: string
117
+ readonly principalId?: string
118
+ readonly state: DurableEffectState
119
+ readonly createdAt: number
120
+ readonly updatedAt: number
121
+ readonly errorCode?: string
122
+ readonly version: number
123
+ }
124
+
125
+ export interface DurableEffectStore {
126
+ readonly durability?: "memory" | "durable"
127
+ create(record: DurableEffectRecord): boolean | Promise<boolean>
128
+ get(effectId: string): DurableEffectRecord | undefined | Promise<DurableEffectRecord | undefined>
129
+ /** Atomic compare-and-set; exactly one caller may advance the supplied `version` and `from` state. */
130
+ transition(input: {
131
+ readonly effectId: string
132
+ readonly version: number
133
+ readonly from: DurableEffectState
134
+ readonly to: DurableEffectState
135
+ readonly updatedAt: number
136
+ readonly errorCode?: string
137
+ }): boolean | Promise<boolean>
138
+ /** Bounded operational scan. Transition-only stores do not need to implement reconciliation. */
139
+ scan?(
140
+ input: ReconciliationScanOptions<DurableEffectState>,
141
+ ):
142
+ | ReconciliationScanPage<DurableEffectRecord>
143
+ | Promise<ReconciliationScanPage<DurableEffectRecord>>
144
+ /** @deprecated Compatibility fallback; production reconciliation should implement `scan`. */
145
+ list?(): readonly DurableEffectRecord[] | Promise<readonly DurableEffectRecord[]>
146
+ }
147
+
148
+ export class DurableEffectTransitionError extends Error {
149
+ constructor(
150
+ public readonly effectId: string,
151
+ public readonly transition: string,
152
+ ) {
153
+ super(`durable effect ${effectId}: ${transition} transition was rejected`)
154
+ this.name = "DurableEffectTransitionError"
155
+ }
156
+ }
157
+
158
+ export interface DurableEffectJournalOptions {
159
+ readonly store: DurableEffectStore
160
+ readonly now?: () => number
161
+ /** Tests/local development only. Production journals require `store.durability === "durable"`. */
162
+ readonly allowMemoryStore?: boolean
163
+ }
164
+
165
+ export function createDurableEffectJournal(
166
+ options: DurableEffectJournalOptions,
167
+ ): CapabilityExecutionJournal {
168
+ if (options.store.durability !== "durable" && options.allowMemoryStore !== true) {
169
+ throw new TypeError('durable effect journal requires store.durability === "durable"')
170
+ }
171
+ const clock = options.now ?? Date.now
172
+ const now = (): number => readClock(clock, "durable effect clock")
173
+
174
+ const current = async (effectId: string): Promise<DurableEffectRecord> => {
175
+ assertToken(effectId, "durable effect id", 64)
176
+ const record = await options.store.get(effectId)
177
+ if (record === undefined) throw new DurableEffectTransitionError(effectId, "missing")
178
+ if (
179
+ record.effectId !== effectId ||
180
+ !validCapabilityId(record.capability) ||
181
+ !["admission", "executing", "committed", "failed", "unknown"].includes(record.state) ||
182
+ !Number.isSafeInteger(record.version) ||
183
+ record.version < 1
184
+ ) {
185
+ throw new TypeError(`durable effect ${effectId}: store returned an invalid record`)
186
+ }
187
+ assertTimestamp(record.createdAt, "durable effect createdAt")
188
+ assertTimestamp(record.updatedAt, "durable effect updatedAt")
189
+ if (record.createdAt > record.updatedAt)
190
+ throw new TypeError(`durable effect ${effectId}: updatedAt precedes createdAt`)
191
+ if (record.target !== undefined) assertToken(record.target, "stored durable effect target", 128)
192
+ if (record.digest !== undefined && !/^[0-9a-f]{64}$/u.test(record.digest))
193
+ throw new TypeError(`durable effect ${effectId}: store returned an invalid digest`)
194
+ if (record.tenantId !== undefined)
195
+ assertToken(record.tenantId, "stored durable effect tenantId")
196
+ if (record.principalId !== undefined)
197
+ assertToken(record.principalId, "stored durable effect principalId")
198
+ if ((record.tenantId === undefined) !== (record.principalId === undefined))
199
+ throw new TypeError(`durable effect ${effectId}: store returned a partial identity`)
200
+ if (record.errorCode !== undefined && !ERROR_CODE.test(record.errorCode))
201
+ throw new TypeError(`durable effect ${effectId}: store returned an invalid error code`)
202
+ return record
203
+ }
204
+ const transition = async (
205
+ effectId: string,
206
+ from: DurableEffectState,
207
+ to: DurableEffectState,
208
+ errorCode?: string,
209
+ ): Promise<void> => {
210
+ const record = await current(effectId)
211
+ if (record.state !== from) throw new DurableEffectTransitionError(effectId, `${from}->${to}`)
212
+ const accepted = await options.store.transition({
213
+ effectId,
214
+ version: record.version,
215
+ from,
216
+ to,
217
+ updatedAt: now(),
218
+ ...(errorCode === undefined ? {} : { errorCode }),
219
+ })
220
+ if (!accepted) throw new DurableEffectTransitionError(effectId, `${from}->${to}`)
221
+ }
222
+
223
+ const journal: CapabilityExecutionJournal = {
224
+ async intent(input) {
225
+ assertToken(input.effectId, "durable effect id", 64)
226
+ if (!validCapabilityId(input.capability))
227
+ throw new TypeError("durable effect capability is invalid")
228
+ if (input.target !== undefined) assertToken(input.target, "durable effect target", 128)
229
+ if (input.digest !== undefined && !/^[0-9a-f]{64}$/u.test(input.digest))
230
+ throw new TypeError("durable effect digest is invalid")
231
+ if (input.identity !== undefined) {
232
+ assertToken(input.identity.tenantId, "durable effect tenantId")
233
+ assertToken(input.identity.principalId, "durable effect principalId")
234
+ }
235
+ const at = now()
236
+ const accepted = await options.store.create(
237
+ Object.freeze({
238
+ effectId: input.effectId,
239
+ capability: input.capability,
240
+ ...(input.target === undefined ? {} : { target: input.target }),
241
+ ...(input.digest === undefined ? {} : { digest: input.digest }),
242
+ ...(input.identity === undefined
243
+ ? {}
244
+ : { tenantId: input.identity.tenantId, principalId: input.identity.principalId }),
245
+ state: "admission" as const,
246
+ createdAt: at,
247
+ updatedAt: at,
248
+ version: 1,
249
+ }),
250
+ )
251
+ if (!accepted) throw new DurableEffectTransitionError(input.effectId, "create")
252
+ },
253
+ async executing(effectId) {
254
+ await transition(effectId, "admission", "executing")
255
+ },
256
+ async committed(effectId) {
257
+ await transition(effectId, "executing", "committed")
258
+ },
259
+ async failed(effectId, input) {
260
+ if (!ERROR_CODE.test(input.errorCode))
261
+ throw new TypeError("durable effect errorCode is invalid")
262
+ const record = await current(effectId)
263
+ const to = input.began ? "unknown" : "failed"
264
+ const accepted = await options.store.transition({
265
+ effectId,
266
+ version: record.version,
267
+ from: record.state,
268
+ to,
269
+ updatedAt: now(),
270
+ errorCode: input.errorCode,
271
+ })
272
+ if (!accepted) throw new DurableEffectTransitionError(effectId, `${record.state}->${to}`)
273
+ },
274
+ }
275
+ return Object.freeze(journal)
276
+ }
277
+
278
+ export class MemoryDurableEffectStore implements DurableEffectStore {
279
+ readonly durability = "memory" as const
280
+ private readonly records = new Map<string, DurableEffectRecord>()
281
+ // Secondary index: effectIds grouped by state, so reconciliation scans only the requested (few,
282
+ // non-terminal) states instead of walking every retained record. See {@link indexedScan}.
283
+ private readonly byState = new Map<DurableEffectState, Set<string>>()
284
+
285
+ create(record: DurableEffectRecord): boolean {
286
+ if (this.records.has(record.effectId)) return false
287
+ this.records.set(record.effectId, Object.freeze(cloneValue(record)))
288
+ bucketAdd(this.byState, record.state, record.effectId)
289
+ return true
290
+ }
291
+
292
+ get(effectId: string): DurableEffectRecord | undefined {
293
+ const record = this.records.get(effectId)
294
+ return record === undefined ? undefined : Object.freeze(cloneValue(record))
295
+ }
296
+
297
+ transition(input: Parameters<DurableEffectStore["transition"]>[0]): boolean {
298
+ const current = this.records.get(input.effectId)
299
+ if (current === undefined || current.version !== input.version || current.state !== input.from)
300
+ return false
301
+ this.records.set(
302
+ input.effectId,
303
+ Object.freeze({
304
+ ...current,
305
+ state: input.to,
306
+ updatedAt: input.updatedAt,
307
+ version: current.version + 1,
308
+ ...(input.errorCode === undefined ? {} : { errorCode: input.errorCode }),
309
+ }),
310
+ )
311
+ bucketMove(this.byState, current.state, input.to, input.effectId)
312
+ return true
313
+ }
314
+
315
+ list(): readonly DurableEffectRecord[] {
316
+ return Object.freeze(
317
+ [...this.records.values()].map((record) => Object.freeze(cloneValue(record))),
318
+ )
319
+ }
320
+
321
+ scan(
322
+ input: ReconciliationScanOptions<DurableEffectState>,
323
+ ): ReconciliationScanPage<DurableEffectRecord> {
324
+ return indexedScan(this.byState, (id) => this.records.get(id), input)
325
+ }
326
+ }
327
+
328
+ export interface EffectReconciliationFinding {
329
+ readonly effectId: string
330
+ readonly capability: string
331
+ readonly state: "incomplete" | "ambiguous"
332
+ readonly updatedAt: number
333
+ }
334
+
335
+ const DEFAULT_RECONCILIATION_LIMIT = 100
336
+ const MAX_RECONCILIATION_LIMIT = 1_000
337
+
338
+ function reconciliationLimit(value = DEFAULT_RECONCILIATION_LIMIT): number {
339
+ if (!Number.isSafeInteger(value) || value < 1 || value > MAX_RECONCILIATION_LIMIT) {
340
+ throw new RangeError(`reconciliation limit must be between 1 and ${MAX_RECONCILIATION_LIMIT}`)
341
+ }
342
+ return value
343
+ }
344
+
345
+ function cursorOffset(cursor?: string): number {
346
+ if (cursor === undefined) return 0
347
+ if (!/^(?:0|[1-9][0-9]*)$/u.test(cursor)) throw new TypeError("invalid reconciliation cursor")
348
+ const offset = Number(cursor)
349
+ if (!Number.isSafeInteger(offset)) throw new TypeError("invalid reconciliation cursor")
350
+ return offset
351
+ }
352
+
353
+ function memoryScan<
354
+ Record extends { readonly state: State; readonly updatedAt: number },
355
+ State extends string,
356
+ >(
357
+ source: Iterable<Record>,
358
+ input: ReconciliationScanOptions<State>,
359
+ ): ReconciliationScanPage<Record> {
360
+ const states = new Set(input.states)
361
+ const offset = cursorOffset(input.cursor)
362
+ const end = offset + input.limit
363
+ const records: Record[] = []
364
+ // Stream the source: skip the first `offset` eligible records, collect up to `limit`, and stop as
365
+ // soon as one more eligible record proves a next page exists. Bounds allocation to the page and
366
+ // avoids materializing the whole store when the page fills early. (An unindexed in-memory store still
367
+ // walks its records to find sparse matches; a production store implements `scan()` as an indexed
368
+ // query - state + updatedAt predicate, keyset cursor - instead of relying on this reference scan.)
369
+ let seen = 0
370
+ let more = false
371
+ for (const record of source) {
372
+ if (!states.has(record.state)) continue
373
+ if (input.updatedBefore !== undefined && record.updatedAt > input.updatedBefore) continue
374
+ if (seen >= end) {
375
+ more = true
376
+ break
377
+ }
378
+ if (seen >= offset) records.push(cloneValue(record))
379
+ seen++
380
+ }
381
+ return Object.freeze({
382
+ records: Object.freeze(records),
383
+ ...(more ? { cursor: String(offset + records.length) } : {}),
384
+ })
385
+ }
386
+
387
+ function bucketAdd<State extends string>(
388
+ byState: Map<State, Set<string>>,
389
+ state: State,
390
+ id: string,
391
+ ): void {
392
+ let bucket = byState.get(state)
393
+ if (bucket === undefined) {
394
+ bucket = new Set()
395
+ byState.set(state, bucket)
396
+ }
397
+ bucket.add(id)
398
+ }
399
+
400
+ function bucketMove<State extends string>(
401
+ byState: Map<State, Set<string>>,
402
+ from: State,
403
+ to: State,
404
+ id: string,
405
+ ): void {
406
+ if (from === to) return
407
+ byState.get(from)?.delete(id)
408
+ bucketAdd(byState, to, id)
409
+ }
410
+
411
+ /**
412
+ * Paginate a state-bucketed in-memory index: walk only the requested states' buckets (each a Set of
413
+ * ids in insertion order), resolve + `updatedBefore`-filter each record, and page by offset cursor.
414
+ * O(sum of the requested buckets) instead of O(total records) - the store still retains terminal
415
+ * records, but reconciliation never walks them. Matches {@link memoryScan}'s paging semantics.
416
+ */
417
+ function indexedScan<Record extends { readonly updatedAt: number }, State extends string>(
418
+ byState: Map<State, Set<string>>,
419
+ resolve: (id: string) => Record | undefined,
420
+ input: ReconciliationScanOptions<State>,
421
+ ): ReconciliationScanPage<Record> {
422
+ const offset = cursorOffset(input.cursor)
423
+ const end = offset + input.limit
424
+ const records: Record[] = []
425
+ let seen = 0
426
+ let more = false
427
+ for (const state of new Set(input.states)) {
428
+ if (more) break
429
+ const bucket = byState.get(state)
430
+ if (bucket === undefined) continue
431
+ for (const id of bucket) {
432
+ const record = resolve(id)
433
+ if (record === undefined) continue
434
+ if (input.updatedBefore !== undefined && record.updatedAt > input.updatedBefore) continue
435
+ if (seen >= end) {
436
+ more = true
437
+ break
438
+ }
439
+ if (seen >= offset) records.push(cloneValue(record))
440
+ seen++
441
+ }
442
+ }
443
+ return Object.freeze({
444
+ records: Object.freeze(records),
445
+ ...(more ? { cursor: String(offset + records.length) } : {}),
446
+ })
447
+ }
448
+
449
+ async function scanEffectRecords(
450
+ store: DurableEffectStore,
451
+ input: ReconciliationScanOptions<DurableEffectState>,
452
+ ): Promise<ReconciliationScanPage<DurableEffectRecord>> {
453
+ if (store.scan !== undefined) return await store.scan(input)
454
+ if (store.list === undefined) throw new TypeError("effect store does not support reconciliation")
455
+ return memoryScan(await store.list(), input)
456
+ }
457
+
458
+ export async function reconcileEffectsPage(
459
+ store: DurableEffectStore,
460
+ options: {
461
+ readonly staleBefore: number
462
+ readonly observer?: EffectLifecycleObserver
463
+ readonly cursor?: string
464
+ readonly limit?: number
465
+ },
466
+ ): Promise<ReconciliationPage<EffectReconciliationFinding>> {
467
+ const findings: EffectReconciliationFinding[] = []
468
+ const page = await scanEffectRecords(store, {
469
+ states: ["admission", "executing", "unknown"],
470
+ updatedBefore: options.staleBefore,
471
+ ...(options.cursor === undefined ? {} : { cursor: options.cursor }),
472
+ limit: reconciliationLimit(options.limit),
473
+ })
474
+ for (const record of page.records) {
475
+ if (!validCapabilityId(record.capability) || !/^[!-~]{1,64}$/u.test(record.effectId)) continue
476
+ if (record.updatedAt > options.staleBefore) continue
477
+ const state =
478
+ record.state === "admission"
479
+ ? "incomplete"
480
+ : record.state === "executing" || record.state === "unknown"
481
+ ? "ambiguous"
482
+ : undefined
483
+ if (state === undefined) continue
484
+ findings.push(
485
+ Object.freeze({
486
+ effectId: record.effectId,
487
+ capability: record.capability,
488
+ state,
489
+ updatedAt: record.updatedAt,
490
+ }),
491
+ )
492
+ if (options.observer !== undefined) {
493
+ emitEffectLifecycle([options.observer], {
494
+ effectId: record.effectId,
495
+ capability: record.capability,
496
+ stage: "reconciliation",
497
+ phase: state === "ambiguous" ? "ambiguous" : "failed",
498
+ errorCode: state === "ambiguous" ? "effect_ambiguous" : "effect_incomplete",
499
+ })
500
+ }
501
+ }
502
+ return Object.freeze({
503
+ findings: Object.freeze(findings),
504
+ ...(page.cursor === undefined ? {} : { cursor: page.cursor }),
505
+ })
506
+ }
507
+
508
+ export async function reconcileEffects(
509
+ store: DurableEffectStore,
510
+ options: { readonly staleBefore: number; readonly observer?: EffectLifecycleObserver },
511
+ ): Promise<readonly EffectReconciliationFinding[]> {
512
+ const page = await reconcileEffectsPage(store, {
513
+ ...options,
514
+ limit: MAX_RECONCILIATION_LIMIT,
515
+ })
516
+ if (page.cursor !== undefined) {
517
+ throw new RangeError(
518
+ `effect reconciliation exceeds ${MAX_RECONCILIATION_LIMIT} records; use reconcileEffectsPage()`,
519
+ )
520
+ }
521
+ return page.findings
522
+ }
523
+
524
+ // -------------------------------------------------------------------------------------------------
525
+ // Durable human approval with signed, single-use resume tokens
526
+
527
+ export type ApprovalState = "pending" | "approved" | "denied" | "consumed" | "expired"
528
+
529
+ export interface ApprovalRecord {
530
+ readonly approvalId: string
531
+ readonly effectId: string
532
+ readonly capability: string
533
+ readonly target?: string
534
+ readonly digest?: string
535
+ readonly tenantId: string
536
+ readonly principalId: string
537
+ readonly tokenHash: string
538
+ readonly state: ApprovalState
539
+ readonly createdAt: number
540
+ readonly expiresAt: number
541
+ readonly updatedAt: number
542
+ readonly decidedBy?: string
543
+ readonly version: number
544
+ }
545
+
546
+ export type ApprovalConsumeResult =
547
+ | { readonly state: "consumed" }
548
+ | {
549
+ readonly state: "missing" | "pending" | "denied" | "expired" | "replay" | "binding" | "token"
550
+ }
551
+
552
+ export interface ApprovalStore {
553
+ readonly durability?: "memory" | "durable"
554
+ create(record: ApprovalRecord): boolean | Promise<boolean>
555
+ get(approvalId: string): ApprovalRecord | undefined | Promise<ApprovalRecord | undefined>
556
+ decide(input: {
557
+ readonly approvalId: string
558
+ readonly tenantId: string
559
+ readonly decision: "approved" | "denied"
560
+ readonly decidedBy: string
561
+ readonly now: number
562
+ }): boolean | Promise<boolean>
563
+ /**
564
+ * Atomically validate binding/token/state and change `approved` to `consumed`. Two concurrent
565
+ * callers with one token must yield exactly one `consumed` and one `replay` result.
566
+ */
567
+ consume(input: {
568
+ readonly approvalId: string
569
+ readonly tenantId: string
570
+ readonly principalId: string
571
+ readonly capability: string
572
+ readonly target?: string
573
+ readonly digest?: string
574
+ readonly tokenHash: string
575
+ readonly now: number
576
+ }): ApprovalConsumeResult | Promise<ApprovalConsumeResult>
577
+ }
578
+
579
+ export class ApprovalRequiredError extends Error {
580
+ readonly approvalId: string
581
+ readonly effectId: string
582
+ readonly resumeToken!: string
583
+ readonly expiresAt: number
584
+
585
+ constructor(approvalId: string, effectId: string, resumeToken: string, expiresAt: number) {
586
+ super("capability approval is required")
587
+ this.approvalId = approvalId
588
+ this.effectId = effectId
589
+ this.expiresAt = expiresAt
590
+ Object.defineProperty(this, "resumeToken", {
591
+ value: resumeToken,
592
+ enumerable: false,
593
+ configurable: false,
594
+ writable: false,
595
+ })
596
+ this.name = "ApprovalRequiredError"
597
+ }
598
+ }
599
+
600
+ export class ApprovalTokenInvalidError extends Error {
601
+ constructor() {
602
+ super("approval resume token is invalid")
603
+ this.name = "ApprovalTokenInvalidError"
604
+ }
605
+ }
606
+ export class ApprovalTokenExpiredError extends Error {
607
+ constructor() {
608
+ super("approval resume token has expired")
609
+ this.name = "ApprovalTokenExpiredError"
610
+ }
611
+ }
612
+ export class ApprovalTokenReplayError extends Error {
613
+ constructor() {
614
+ super("approval resume token has already been consumed")
615
+ this.name = "ApprovalTokenReplayError"
616
+ }
617
+ }
618
+ export class ApprovalBindingError extends Error {
619
+ constructor() {
620
+ super("approval resume token is bound to another tenant or principal")
621
+ this.name = "ApprovalBindingError"
622
+ }
623
+ }
624
+ export class ApprovalPendingError extends Error {
625
+ constructor() {
626
+ super("capability approval is still pending")
627
+ this.name = "ApprovalPendingError"
628
+ }
629
+ }
630
+ export class ApprovalDeniedError extends Error {
631
+ constructor() {
632
+ super("capability approval was denied")
633
+ this.name = "ApprovalDeniedError"
634
+ }
635
+ }
636
+
637
+ interface ResumeClaims {
638
+ readonly v: 1
639
+ readonly id: string
640
+ readonly nonce: string
641
+ readonly exp: number
642
+ }
643
+
644
+ export interface ApprovalCoordinator extends CapabilityApprovalGate {
645
+ decide(input: {
646
+ readonly approvalId: string
647
+ readonly tenantId: string
648
+ readonly decision: "approved" | "denied"
649
+ readonly decidedBy: string
650
+ }): Promise<void>
651
+ get(approvalId: string): Promise<ApprovalRecord | undefined>
652
+ }
653
+
654
+ export interface ApprovalCoordinatorOptions {
655
+ readonly store: ApprovalStore
656
+ /** At least 32 random bytes, kept separately from the approval store. */
657
+ readonly secret: Uint8Array
658
+ readonly ttlMs?: number
659
+ readonly now?: () => number
660
+ /** Tests/local development only. Production approval records require a durable store. */
661
+ readonly allowMemoryStore?: boolean
662
+ }
663
+
664
+ export function createApprovalCoordinator(
665
+ options: ApprovalCoordinatorOptions,
666
+ ): ApprovalCoordinator {
667
+ if (options.store.durability !== "durable" && options.allowMemoryStore !== true) {
668
+ throw new TypeError('approval coordinator requires store.durability === "durable"')
669
+ }
670
+ if (!(options.secret instanceof Uint8Array) || options.secret.byteLength < 32) {
671
+ throw new TypeError("approval secret must contain at least 32 random bytes")
672
+ }
673
+ const secret = new Uint8Array(options.secret)
674
+ const ttlMs = options.ttlMs ?? 15 * 60_000
675
+ assertPositiveMs(ttlMs, "approval ttlMs")
676
+ const clock = options.now ?? Date.now
677
+ const now = (): number => readClock(clock, "approval clock")
678
+ const key = crypto.subtle.importKey("raw", secret, { name: "HMAC", hash: "SHA-256" }, false, [
679
+ "sign",
680
+ "verify",
681
+ ])
682
+
683
+ const sign = async (claims: ResumeClaims): Promise<string> => {
684
+ const payload = bytesToBase64Url(encoder.encode(JSON.stringify(claims)))
685
+ const signature = new Uint8Array(
686
+ await crypto.subtle.sign("HMAC", await key, encoder.encode(payload)),
687
+ )
688
+ return `v1.${payload}.${bytesToBase64Url(signature)}`
689
+ }
690
+ const verify = async (token: string): Promise<ResumeClaims> => {
691
+ if (typeof token !== "string" || token.length > 2048) throw new ApprovalTokenInvalidError()
692
+ const parts = token.split(".")
693
+ if (parts.length !== 3 || parts[0] !== "v1") throw new ApprovalTokenInvalidError()
694
+ const payload = parts[1] as string
695
+ const valid = await crypto.subtle.verify(
696
+ "HMAC",
697
+ await key,
698
+ base64UrlToBytes(parts[2] as string).buffer as ArrayBuffer,
699
+ encoder.encode(payload),
700
+ )
701
+ if (!valid) throw new ApprovalTokenInvalidError()
702
+ let claims: unknown
703
+ try {
704
+ claims = JSON.parse(decoder.decode(base64UrlToBytes(payload)))
705
+ } catch {
706
+ throw new ApprovalTokenInvalidError()
707
+ }
708
+ if (typeof claims !== "object" || claims === null) throw new ApprovalTokenInvalidError()
709
+ const candidate = claims as Partial<ResumeClaims>
710
+ if (
711
+ candidate.v !== 1 ||
712
+ typeof candidate.id !== "string" ||
713
+ typeof candidate.nonce !== "string" ||
714
+ !Number.isSafeInteger(candidate.exp)
715
+ ) {
716
+ throw new ApprovalTokenInvalidError()
717
+ }
718
+ assertToken(candidate.id, "approval id", 128)
719
+ assertToken(candidate.nonce, "approval nonce", 128)
720
+ if ((candidate.exp as number) <= now()) throw new ApprovalTokenExpiredError()
721
+ return candidate as ResumeClaims
722
+ }
723
+
724
+ const coordinator: ApprovalCoordinator = {
725
+ async authorize(input: Parameters<CapabilityApprovalGate["authorize"]>[0]) {
726
+ if (input.signal.aborted) throw input.signal.reason
727
+ assertToken(input.identity.tenantId, "approval tenantId")
728
+ assertToken(input.identity.principalId, "approval principalId")
729
+ if (input.resumeToken === undefined) {
730
+ const approvalId = crypto.randomUUID()
731
+ const nonce = bytesToBase64Url(crypto.getRandomValues(new Uint8Array(18)))
732
+ const issuedAt = now()
733
+ const expiresAt = addDuration(issuedAt, ttlMs, "approval expiry")
734
+ const resumeToken = await sign({ v: 1, id: approvalId, nonce, exp: expiresAt })
735
+ const accepted = await options.store.create(
736
+ Object.freeze({
737
+ approvalId,
738
+ effectId: input.effectId,
739
+ capability: input.capability,
740
+ ...(input.target === undefined ? {} : { target: input.target }),
741
+ ...(input.digest === undefined ? {} : { digest: input.digest }),
742
+ tenantId: input.identity.tenantId,
743
+ principalId: input.identity.principalId,
744
+ tokenHash: await sha256(resumeToken),
745
+ state: "pending" as const,
746
+ createdAt: issuedAt,
747
+ expiresAt,
748
+ updatedAt: issuedAt,
749
+ version: 1,
750
+ }),
751
+ )
752
+ if (!accepted) throw new Error("approval store rejected a unique approval id")
753
+ throw new ApprovalRequiredError(approvalId, input.effectId, resumeToken, expiresAt)
754
+ }
755
+ const claims = await verify(input.resumeToken)
756
+ const consumed = await options.store.consume({
757
+ approvalId: claims.id,
758
+ tenantId: input.identity.tenantId,
759
+ principalId: input.identity.principalId,
760
+ capability: input.capability,
761
+ ...(input.target === undefined ? {} : { target: input.target }),
762
+ ...(input.digest === undefined ? {} : { digest: input.digest }),
763
+ tokenHash: await sha256(input.resumeToken),
764
+ now: now(),
765
+ })
766
+ if (consumed.state === "consumed") return
767
+ if (consumed.state === "replay") throw new ApprovalTokenReplayError()
768
+ if (consumed.state === "binding") throw new ApprovalBindingError()
769
+ if (consumed.state === "expired") throw new ApprovalTokenExpiredError()
770
+ if (consumed.state === "pending") throw new ApprovalPendingError()
771
+ if (consumed.state === "denied") throw new ApprovalDeniedError()
772
+ throw new ApprovalTokenInvalidError()
773
+ },
774
+ async decide(input: Parameters<ApprovalCoordinator["decide"]>[0]) {
775
+ assertToken(input.approvalId, "approval id", 128)
776
+ assertToken(input.tenantId, "approval tenantId")
777
+ assertToken(input.decidedBy, "approval decidedBy")
778
+ const accepted = await options.store.decide({ ...input, now: now() })
779
+ if (!accepted) throw new Error("approval decision rejected")
780
+ },
781
+ async get(approvalId: string) {
782
+ assertToken(approvalId, "approval id", 128)
783
+ return await options.store.get(approvalId)
784
+ },
785
+ }
786
+ return Object.freeze(coordinator)
787
+ }
788
+
789
+ export class MemoryApprovalStore implements ApprovalStore {
790
+ readonly durability = "memory" as const
791
+ private readonly records = new Map<string, ApprovalRecord>()
792
+
793
+ create(record: ApprovalRecord): boolean {
794
+ if (this.records.has(record.approvalId)) return false
795
+ this.records.set(record.approvalId, Object.freeze(cloneValue(record)))
796
+ return true
797
+ }
798
+ get(approvalId: string): ApprovalRecord | undefined {
799
+ const record = this.records.get(approvalId)
800
+ return record === undefined ? undefined : Object.freeze(cloneValue(record))
801
+ }
802
+ decide(input: Parameters<ApprovalStore["decide"]>[0]): boolean {
803
+ const record = this.records.get(input.approvalId)
804
+ if (
805
+ record === undefined ||
806
+ record.tenantId !== input.tenantId ||
807
+ record.state !== "pending" ||
808
+ record.expiresAt <= input.now
809
+ )
810
+ return false
811
+ this.records.set(
812
+ input.approvalId,
813
+ Object.freeze({
814
+ ...record,
815
+ state: input.decision,
816
+ decidedBy: input.decidedBy,
817
+ updatedAt: input.now,
818
+ version: record.version + 1,
819
+ }),
820
+ )
821
+ return true
822
+ }
823
+ consume(input: Parameters<ApprovalStore["consume"]>[0]): ApprovalConsumeResult {
824
+ const record = this.records.get(input.approvalId)
825
+ if (record === undefined) return { state: "missing" }
826
+ if (
827
+ record.tenantId !== input.tenantId ||
828
+ record.principalId !== input.principalId ||
829
+ record.capability !== input.capability ||
830
+ record.target !== input.target ||
831
+ !safeEqual(record.digest, input.digest)
832
+ )
833
+ return { state: "binding" }
834
+ if (!safeEqual(record.tokenHash, input.tokenHash)) return { state: "token" }
835
+ if (record.state === "consumed") return { state: "replay" }
836
+ if (record.expiresAt <= input.now || record.state === "expired") {
837
+ if (record.state !== "expired")
838
+ this.records.set(
839
+ input.approvalId,
840
+ Object.freeze({
841
+ ...record,
842
+ state: "expired",
843
+ updatedAt: input.now,
844
+ version: record.version + 1,
845
+ }),
846
+ )
847
+ return { state: "expired" }
848
+ }
849
+ if (record.state === "pending") return { state: "pending" }
850
+ if (record.state === "denied") return { state: "denied" }
851
+ if (record.state !== "approved") return { state: "token" }
852
+ this.records.set(
853
+ input.approvalId,
854
+ Object.freeze({
855
+ ...record,
856
+ state: "consumed",
857
+ updatedAt: input.now,
858
+ version: record.version + 1,
859
+ }),
860
+ )
861
+ return { state: "consumed" }
862
+ }
863
+ list(): readonly ApprovalRecord[] {
864
+ return Object.freeze(
865
+ [...this.records.values()].map((record) => Object.freeze(cloneValue(record))),
866
+ )
867
+ }
868
+ }
869
+
870
+ // -------------------------------------------------------------------------------------------------
871
+ // Durable saga + compensation state machine
872
+
873
+ export type SagaState = "running" | "compensating" | "completed" | "compensated" | "manual-review"
874
+ export type SagaStepState =
875
+ | "executing"
876
+ | "committed"
877
+ | "failed"
878
+ | "ambiguous"
879
+ | "compensating"
880
+ | "compensation-failed"
881
+ | "compensated"
882
+
883
+ export interface SagaStepRecord {
884
+ readonly name: string
885
+ readonly effectId: string
886
+ readonly compensationEffectId: string
887
+ readonly state: SagaStepState
888
+ readonly compensationArgs: unknown
889
+ readonly result?: unknown
890
+ readonly attempts: number
891
+ readonly nextAttemptAt?: number
892
+ readonly errorCode?: string
893
+ }
894
+
895
+ export interface SagaRecord {
896
+ readonly sagaId: string
897
+ readonly definition: string
898
+ readonly state: SagaState
899
+ readonly input: unknown
900
+ readonly steps: readonly SagaStepRecord[]
901
+ readonly createdAt: number
902
+ readonly updatedAt: number
903
+ readonly version: number
904
+ }
905
+
906
+ export interface SagaStore {
907
+ readonly durability?: "memory" | "durable"
908
+ create(record: SagaRecord): boolean | Promise<boolean>
909
+ get(sagaId: string): SagaRecord | undefined | Promise<SagaRecord | undefined>
910
+ /** Atomic version compare-and-set; this is the saga engine's crash/concurrency boundary. */
911
+ compareAndSet(input: {
912
+ readonly sagaId: string
913
+ readonly version: number
914
+ readonly record: SagaRecord
915
+ }): boolean | Promise<boolean>
916
+ /** Bounded operational scan. Transition-only stores do not need to implement reconciliation. */
917
+ scan?(
918
+ input: ReconciliationScanOptions<SagaState>,
919
+ ): ReconciliationScanPage<SagaRecord> | Promise<ReconciliationScanPage<SagaRecord>>
920
+ /** @deprecated Compatibility fallback; production reconciliation should implement `scan`. */
921
+ list?(): readonly SagaRecord[] | Promise<readonly SagaRecord[]>
922
+ }
923
+
924
+ export interface SagaStepExecutionContext {
925
+ readonly effectId: string
926
+ readonly signal: AbortSignal
927
+ }
928
+ export interface SagaCompensationContext {
929
+ readonly effectId: string
930
+ readonly sagaId: string
931
+ readonly attempt: number
932
+ readonly signal: AbortSignal
933
+ }
934
+
935
+ export interface SagaRunContext<C extends Record<string, unknown>> {
936
+ step<K extends keyof C & string, T>(
937
+ name: K,
938
+ compensationArgs: C[K],
939
+ execute: (context: SagaStepExecutionContext) => T | PromiseLike<T>,
940
+ ): Promise<T>
941
+ }
942
+
943
+ export interface SagaDefinition<I, C extends Record<string, unknown>> {
944
+ readonly name: string
945
+ readonly capability?: string
946
+ readonly run: (context: SagaRunContext<C>, input: I) => void | PromiseLike<void>
947
+ readonly compensators: {
948
+ readonly [K in keyof C]: (
949
+ args: C[K],
950
+ context: SagaCompensationContext,
951
+ ) => void | PromiseLike<void>
952
+ }
953
+ readonly retry?: {
954
+ readonly maxAttempts?: number
955
+ readonly backoffMs?: (attempt: number) => number
956
+ }
957
+ }
958
+
959
+ function assertSagaDefinition<I, C extends Record<string, unknown>>(
960
+ definition: SagaDefinition<I, C>,
961
+ ): void {
962
+ if (typeof definition !== "object" || definition === null)
963
+ throw new TypeError("saga definition must be an object")
964
+ assertToken(definition.name, "saga definition", 128)
965
+ if (definition.capability !== undefined && !validCapabilityId(definition.capability))
966
+ throw new TypeError("saga capability is invalid")
967
+ if (typeof definition.run !== "function") throw new TypeError("saga run must be a function")
968
+ if (
969
+ typeof definition.compensators !== "object" ||
970
+ definition.compensators === null ||
971
+ Array.isArray(definition.compensators)
972
+ ) {
973
+ throw new TypeError("saga compensators must be an object")
974
+ }
975
+ for (const [name, compensator] of Object.entries(definition.compensators)) {
976
+ assertToken(name, "saga compensator name", 128)
977
+ if (typeof compensator !== "function")
978
+ throw new TypeError(`saga compensator ${name} must be a function`)
979
+ }
980
+ if (definition.retry !== undefined) {
981
+ if (typeof definition.retry !== "object" || definition.retry === null)
982
+ throw new TypeError("saga retry must be an object")
983
+ if (definition.retry.maxAttempts !== undefined)
984
+ assertPositiveMs(definition.retry.maxAttempts, "saga maxAttempts")
985
+ if (
986
+ definition.retry.backoffMs !== undefined &&
987
+ typeof definition.retry.backoffMs !== "function"
988
+ )
989
+ throw new TypeError("saga backoffMs must be a function")
990
+ }
991
+ }
992
+
993
+ export function defineSaga<I, C extends Record<string, unknown>>(
994
+ definition: SagaDefinition<I, C>,
995
+ ): SagaDefinition<I, C> {
996
+ assertSagaDefinition(definition)
997
+ return Object.freeze({
998
+ ...definition,
999
+ compensators: Object.freeze({ ...definition.compensators }),
1000
+ ...(definition.retry === undefined ? {} : { retry: Object.freeze({ ...definition.retry }) }),
1001
+ })
1002
+ }
1003
+
1004
+ export class SagaConcurrencyError extends Error {
1005
+ constructor(public readonly sagaId: string) {
1006
+ super(`saga ${sagaId}: concurrent transition rejected`)
1007
+ this.name = "SagaConcurrencyError"
1008
+ }
1009
+ }
1010
+ export class SagaAmbiguousStepError extends Error {
1011
+ constructor(
1012
+ public readonly sagaId: string,
1013
+ public readonly step: string,
1014
+ public readonly effectId: string,
1015
+ ) {
1016
+ super(`saga ${sagaId}: step ${step} has an ambiguous effect`)
1017
+ this.name = "SagaAmbiguousStepError"
1018
+ }
1019
+ }
1020
+
1021
+ export class SagaResolutionError extends Error {
1022
+ constructor(
1023
+ public readonly sagaId: string,
1024
+ public readonly step: string,
1025
+ message: string,
1026
+ ) {
1027
+ super(`saga ${sagaId}: step ${step} ${message}`)
1028
+ this.name = "SagaResolutionError"
1029
+ }
1030
+ }
1031
+ /** Throw this only when a provider conclusively proves that no effect committed. */
1032
+ export class SagaStepNotCommittedError extends Error {
1033
+ constructor(public readonly code = "not_committed") {
1034
+ super("saga step conclusively did not commit")
1035
+ this.name = "SagaStepNotCommittedError"
1036
+ if (!ERROR_CODE.test(code)) throw new TypeError("saga step error code is invalid")
1037
+ }
1038
+ }
1039
+
1040
+ export interface SagaEngineOptions {
1041
+ readonly store: SagaStore
1042
+ readonly now?: () => number
1043
+ readonly observer?: EffectLifecycleObserver
1044
+ /** Tests/local development only. Production sagas require a durable store. */
1045
+ readonly allowMemoryStore?: boolean
1046
+ }
1047
+
1048
+ export type SagaAmbiguityResolution =
1049
+ | {
1050
+ readonly kind: "execution"
1051
+ readonly step: string
1052
+ readonly effectId: string
1053
+ readonly outcome: "committed"
1054
+ /** Provider-confirmed result required by later saga steps. */
1055
+ readonly result: unknown
1056
+ }
1057
+ | {
1058
+ readonly kind: "execution"
1059
+ readonly step: string
1060
+ readonly effectId: string
1061
+ readonly outcome: "not-committed"
1062
+ readonly errorCode?: string
1063
+ }
1064
+ | {
1065
+ readonly kind: "compensation"
1066
+ readonly step: string
1067
+ readonly effectId: string
1068
+ readonly outcome: "compensated" | "not-compensated"
1069
+ }
1070
+
1071
+ export interface SagaEngine {
1072
+ execute<I, C extends Record<string, unknown>>(
1073
+ definition: SagaDefinition<I, C>,
1074
+ sagaId: string,
1075
+ input: I,
1076
+ options?: { readonly signal?: AbortSignal },
1077
+ ): Promise<SagaRecord>
1078
+ resume<I, C extends Record<string, unknown>>(
1079
+ definition: SagaDefinition<I, C>,
1080
+ sagaId: string,
1081
+ options?: { readonly signal?: AbortSignal },
1082
+ ): Promise<SagaRecord>
1083
+ compensate<I, C extends Record<string, unknown>>(
1084
+ definition: SagaDefinition<I, C>,
1085
+ sagaId: string,
1086
+ options?: { readonly signal?: AbortSignal },
1087
+ ): Promise<SagaRecord>
1088
+ /**
1089
+ * Apply a provider/operator-confirmed outcome to an ambiguous durable transition. The supplied
1090
+ * effect id must match the stored execution/compensation id, preventing a stale review from
1091
+ * resolving a later operation. The caller remains responsible for authenticating and authorizing
1092
+ * the operator. Call `resume` or `compensate` after the resolution.
1093
+ */
1094
+ resolveAmbiguity<I, C extends Record<string, unknown>>(
1095
+ definition: SagaDefinition<I, C>,
1096
+ sagaId: string,
1097
+ resolution: SagaAmbiguityResolution,
1098
+ ): Promise<SagaRecord>
1099
+ }
1100
+
1101
+ let neverAbortSignal: AbortSignal | undefined
1102
+ function signalOrNever(signal?: AbortSignal): AbortSignal {
1103
+ neverAbortSignal ??= new AbortController().signal
1104
+ return signal ?? neverAbortSignal
1105
+ }
1106
+
1107
+ function throwIfAborted(signal: AbortSignal): void {
1108
+ if (signal.aborted) {
1109
+ throw signal.reason instanceof Error ? signal.reason : new Error("saga execution aborted")
1110
+ }
1111
+ }
1112
+
1113
+ export function createSagaEngine(options: SagaEngineOptions): SagaEngine {
1114
+ if (options.store.durability !== "durable" && options.allowMemoryStore !== true)
1115
+ throw new TypeError('saga engine requires store.durability === "durable"')
1116
+ const clock = options.now ?? Date.now
1117
+ const now = (): number => readClock(clock, "saga clock")
1118
+ const observer = options.observer
1119
+
1120
+ const load = async (sagaId: string): Promise<SagaRecord> => {
1121
+ const record = await options.store.get(sagaId)
1122
+ if (record === undefined) throw new Error(`saga ${sagaId}: not found`)
1123
+ if (
1124
+ record.sagaId !== sagaId ||
1125
+ !["running", "compensating", "completed", "compensated", "manual-review"].includes(
1126
+ record.state,
1127
+ ) ||
1128
+ !Array.isArray(record.steps) ||
1129
+ !Number.isSafeInteger(record.version) ||
1130
+ record.version < 1
1131
+ ) {
1132
+ throw new TypeError(`saga ${sagaId}: store returned an invalid record`)
1133
+ }
1134
+ assertToken(record.definition, "stored saga definition", 128)
1135
+ assertTimestamp(record.createdAt, "stored saga createdAt")
1136
+ assertTimestamp(record.updatedAt, "stored saga updatedAt")
1137
+ if (record.createdAt > record.updatedAt)
1138
+ throw new TypeError(`saga ${sagaId}: updatedAt precedes createdAt`)
1139
+ const names = new Set<string>()
1140
+ const effectIds = new Set<string>()
1141
+ for (const step of record.steps) {
1142
+ assertToken(step.name, "stored saga step", 128)
1143
+ assertToken(step.effectId, "stored saga effect id", 64)
1144
+ assertToken(step.compensationEffectId, "stored saga compensation effect id", 64)
1145
+ if (
1146
+ ![
1147
+ "executing",
1148
+ "committed",
1149
+ "failed",
1150
+ "ambiguous",
1151
+ "compensating",
1152
+ "compensation-failed",
1153
+ "compensated",
1154
+ ].includes(step.state) ||
1155
+ !Number.isSafeInteger(step.attempts) ||
1156
+ step.attempts < 0 ||
1157
+ names.has(step.name) ||
1158
+ effectIds.has(step.effectId) ||
1159
+ effectIds.has(step.compensationEffectId)
1160
+ ) {
1161
+ throw new TypeError(`saga ${sagaId}: store returned an invalid step record`)
1162
+ }
1163
+ names.add(step.name)
1164
+ effectIds.add(step.effectId)
1165
+ effectIds.add(step.compensationEffectId)
1166
+ if (step.nextAttemptAt !== undefined)
1167
+ assertTimestamp(step.nextAttemptAt, "stored saga nextAttemptAt")
1168
+ if (step.errorCode !== undefined && !ERROR_CODE.test(step.errorCode))
1169
+ throw new TypeError(`saga ${sagaId}: store returned an invalid error code`)
1170
+ }
1171
+ return record
1172
+ }
1173
+ const save = async (
1174
+ current: SagaRecord,
1175
+ update: Omit<SagaRecord, "version">,
1176
+ ): Promise<SagaRecord> => {
1177
+ const next = Object.freeze({ ...update, version: current.version + 1 })
1178
+ if (
1179
+ !(await options.store.compareAndSet({
1180
+ sagaId: current.sagaId,
1181
+ version: current.version,
1182
+ record: next,
1183
+ }))
1184
+ )
1185
+ throw new SagaConcurrencyError(current.sagaId)
1186
+ return next
1187
+ }
1188
+ const withStep = (
1189
+ record: SagaRecord,
1190
+ index: number,
1191
+ step: SagaStepRecord,
1192
+ state = record.state,
1193
+ ): Omit<SagaRecord, "version"> => ({
1194
+ ...record,
1195
+ state,
1196
+ steps: Object.freeze(
1197
+ record.steps.map((candidate, candidateIndex) =>
1198
+ candidateIndex === index ? Object.freeze(step) : candidate,
1199
+ ),
1200
+ ),
1201
+ updatedAt: now(),
1202
+ })
1203
+ const effectScope = createEffectScope({
1204
+ ...(observer === undefined ? {} : { observers: [observer] }),
1205
+ })
1206
+
1207
+ const compensate = async <I, C extends Record<string, unknown>>(
1208
+ definition: SagaDefinition<I, C>,
1209
+ sagaId: string,
1210
+ runOptions: { readonly signal?: AbortSignal } = {},
1211
+ ): Promise<SagaRecord> => {
1212
+ assertSagaDefinition(definition)
1213
+ assertToken(sagaId, "saga id", 128)
1214
+ const signal = signalOrNever(runOptions.signal)
1215
+ throwIfAborted(signal)
1216
+ let record = await load(sagaId)
1217
+ if (record.definition !== definition.name) throw new TypeError("saga definition mismatch")
1218
+ if (record.state === "completed" || record.state === "compensated") return record
1219
+ if (
1220
+ record.steps.some(
1221
+ (step) =>
1222
+ step.state === "ambiguous" || step.state === "executing" || step.state === "compensating",
1223
+ )
1224
+ ) {
1225
+ if (record.state !== "manual-review")
1226
+ record = await save(record, { ...record, state: "manual-review", updatedAt: now() })
1227
+ const ambiguous = record.steps.find(
1228
+ (step) =>
1229
+ step.state === "ambiguous" || step.state === "executing" || step.state === "compensating",
1230
+ ) as SagaStepRecord
1231
+ throw new SagaAmbiguousStepError(
1232
+ sagaId,
1233
+ ambiguous.name,
1234
+ ambiguous.state === "compensating" ? ambiguous.compensationEffectId : ambiguous.effectId,
1235
+ )
1236
+ }
1237
+ if (record.state !== "compensating")
1238
+ record = await save(record, { ...record, state: "compensating", updatedAt: now() })
1239
+ const maxAttempts = definition.retry?.maxAttempts ?? 3
1240
+ assertPositiveMs(maxAttempts, "saga maxAttempts")
1241
+ const backoff =
1242
+ definition.retry?.backoffMs ??
1243
+ ((attempt: number) => Math.min(60_000, 100 * 2 ** (attempt - 1)))
1244
+
1245
+ for (let index = record.steps.length - 1; index >= 0; index--) {
1246
+ throwIfAborted(signal)
1247
+ let step = record.steps[index] as SagaStepRecord
1248
+ if (step.state === "compensated" || step.state === "failed") continue
1249
+ if (step.state !== "committed" && step.state !== "compensation-failed") continue
1250
+ if (step.nextAttemptAt !== undefined && step.nextAttemptAt > now()) return record
1251
+ const compensator = definition.compensators[step.name as keyof C]
1252
+ if (typeof compensator !== "function") {
1253
+ record = await save(record, { ...record, state: "manual-review", updatedAt: now() })
1254
+ return record
1255
+ }
1256
+ if (step.attempts >= maxAttempts) {
1257
+ if (record.state !== "manual-review")
1258
+ record = await save(record, { ...record, state: "manual-review", updatedAt: now() })
1259
+ return record
1260
+ }
1261
+ const attempt = step.attempts + 1
1262
+ const { errorCode: _errorCode, nextAttemptAt: _nextAttemptAt, ...stepBase } = step
1263
+ step = { ...stepBase, state: "compensating", attempts: attempt }
1264
+ let transitionError: unknown
1265
+ try {
1266
+ await effectScope.run(
1267
+ {
1268
+ effectId: step.compensationEffectId,
1269
+ capability: definition.capability ?? "saga.compensate",
1270
+ stage: "compensation",
1271
+ signal,
1272
+ attempt,
1273
+ failurePhase: () => "failed",
1274
+ errorCode: () => "compensation_failed",
1275
+ transitions: {
1276
+ async executing() {
1277
+ record = await save(record, withStep(record, index, step))
1278
+ },
1279
+ async committed() {
1280
+ step = { ...step, state: "compensated" }
1281
+ record = await save(record, withStep(record, index, step))
1282
+ },
1283
+ async failed() {
1284
+ const exhausted = attempt >= maxAttempts
1285
+ try {
1286
+ const delay = exhausted ? undefined : backoff(attempt)
1287
+ if (delay !== undefined && (!Number.isSafeInteger(delay) || delay < 0))
1288
+ throw new RangeError("saga backoff must return a non-negative safe integer")
1289
+ const failed: SagaStepRecord = {
1290
+ ...step,
1291
+ state: "compensation-failed",
1292
+ errorCode: "compensation_failed",
1293
+ ...(delay === undefined
1294
+ ? {}
1295
+ : { nextAttemptAt: addDuration(now(), delay, "saga next retry") }),
1296
+ }
1297
+ record = await save(
1298
+ record,
1299
+ withStep(record, index, failed, exhausted ? "manual-review" : "compensating"),
1300
+ )
1301
+ } catch (error) {
1302
+ transitionError = error
1303
+ const failed: SagaStepRecord = {
1304
+ ...step,
1305
+ state: "compensation-failed",
1306
+ errorCode: "invalid_retry_policy",
1307
+ }
1308
+ record = await save(record, withStep(record, index, failed, "manual-review"))
1309
+ }
1310
+ },
1311
+ },
1312
+ },
1313
+ async (owned) => {
1314
+ await compensator(cloneValue(step.compensationArgs) as C[keyof C], {
1315
+ effectId: owned.effectId,
1316
+ sagaId,
1317
+ attempt,
1318
+ signal: owned.signal,
1319
+ })
1320
+ },
1321
+ )
1322
+ } catch {
1323
+ if (transitionError !== undefined) throw transitionError
1324
+ return record
1325
+ }
1326
+ }
1327
+ return await save(record, { ...record, state: "compensated", updatedAt: now() })
1328
+ }
1329
+
1330
+ const resume = async <I, C extends Record<string, unknown>>(
1331
+ definition: SagaDefinition<I, C>,
1332
+ sagaId: string,
1333
+ runOptions: { readonly signal?: AbortSignal } = {},
1334
+ ): Promise<SagaRecord> => {
1335
+ assertSagaDefinition(definition)
1336
+ assertToken(sagaId, "saga id", 128)
1337
+ const signal = signalOrNever(runOptions.signal)
1338
+ throwIfAborted(signal)
1339
+ let record = await load(sagaId)
1340
+ if (record.definition !== definition.name) throw new TypeError("saga definition mismatch")
1341
+ if (record.state !== "running") return record
1342
+ const context: SagaRunContext<C> = {
1343
+ async step(name, compensationArgs, execute) {
1344
+ throwIfAborted(signal)
1345
+ assertToken(name, "saga step", 128)
1346
+ if (typeof execute !== "function")
1347
+ throw new TypeError("saga step execute must be a function")
1348
+ if (typeof definition.compensators[name] !== "function")
1349
+ throw new TypeError(`saga step ${name} has no compensator`)
1350
+ record = await load(sagaId)
1351
+ const existingIndex = record.steps.findIndex((step) => step.name === name)
1352
+ if (existingIndex >= 0) {
1353
+ const existing = record.steps[existingIndex] as SagaStepRecord
1354
+ if (existing.state === "committed")
1355
+ return cloneValue(existing.result) as Awaited<ReturnType<typeof execute>>
1356
+ if (existing.state === "executing" || existing.state === "ambiguous") {
1357
+ if (record.state !== "manual-review")
1358
+ record = await save(record, { ...record, state: "manual-review", updatedAt: now() })
1359
+ throw new SagaAmbiguousStepError(sagaId, name, existing.effectId)
1360
+ }
1361
+ throw new Error(`saga ${sagaId}: step ${name} cannot resume from ${existing.state}`)
1362
+ }
1363
+ const effectId = crypto.randomUUID()
1364
+ const step: SagaStepRecord = Object.freeze({
1365
+ name,
1366
+ effectId,
1367
+ compensationEffectId: crypto.randomUUID(),
1368
+ state: "executing" as const,
1369
+ compensationArgs: cloneValue(compensationArgs),
1370
+ attempts: 0,
1371
+ })
1372
+ return await effectScope.run(
1373
+ {
1374
+ effectId,
1375
+ capability: definition.capability ?? "saga.execute",
1376
+ stage: "execution",
1377
+ signal,
1378
+ failurePhase: (error) =>
1379
+ error instanceof SagaStepNotCommittedError ? "failed" : "ambiguous",
1380
+ errorCode: (error, began) =>
1381
+ error instanceof SagaStepNotCommittedError
1382
+ ? error.code
1383
+ : began
1384
+ ? "execution_unknown"
1385
+ : "aborted_before_execution",
1386
+ transitions: {
1387
+ async intent() {
1388
+ record = await save(record, {
1389
+ ...record,
1390
+ steps: Object.freeze([...record.steps, step]),
1391
+ updatedAt: now(),
1392
+ })
1393
+ },
1394
+ async committed(_owned, result) {
1395
+ record = await load(sagaId)
1396
+ const index = record.steps.findIndex((candidate) => candidate.effectId === effectId)
1397
+ const committed = {
1398
+ ...(record.steps[index] as SagaStepRecord),
1399
+ state: "committed" as const,
1400
+ result: cloneValue(result),
1401
+ }
1402
+ record = await save(record, withStep(record, index, committed))
1403
+ },
1404
+ async failed(_owned, failure) {
1405
+ record = await load(sagaId)
1406
+ const index = record.steps.findIndex((candidate) => candidate.effectId === effectId)
1407
+ const known = failure.error instanceof SagaStepNotCommittedError || !failure.began
1408
+ const failed = {
1409
+ ...(record.steps[index] as SagaStepRecord),
1410
+ state: known ? ("failed" as const) : ("ambiguous" as const),
1411
+ errorCode:
1412
+ failure.error instanceof SagaStepNotCommittedError
1413
+ ? failure.error.code
1414
+ : failure.began
1415
+ ? "execution_unknown"
1416
+ : "aborted_before_execution",
1417
+ }
1418
+ record = await save(
1419
+ record,
1420
+ withStep(record, index, failed, known ? "compensating" : "manual-review"),
1421
+ )
1422
+ },
1423
+ },
1424
+ },
1425
+ (owned) => execute({ effectId: owned.effectId, signal: owned.signal }),
1426
+ )
1427
+ },
1428
+ }
1429
+ try {
1430
+ throwIfAborted(signal)
1431
+ await definition.run(context, cloneValue(record.input) as I)
1432
+ record = await load(sagaId)
1433
+ if (record.state === "running")
1434
+ record = await save(record, { ...record, state: "completed", updatedAt: now() })
1435
+ return record
1436
+ } catch (error) {
1437
+ record = await load(sagaId)
1438
+ if (record.state === "manual-review") throw error
1439
+ await compensate(definition, sagaId, runOptions)
1440
+ throw error
1441
+ }
1442
+ }
1443
+
1444
+ const resolveAmbiguity = async <I, C extends Record<string, unknown>>(
1445
+ definition: SagaDefinition<I, C>,
1446
+ sagaId: string,
1447
+ resolution: SagaAmbiguityResolution,
1448
+ ): Promise<SagaRecord> => {
1449
+ assertSagaDefinition(definition)
1450
+ assertToken(sagaId, "saga id", 128)
1451
+ if (typeof resolution !== "object" || resolution === null)
1452
+ throw new TypeError("saga resolution must be an object")
1453
+ if (
1454
+ (resolution.kind === "execution" &&
1455
+ resolution.outcome !== "committed" &&
1456
+ resolution.outcome !== "not-committed") ||
1457
+ (resolution.kind === "compensation" &&
1458
+ resolution.outcome !== "compensated" &&
1459
+ resolution.outcome !== "not-compensated") ||
1460
+ (resolution.kind !== "execution" && resolution.kind !== "compensation")
1461
+ ) {
1462
+ throw new TypeError("saga resolution kind or outcome is invalid")
1463
+ }
1464
+ assertToken(resolution.step, "saga resolution step", 128)
1465
+ assertToken(resolution.effectId, "saga resolution effect id", 64)
1466
+ let record = await load(sagaId)
1467
+ if (record.definition !== definition.name) throw new TypeError("saga definition mismatch")
1468
+ const index = record.steps.findIndex((step) => step.name === resolution.step)
1469
+ if (index < 0) throw new SagaResolutionError(sagaId, resolution.step, "does not exist")
1470
+ const current = record.steps[index] as SagaStepRecord
1471
+
1472
+ let step: SagaStepRecord
1473
+ let state: SagaState
1474
+ if (resolution.kind === "execution") {
1475
+ if (current.effectId !== resolution.effectId)
1476
+ throw new SagaResolutionError(sagaId, resolution.step, "execution effect id does not match")
1477
+ if (current.state !== "executing" && current.state !== "ambiguous")
1478
+ throw new SagaResolutionError(
1479
+ sagaId,
1480
+ resolution.step,
1481
+ `is not awaiting an execution resolution (${current.state})`,
1482
+ )
1483
+ const { errorCode: _errorCode, result: _result, ...base } = current
1484
+ if (resolution.outcome === "committed") {
1485
+ step = { ...base, state: "committed", result: cloneValue(resolution.result) }
1486
+ state = "running"
1487
+ } else {
1488
+ const errorCode = resolution.errorCode ?? "not_committed"
1489
+ if (!ERROR_CODE.test(errorCode)) throw new TypeError("saga resolution errorCode is invalid")
1490
+ step = { ...base, state: "failed", errorCode }
1491
+ state = "compensating"
1492
+ }
1493
+ } else {
1494
+ if (current.compensationEffectId !== resolution.effectId)
1495
+ throw new SagaResolutionError(
1496
+ sagaId,
1497
+ resolution.step,
1498
+ "compensation effect id does not match",
1499
+ )
1500
+ if (current.state !== "compensating")
1501
+ throw new SagaResolutionError(
1502
+ sagaId,
1503
+ resolution.step,
1504
+ `is not awaiting a compensation resolution (${current.state})`,
1505
+ )
1506
+ const { errorCode: _errorCode, nextAttemptAt: _nextAttemptAt, ...base } = current
1507
+ step = {
1508
+ ...base,
1509
+ state: resolution.outcome === "compensated" ? "compensated" : "compensation-failed",
1510
+ }
1511
+ state =
1512
+ resolution.outcome === "not-compensated" &&
1513
+ current.attempts >= (definition.retry?.maxAttempts ?? 3)
1514
+ ? "manual-review"
1515
+ : "compensating"
1516
+ }
1517
+ record = await save(record, withStep(record, index, Object.freeze(step), state))
1518
+ return record
1519
+ }
1520
+
1521
+ const engine: SagaEngine = {
1522
+ async execute<I, C extends Record<string, unknown>>(
1523
+ definition: SagaDefinition<I, C>,
1524
+ sagaId: string,
1525
+ input: I,
1526
+ runOptions: { readonly signal?: AbortSignal } = {},
1527
+ ) {
1528
+ assertSagaDefinition(definition)
1529
+ assertToken(sagaId, "saga id", 128)
1530
+ throwIfAborted(signalOrNever(runOptions.signal))
1531
+ const at = now()
1532
+ const accepted = await options.store.create(
1533
+ Object.freeze({
1534
+ sagaId,
1535
+ definition: definition.name,
1536
+ state: "running" as const,
1537
+ input: cloneValue(input),
1538
+ steps: Object.freeze([]),
1539
+ createdAt: at,
1540
+ updatedAt: at,
1541
+ version: 1,
1542
+ }),
1543
+ )
1544
+ if (!accepted) throw new Error(`saga ${sagaId}: already exists`)
1545
+ return await resume(definition, sagaId, runOptions)
1546
+ },
1547
+ resume,
1548
+ compensate,
1549
+ resolveAmbiguity,
1550
+ }
1551
+ return Object.freeze(engine)
1552
+ }
1553
+
1554
+ export class MemorySagaStore implements SagaStore {
1555
+ readonly durability = "memory" as const
1556
+ private readonly records = new Map<string, SagaRecord>()
1557
+ // Secondary index: sagaIds grouped by state, so reconciliation scans only the requested (few,
1558
+ // non-terminal) states instead of walking every retained record. See {@link indexedScan}.
1559
+ private readonly byState = new Map<SagaState, Set<string>>()
1560
+ create(record: SagaRecord): boolean {
1561
+ if (this.records.has(record.sagaId)) return false
1562
+ this.records.set(record.sagaId, Object.freeze(cloneValue(record)))
1563
+ bucketAdd(this.byState, record.state, record.sagaId)
1564
+ return true
1565
+ }
1566
+ get(sagaId: string): SagaRecord | undefined {
1567
+ const record = this.records.get(sagaId)
1568
+ return record === undefined ? undefined : Object.freeze(cloneValue(record))
1569
+ }
1570
+ compareAndSet(input: Parameters<SagaStore["compareAndSet"]>[0]): boolean {
1571
+ const current = this.records.get(input.sagaId)
1572
+ if (
1573
+ current === undefined ||
1574
+ current.version !== input.version ||
1575
+ input.record.version !== input.version + 1
1576
+ )
1577
+ return false
1578
+ this.records.set(input.sagaId, Object.freeze(cloneValue(input.record)))
1579
+ bucketMove(this.byState, current.state, input.record.state, input.sagaId)
1580
+ return true
1581
+ }
1582
+ list(): readonly SagaRecord[] {
1583
+ return Object.freeze(
1584
+ [...this.records.values()].map((record) => Object.freeze(cloneValue(record))),
1585
+ )
1586
+ }
1587
+
1588
+ scan(input: ReconciliationScanOptions<SagaState>): ReconciliationScanPage<SagaRecord> {
1589
+ return indexedScan(this.byState, (id) => this.records.get(id), input)
1590
+ }
1591
+ }
1592
+
1593
+ export interface SagaReconciliationFinding {
1594
+ readonly sagaId: string
1595
+ readonly state: SagaState
1596
+ readonly step?: string
1597
+ readonly effectId?: string
1598
+ readonly reason:
1599
+ | "stale-running"
1600
+ | "ambiguous-execution"
1601
+ | "ambiguous-compensation"
1602
+ | "manual-review"
1603
+ }
1604
+
1605
+ async function scanSagaRecords(
1606
+ store: SagaStore,
1607
+ input: ReconciliationScanOptions<SagaState>,
1608
+ ): Promise<ReconciliationScanPage<SagaRecord>> {
1609
+ if (store.scan !== undefined) return await store.scan(input)
1610
+ if (store.list === undefined) throw new TypeError("saga store does not support reconciliation")
1611
+ return memoryScan(await store.list(), input)
1612
+ }
1613
+
1614
+ export async function reconcileSagasPage(
1615
+ store: SagaStore,
1616
+ options: { readonly staleBefore: number; readonly cursor?: string; readonly limit?: number },
1617
+ ): Promise<ReconciliationPage<SagaReconciliationFinding>> {
1618
+ const findings: SagaReconciliationFinding[] = []
1619
+ const page = await scanSagaRecords(store, {
1620
+ states: ["running", "compensating", "manual-review"],
1621
+ ...(options.cursor === undefined ? {} : { cursor: options.cursor }),
1622
+ limit: reconciliationLimit(options.limit),
1623
+ })
1624
+ for (const record of page.records) {
1625
+ const ambiguous = record.steps.find(
1626
+ (step) =>
1627
+ step.state === "executing" || step.state === "ambiguous" || step.state === "compensating",
1628
+ )
1629
+ if (ambiguous !== undefined) {
1630
+ findings.push(
1631
+ Object.freeze({
1632
+ sagaId: record.sagaId,
1633
+ state: record.state,
1634
+ step: ambiguous.name,
1635
+ effectId:
1636
+ ambiguous.state === "compensating"
1637
+ ? ambiguous.compensationEffectId
1638
+ : ambiguous.effectId,
1639
+ reason:
1640
+ ambiguous.state === "compensating" ? "ambiguous-compensation" : "ambiguous-execution",
1641
+ }),
1642
+ )
1643
+ } else if (record.state === "manual-review") {
1644
+ findings.push(
1645
+ Object.freeze({ sagaId: record.sagaId, state: record.state, reason: "manual-review" }),
1646
+ )
1647
+ } else if (
1648
+ (record.state === "running" || record.state === "compensating") &&
1649
+ record.updatedAt <= options.staleBefore
1650
+ ) {
1651
+ findings.push(
1652
+ Object.freeze({ sagaId: record.sagaId, state: record.state, reason: "stale-running" }),
1653
+ )
1654
+ }
1655
+ }
1656
+ return Object.freeze({
1657
+ findings: Object.freeze(findings),
1658
+ ...(page.cursor === undefined ? {} : { cursor: page.cursor }),
1659
+ })
1660
+ }
1661
+
1662
+ export async function reconcileSagas(
1663
+ store: SagaStore,
1664
+ options: { readonly staleBefore: number },
1665
+ ): Promise<readonly SagaReconciliationFinding[]> {
1666
+ const page = await reconcileSagasPage(store, {
1667
+ ...options,
1668
+ limit: MAX_RECONCILIATION_LIMIT,
1669
+ })
1670
+ if (page.cursor !== undefined) {
1671
+ throw new RangeError(
1672
+ `saga reconciliation exceeds ${MAX_RECONCILIATION_LIMIT} records; use reconcileSagasPage()`,
1673
+ )
1674
+ }
1675
+ return page.findings
1676
+ }