@nifrajs/core 3.1.0 → 3.3.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 (146) hide show
  1. package/README.md +21 -0
  2. package/dist/durable-adapters.d.ts.map +1 -1
  3. package/dist/durable-adapters.js +26 -3
  4. package/dist/durable-adapters.js.map +1 -1
  5. package/dist/durable-approval.d.ts +56 -0
  6. package/dist/durable-approval.d.ts.map +1 -0
  7. package/dist/durable-approval.js +233 -0
  8. package/dist/durable-approval.js.map +1 -0
  9. package/dist/durable-effect.d.ts +42 -0
  10. package/dist/durable-effect.d.ts.map +1 -0
  11. package/dist/durable-effect.js +234 -0
  12. package/dist/durable-effect.js.map +1 -0
  13. package/dist/durable-execution.d.ts +8 -346
  14. package/dist/durable-execution.d.ts.map +1 -1
  15. package/dist/durable-execution.js +7 -1150
  16. package/dist/durable-execution.js.map +1 -1
  17. package/dist/durable-saga.d.ts +94 -0
  18. package/dist/durable-saga.d.ts.map +1 -0
  19. package/dist/durable-saga.js +550 -0
  20. package/dist/durable-saga.js.map +1 -0
  21. package/dist/edge-kit.d.ts +2 -2
  22. package/dist/edge-kit.d.ts.map +1 -1
  23. package/dist/edge-kit.js +2 -2
  24. package/dist/edge-kit.js.map +1 -1
  25. package/dist/index.d.ts +23 -2
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +18 -2
  28. package/dist/index.js.map +1 -1
  29. package/dist/internal/durable-approval-protocol.d.ts +1 -1
  30. package/dist/internal/durable-approval-protocol.d.ts.map +1 -1
  31. package/dist/internal/durable-effect-protocol.d.ts +1 -1
  32. package/dist/internal/durable-effect-protocol.d.ts.map +1 -1
  33. package/dist/internal/durable-saga-protocol.d.ts +1 -1
  34. package/dist/internal/durable-saga-protocol.d.ts.map +1 -1
  35. package/dist/internal/durable-shared.d.ts +26 -0
  36. package/dist/internal/durable-shared.d.ts.map +1 -0
  37. package/dist/internal/durable-shared.js +131 -0
  38. package/dist/internal/durable-shared.js.map +1 -0
  39. package/dist/internal/durable-types.d.ts +159 -0
  40. package/dist/internal/durable-types.d.ts.map +1 -0
  41. package/dist/internal/durable-types.js +2 -0
  42. package/dist/internal/durable-types.js.map +1 -0
  43. package/dist/internal/route-compiler.d.ts +61 -0
  44. package/dist/internal/route-compiler.d.ts.map +1 -0
  45. package/dist/internal/route-compiler.js +121 -0
  46. package/dist/internal/route-compiler.js.map +1 -0
  47. package/dist/internal/route-execution.d.ts +6 -4
  48. package/dist/internal/route-execution.d.ts.map +1 -1
  49. package/dist/internal/route-execution.js +2 -17
  50. package/dist/internal/route-execution.js.map +1 -1
  51. package/dist/internal/route-lanes.d.ts +35 -0
  52. package/dist/internal/route-lanes.d.ts.map +1 -0
  53. package/dist/internal/route-lanes.js +150 -0
  54. package/dist/internal/route-lanes.js.map +1 -0
  55. package/dist/internal/route-program.d.ts +67 -0
  56. package/dist/internal/route-program.d.ts.map +1 -0
  57. package/dist/internal/route-program.js +199 -0
  58. package/dist/internal/route-program.js.map +1 -0
  59. package/dist/server/bare-error-lane.d.ts +1 -1
  60. package/dist/server/bare-error-lane.d.ts.map +1 -1
  61. package/dist/server/bare-error-lane.js +3 -3
  62. package/dist/server/bare-error-lane.js.map +1 -1
  63. package/dist/server/body-lane.d.ts +13 -0
  64. package/dist/server/body-lane.d.ts.map +1 -0
  65. package/dist/server/body-lane.js +134 -0
  66. package/dist/server/body-lane.js.map +1 -0
  67. package/dist/server/contract.d.ts +40 -14
  68. package/dist/server/contract.d.ts.map +1 -1
  69. package/dist/server/contract.js +7 -0
  70. package/dist/server/contract.js.map +1 -1
  71. package/dist/server/cookies.d.ts.map +1 -1
  72. package/dist/server/cookies.js +16 -2
  73. package/dist/server/cookies.js.map +1 -1
  74. package/dist/server/plugin.d.ts +2 -2
  75. package/dist/server/plugin.d.ts.map +1 -1
  76. package/dist/server/plugin.js +6 -1
  77. package/dist/server/plugin.js.map +1 -1
  78. package/dist/server/registry.d.ts +40 -12
  79. package/dist/server/registry.d.ts.map +1 -1
  80. package/dist/server/request-context.d.ts +4 -28
  81. package/dist/server/request-context.d.ts.map +1 -1
  82. package/dist/server/request-context.js +10 -185
  83. package/dist/server/request-context.js.map +1 -1
  84. package/dist/server/respond.d.ts.map +1 -1
  85. package/dist/server/respond.js +39 -2
  86. package/dist/server/respond.js.map +1 -1
  87. package/dist/server/runtime-core.d.ts +18 -2
  88. package/dist/server/runtime-core.d.ts.map +1 -1
  89. package/dist/server/runtime-core.js +0 -23
  90. package/dist/server/runtime-core.js.map +1 -1
  91. package/dist/server/server-types.d.ts +3 -0
  92. package/dist/server/server-types.d.ts.map +1 -1
  93. package/dist/server/server.d.ts +113 -84
  94. package/dist/server/server.d.ts.map +1 -1
  95. package/dist/server/server.js +506 -639
  96. package/dist/server/server.js.map +1 -1
  97. package/dist/server/validation.d.ts +5 -0
  98. package/dist/server/validation.d.ts.map +1 -0
  99. package/dist/server/validation.js +13 -0
  100. package/dist/server/validation.js.map +1 -0
  101. package/dist/server/ws-bun.d.ts +11 -3
  102. package/dist/server/ws-bun.d.ts.map +1 -1
  103. package/dist/server/ws-bun.js +42 -12
  104. package/dist/server/ws-bun.js.map +1 -1
  105. package/dist/server/ws-hook.d.ts +3 -2
  106. package/dist/server/ws-hook.d.ts.map +1 -1
  107. package/dist/server.d.ts +2 -2
  108. package/dist/server.d.ts.map +1 -1
  109. package/dist/server.js +1 -1
  110. package/dist/server.js.map +1 -1
  111. package/dist/single-copy.d.ts.map +1 -1
  112. package/dist/single-copy.js +3 -1
  113. package/dist/single-copy.js.map +1 -1
  114. package/package.json +6 -3
  115. package/src/durable-adapters.ts +20 -0
  116. package/src/durable-approval.ts +281 -0
  117. package/src/durable-effect.ts +300 -0
  118. package/src/durable-execution.ts +8 -1627
  119. package/src/durable-saga.ts +744 -0
  120. package/src/edge-kit.ts +2 -2
  121. package/src/index.ts +129 -2
  122. package/src/internal/durable-approval-protocol.ts +1 -1
  123. package/src/internal/durable-effect-protocol.ts +1 -1
  124. package/src/internal/durable-saga-protocol.ts +1 -1
  125. package/src/internal/durable-shared.ts +157 -0
  126. package/src/internal/durable-types.ts +194 -0
  127. package/src/internal/route-compiler.ts +234 -0
  128. package/src/internal/route-execution.ts +34 -84
  129. package/src/internal/route-lanes.ts +221 -0
  130. package/src/internal/route-program.ts +404 -0
  131. package/src/server/bare-error-lane.ts +3 -2
  132. package/src/server/body-lane.ts +203 -0
  133. package/src/server/contract.ts +70 -20
  134. package/src/server/cookies.ts +16 -2
  135. package/src/server/plugin.ts +11 -5
  136. package/src/server/registry.ts +71 -16
  137. package/src/server/request-context.ts +7 -262
  138. package/src/server/respond.ts +45 -2
  139. package/src/server/runtime-core.ts +28 -2
  140. package/src/server/server-types.ts +3 -0
  141. package/src/server/server.ts +1152 -1260
  142. package/src/server/validation.ts +19 -0
  143. package/src/server/ws-bun.ts +44 -11
  144. package/src/server/ws-hook.ts +3 -2
  145. package/src/server.ts +7 -2
  146. package/src/single-copy.ts +3 -1
@@ -0,0 +1,281 @@
1
+ import type { CapabilityApprovalGate } from "./internal/capability-runtime.ts"
2
+ import { durableApprovalProtocol } from "./internal/durable-approval-protocol.ts"
3
+ import {
4
+ addDuration,
5
+ assertPositiveMs,
6
+ assertToken,
7
+ bytesToBase64Url,
8
+ cloneValue,
9
+ encoder,
10
+ readClock,
11
+ sha256,
12
+ } from "./internal/durable-shared.ts"
13
+ import type {
14
+ ApprovalConsumeResult,
15
+ ApprovalRecord,
16
+ ApprovalStore,
17
+ } from "./internal/durable-types.ts"
18
+
19
+ const decoder = new TextDecoder()
20
+
21
+ function base64UrlToBytes(value: string): Uint8Array {
22
+ if (!/^[A-Za-z0-9_-]+$/u.test(value)) throw new ApprovalTokenInvalidError()
23
+ const padded = value
24
+ .replaceAll("-", "+")
25
+ .replaceAll("_", "/")
26
+ .padEnd(Math.ceil(value.length / 4) * 4, "=")
27
+ let binary: string
28
+ try {
29
+ binary = atob(padded)
30
+ } catch {
31
+ throw new ApprovalTokenInvalidError()
32
+ }
33
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0))
34
+ }
35
+ // Durable human approval with signed, single-use resume tokens
36
+
37
+ export class ApprovalRequiredError extends Error {
38
+ readonly approvalId: string
39
+ readonly effectId: string
40
+ readonly resumeToken!: string
41
+ readonly expiresAt: number
42
+
43
+ constructor(approvalId: string, effectId: string, resumeToken: string, expiresAt: number) {
44
+ super("capability approval is required")
45
+ this.approvalId = approvalId
46
+ this.effectId = effectId
47
+ this.expiresAt = expiresAt
48
+ Object.defineProperty(this, "resumeToken", {
49
+ value: resumeToken,
50
+ enumerable: false,
51
+ configurable: false,
52
+ writable: false,
53
+ })
54
+ this.name = "ApprovalRequiredError"
55
+ }
56
+ }
57
+
58
+ export class ApprovalTokenInvalidError extends Error {
59
+ constructor() {
60
+ super("approval resume token is invalid")
61
+ this.name = "ApprovalTokenInvalidError"
62
+ }
63
+ }
64
+ export class ApprovalTokenExpiredError extends Error {
65
+ constructor() {
66
+ super("approval resume token has expired")
67
+ this.name = "ApprovalTokenExpiredError"
68
+ }
69
+ }
70
+ export class ApprovalTokenReplayError extends Error {
71
+ constructor() {
72
+ super("approval resume token has already been consumed")
73
+ this.name = "ApprovalTokenReplayError"
74
+ }
75
+ }
76
+ export class ApprovalBindingError extends Error {
77
+ constructor() {
78
+ super("approval resume token is bound to another tenant or principal")
79
+ this.name = "ApprovalBindingError"
80
+ }
81
+ }
82
+ export class ApprovalPendingError extends Error {
83
+ constructor() {
84
+ super("capability approval is still pending")
85
+ this.name = "ApprovalPendingError"
86
+ }
87
+ }
88
+ export class ApprovalDeniedError extends Error {
89
+ constructor() {
90
+ super("capability approval was denied")
91
+ this.name = "ApprovalDeniedError"
92
+ }
93
+ }
94
+
95
+ interface ResumeClaims {
96
+ readonly v: 1
97
+ readonly id: string
98
+ readonly nonce: string
99
+ readonly exp: number
100
+ }
101
+
102
+ export interface ApprovalCoordinator extends CapabilityApprovalGate {
103
+ decide(input: {
104
+ readonly approvalId: string
105
+ readonly tenantId: string
106
+ readonly decision: "approved" | "denied"
107
+ readonly decidedBy: string
108
+ }): Promise<void>
109
+ get(approvalId: string): Promise<ApprovalRecord | undefined>
110
+ }
111
+
112
+ export interface ApprovalCoordinatorOptions {
113
+ readonly store: ApprovalStore
114
+ /** At least 32 random bytes, kept separately from the approval store. */
115
+ readonly secret: Uint8Array
116
+ readonly ttlMs?: number
117
+ readonly now?: () => number
118
+ /** Tests/local development only. Production approval records require a durable store. */
119
+ readonly allowMemoryStore?: boolean
120
+ }
121
+
122
+ export function createApprovalCoordinator(
123
+ options: ApprovalCoordinatorOptions,
124
+ ): ApprovalCoordinator {
125
+ if (options.store.durability !== "durable" && options.allowMemoryStore !== true) {
126
+ throw new TypeError('approval coordinator requires store.durability === "durable"')
127
+ }
128
+ if (!(options.secret instanceof Uint8Array) || options.secret.byteLength < 32) {
129
+ throw new TypeError("approval secret must contain at least 32 random bytes")
130
+ }
131
+ const secret = new Uint8Array(options.secret)
132
+ const ttlMs = options.ttlMs ?? 15 * 60_000
133
+ assertPositiveMs(ttlMs, "approval ttlMs")
134
+ const clock = options.now ?? Date.now
135
+ const now = (): number => readClock(clock, "approval clock")
136
+ const key = crypto.subtle.importKey("raw", secret, { name: "HMAC", hash: "SHA-256" }, false, [
137
+ "sign",
138
+ "verify",
139
+ ])
140
+
141
+ const sign = async (claims: ResumeClaims): Promise<string> => {
142
+ const payload = bytesToBase64Url(encoder.encode(JSON.stringify(claims)))
143
+ const signature = new Uint8Array(
144
+ await crypto.subtle.sign("HMAC", await key, encoder.encode(payload)),
145
+ )
146
+ return `v1.${payload}.${bytesToBase64Url(signature)}`
147
+ }
148
+ const verify = async (token: string): Promise<ResumeClaims> => {
149
+ if (typeof token !== "string" || token.length > 2048) throw new ApprovalTokenInvalidError()
150
+ const parts = token.split(".")
151
+ if (parts.length !== 3 || parts[0] !== "v1") throw new ApprovalTokenInvalidError()
152
+ const payload = parts[1] as string
153
+ const valid = await crypto.subtle.verify(
154
+ "HMAC",
155
+ await key,
156
+ base64UrlToBytes(parts[2] as string).buffer as ArrayBuffer,
157
+ encoder.encode(payload),
158
+ )
159
+ if (!valid) throw new ApprovalTokenInvalidError()
160
+ let claims: unknown
161
+ try {
162
+ claims = JSON.parse(decoder.decode(base64UrlToBytes(payload)))
163
+ } catch {
164
+ throw new ApprovalTokenInvalidError()
165
+ }
166
+ if (typeof claims !== "object" || claims === null) throw new ApprovalTokenInvalidError()
167
+ const candidate = claims as Partial<ResumeClaims>
168
+ if (
169
+ candidate.v !== 1 ||
170
+ typeof candidate.id !== "string" ||
171
+ typeof candidate.nonce !== "string" ||
172
+ !Number.isSafeInteger(candidate.exp)
173
+ ) {
174
+ throw new ApprovalTokenInvalidError()
175
+ }
176
+ assertToken(candidate.id, "approval id", 128)
177
+ assertToken(candidate.nonce, "approval nonce", 128)
178
+ if ((candidate.exp as number) <= now()) throw new ApprovalTokenExpiredError()
179
+ return candidate as ResumeClaims
180
+ }
181
+
182
+ const coordinator: ApprovalCoordinator = {
183
+ async authorize(input: Parameters<CapabilityApprovalGate["authorize"]>[0]) {
184
+ if (input.signal.aborted) throw input.signal.reason
185
+ assertToken(input.identity.tenantId, "approval tenantId")
186
+ assertToken(input.identity.principalId, "approval principalId")
187
+ if (input.resumeToken === undefined) {
188
+ const approvalId = crypto.randomUUID()
189
+ const nonce = bytesToBase64Url(crypto.getRandomValues(new Uint8Array(18)))
190
+ const issuedAt = now()
191
+ const expiresAt = addDuration(issuedAt, ttlMs, "approval expiry")
192
+ const resumeToken = await sign({ v: 1, id: approvalId, nonce, exp: expiresAt })
193
+ const accepted = await options.store.create(
194
+ Object.freeze({
195
+ approvalId,
196
+ effectId: input.effectId,
197
+ capability: input.capability,
198
+ ...(input.target === undefined ? {} : { target: input.target }),
199
+ ...(input.digest === undefined ? {} : { digest: input.digest }),
200
+ tenantId: input.identity.tenantId,
201
+ principalId: input.identity.principalId,
202
+ tokenHash: await sha256(resumeToken),
203
+ state: "pending" as const,
204
+ createdAt: issuedAt,
205
+ expiresAt,
206
+ updatedAt: issuedAt,
207
+ version: 1,
208
+ }),
209
+ )
210
+ if (!accepted) throw new Error("approval store rejected a unique approval id")
211
+ throw new ApprovalRequiredError(approvalId, input.effectId, resumeToken, expiresAt)
212
+ }
213
+ const claims = await verify(input.resumeToken)
214
+ const consumed = await options.store.consume({
215
+ approvalId: claims.id,
216
+ tenantId: input.identity.tenantId,
217
+ principalId: input.identity.principalId,
218
+ capability: input.capability,
219
+ ...(input.target === undefined ? {} : { target: input.target }),
220
+ ...(input.digest === undefined ? {} : { digest: input.digest }),
221
+ tokenHash: await sha256(input.resumeToken),
222
+ now: now(),
223
+ })
224
+ if (consumed.state === "consumed") return
225
+ if (consumed.state === "replay") throw new ApprovalTokenReplayError()
226
+ if (consumed.state === "binding") throw new ApprovalBindingError()
227
+ if (consumed.state === "expired") throw new ApprovalTokenExpiredError()
228
+ if (consumed.state === "pending") throw new ApprovalPendingError()
229
+ if (consumed.state === "denied") throw new ApprovalDeniedError()
230
+ throw new ApprovalTokenInvalidError()
231
+ },
232
+ async decide(input: Parameters<ApprovalCoordinator["decide"]>[0]) {
233
+ assertToken(input.approvalId, "approval id", 128)
234
+ assertToken(input.tenantId, "approval tenantId")
235
+ assertToken(input.decidedBy, "approval decidedBy")
236
+ const accepted = await options.store.decide({ ...input, now: now() })
237
+ if (!accepted) throw new Error("approval decision rejected")
238
+ },
239
+ async get(approvalId: string) {
240
+ assertToken(approvalId, "approval id", 128)
241
+ return await options.store.get(approvalId)
242
+ },
243
+ }
244
+ return Object.freeze(coordinator)
245
+ }
246
+
247
+ export class MemoryApprovalStore implements ApprovalStore {
248
+ readonly durability = "memory" as const
249
+ private readonly records = new Map<string, ApprovalRecord>()
250
+
251
+ create(record: ApprovalRecord): boolean {
252
+ if (this.records.has(record.approvalId)) return false
253
+ this.records.set(record.approvalId, Object.freeze(cloneValue(record)))
254
+ return true
255
+ }
256
+ get(approvalId: string): ApprovalRecord | undefined {
257
+ const record = this.records.get(approvalId)
258
+ return record === undefined ? undefined : Object.freeze(cloneValue(record))
259
+ }
260
+ decide(input: Parameters<ApprovalStore["decide"]>[0]): boolean {
261
+ const record = this.records.get(input.approvalId)
262
+ const next = durableApprovalProtocol.decide(record, input)
263
+ if (next === undefined) return false
264
+ this.records.set(input.approvalId, Object.freeze(next))
265
+ return true
266
+ }
267
+ consume(input: Parameters<ApprovalStore["consume"]>[0]): ApprovalConsumeResult {
268
+ const record = this.records.get(input.approvalId)
269
+ const transition = durableApprovalProtocol.consume(record, input)
270
+ if (transition.next !== undefined)
271
+ this.records.set(input.approvalId, Object.freeze(transition.next))
272
+ return transition.result
273
+ }
274
+ list(): readonly ApprovalRecord[] {
275
+ return Object.freeze(
276
+ [...this.records.values()].map((record) => Object.freeze(cloneValue(record))),
277
+ )
278
+ }
279
+ }
280
+
281
+ // -------------------------------------------------------------------------------------------------
@@ -0,0 +1,300 @@
1
+ import { type EffectLifecycleObserver, emitEffectLifecycle } from "./effect-lifecycle.ts"
2
+ import type { CapabilityExecutionJournal } from "./internal/capability-runtime.ts"
3
+ import { validCapabilityId } from "./internal/capability-runtime.ts"
4
+ import { durableEffectProtocol } from "./internal/durable-effect-protocol.ts"
5
+ import {
6
+ assertTimestamp,
7
+ assertToken,
8
+ bucketAdd,
9
+ bucketMove,
10
+ cloneValue,
11
+ ERROR_CODE,
12
+ indexedScan,
13
+ MAX_RECONCILIATION_LIMIT,
14
+ memoryScan,
15
+ readClock,
16
+ reconciliationLimit,
17
+ } from "./internal/durable-shared.ts"
18
+ import type {
19
+ DurableEffectRecord,
20
+ DurableEffectState,
21
+ DurableEffectStore,
22
+ ReconciliationPage,
23
+ ReconciliationScanOptions,
24
+ ReconciliationScanPage,
25
+ } from "./internal/durable-types.ts"
26
+ // Durable effect journal + reconciliation
27
+
28
+ export class DurableEffectTransitionError extends Error {
29
+ constructor(
30
+ public readonly effectId: string,
31
+ public readonly transition: string,
32
+ ) {
33
+ super(`durable effect ${effectId}: ${transition} transition was rejected`)
34
+ this.name = "DurableEffectTransitionError"
35
+ }
36
+ }
37
+
38
+ export interface DurableEffectJournalOptions {
39
+ readonly store: DurableEffectStore
40
+ readonly now?: () => number
41
+ /** Tests/local development only. Production journals require `store.durability === "durable"`. */
42
+ readonly allowMemoryStore?: boolean
43
+ }
44
+
45
+ export function createDurableEffectJournal(
46
+ options: DurableEffectJournalOptions,
47
+ ): CapabilityExecutionJournal {
48
+ if (options.store.durability !== "durable" && options.allowMemoryStore !== true) {
49
+ throw new TypeError('durable effect journal requires store.durability === "durable"')
50
+ }
51
+ const clock = options.now ?? Date.now
52
+ const now = (): number => readClock(clock, "durable effect clock")
53
+
54
+ const current = async (effectId: string): Promise<DurableEffectRecord> => {
55
+ assertToken(effectId, "durable effect id", 64)
56
+ const record = await options.store.get(effectId)
57
+ if (record === undefined) throw new DurableEffectTransitionError(effectId, "missing")
58
+ if (
59
+ record.effectId !== effectId ||
60
+ !validCapabilityId(record.capability) ||
61
+ !["admission", "executing", "committed", "failed", "unknown"].includes(record.state) ||
62
+ !Number.isSafeInteger(record.version) ||
63
+ record.version < 1
64
+ ) {
65
+ throw new TypeError(`durable effect ${effectId}: store returned an invalid record`)
66
+ }
67
+ assertTimestamp(record.createdAt, "durable effect createdAt")
68
+ assertTimestamp(record.updatedAt, "durable effect updatedAt")
69
+ if (record.createdAt > record.updatedAt)
70
+ throw new TypeError(`durable effect ${effectId}: updatedAt precedes createdAt`)
71
+ if (record.target !== undefined) assertToken(record.target, "stored durable effect target", 128)
72
+ if (record.digest !== undefined && !/^[0-9a-f]{64}$/u.test(record.digest))
73
+ throw new TypeError(`durable effect ${effectId}: store returned an invalid digest`)
74
+ if (record.tenantId !== undefined)
75
+ assertToken(record.tenantId, "stored durable effect tenantId")
76
+ if (record.principalId !== undefined)
77
+ assertToken(record.principalId, "stored durable effect principalId")
78
+ if ((record.tenantId === undefined) !== (record.principalId === undefined))
79
+ throw new TypeError(`durable effect ${effectId}: store returned a partial identity`)
80
+ if (record.errorCode !== undefined && !ERROR_CODE.test(record.errorCode))
81
+ throw new TypeError(`durable effect ${effectId}: store returned an invalid error code`)
82
+ return record
83
+ }
84
+ const transition = async (
85
+ effectId: string,
86
+ from: DurableEffectState,
87
+ to: DurableEffectState,
88
+ errorCode?: string,
89
+ ): Promise<void> => {
90
+ const record = await current(effectId)
91
+ const next = durableEffectProtocol.transition(record, {
92
+ effectId,
93
+ version: record.version,
94
+ from,
95
+ to,
96
+ updatedAt: now(),
97
+ ...(errorCode === undefined ? {} : { errorCode }),
98
+ })
99
+ if (next === undefined) throw new DurableEffectTransitionError(effectId, `${from}->${to}`)
100
+ const accepted = await options.store.transition({
101
+ effectId,
102
+ version: record.version,
103
+ from,
104
+ to,
105
+ updatedAt: next.updatedAt,
106
+ ...(errorCode === undefined ? {} : { errorCode }),
107
+ })
108
+ if (!accepted) throw new DurableEffectTransitionError(effectId, `${from}->${to}`)
109
+ }
110
+
111
+ const journal: CapabilityExecutionJournal = {
112
+ async intent(input) {
113
+ assertToken(input.effectId, "durable effect id", 64)
114
+ if (!validCapabilityId(input.capability))
115
+ throw new TypeError("durable effect capability is invalid")
116
+ if (input.target !== undefined) assertToken(input.target, "durable effect target", 128)
117
+ if (input.digest !== undefined && !/^[0-9a-f]{64}$/u.test(input.digest))
118
+ throw new TypeError("durable effect digest is invalid")
119
+ if (input.identity !== undefined) {
120
+ assertToken(input.identity.tenantId, "durable effect tenantId")
121
+ assertToken(input.identity.principalId, "durable effect principalId")
122
+ }
123
+ const at = now()
124
+ const accepted = await options.store.create(
125
+ Object.freeze({
126
+ effectId: input.effectId,
127
+ capability: input.capability,
128
+ ...(input.target === undefined ? {} : { target: input.target }),
129
+ ...(input.digest === undefined ? {} : { digest: input.digest }),
130
+ ...(input.identity === undefined
131
+ ? {}
132
+ : { tenantId: input.identity.tenantId, principalId: input.identity.principalId }),
133
+ state: "admission" as const,
134
+ createdAt: at,
135
+ updatedAt: at,
136
+ version: 1,
137
+ }),
138
+ )
139
+ if (!accepted) throw new DurableEffectTransitionError(input.effectId, "create")
140
+ },
141
+ async executing(effectId) {
142
+ await transition(effectId, "admission", "executing")
143
+ },
144
+ async committed(effectId) {
145
+ await transition(effectId, "executing", "committed")
146
+ },
147
+ async failed(effectId, input) {
148
+ if (!ERROR_CODE.test(input.errorCode))
149
+ throw new TypeError("durable effect errorCode is invalid")
150
+ const record = await current(effectId)
151
+ const to = input.began ? "unknown" : "failed"
152
+ const next = durableEffectProtocol.transition(record, {
153
+ effectId,
154
+ version: record.version,
155
+ from: record.state,
156
+ to,
157
+ updatedAt: now(),
158
+ errorCode: input.errorCode,
159
+ })
160
+ if (next === undefined)
161
+ throw new DurableEffectTransitionError(effectId, `${record.state}->${to}`)
162
+ const accepted = await options.store.transition({
163
+ effectId,
164
+ version: record.version,
165
+ from: record.state,
166
+ to,
167
+ updatedAt: next.updatedAt,
168
+ errorCode: input.errorCode,
169
+ })
170
+ if (!accepted) throw new DurableEffectTransitionError(effectId, `${record.state}->${to}`)
171
+ },
172
+ }
173
+ return Object.freeze(journal)
174
+ }
175
+
176
+ export class MemoryDurableEffectStore implements DurableEffectStore {
177
+ readonly durability = "memory" as const
178
+ private readonly records = new Map<string, DurableEffectRecord>()
179
+ // Secondary index: effectIds grouped by state, so reconciliation scans only the requested (few,
180
+ // non-terminal) states instead of walking every retained record. See {@link indexedScan}.
181
+ private readonly byState = new Map<DurableEffectState, Set<string>>()
182
+
183
+ create(record: DurableEffectRecord): boolean {
184
+ if (this.records.has(record.effectId)) return false
185
+ this.records.set(record.effectId, Object.freeze(cloneValue(record)))
186
+ bucketAdd(this.byState, record.state, record.effectId)
187
+ return true
188
+ }
189
+
190
+ get(effectId: string): DurableEffectRecord | undefined {
191
+ const record = this.records.get(effectId)
192
+ return record === undefined ? undefined : Object.freeze(cloneValue(record))
193
+ }
194
+
195
+ transition(input: Parameters<DurableEffectStore["transition"]>[0]): boolean {
196
+ const current = this.records.get(input.effectId)
197
+ const next = durableEffectProtocol.transition(current, input)
198
+ if (next === undefined) return false
199
+ if (current === undefined) return false
200
+ this.records.set(input.effectId, Object.freeze(next))
201
+ bucketMove(this.byState, current.state, input.to, input.effectId)
202
+ return true
203
+ }
204
+
205
+ list(): readonly DurableEffectRecord[] {
206
+ return Object.freeze(
207
+ [...this.records.values()].map((record) => Object.freeze(cloneValue(record))),
208
+ )
209
+ }
210
+
211
+ scan(
212
+ input: ReconciliationScanOptions<DurableEffectState>,
213
+ ): ReconciliationScanPage<DurableEffectRecord> {
214
+ return indexedScan(this.byState, (id) => this.records.get(id), input)
215
+ }
216
+ }
217
+
218
+ export interface EffectReconciliationFinding {
219
+ readonly effectId: string
220
+ readonly capability: string
221
+ readonly state: "incomplete" | "ambiguous"
222
+ readonly updatedAt: number
223
+ }
224
+
225
+ async function scanEffectRecords(
226
+ store: DurableEffectStore,
227
+ input: ReconciliationScanOptions<DurableEffectState>,
228
+ ): Promise<ReconciliationScanPage<DurableEffectRecord>> {
229
+ if (store.scan !== undefined) return await store.scan(input)
230
+ if (store.list === undefined) throw new TypeError("effect store does not support reconciliation")
231
+ return memoryScan(await store.list(), input)
232
+ }
233
+
234
+ export async function reconcileEffectsPage(
235
+ store: DurableEffectStore,
236
+ options: {
237
+ readonly staleBefore: number
238
+ readonly observer?: EffectLifecycleObserver
239
+ readonly cursor?: string
240
+ readonly limit?: number
241
+ },
242
+ ): Promise<ReconciliationPage<EffectReconciliationFinding>> {
243
+ const findings: EffectReconciliationFinding[] = []
244
+ const page = await scanEffectRecords(store, {
245
+ states: ["admission", "executing", "unknown"],
246
+ updatedBefore: options.staleBefore,
247
+ ...(options.cursor === undefined ? {} : { cursor: options.cursor }),
248
+ limit: reconciliationLimit(options.limit),
249
+ })
250
+ for (const record of page.records) {
251
+ if (!validCapabilityId(record.capability) || !/^[!-~]{1,64}$/u.test(record.effectId)) continue
252
+ if (record.updatedAt > options.staleBefore) continue
253
+ const state =
254
+ record.state === "admission"
255
+ ? "incomplete"
256
+ : record.state === "executing" || record.state === "unknown"
257
+ ? "ambiguous"
258
+ : undefined
259
+ if (state === undefined) continue
260
+ findings.push(
261
+ Object.freeze({
262
+ effectId: record.effectId,
263
+ capability: record.capability,
264
+ state,
265
+ updatedAt: record.updatedAt,
266
+ }),
267
+ )
268
+ if (options.observer !== undefined) {
269
+ emitEffectLifecycle([options.observer], {
270
+ effectId: record.effectId,
271
+ capability: record.capability,
272
+ stage: "reconciliation",
273
+ phase: state === "ambiguous" ? "ambiguous" : "failed",
274
+ errorCode: state === "ambiguous" ? "effect_ambiguous" : "effect_incomplete",
275
+ })
276
+ }
277
+ }
278
+ return Object.freeze({
279
+ findings: Object.freeze(findings),
280
+ ...(page.cursor === undefined ? {} : { cursor: page.cursor }),
281
+ })
282
+ }
283
+
284
+ export async function reconcileEffects(
285
+ store: DurableEffectStore,
286
+ options: { readonly staleBefore: number; readonly observer?: EffectLifecycleObserver },
287
+ ): Promise<readonly EffectReconciliationFinding[]> {
288
+ const page = await reconcileEffectsPage(store, {
289
+ ...options,
290
+ limit: MAX_RECONCILIATION_LIMIT,
291
+ })
292
+ if (page.cursor !== undefined) {
293
+ throw new RangeError(
294
+ `effect reconciliation exceeds ${MAX_RECONCILIATION_LIMIT} records; use reconcileEffectsPage()`,
295
+ )
296
+ }
297
+ return page.findings
298
+ }
299
+
300
+ // -------------------------------------------------------------------------------------------------