@entifix/transactions 0.5.0 → 0.6.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.
- package/dist/contracts/command.d.ts +2 -3
- package/dist/contracts/command.d.ts.map +1 -1
- package/dist/contracts/command.js.map +1 -1
- package/dist/contracts/event.d.ts +3 -3
- package/dist/contracts/event.js.map +1 -1
- package/dist/contracts/inbox.d.ts +1 -1
- package/dist/contracts/inbox.js.map +1 -1
- package/dist/contracts/outbox.d.ts +4 -5
- package/dist/contracts/outbox.d.ts.map +1 -1
- package/dist/contracts/outbox.js.map +1 -1
- package/dist/contracts/record.d.ts +4 -5
- package/dist/contracts/record.d.ts.map +1 -1
- package/dist/contracts/record.js.map +1 -1
- package/dist/contracts/saga-definition.d.ts +15 -20
- package/dist/contracts/saga-definition.d.ts.map +1 -1
- package/dist/contracts/saga-definition.js +6 -6
- package/dist/contracts/saga-definition.js.map +1 -1
- package/dist/engine/resolve-template.d.ts +2 -3
- package/dist/engine/resolve-template.d.ts.map +1 -1
- package/dist/engine/resolve-template.js +2 -3
- package/dist/engine/resolve-template.js.map +1 -1
- package/dist/engine/run-saga.d.ts +1 -2
- package/dist/engine/run-saga.d.ts.map +1 -1
- package/dist/engine/run-saga.js +13 -17
- package/dist/engine/run-saga.js.map +1 -1
- package/dist/ports/event-bus.d.ts +6 -7
- package/dist/ports/event-bus.d.ts.map +1 -1
- package/dist/ports/event-bus.js.map +1 -1
- package/dist/ports/event-source.d.ts +3 -3
- package/dist/ports/event-source.js +3 -3
- package/dist/ports/event-source.js.map +1 -1
- package/dist/ports/saga-dispatcher.d.ts +3 -4
- package/dist/ports/saga-dispatcher.d.ts.map +1 -1
- package/dist/ports/saga-dispatcher.js.map +1 -1
- package/dist/ports/saga-store.d.ts +5 -7
- package/dist/ports/saga-store.d.ts.map +1 -1
- package/dist/ports/saga-store.js +1 -2
- package/dist/ports/saga-store.js.map +1 -1
- package/dist/ports/transaction-handler.d.ts +2 -4
- package/dist/ports/transaction-handler.d.ts.map +1 -1
- package/dist/ports/transaction-handler.js.map +1 -1
- package/dist/ports/transaction-sink.d.ts +6 -5
- package/dist/ports/transaction-sink.d.ts.map +1 -1
- package/dist/ports/transaction-sink.js.map +1 -1
- package/dist/stream/transaction-stream-hub.d.ts +1 -1
- package/dist/stream/transaction-stream-hub.d.ts.map +1 -1
- package/dist/stream/transaction-stream-hub.js +4 -5
- package/dist/stream/transaction-stream-hub.js.map +1 -1
- package/package.json +3 -3
|
@@ -21,8 +21,7 @@ const readPath = (root, path)=>{
|
|
|
21
21
|
* template no longer matches its participant's response shape would otherwise
|
|
22
22
|
* `DELETE /api/reservation/undefined`, get a `404`, and be recorded as a
|
|
23
23
|
* compensation that ran — leaving the hold in place and the saga reporting that
|
|
24
|
-
* it was reversed. That is the "failed and stranded" state
|
|
25
|
-
* plans for, arrived at by string interpolation.
|
|
24
|
+
* it was reversed. That is the "failed and stranded" state nobody plans for, arrived at by string interpolation.
|
|
26
25
|
*
|
|
27
26
|
* Values are URI-encoded: a participant's id is data, and a path segment is not
|
|
28
27
|
* the place to discover it contained a slash.
|
|
@@ -51,7 +50,7 @@ const readPath = (root, path)=>{
|
|
|
51
50
|
* with a payment attached to nothing.
|
|
52
51
|
*
|
|
53
52
|
* ⚠️ **The template lives in the caller's `inputs`, never in the definition.**
|
|
54
|
-
* That is
|
|
53
|
+
* That is a constraint, not an accident: a definition that carried
|
|
55
54
|
* domain payloads would be importing the shape of another domain's entity, which
|
|
56
55
|
* is the class of thing that has no legal home. The definition stays a list of
|
|
57
56
|
* verbs and addresses; what to send is the caller's, and this only lets the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/engine/resolve-template.ts"],"sourcesContent":["import { EntifixLogicError } from '@entifix/core';\n\n/** The `{a.b.c}` placeholders a {@link SagaCall}'s path may carry. */\nconst PLACEHOLDER = /\\{([^{}]+)\\}/g;\n\nconst readPath = (root: unknown, path: string): unknown => {\n let value = root;\n for (const segment of path.split('.')) {\n if (value === null || typeof value !== 'object') {\n return undefined;\n }\n value = (value as Record<string, unknown>)[segment];\n }\n return value;\n};\n\n/**\n * Resolve a path template against a scope.\n *\n * `/api/reservation/{outcome.data.id}` with\n * `{ outcome: { data: { id: 'r-1' } } }` becomes `/api/reservation/r-1`.\n *\n * ⚠️ **An unresolved placeholder throws rather than interpolating `undefined`.**\n * The failure this prevents is specific and silent: a compensation whose\n * template no longer matches its participant's response shape would otherwise\n * `DELETE /api/reservation/undefined`, get a `404`, and be recorded as a\n * compensation that ran — leaving the hold in place and the saga reporting that\n * it was reversed. That is the \"failed and stranded\" state
|
|
1
|
+
{"version":3,"sources":["../../src/engine/resolve-template.ts"],"sourcesContent":["import { EntifixLogicError } from '@entifix/core';\n\n/** The `{a.b.c}` placeholders a {@link SagaCall}'s path may carry. */\nconst PLACEHOLDER = /\\{([^{}]+)\\}/g;\n\nconst readPath = (root: unknown, path: string): unknown => {\n let value = root;\n for (const segment of path.split('.')) {\n if (value === null || typeof value !== 'object') {\n return undefined;\n }\n value = (value as Record<string, unknown>)[segment];\n }\n return value;\n};\n\n/**\n * Resolve a path template against a scope.\n *\n * `/api/reservation/{outcome.data.id}` with\n * `{ outcome: { data: { id: 'r-1' } } }` becomes `/api/reservation/r-1`.\n *\n * ⚠️ **An unresolved placeholder throws rather than interpolating `undefined`.**\n * The failure this prevents is specific and silent: a compensation whose\n * template no longer matches its participant's response shape would otherwise\n * `DELETE /api/reservation/undefined`, get a `404`, and be recorded as a\n * compensation that ran — leaving the hold in place and the saga reporting that\n * it was reversed. That is the \"failed and stranded\" state nobody plans for, arrived at by string interpolation.\n *\n * Values are URI-encoded: a participant's id is data, and a path segment is not\n * the place to discover it contained a slash.\n */\nexport function resolveTemplate(\n template: string,\n scope: Record<string, unknown>,\n): string {\n return template.replaceAll(PLACEHOLDER, (_match, path: string) => {\n const value = readPath(scope, path);\n if (value === undefined || value === null) {\n throw new EntifixLogicError(\n `saga path template '${template}' has no value for '{${path}}'`,\n undefined,\n { template, path },\n );\n }\n return encodeURIComponent(String(value));\n });\n}\n\n/** A string that is nothing but one placeholder, so its type can be preserved. */\nconst WHOLE_PLACEHOLDER = /^\\{([^{}]+)\\}$/;\n\n/**\n * Resolve the placeholders inside a **request body**, recursively.\n *\n * ⚠️ **Why a body needs this at all.** A step's payload can depend on what an\n * earlier step created: checkout's capture has to name the order that was just\n * written, and the order id is minted by order-service — so a caller cannot put\n * it in the body it sends when it starts the flow. Without this, the capture\n * carries a placeholder string and the order it names never advances, which is\n * precisely the defect measured on the live lab: a saga reporting `COMPLETED`\n * with a payment attached to nothing.\n *\n * ⚠️ **The template lives in the caller's `inputs`, never in the definition.**\n * That is a constraint, not an accident: a definition that carried\n * domain payloads would be importing the shape of another domain's entity, which\n * is the class of thing that has no legal home. The definition stays a list of\n * verbs and addresses; what to send is the caller's, and this only lets the\n * caller point at a value it could not have known yet.\n *\n * Two behaviours, and the difference is load-bearing:\n *\n * - A string that is **exactly** one placeholder resolves to the raw value, so\n * a number stays a number and an object stays an object. `\"{steps.x.data.qty}\"`\n * becoming the string `\"3\"` would reach a validator expecting a number.\n * - A string that merely **contains** placeholders is interpolated textually,\n * and — unlike {@link resolveTemplate} — **not** URI-encoded. A body is JSON,\n * not a path segment; encoding here would put `%20` in a customer's name.\n *\n * An unresolved placeholder throws, for the same reason it does in a path.\n */\nexport function resolveBodyTemplate(\n value: unknown,\n scope: Record<string, unknown>,\n): unknown {\n if (typeof value === 'string') {\n const whole = WHOLE_PLACEHOLDER.exec(value);\n if (whole?.[1] !== undefined) {\n const resolved = readPath(scope, whole[1]);\n if (resolved === undefined || resolved === null) {\n throw new EntifixLogicError(\n `saga body template '${value}' has no value for '{${whole[1]}}'`,\n undefined,\n { template: value, path: whole[1] },\n );\n }\n return resolved;\n }\n return value.replaceAll(PLACEHOLDER, (_match, path: string) => {\n const resolved = readPath(scope, path);\n if (resolved === undefined || resolved === null) {\n throw new EntifixLogicError(\n `saga body template '${value}' has no value for '{${path}}'`,\n undefined,\n { template: value, path },\n );\n }\n return String(resolved);\n });\n }\n\n if (Array.isArray(value)) {\n return value.map(element => resolveBodyTemplate(element, scope));\n }\n\n if (value !== null && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, entry]) => [\n key,\n resolveBodyTemplate(entry, scope),\n ]),\n );\n }\n\n return value;\n}\n"],"names":["EntifixLogicError","PLACEHOLDER","readPath","root","path","value","segment","split","undefined","resolveTemplate","template","scope","replaceAll","_match","encodeURIComponent","String","WHOLE_PLACEHOLDER","resolveBodyTemplate","whole","exec","resolved","Array","isArray","map","element","Object","fromEntries","entries","key","entry"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,gBAAgB;AAElD,oEAAoE,GACpE,MAAMC,cAAc;AAEpB,MAAMC,WAAW,CAACC,MAAeC;IAC/B,IAAIC,QAAQF;IACZ,KAAK,MAAMG,WAAWF,KAAKG,KAAK,CAAC,KAAM;QACrC,IAAIF,UAAU,QAAQ,OAAOA,UAAU,UAAU;YAC/C,OAAOG;QACT;QACAH,QAAQ,AAACA,KAAiC,CAACC,QAAQ;IACrD;IACA,OAAOD;AACT;AAEA;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAASI,gBACdC,QAAgB,EAChBC,KAA8B;IAE9B,OAAOD,SAASE,UAAU,CAACX,aAAa,CAACY,QAAQT;QAC/C,MAAMC,QAAQH,SAASS,OAAOP;QAC9B,IAAIC,UAAUG,aAAaH,UAAU,MAAM;YACzC,MAAM,IAAIL,kBACR,CAAC,oBAAoB,EAAEU,SAAS,qBAAqB,EAAEN,KAAK,EAAE,CAAC,EAC/DI,WACA;gBAAEE;gBAAUN;YAAK;QAErB;QACA,OAAOU,mBAAmBC,OAAOV;IACnC;AACF;AAEA,gFAAgF,GAChF,MAAMW,oBAAoB;AAE1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GACD,OAAO,SAASC,oBACdZ,KAAc,EACdM,KAA8B;IAE9B,IAAI,OAAON,UAAU,UAAU;QAC7B,MAAMa,QAAQF,kBAAkBG,IAAI,CAACd;QACrC,IAAIa,CAAAA,yBAAAA,KAAO,CAAC,EAAE,MAAKV,WAAW;YAC5B,MAAMY,WAAWlB,SAASS,OAAOO,KAAK,CAAC,EAAE;YACzC,IAAIE,aAAaZ,aAAaY,aAAa,MAAM;gBAC/C,MAAM,IAAIpB,kBACR,CAAC,oBAAoB,EAAEK,MAAM,qBAAqB,EAAEa,KAAK,CAAC,EAAE,CAAC,EAAE,CAAC,EAChEV,WACA;oBAAEE,UAAUL;oBAAOD,MAAMc,KAAK,CAAC,EAAE;gBAAC;YAEtC;YACA,OAAOE;QACT;QACA,OAAOf,MAAMO,UAAU,CAACX,aAAa,CAACY,QAAQT;YAC5C,MAAMgB,WAAWlB,SAASS,OAAOP;YACjC,IAAIgB,aAAaZ,aAAaY,aAAa,MAAM;gBAC/C,MAAM,IAAIpB,kBACR,CAAC,oBAAoB,EAAEK,MAAM,qBAAqB,EAAED,KAAK,EAAE,CAAC,EAC5DI,WACA;oBAAEE,UAAUL;oBAAOD;gBAAK;YAE5B;YACA,OAAOW,OAAOK;QAChB;IACF;IAEA,IAAIC,MAAMC,OAAO,CAACjB,QAAQ;QACxB,OAAOA,MAAMkB,GAAG,CAACC,CAAAA,UAAWP,oBAAoBO,SAASb;IAC3D;IAEA,IAAIN,UAAU,QAAQ,OAAOA,UAAU,UAAU;QAC/C,OAAOoB,OAAOC,WAAW,CACvBD,OAAOE,OAAO,CAACtB,OAAkCkB,GAAG,CAAC,CAAC,CAACK,KAAKC,MAAM,GAAK;gBACrED;gBACAX,oBAAoBY,OAAOlB;aAC5B;IAEL;IAEA,OAAON;AACT"}
|
|
@@ -42,8 +42,7 @@ export interface ResumeSagaOptions {
|
|
|
42
42
|
* - the step at `stepIndex` recorded no outcome — the process died during the
|
|
43
43
|
* dispatch, so **re-dispatch it**. Safe because `sagaCommandId` is stable
|
|
44
44
|
* across attempts and every participant claims it in its own command inbox,
|
|
45
|
-
* so calls that did land are recognised as replays rather than repeated
|
|
46
|
-
* (ADR 0052).
|
|
45
|
+
* so calls that did land are recognised as replays rather than repeated.
|
|
47
46
|
* - it recorded a successful outcome — the process died between
|
|
48
47
|
* `recordOutcome` and the next `beginStep`, so **start at the one after**.
|
|
49
48
|
* - it recorded a refusal — the process died deciding what to do about it, so
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-saga.d.ts","sourceRoot":"","sources":["../../src/engine/run-saga.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,OAAO,EAIL,KAAK,cAAc,EACnB,KAAK,UAAU,EAEf,KAAK,aAAa,EAClB,KAAK,eAAe,EACrB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EACL,KAAK,YAAY,EAEjB,YAAY,EACb,MAAM,wBAAwB,CAAC;AAGhC,YAAY,EAAE,UAAU,EAAE,aAAa,EAAE,CAAC;AAa1C,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,UAAU,EAAE,cAAc,CAAC;IACpC,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;CAC7B;AAED,uBAAuB;AACvB,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,KAAK,EAAE,WAAW,GAAG,aAAa,GAAG,UAAU,CAAC;IACzD,QAAQ,CAAC,QAAQ,EAAE,SAAS,eAAe,EAAE,CAAC;IAC9C,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;CACzB;
|
|
1
|
+
{"version":3,"file":"run-saga.d.ts","sourceRoot":"","sources":["../../src/engine/run-saga.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAA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run-saga.js
CHANGED
|
@@ -119,12 +119,10 @@ const dispatchCall = (step, call, sagaId, index, input, scope)=>Effect.gen(funct
|
|
|
119
119
|
* ⚠️ This is the whole reason an outcome is kept per fan-out element. Five lines
|
|
120
120
|
* with three holds taken and the fourth refused must release exactly three:
|
|
121
121
|
* compensating the step as a unit would either release nothing or attempt to
|
|
122
|
-
* release two holds that were never taken
|
|
123
|
-
* ([ADR 0052](../../../../../../docs/adr/0052-the-checkout-saga.md)).
|
|
122
|
+
* release two holds that were never taken.
|
|
124
123
|
*
|
|
125
124
|
* Never fails: a compensation's own failure is reported by the caller and must
|
|
126
|
-
* not stop the compensations after it,
|
|
127
|
-
* stranded saga nobody is told about is the same as a lost one.
|
|
125
|
+
* not stop the compensations after it, because a stranded saga nobody is told about is the same as a lost one.
|
|
128
126
|
*/ const compensateStep = (step, sagaId, outcome)=>Effect.gen(function*() {
|
|
129
127
|
const compensation = step.compensation;
|
|
130
128
|
if (!compensation) {
|
|
@@ -162,8 +160,8 @@ const dispatchCall = (step, call, sagaId, index, input, scope)=>Effect.gen(funct
|
|
|
162
160
|
// coordinator can retry it, and a participant answering "no such record"
|
|
163
161
|
// on the second delivery is describing a flow that *was* reversed. Left
|
|
164
162
|
// as a refusal it strands exactly the sagas that were cleaned up
|
|
165
|
-
// correctly
|
|
166
|
-
//
|
|
163
|
+
// correctly — the same failure a conversion route that refuses a
|
|
164
|
+
// redelivery has, from the other side.
|
|
167
165
|
if (!result.ok && result.status !== 404) {
|
|
168
166
|
failures.push(`compensation for '${step.id}' call ${String(call.index)} failed: ${String(result.body)}`);
|
|
169
167
|
}
|
|
@@ -180,7 +178,7 @@ const dispatchCall = (step, call, sagaId, index, input, scope)=>Effect.gen(funct
|
|
|
180
178
|
* a permanent failure while a customer's money sits captured.
|
|
181
179
|
*
|
|
182
180
|
* Durable retry across a coordinator restart is a different mechanism and is not
|
|
183
|
-
* built:
|
|
181
|
+
* built: the alternative makes a step dispatch an outbox entry whose relay
|
|
184
182
|
* performs the POST.
|
|
185
183
|
*/ const POST_PIVOT_RETRIES = 3;
|
|
186
184
|
/**
|
|
@@ -189,8 +187,8 @@ const dispatchCall = (step, call, sagaId, index, input, scope)=>Effect.gen(funct
|
|
|
189
187
|
* ⚠️ **A retry re-dispatches the calls that already succeeded**, and that is
|
|
190
188
|
* safe for exactly one reason: `sagaCommandId(sagaId, step.id, index)` is stable
|
|
191
189
|
* across attempts, so a participant that is idempotent on the command id
|
|
192
|
-
* recognises the replay.
|
|
193
|
-
* this is the code that depends on it.
|
|
190
|
+
* recognises the replay. That is a requirement on every participant a saga may
|
|
191
|
+
* retry; this is the code that depends on it.
|
|
194
192
|
*/ const runStepWithRetries = (step, sagaId, elements, retries)=>Effect.gen(function*() {
|
|
195
193
|
let result = yield* runStep(step, sagaId, elements);
|
|
196
194
|
for(let attempt = 1; attempt <= retries && result.error !== undefined; attempt += 1){
|
|
@@ -273,7 +271,7 @@ const dispatchCall = (step, call, sagaId, index, input, scope)=>Effect.gen(funct
|
|
|
273
271
|
if (failures.length > 0) {
|
|
274
272
|
// ⚠️ Surfaced, never swallowed. This is the state that leaves a
|
|
275
273
|
// reservation held and — once payment lands — a customer charged, and
|
|
276
|
-
//
|
|
274
|
+
// it is the failure class nobody plans for.
|
|
277
275
|
return yield* strand(store, sagaId, outcomes, error, 'saga compensation failed', {
|
|
278
276
|
definition: definition.name,
|
|
279
277
|
failures: failures.join('; ')
|
|
@@ -290,8 +288,8 @@ const dispatchCall = (step, call, sagaId, index, input, scope)=>Effect.gen(funct
|
|
|
290
288
|
* Dispatch the definition's steps from `startIndex` on, and unwind on a refusal.
|
|
291
289
|
*
|
|
292
290
|
* The state transition is persisted **before** each dispatch, so a crash leaves
|
|
293
|
-
* a record that says what was actually attempted
|
|
294
|
-
*
|
|
291
|
+
* a record that says what was actually attempted — the outbox's rule, extended
|
|
292
|
+
* from events to commands.
|
|
295
293
|
*
|
|
296
294
|
* ⚠️ **Once the pivot has committed, nothing is unwound.** That is what a pivot
|
|
297
295
|
* means, and the walk has to know it rather than the definition merely declaring
|
|
@@ -300,8 +298,7 @@ const dispatchCall = (step, call, sagaId, index, input, scope)=>Effect.gen(funct
|
|
|
300
298
|
* silence and then delete the order behind it and release the holds behind that
|
|
301
299
|
* — money taken, goods back on sale, every probe green. The step is retried
|
|
302
300
|
* instead, and a saga that still cannot go forward is settled `STRANDED` and
|
|
303
|
-
* logged, because
|
|
304
|
-
* is the same as a lost one.
|
|
301
|
+
* logged, because a stranded saga nobody is told about is the same as a lost one.
|
|
305
302
|
*/ const walk = (store, options, from)=>Effect.gen(function*() {
|
|
306
303
|
const { sagaId, definition, inputs } = options;
|
|
307
304
|
// Step and outcome are kept **together**: looking the step back up by id
|
|
@@ -376,7 +373,7 @@ const dispatchCall = (step, call, sagaId, index, input, scope)=>Effect.gen(funct
|
|
|
376
373
|
stepIndex: 0,
|
|
377
374
|
outcomes: [],
|
|
378
375
|
// ⚠️ Persisted, because a resume has nothing to dispatch without it: a
|
|
379
|
-
// fan-out step's cardinality *is* its input's length
|
|
376
|
+
// fan-out step's cardinality *is* its input's length.
|
|
380
377
|
inputs,
|
|
381
378
|
resumeAttempts: 0,
|
|
382
379
|
createdAt: new Date().toISOString()
|
|
@@ -398,8 +395,7 @@ const dispatchCall = (step, call, sagaId, index, input, scope)=>Effect.gen(funct
|
|
|
398
395
|
* - the step at `stepIndex` recorded no outcome — the process died during the
|
|
399
396
|
* dispatch, so **re-dispatch it**. Safe because `sagaCommandId` is stable
|
|
400
397
|
* across attempts and every participant claims it in its own command inbox,
|
|
401
|
-
* so calls that did land are recognised as replays rather than repeated
|
|
402
|
-
* (ADR 0052).
|
|
398
|
+
* so calls that did land are recognised as replays rather than repeated.
|
|
403
399
|
* - it recorded a successful outcome — the process died between
|
|
404
400
|
* `recordOutcome` and the next `beginStep`, so **start at the one after**.
|
|
405
401
|
* - it recorded a refusal — the process died deciding what to do about it, so
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/engine/run-saga.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Effect } from 'effect';\n\nimport {\n type SagaCall,\n type SagaCallOutcome,\n sagaCommandId,\n type SagaDefinition,\n type SagaInputs,\n type SagaStep,\n type SagaStepInput,\n type SagaStepOutcome,\n} from '../contracts/saga-definition.js';\nimport { SagaDispatcherTag } from '../ports/saga-dispatcher.js';\nimport {\n type SagaInstance,\n type SagaStore,\n SagaStoreTag,\n} from '../ports/saga-store.js';\nimport { resolveBodyTemplate, resolveTemplate } from './resolve-template.js';\n\nexport type { SagaInputs, SagaStepInput };\n\n/**\n * The steps that have run, kept with their outcomes.\n *\n * Paired rather than looked back up by id, because a lookup introduces a\n * not-found branch that cannot happen — and an unreachable branch is a line\n * nothing can ever prove correct. A resumed walk rebuilds this from the stored\n * outcomes, which is the one place the lookup does happen and can genuinely\n * fail.\n */\ntype Taken = Array<{ step: SagaStep; outcome: SagaStepOutcome }>;\n\nexport interface RunSagaOptions {\n readonly sagaId: string;\n readonly definition: SagaDefinition;\n readonly inputs: SagaInputs;\n}\n\n/** How a run ended. */\nexport interface SagaResult {\n readonly state: 'COMPLETED' | 'COMPENSATED' | 'STRANDED';\n readonly outcomes: readonly SagaStepOutcome[];\n readonly error?: string;\n}\n\n/**\n * What one element of a `fanOutFrom` step is dispatched with.\n *\n * The earlier call's body travels as `outcome` rather than `input`, which is the\n * same scope a compensation resolves against and for the same reason: the id\n * being addressed was minted by the participant and is in its response.\n */\ninterface DerivedElement {\n readonly input: SagaStepInput;\n readonly scope: Record<string, unknown>;\n}\n\nconst inputsFor = (\n step: SagaStep,\n inputs: SagaInputs,\n): readonly SagaStepInput[] => {\n const declared = inputs[step.id] ?? [];\n // A non-fan-out step makes exactly one call whether or not it was given an\n // input, so an absent entry is an empty body rather than a skipped step.\n return step.fanOut ? declared : [declared[0] ?? {}];\n};\n\n/**\n * The elements a step actually dispatches: derived from an earlier step's\n * successful calls when it declares `fanOutFrom`, and from the caller's input\n * otherwise.\n *\n * ⚠️ **A `fanOutFrom` step ignores whatever the caller supplied for it.** The\n * cardinality is the earlier step's, and taking the caller's would let a\n * checkout convert a hold it never took — or, more likely, silently convert\n * none, which is how a saga reports COMPLETED with the goods still held.\n */\n/**\n * What every step can point at: the **first successful call** of each step that\n * has already run, by step id.\n *\n * First rather than all, because a template naming a fan-out step is ambiguous\n * by construction — \"the order id\" is one value and \"the reservation ids\" are\n * many, and the many case is what `fanOutFrom` exists for. Keeping this to the\n * unambiguous case is what stops `{steps.reserve.data.id}` quietly meaning\n * \"whichever hold happened to be first\".\n */\nconst stepsScope = (\n taken: ReadonlyArray<{ step: SagaStep; outcome: SagaStepOutcome }>,\n): Record<string, unknown> =>\n Object.fromEntries(\n taken\n .filter(entry => entry.outcome.calls.length > 0)\n .map(entry => [entry.step.id, entry.outcome.calls[0]?.body]),\n );\n\nconst elementsFor = (\n step: SagaStep,\n inputs: SagaInputs,\n taken: ReadonlyArray<{ step: SagaStep; outcome: SagaStepOutcome }>,\n): readonly DerivedElement[] => {\n const steps = stepsScope(taken);\n\n if (step.fanOutFrom === undefined) {\n return inputsFor(step, inputs).map(input => ({\n input,\n scope: { input: input.body, steps },\n }));\n }\n\n const source = taken.find(entry => entry.step.id === step.fanOutFrom);\n const body = inputs[step.id]?.[0]?.body;\n\n return (source?.outcome.calls ?? []).map(call => ({\n // ⚠️ The organization the *earlier call* acted for, never the caller's.\n // A tenant-plane participant resolves its handle from the header, so a\n // conversion dispatched without it is refused `400` and the hold expires\n // under a buyer who has already been charged.\n input: { body, organizationId: call.organizationId },\n scope: { outcome: call.body, input: body, steps },\n }));\n};\n\nconst dispatchCall = (\n step: SagaStep,\n call: SagaCall,\n sagaId: string,\n index: number,\n input: SagaStepInput,\n scope: Record<string, unknown>,\n) =>\n Effect.gen(function* () {\n const dispatcher = yield* SagaDispatcherTag;\n return yield* dispatcher.dispatch({\n participant: step.participant,\n call: { method: call.method, path: resolveTemplate(call.path, scope) },\n commandId: sagaCommandId(\n sagaId,\n step.id,\n step.fanOut ? index : undefined,\n ),\n organizationId: input.organizationId,\n body:\n call.method === 'GET' || call.method === 'DELETE'\n ? undefined\n : resolveBodyTemplate(input.body, scope),\n });\n });\n\n/**\n * Run one step: every call it makes, in order, stopping at the first refusal.\n *\n * Returns the calls that **succeeded** alongside the failure, because those are\n * exactly the calls a compensation has to undo — see {@link compensateStep}.\n */\nconst runStep = (\n step: SagaStep,\n sagaId: string,\n elements: readonly DerivedElement[],\n): Effect.Effect<\n { readonly calls: readonly SagaCallOutcome[]; readonly error?: string },\n EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n const calls: SagaCallOutcome[] = [];\n\n for (const [index, element] of elements.entries()) {\n const { input } = element;\n const response = yield* dispatchCall(\n step,\n step.command,\n sagaId,\n index,\n input,\n element.scope,\n );\n\n if (!response.ok) {\n // A business refusal. The saga fails *forward* into compensation, and\n // the calls already recorded are the ones that have to come back.\n return {\n calls,\n error: `step '${step.id}' call ${String(index)} refused with ${String(\n response.status,\n )}`,\n };\n }\n\n calls.push({\n index,\n status: response.status,\n body: response.body,\n // Carried so the compensation reaches the same tenant. Without it a\n // release is refused `400` and the saga strands holding stock.\n organizationId: input.organizationId,\n });\n }\n\n return { calls };\n });\n\n/**\n * Undo one step — **one compensation per successful call**, never one per step.\n *\n * ⚠️ This is the whole reason an outcome is kept per fan-out element. Five lines\n * with three holds taken and the fourth refused must release exactly three:\n * compensating the step as a unit would either release nothing or attempt to\n * release two holds that were never taken\n * ([ADR 0052](../../../../../../docs/adr/0052-the-checkout-saga.md)).\n *\n * Never fails: a compensation's own failure is reported by the caller and must\n * not stop the compensations after it, for the reason ADR 0039 gives — a\n * stranded saga nobody is told about is the same as a lost one.\n */\nconst compensateStep = (\n step: SagaStep,\n sagaId: string,\n outcome: SagaStepOutcome,\n): Effect.Effect<readonly string[], never, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const compensation = step.compensation;\n if (!compensation) {\n return [];\n }\n\n const failures: string[] = [];\n // Reverse order: the last thing done is the first thing undone, which is\n // what a reader expects of a stack of effects and what keeps a future\n // ordering dependency from being an accident.\n for (const call of [...outcome.calls].reverse()) {\n const result = yield* dispatchCall(\n step,\n compensation,\n sagaId,\n call.index,\n // ⚠️ The organization the *call* acted for, not an empty input. A\n // tenant-plane participant resolves its handle from the header, so a\n // compensation without it is refused before it reaches the hold.\n { organizationId: call.organizationId },\n { outcome: call.body },\n ).pipe(\n Effect.catch(error =>\n Effect.succeed({ ok: false, status: 0, body: error }),\n ),\n // A template that no longer matches the participant's response shape\n // throws rather than interpolating `undefined`; that is a defect, and\n // it is reported as a stranded compensation rather than crashing the\n // walk and leaving every later hold in place.\n Effect.catchDefect(defect =>\n Effect.succeed({ ok: false, status: 0, body: defect }),\n ),\n );\n\n // ⚠️ **A `404` is a compensation that has nothing left to undo**, and it\n // counts as success. Compensation is at-least-once the moment a resumed\n // coordinator can retry it, and a participant answering \"no such record\"\n // on the second delivery is describing a flow that *was* reversed. Left\n // as a refusal it strands exactly the sagas that were cleaned up\n // correctly, which is the failure ADR 0054 named on the conversion route\n // and is the same one from the other side.\n if (!result.ok && result.status !== 404) {\n failures.push(\n `compensation for '${step.id}' call ${String(call.index)} failed: ${String(\n result.body,\n )}`,\n );\n }\n }\n\n return failures;\n });\n\n/**\n * How many extra times a step is dispatched once the pivot has committed.\n *\n * Small and immediate on purpose. This is the in-process half of \"roll forward\",\n * and it exists to ride out the blip — a participant restarting, a connection\n * reset — not to be a retry policy. A step that is still refusing after these\n * strands the saga, loudly, because the alternative is a coordinator spinning on\n * a permanent failure while a customer's money sits captured.\n *\n * Durable retry across a coordinator restart is a different mechanism and is not\n * built: see #233, which makes a step dispatch an outbox entry whose relay\n * performs the POST.\n */\nconst POST_PIVOT_RETRIES = 3;\n\n/**\n * Dispatch a step, retrying it `retries` more times while it refuses.\n *\n * ⚠️ **A retry re-dispatches the calls that already succeeded**, and that is\n * safe for exactly one reason: `sagaCommandId(sagaId, step.id, index)` is stable\n * across attempts, so a participant that is idempotent on the command id\n * recognises the replay. ADR 0052 states that requirement on the participant;\n * this is the code that depends on it.\n */\nconst runStepWithRetries = (\n step: SagaStep,\n sagaId: string,\n elements: readonly DerivedElement[],\n retries: number,\n): Effect.Effect<\n { readonly calls: readonly SagaCallOutcome[]; readonly error?: string },\n EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n let result = yield* runStep(step, sagaId, elements);\n\n for (\n let attempt = 1;\n attempt <= retries && result.error !== undefined;\n attempt += 1\n ) {\n yield* Effect.logWarning('retrying a saga step after the pivot').pipe(\n Effect.annotateLogs({\n sagaId,\n stepId: step.id,\n attempt,\n error: result.error,\n }),\n );\n result = yield* runStep(step, sagaId, elements);\n }\n\n return result;\n });\n\n/** Pair each recorded outcome with the step that produced it. */\nconst rebuildTaken = (\n definition: SagaDefinition,\n outcomes: readonly SagaStepOutcome[],\n): Taken | { readonly unknownStep: string } => {\n const taken: Taken = [];\n for (const outcome of outcomes) {\n const step = definition.steps.find(\n candidate => candidate.id === outcome.stepId,\n );\n // ⚠️ Not skipped. An outcome naming a step the definition no longer has\n // means the definition changed under a live instance, so the flow this\n // record describes and the flow the engine would walk are different flows.\n // Carrying on would compensate the wrong steps in the wrong order.\n if (!step) {\n return { unknownStep: outcome.stepId };\n }\n taken.push({ step, outcome });\n }\n return taken;\n};\n\n/** Whether the point of no return is behind us, read off what actually ran. */\nconst pivotCommittedIn = (taken: Taken): boolean =>\n taken.some(\n entry => entry.step.kind === 'pivot' && entry.outcome.error === undefined,\n );\n\n/**\n * Settle a saga that cannot go forward and cannot be reversed, loudly.\n *\n * ⚠️ The message is a parameter because these are **different operational\n * events** and each is grepped for on its own: money is captured behind a\n * pivot, a release was refused and stock is still held, a definition changed\n * under a live instance. Collapsing them into one string would make the log\n * line say only that something is wrong.\n */\nconst strand = (\n store: SagaStore,\n sagaId: string,\n outcomes: readonly SagaStepOutcome[],\n error: string,\n message: string,\n log: Record<string, unknown>,\n) =>\n Effect.gen(function* () {\n yield* Effect.logError(message).pipe(\n Effect.annotateLogs({ sagaId, error, ...log }),\n );\n yield* store.settle(sagaId, 'STRANDED', error);\n return { state: 'STRANDED', outcomes, error } as const;\n });\n\n/**\n * Unwind every compensatable step already taken, newest first.\n *\n * Shared by the in-process walk and by a resumed one, which is the whole reason\n * it is a function: a coordinator that died *while* compensating comes back\n * into exactly this loop, and the steps it already gave back carry\n * `compensated` so they are not given back twice.\n */\nconst unwind = (\n store: SagaStore,\n sagaId: string,\n definition: SagaDefinition,\n taken: Taken,\n error: string,\n): Effect.Effect<SagaResult, EntifixConnError, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const outcomes = taken.map(entry => entry.outcome);\n const failures: string[] = [];\n\n for (const done of [...taken].reverse()) {\n if (done.outcome.compensated === true) {\n continue;\n }\n const stepFailures = yield* compensateStep(\n done.step,\n sagaId,\n done.outcome,\n );\n failures.push(...stepFailures);\n // Marked only when the step came back whole. A partial failure stays\n // unmarked so a later resume retries it — safe because a compensation\n // with nothing left to undo answers `404`, which is a success above.\n if (stepFailures.length === 0) {\n yield* store.markCompensated(sagaId, done.step.id);\n }\n }\n\n if (failures.length > 0) {\n // ⚠️ Surfaced, never swallowed. This is the state that leaves a\n // reservation held and — once payment lands — a customer charged, and\n // ADR 0039 names it as the failure class nobody plans for.\n return yield* strand(\n store,\n sagaId,\n outcomes,\n error,\n 'saga compensation failed',\n { definition: definition.name, failures: failures.join('; ') },\n );\n }\n\n yield* store.settle(sagaId, 'COMPENSATED', error);\n return { state: 'COMPENSATED', outcomes, error };\n });\n\n/**\n * Dispatch the definition's steps from `startIndex` on, and unwind on a refusal.\n *\n * The state transition is persisted **before** each dispatch, so a crash leaves\n * a record that says what was actually attempted (ADR 0028, extended to\n * commands by ADR 0039).\n *\n * ⚠️ **Once the pivot has committed, nothing is unwound.** That is what a pivot\n * means, and the walk has to know it rather than the definition merely declaring\n * it: `compensateStep` no-ops on a step that declares no compensation, so an\n * unconditional unwind after a successful capture would skip the pivot in\n * silence and then delete the order behind it and release the holds behind that\n * — money taken, goods back on sale, every probe green. The step is retried\n * instead, and a saga that still cannot go forward is settled `STRANDED` and\n * logged, because ADR 0039 is explicit that a stranded saga nobody is told about\n * is the same as a lost one.\n */\nconst walk = (\n store: SagaStore,\n options: RunSagaOptions,\n from: { readonly taken: Taken; readonly startIndex: number },\n): Effect.Effect<SagaResult, EntifixConnError, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const { sagaId, definition, inputs } = options;\n // Step and outcome are kept **together**: looking the step back up by id\n // would introduce a not-found branch that cannot happen, and an unreachable\n // branch is a line nothing can ever prove correct.\n const taken = from.taken;\n const outcomes = () => taken.map(entry => entry.outcome);\n\n // The point of no return, once it is behind us. Tracked rather than read off\n // the definition because what matters is not that a pivot exists but that it\n // *committed* — a pivot that refuses is still fully reversible, and is the\n // ordinary compensation case below.\n let pivotCommitted = pivotCommittedIn(taken);\n\n for (\n let index = from.startIndex;\n index < definition.steps.length;\n index++\n ) {\n const step = definition.steps[index];\n /* v8 ignore next 3 -- the loop bound makes this unreachable; it exists\n because `noUncheckedIndexedAccess` cannot see that. */\n if (!step) {\n continue;\n }\n\n yield* store.beginStep(sagaId, index);\n const { calls, error } = yield* runStepWithRetries(\n step,\n sagaId,\n elementsFor(step, inputs, taken),\n pivotCommitted ? POST_PIVOT_RETRIES : 0,\n );\n\n const outcome: SagaStepOutcome = {\n stepId: step.id,\n calls,\n ...(error === undefined ? {} : { error }),\n };\n taken.push({ step, outcome });\n yield* store.recordOutcome(sagaId, outcome);\n\n if (error === undefined) {\n if (step.kind === 'pivot') {\n pivotCommitted = true;\n }\n continue;\n }\n\n if (pivotCommitted) {\n // ⚠️ Forward or nowhere. Compensating from here would undo steps whose\n // effects the pivot has already been paid for.\n return yield* strand(\n store,\n sagaId,\n outcomes(),\n error,\n 'saga stranded after the pivot',\n { definition: definition.name, stepId: step.id },\n );\n }\n\n // Unwind. The failing step's own successful calls are compensated too —\n // a fan-out step that took three holds before its fourth was refused has\n // three to give back.\n yield* store.settle(sagaId, 'COMPENSATING', error);\n return yield* unwind(store, sagaId, definition, taken, error);\n }\n\n yield* store.settle(sagaId, 'COMPLETED');\n return { state: 'COMPLETED', outcomes: outcomes() };\n });\n\n/**\n * Start a flow and walk it to a terminal state.\n *\n * ⚠️ **Synchronous, and that is the buyer's requirement.** A checkout needs a\n * yes/no now, so this answers the settled result. What {@link resumeSaga} adds\n * is durability *behind* that answer: if this process dies mid-walk, the record\n * it has been writing all along is enough for another one to finish the flow.\n */\nexport const runSaga = (\n options: RunSagaOptions,\n): Effect.Effect<\n SagaResult,\n EntifixConnError,\n SagaDispatcherTag | SagaStoreTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const { sagaId, definition, inputs } = options;\n\n yield* store.start({\n sagaId,\n definition: definition.name,\n state: 'RUNNING',\n stepIndex: 0,\n outcomes: [],\n // ⚠️ Persisted, because a resume has nothing to dispatch without it: a\n // fan-out step's cardinality *is* its input's length (ADR 0055).\n inputs,\n resumeAttempts: 0,\n createdAt: new Date().toISOString(),\n });\n\n return yield* walk(store, options, { taken: [], startIndex: 0 });\n });\n\nexport interface ResumeSagaOptions {\n readonly instance: SagaInstance;\n readonly definition: SagaDefinition;\n /** Past this many sweeps, the instance is surfaced instead of retried. */\n readonly maxResumeAttempts: number;\n}\n\n/**\n * Finish a flow another coordinator abandoned.\n *\n * ⚠️ **Where to re-enter is derived, never stored.** A resume point written\n * beside the outcomes would be a second record of the same fact, free to\n * disagree with them; the outcomes already say what happened, and\n * `beginStep`-before-dispatch means `stepIndex` says what was attempted. The\n * four cases are exhaustive:\n *\n * - the step at `stepIndex` recorded no outcome — the process died during the\n * dispatch, so **re-dispatch it**. Safe because `sagaCommandId` is stable\n * across attempts and every participant claims it in its own command inbox,\n * so calls that did land are recognised as replays rather than repeated\n * (ADR 0052).\n * - it recorded a successful outcome — the process died between\n * `recordOutcome` and the next `beginStep`, so **start at the one after**.\n * - it recorded a refusal — the process died deciding what to do about it, so\n * **re-enter that decision**: unwind, or strand if the pivot had committed.\n * - the instance is `COMPENSATING` — it died mid-unwind, so **continue the\n * unwind**, skipping steps already marked `compensated`.\n */\nexport const resumeSaga = (\n options: ResumeSagaOptions,\n): Effect.Effect<\n SagaResult,\n EntifixConnError,\n SagaDispatcherTag | SagaStoreTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const { instance, definition, maxResumeAttempts } = options;\n const { sagaId, outcomes } = instance;\n\n if (instance.resumeAttempts > maxResumeAttempts) {\n // Surfaced rather than retried forever. A coordinator spinning on a\n // permanent failure is how money stays captured with nobody told.\n return yield* strand(\n store,\n sagaId,\n outcomes,\n instance.error ??\n `resumed ${String(instance.resumeAttempts - 1)} times without settling`,\n 'saga abandoned after too many resumes',\n {\n definition: definition.name,\n resumeAttempts: instance.resumeAttempts,\n },\n );\n }\n\n const rebuilt = rebuildTaken(definition, outcomes);\n if ('unknownStep' in rebuilt) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n `recorded step '${rebuilt.unknownStep}' is not in definition '${definition.name}'`,\n 'saga instance does not match its definition',\n { definition: definition.name },\n );\n }\n\n const resumeOptions: RunSagaOptions = {\n sagaId,\n definition,\n inputs: instance.inputs,\n };\n\n if (instance.state === 'COMPENSATING') {\n return yield* unwind(\n store,\n sagaId,\n definition,\n rebuilt,\n instance.error ?? 'compensation resumed',\n );\n }\n\n const step = definition.steps[instance.stepIndex];\n if (!step) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n `step ${String(instance.stepIndex)} is not in definition '${definition.name}'`,\n 'saga instance does not match its definition',\n { definition: definition.name },\n );\n }\n\n const recorded = rebuilt.find(entry => entry.step.id === step.id);\n\n if (recorded === undefined) {\n return yield* walk(store, resumeOptions, {\n taken: rebuilt,\n startIndex: instance.stepIndex,\n });\n }\n\n if (recorded.outcome.error === undefined) {\n return yield* walk(store, resumeOptions, {\n taken: rebuilt,\n startIndex: instance.stepIndex + 1,\n });\n }\n\n const error = recorded.outcome.error;\n if (pivotCommittedIn(rebuilt)) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n error,\n 'saga stranded after the pivot',\n { definition: definition.name, stepId: step.id },\n );\n }\n\n yield* store.settle(sagaId, 'COMPENSATING', error);\n return yield* unwind(store, sagaId, definition, rebuilt, error);\n });\n"],"names":["Effect","sagaCommandId","SagaDispatcherTag","SagaStoreTag","resolveBodyTemplate","resolveTemplate","inputsFor","step","inputs","declared","id","fanOut","stepsScope","taken","Object","fromEntries","filter","entry","outcome","calls","length","map","body","elementsFor","steps","fanOutFrom","undefined","input","scope","source","find","call","organizationId","dispatchCall","sagaId","index","gen","dispatcher","dispatch","participant","method","path","commandId","runStep","elements","element","entries","response","command","ok","error","String","status","push","compensateStep","compensation","failures","reverse","result","pipe","catch","succeed","catchDefect","defect","POST_PIVOT_RETRIES","runStepWithRetries","retries","attempt","logWarning","annotateLogs","stepId","rebuildTaken","definition","outcomes","candidate","unknownStep","pivotCommittedIn","some","kind","strand","store","message","log","logError","settle","state","unwind","done","compensated","stepFailures","markCompensated","name","join","walk","options","from","pivotCommitted","startIndex","beginStep","recordOutcome","runSaga","start","stepIndex","resumeAttempts","createdAt","Date","toISOString","resumeSaga","instance","maxResumeAttempts","rebuilt","resumeOptions","recorded"],"mappings":";AACA,SAASA,MAAM,QAAQ,SAAS;AAEhC,SAGEC,aAAa,QAMR,kCAAkC;AACzC,SAASC,iBAAiB,QAAQ,8BAA8B;AAChE,SAGEC,YAAY,QACP,yBAAyB;AAChC,SAASC,mBAAmB,EAAEC,eAAe,QAAQ,wBAAwB;AAwC7E,MAAMC,YAAY,CAChBC,MACAC;QAEiBA,iBAGgBC;IAHjC,MAAMA,YAAWD,kBAAAA,MAAM,CAACD,KAAKG,EAAE,CAAC,YAAfF,kBAAmB,EAAE;IACtC,2EAA2E;IAC3E,yEAAyE;IACzE,OAAOD,KAAKI,MAAM,GAAGF,WAAW;SAACA,aAAAA,QAAQ,CAAC,EAAE,YAAXA,aAAe,CAA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uC,UACAvB,OACA,iCACA;gBAAEsB,YAAYA,WAAWmB,IAAI;gBAAErB,QAAQ/D,KAAKG,EAAE;YAAC;QAEnD;QAEA,OAAOsE,MAAMI,MAAM,CAAClD,QAAQ,gBAAgBgB;QAC5C,OAAO,OAAOoC,OAAON,OAAO9C,QAAQsC,YAAYsC,SAAS5D;IAC3D,GAAG"}
|
|
1
|
+
{"version":3,"sources":["../../src/engine/run-saga.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Effect } from 'effect';\n\nimport {\n type SagaCall,\n type SagaCallOutcome,\n sagaCommandId,\n type SagaDefinition,\n type SagaInputs,\n type SagaStep,\n type SagaStepInput,\n type SagaStepOutcome,\n} from '../contracts/saga-definition.js';\nimport { SagaDispatcherTag } from '../ports/saga-dispatcher.js';\nimport {\n type SagaInstance,\n type SagaStore,\n SagaStoreTag,\n} from '../ports/saga-store.js';\nimport { resolveBodyTemplate, resolveTemplate } from './resolve-template.js';\n\nexport type { SagaInputs, SagaStepInput };\n\n/**\n * The steps that have run, kept with their outcomes.\n *\n * Paired rather than looked back up by id, because a lookup introduces a\n * not-found branch that cannot happen — and an unreachable branch is a line\n * nothing can ever prove correct. A resumed walk rebuilds this from the stored\n * outcomes, which is the one place the lookup does happen and can genuinely\n * fail.\n */\ntype Taken = Array<{ step: SagaStep; outcome: SagaStepOutcome }>;\n\nexport interface RunSagaOptions {\n readonly sagaId: string;\n readonly definition: SagaDefinition;\n readonly inputs: SagaInputs;\n}\n\n/** How a run ended. */\nexport interface SagaResult {\n readonly state: 'COMPLETED' | 'COMPENSATED' | 'STRANDED';\n readonly outcomes: readonly SagaStepOutcome[];\n readonly error?: string;\n}\n\n/**\n * What one element of a `fanOutFrom` step is dispatched with.\n *\n * The earlier call's body travels as `outcome` rather than `input`, which is the\n * same scope a compensation resolves against and for the same reason: the id\n * being addressed was minted by the participant and is in its response.\n */\ninterface DerivedElement {\n readonly input: SagaStepInput;\n readonly scope: Record<string, unknown>;\n}\n\nconst inputsFor = (\n step: SagaStep,\n inputs: SagaInputs,\n): readonly SagaStepInput[] => {\n const declared = inputs[step.id] ?? [];\n // A non-fan-out step makes exactly one call whether or not it was given an\n // input, so an absent entry is an empty body rather than a skipped step.\n return step.fanOut ? declared : [declared[0] ?? {}];\n};\n\n/**\n * The elements a step actually dispatches: derived from an earlier step's\n * successful calls when it declares `fanOutFrom`, and from the caller's input\n * otherwise.\n *\n * ⚠️ **A `fanOutFrom` step ignores whatever the caller supplied for it.** The\n * cardinality is the earlier step's, and taking the caller's would let a\n * checkout convert a hold it never took — or, more likely, silently convert\n * none, which is how a saga reports COMPLETED with the goods still held.\n */\n/**\n * What every step can point at: the **first successful call** of each step that\n * has already run, by step id.\n *\n * First rather than all, because a template naming a fan-out step is ambiguous\n * by construction — \"the order id\" is one value and \"the reservation ids\" are\n * many, and the many case is what `fanOutFrom` exists for. Keeping this to the\n * unambiguous case is what stops `{steps.reserve.data.id}` quietly meaning\n * \"whichever hold happened to be first\".\n */\nconst stepsScope = (\n taken: ReadonlyArray<{ step: SagaStep; outcome: SagaStepOutcome }>,\n): Record<string, unknown> =>\n Object.fromEntries(\n taken\n .filter(entry => entry.outcome.calls.length > 0)\n .map(entry => [entry.step.id, entry.outcome.calls[0]?.body]),\n );\n\nconst elementsFor = (\n step: SagaStep,\n inputs: SagaInputs,\n taken: ReadonlyArray<{ step: SagaStep; outcome: SagaStepOutcome }>,\n): readonly DerivedElement[] => {\n const steps = stepsScope(taken);\n\n if (step.fanOutFrom === undefined) {\n return inputsFor(step, inputs).map(input => ({\n input,\n scope: { input: input.body, steps },\n }));\n }\n\n const source = taken.find(entry => entry.step.id === step.fanOutFrom);\n const body = inputs[step.id]?.[0]?.body;\n\n return (source?.outcome.calls ?? []).map(call => ({\n // ⚠️ The organization the *earlier call* acted for, never the caller's.\n // A tenant-plane participant resolves its handle from the header, so a\n // conversion dispatched without it is refused `400` and the hold expires\n // under a buyer who has already been charged.\n input: { body, organizationId: call.organizationId },\n scope: { outcome: call.body, input: body, steps },\n }));\n};\n\nconst dispatchCall = (\n step: SagaStep,\n call: SagaCall,\n sagaId: string,\n index: number,\n input: SagaStepInput,\n scope: Record<string, unknown>,\n) =>\n Effect.gen(function* () {\n const dispatcher = yield* SagaDispatcherTag;\n return yield* dispatcher.dispatch({\n participant: step.participant,\n call: { method: call.method, path: resolveTemplate(call.path, scope) },\n commandId: sagaCommandId(\n sagaId,\n step.id,\n step.fanOut ? index : undefined,\n ),\n organizationId: input.organizationId,\n body:\n call.method === 'GET' || call.method === 'DELETE'\n ? undefined\n : resolveBodyTemplate(input.body, scope),\n });\n });\n\n/**\n * Run one step: every call it makes, in order, stopping at the first refusal.\n *\n * Returns the calls that **succeeded** alongside the failure, because those are\n * exactly the calls a compensation has to undo — see {@link compensateStep}.\n */\nconst runStep = (\n step: SagaStep,\n sagaId: string,\n elements: readonly DerivedElement[],\n): Effect.Effect<\n { readonly calls: readonly SagaCallOutcome[]; readonly error?: string },\n EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n const calls: SagaCallOutcome[] = [];\n\n for (const [index, element] of elements.entries()) {\n const { input } = element;\n const response = yield* dispatchCall(\n step,\n step.command,\n sagaId,\n index,\n input,\n element.scope,\n );\n\n if (!response.ok) {\n // A business refusal. The saga fails *forward* into compensation, and\n // the calls already recorded are the ones that have to come back.\n return {\n calls,\n error: `step '${step.id}' call ${String(index)} refused with ${String(\n response.status,\n )}`,\n };\n }\n\n calls.push({\n index,\n status: response.status,\n body: response.body,\n // Carried so the compensation reaches the same tenant. Without it a\n // release is refused `400` and the saga strands holding stock.\n organizationId: input.organizationId,\n });\n }\n\n return { calls };\n });\n\n/**\n * Undo one step — **one compensation per successful call**, never one per step.\n *\n * ⚠️ This is the whole reason an outcome is kept per fan-out element. Five lines\n * with three holds taken and the fourth refused must release exactly three:\n * compensating the step as a unit would either release nothing or attempt to\n * release two holds that were never taken.\n *\n * Never fails: a compensation's own failure is reported by the caller and must\n * not stop the compensations after it, because a stranded saga nobody is told about is the same as a lost one.\n */\nconst compensateStep = (\n step: SagaStep,\n sagaId: string,\n outcome: SagaStepOutcome,\n): Effect.Effect<readonly string[], never, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const compensation = step.compensation;\n if (!compensation) {\n return [];\n }\n\n const failures: string[] = [];\n // Reverse order: the last thing done is the first thing undone, which is\n // what a reader expects of a stack of effects and what keeps a future\n // ordering dependency from being an accident.\n for (const call of [...outcome.calls].reverse()) {\n const result = yield* dispatchCall(\n step,\n compensation,\n sagaId,\n call.index,\n // ⚠️ The organization the *call* acted for, not an empty input. A\n // tenant-plane participant resolves its handle from the header, so a\n // compensation without it is refused before it reaches the hold.\n { organizationId: call.organizationId },\n { outcome: call.body },\n ).pipe(\n Effect.catch(error =>\n Effect.succeed({ ok: false, status: 0, body: error }),\n ),\n // A template that no longer matches the participant's response shape\n // throws rather than interpolating `undefined`; that is a defect, and\n // it is reported as a stranded compensation rather than crashing the\n // walk and leaving every later hold in place.\n Effect.catchDefect(defect =>\n Effect.succeed({ ok: false, status: 0, body: defect }),\n ),\n );\n\n // ⚠️ **A `404` is a compensation that has nothing left to undo**, and it\n // counts as success. Compensation is at-least-once the moment a resumed\n // coordinator can retry it, and a participant answering \"no such record\"\n // on the second delivery is describing a flow that *was* reversed. Left\n // as a refusal it strands exactly the sagas that were cleaned up\n // correctly — the same failure a conversion route that refuses a\n // redelivery has, from the other side.\n if (!result.ok && result.status !== 404) {\n failures.push(\n `compensation for '${step.id}' call ${String(call.index)} failed: ${String(\n result.body,\n )}`,\n );\n }\n }\n\n return failures;\n });\n\n/**\n * How many extra times a step is dispatched once the pivot has committed.\n *\n * Small and immediate on purpose. This is the in-process half of \"roll forward\",\n * and it exists to ride out the blip — a participant restarting, a connection\n * reset — not to be a retry policy. A step that is still refusing after these\n * strands the saga, loudly, because the alternative is a coordinator spinning on\n * a permanent failure while a customer's money sits captured.\n *\n * Durable retry across a coordinator restart is a different mechanism and is not\n * built: the alternative makes a step dispatch an outbox entry whose relay\n * performs the POST.\n */\nconst POST_PIVOT_RETRIES = 3;\n\n/**\n * Dispatch a step, retrying it `retries` more times while it refuses.\n *\n * ⚠️ **A retry re-dispatches the calls that already succeeded**, and that is\n * safe for exactly one reason: `sagaCommandId(sagaId, step.id, index)` is stable\n * across attempts, so a participant that is idempotent on the command id\n * recognises the replay. That is a requirement on every participant a saga may\n * retry; this is the code that depends on it.\n */\nconst runStepWithRetries = (\n step: SagaStep,\n sagaId: string,\n elements: readonly DerivedElement[],\n retries: number,\n): Effect.Effect<\n { readonly calls: readonly SagaCallOutcome[]; readonly error?: string },\n EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n let result = yield* runStep(step, sagaId, elements);\n\n for (\n let attempt = 1;\n attempt <= retries && result.error !== undefined;\n attempt += 1\n ) {\n yield* Effect.logWarning('retrying a saga step after the pivot').pipe(\n Effect.annotateLogs({\n sagaId,\n stepId: step.id,\n attempt,\n error: result.error,\n }),\n );\n result = yield* runStep(step, sagaId, elements);\n }\n\n return result;\n });\n\n/** Pair each recorded outcome with the step that produced it. */\nconst rebuildTaken = (\n definition: SagaDefinition,\n outcomes: readonly SagaStepOutcome[],\n): Taken | { readonly unknownStep: string } => {\n const taken: Taken = [];\n for (const outcome of outcomes) {\n const step = definition.steps.find(\n candidate => candidate.id === outcome.stepId,\n );\n // ⚠️ Not skipped. An outcome naming a step the definition no longer has\n // means the definition changed under a live instance, so the flow this\n // record describes and the flow the engine would walk are different flows.\n // Carrying on would compensate the wrong steps in the wrong order.\n if (!step) {\n return { unknownStep: outcome.stepId };\n }\n taken.push({ step, outcome });\n }\n return taken;\n};\n\n/** Whether the point of no return is behind us, read off what actually ran. */\nconst pivotCommittedIn = (taken: Taken): boolean =>\n taken.some(\n entry => entry.step.kind === 'pivot' && entry.outcome.error === undefined,\n );\n\n/**\n * Settle a saga that cannot go forward and cannot be reversed, loudly.\n *\n * ⚠️ The message is a parameter because these are **different operational\n * events** and each is grepped for on its own: money is captured behind a\n * pivot, a release was refused and stock is still held, a definition changed\n * under a live instance. Collapsing them into one string would make the log\n * line say only that something is wrong.\n */\nconst strand = (\n store: SagaStore,\n sagaId: string,\n outcomes: readonly SagaStepOutcome[],\n error: string,\n message: string,\n log: Record<string, unknown>,\n) =>\n Effect.gen(function* () {\n yield* Effect.logError(message).pipe(\n Effect.annotateLogs({ sagaId, error, ...log }),\n );\n yield* store.settle(sagaId, 'STRANDED', error);\n return { state: 'STRANDED', outcomes, error } as const;\n });\n\n/**\n * Unwind every compensatable step already taken, newest first.\n *\n * Shared by the in-process walk and by a resumed one, which is the whole reason\n * it is a function: a coordinator that died *while* compensating comes back\n * into exactly this loop, and the steps it already gave back carry\n * `compensated` so they are not given back twice.\n */\nconst unwind = (\n store: SagaStore,\n sagaId: string,\n definition: SagaDefinition,\n taken: Taken,\n error: string,\n): Effect.Effect<SagaResult, EntifixConnError, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const outcomes = taken.map(entry => entry.outcome);\n const failures: string[] = [];\n\n for (const done of [...taken].reverse()) {\n if (done.outcome.compensated === true) {\n continue;\n }\n const stepFailures = yield* compensateStep(\n done.step,\n sagaId,\n done.outcome,\n );\n failures.push(...stepFailures);\n // Marked only when the step came back whole. A partial failure stays\n // unmarked so a later resume retries it — safe because a compensation\n // with nothing left to undo answers `404`, which is a success above.\n if (stepFailures.length === 0) {\n yield* store.markCompensated(sagaId, done.step.id);\n }\n }\n\n if (failures.length > 0) {\n // ⚠️ Surfaced, never swallowed. This is the state that leaves a\n // reservation held and — once payment lands — a customer charged, and\n // it is the failure class nobody plans for.\n return yield* strand(\n store,\n sagaId,\n outcomes,\n error,\n 'saga compensation failed',\n { definition: definition.name, failures: failures.join('; ') },\n );\n }\n\n yield* store.settle(sagaId, 'COMPENSATED', error);\n return { state: 'COMPENSATED', outcomes, error };\n });\n\n/**\n * Dispatch the definition's steps from `startIndex` on, and unwind on a refusal.\n *\n * The state transition is persisted **before** each dispatch, so a crash leaves\n * a record that says what was actually attempted — the outbox's rule, extended\n * from events to commands.\n *\n * ⚠️ **Once the pivot has committed, nothing is unwound.** That is what a pivot\n * means, and the walk has to know it rather than the definition merely declaring\n * it: `compensateStep` no-ops on a step that declares no compensation, so an\n * unconditional unwind after a successful capture would skip the pivot in\n * silence and then delete the order behind it and release the holds behind that\n * — money taken, goods back on sale, every probe green. The step is retried\n * instead, and a saga that still cannot go forward is settled `STRANDED` and\n * logged, because a stranded saga nobody is told about is the same as a lost one.\n */\nconst walk = (\n store: SagaStore,\n options: RunSagaOptions,\n from: { readonly taken: Taken; readonly startIndex: number },\n): Effect.Effect<SagaResult, EntifixConnError, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const { sagaId, definition, inputs } = options;\n // Step and outcome are kept **together**: looking the step back up by id\n // would introduce a not-found branch that cannot happen, and an unreachable\n // branch is a line nothing can ever prove correct.\n const taken = from.taken;\n const outcomes = () => taken.map(entry => entry.outcome);\n\n // The point of no return, once it is behind us. Tracked rather than read off\n // the definition because what matters is not that a pivot exists but that it\n // *committed* — a pivot that refuses is still fully reversible, and is the\n // ordinary compensation case below.\n let pivotCommitted = pivotCommittedIn(taken);\n\n for (\n let index = from.startIndex;\n index < definition.steps.length;\n index++\n ) {\n const step = definition.steps[index];\n /* v8 ignore next 3 -- the loop bound makes this unreachable; it exists\n because `noUncheckedIndexedAccess` cannot see that. */\n if (!step) {\n continue;\n }\n\n yield* store.beginStep(sagaId, index);\n const { calls, error } = yield* runStepWithRetries(\n step,\n sagaId,\n elementsFor(step, inputs, taken),\n pivotCommitted ? POST_PIVOT_RETRIES : 0,\n );\n\n const outcome: SagaStepOutcome = {\n stepId: step.id,\n calls,\n ...(error === undefined ? {} : { error }),\n };\n taken.push({ step, outcome });\n yield* store.recordOutcome(sagaId, outcome);\n\n if (error === undefined) {\n if (step.kind === 'pivot') {\n pivotCommitted = true;\n }\n continue;\n }\n\n if (pivotCommitted) {\n // ⚠️ Forward or nowhere. Compensating from here would undo steps whose\n // effects the pivot has already been paid for.\n return yield* strand(\n store,\n sagaId,\n outcomes(),\n error,\n 'saga stranded after the pivot',\n { definition: definition.name, stepId: step.id },\n );\n }\n\n // Unwind. The failing step's own successful calls are compensated too —\n // a fan-out step that took three holds before its fourth was refused has\n // three to give back.\n yield* store.settle(sagaId, 'COMPENSATING', error);\n return yield* unwind(store, sagaId, definition, taken, error);\n }\n\n yield* store.settle(sagaId, 'COMPLETED');\n return { state: 'COMPLETED', outcomes: outcomes() };\n });\n\n/**\n * Start a flow and walk it to a terminal state.\n *\n * ⚠️ **Synchronous, and that is the buyer's requirement.** A checkout needs a\n * yes/no now, so this answers the settled result. What {@link resumeSaga} adds\n * is durability *behind* that answer: if this process dies mid-walk, the record\n * it has been writing all along is enough for another one to finish the flow.\n */\nexport const runSaga = (\n options: RunSagaOptions,\n): Effect.Effect<\n SagaResult,\n EntifixConnError,\n SagaDispatcherTag | SagaStoreTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const { sagaId, definition, inputs } = options;\n\n yield* store.start({\n sagaId,\n definition: definition.name,\n state: 'RUNNING',\n stepIndex: 0,\n outcomes: [],\n // ⚠️ Persisted, because a resume has nothing to dispatch without it: a\n // fan-out step's cardinality *is* its input's length.\n inputs,\n resumeAttempts: 0,\n createdAt: new Date().toISOString(),\n });\n\n return yield* walk(store, options, { taken: [], startIndex: 0 });\n });\n\nexport interface ResumeSagaOptions {\n readonly instance: SagaInstance;\n readonly definition: SagaDefinition;\n /** Past this many sweeps, the instance is surfaced instead of retried. */\n readonly maxResumeAttempts: number;\n}\n\n/**\n * Finish a flow another coordinator abandoned.\n *\n * ⚠️ **Where to re-enter is derived, never stored.** A resume point written\n * beside the outcomes would be a second record of the same fact, free to\n * disagree with them; the outcomes already say what happened, and\n * `beginStep`-before-dispatch means `stepIndex` says what was attempted. The\n * four cases are exhaustive:\n *\n * - the step at `stepIndex` recorded no outcome — the process died during the\n * dispatch, so **re-dispatch it**. Safe because `sagaCommandId` is stable\n * across attempts and every participant claims it in its own command inbox,\n * so calls that did land are recognised as replays rather than repeated.\n * - it recorded a successful outcome — the process died between\n * `recordOutcome` and the next `beginStep`, so **start at the one after**.\n * - it recorded a refusal — the process died deciding what to do about it, so\n * **re-enter that decision**: unwind, or strand if the pivot had committed.\n * - the instance is `COMPENSATING` — it died mid-unwind, so **continue the\n * unwind**, skipping steps already marked `compensated`.\n */\nexport const resumeSaga = (\n options: ResumeSagaOptions,\n): Effect.Effect<\n SagaResult,\n EntifixConnError,\n SagaDispatcherTag | SagaStoreTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const { instance, definition, maxResumeAttempts } = options;\n const { sagaId, outcomes } = instance;\n\n if (instance.resumeAttempts > maxResumeAttempts) {\n // Surfaced rather than retried forever. A coordinator spinning on a\n // permanent failure is how money stays captured with nobody told.\n return yield* strand(\n store,\n sagaId,\n outcomes,\n instance.error ??\n `resumed ${String(instance.resumeAttempts - 1)} times without settling`,\n 'saga abandoned after too many resumes',\n {\n definition: definition.name,\n resumeAttempts: instance.resumeAttempts,\n },\n );\n }\n\n const rebuilt = rebuildTaken(definition, outcomes);\n if ('unknownStep' in rebuilt) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n `recorded step '${rebuilt.unknownStep}' is not in definition '${definition.name}'`,\n 'saga instance does not match its definition',\n { definition: definition.name },\n );\n }\n\n const resumeOptions: RunSagaOptions = {\n sagaId,\n definition,\n inputs: instance.inputs,\n };\n\n if (instance.state === 'COMPENSATING') {\n return yield* unwind(\n store,\n sagaId,\n definition,\n rebuilt,\n instance.error ?? 'compensation resumed',\n );\n }\n\n const step = definition.steps[instance.stepIndex];\n if (!step) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n `step ${String(instance.stepIndex)} is not in definition '${definition.name}'`,\n 'saga instance does not match its definition',\n { definition: definition.name },\n );\n }\n\n const recorded = rebuilt.find(entry => entry.step.id === step.id);\n\n if (recorded === undefined) {\n return yield* walk(store, resumeOptions, {\n taken: rebuilt,\n startIndex: instance.stepIndex,\n });\n }\n\n if (recorded.outcome.error === undefined) {\n return yield* walk(store, resumeOptions, {\n taken: rebuilt,\n startIndex: instance.stepIndex + 1,\n });\n }\n\n const error = recorded.outcome.error;\n if (pivotCommittedIn(rebuilt)) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n error,\n 'saga stranded after the pivot',\n { definition: definition.name, stepId: step.id },\n );\n }\n\n yield* store.settle(sagaId, 'COMPENSATING', error);\n return yield* unwind(store, sagaId, definition, rebuilt, error);\n });\n"],"names":["Effect","sagaCommandId","SagaDispatcherTag","SagaStoreTag","resolveBodyTemplate","resolveTemplate","inputsFor","step","inputs","declared","id","fanOut","stepsScope","taken","Object","fromEntries","filter","entry","outcome","calls","length","map","body","elementsFor","steps","fanOutFrom","undefined","input","scope","source","find","call","organizationId","dispatchCall","sagaId","index","gen","dispatcher","dispatch","participant","method","path","commandId","runStep","elements","element","entries","response","command","ok","error","String","status","push","compensateStep","compensation","failures","reverse","result","pipe","catch","succeed","catchDefect","defect","POST_PIVOT_RETRIES","runStepWithRetries","retries","attempt","logWarning","annotateLogs","stepId","rebuildTaken","definition","outcomes","candidate","unknownStep","pivotCommittedIn","some","kind","strand","store","message","log","logError","settle","state","unwind","done","compensated","stepFailures","markCompensated","name","join","walk","options","from","pivotCommitted","startIndex","beginStep","recordOutcome","runSaga","start","stepIndex","resumeAttempts","createdAt","Date","toISOString","resumeSaga","instance","maxResumeAttempts","rebuilt","resumeOptions","recorded"],"mappings":";AACA,SAASA,MAAM,QAAQ,SAAS;AAEhC,SAGEC,aAAa,QAMR,kCAAkC;AACzC,SAASC,iBAAiB,QAAQ,8BAA8B;AAChE,SAGEC,YAAY,QACP,yBAAyB;AAChC,SAASC,mBAAmB,EAAEC,eAAe,QAAQ,wBAAwB;AAwC7E,MAAMC,YAAY,CAChBC,MACAC;QAEiBA,iBAGgBC;IAHjC,MAAMA,YAAWD,kBAAAA,MAAM,CAACD,KAAKG,EAAE,CAAC,YAAfF,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QACF;QAEA,MAAMpD,QAAQ8D,SAAS9F,OAAO,CAACgC,KAAK;QACpC,IAAI0B,iBAAiBkC,UAAU;YAC7B,OAAO,OAAO/B,OACZC,OACA9C,QACAuC,UACAvB,OACA,iCACA;gBAAEsB,YAAYA,WAAWmB,IAAI;gBAAErB,QAAQ/D,KAAKG,EAAE;YAAC;QAEnD;QAEA,OAAOsE,MAAMI,MAAM,CAAClD,QAAQ,gBAAgBgB;QAC5C,OAAO,OAAOoC,OAAON,OAAO9C,QAAQsC,YAAYsC,SAAS5D;IAC3D,GAAG"}
|
|
@@ -2,7 +2,7 @@ import type { DomainEvent, EntifixConnError, EntifixError } from '@entifix/core'
|
|
|
2
2
|
import { Context, type Effect } from 'effect';
|
|
3
3
|
/**
|
|
4
4
|
* How a subscriber's queue is shaped, which is a property of the *workload*
|
|
5
|
-
* rather than of the transport
|
|
5
|
+
* rather than of the transport.
|
|
6
6
|
*
|
|
7
7
|
* - `work` — a named, durable queue that survives the consumer's restart and
|
|
8
8
|
* accumulates while it is gone. Replicas share it, so each message reaches
|
|
@@ -13,7 +13,7 @@ import { Context, type Effect } from 'effect';
|
|
|
13
13
|
* only when the replicas differ from one another — a socket push holding
|
|
14
14
|
* different clients per process.
|
|
15
15
|
*
|
|
16
|
-
*
|
|
16
|
+
* The bus first built the exclusive queue for every subscriber, with a stated
|
|
17
17
|
* reason: a shared queue delivers each event to one replica, "which reads as
|
|
18
18
|
* flakiness rather than as a design". That reasoning is right for `broadcast`
|
|
19
19
|
* and wrong for `work`; it picked broadcast semantics for a workload that is
|
|
@@ -34,8 +34,7 @@ export interface Subscription {
|
|
|
34
34
|
* name.
|
|
35
35
|
*
|
|
36
36
|
* Deliberately not `EventSourceTag`, which is the *emitting* slice: one
|
|
37
|
-
* deployment
|
|
38
|
-
* marketplace-admin-service), so a process-wide "my slice" would attribute a
|
|
37
|
+
* deployment may host several slices, so a process-wide "my slice" would attribute a
|
|
39
38
|
* consumer's queue to whichever slice happened to publish from the same
|
|
40
39
|
* process.
|
|
41
40
|
*/
|
|
@@ -64,8 +63,8 @@ export interface Subscription {
|
|
|
64
63
|
* what happened; interested slices subscribe to the names they declared.
|
|
65
64
|
*
|
|
66
65
|
* Typed on {@link DomainEvent} rather than on any one publisher's payload: a bus
|
|
67
|
-
* that only knew `TransactionEvent` had nothing for
|
|
68
|
-
*
|
|
66
|
+
* that only knew `TransactionEvent` had nothing for a publication event to
|
|
67
|
+
* travel in, which would have meant a second framing and a second
|
|
69
68
|
* transport for the same job.
|
|
70
69
|
*
|
|
71
70
|
* The port stays event-typed rather than envelope-typed — the adapter owns the
|
|
@@ -87,7 +86,7 @@ export interface EventBus {
|
|
|
87
86
|
* retries — a message that cannot be deserialized never becomes
|
|
88
87
|
* deserializable, and retrying it only spends the budget of the messages
|
|
89
88
|
* behind it. A *business* failure is neither: that message was processed
|
|
90
|
-
* successfully and already produced its own event
|
|
89
|
+
* successfully and already produced its own event.
|
|
91
90
|
*/
|
|
92
91
|
subscribe(subscription: Subscription, handler: (event: DomainEvent) => Effect.Effect<void, EntifixError>): Effect.Effect<void, EntifixConnError>;
|
|
93
92
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-bus.d.ts","sourceRoot":"","sources":["../../src/ports/event-bus.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,gBAAgB,EAChB,YAAY,EACb,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,WAAW,CAAC;AAEpD;;;;;;;GAOG;AACH,MAAM,WAAW,YAAY;IAC3B
|
|
1
|
+
{"version":3,"file":"event-bus.d.ts","sourceRoot":"","sources":["../../src/ports/event-bus.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,gBAAgB,EAChB,YAAY,EACb,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,WAAW,CAAC;AAEpD;;;;;;;GAOG;AACH,MAAM,WAAW,YAAY;IAC3B;;;;;;;;OAQG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB;;;;;;OAMG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,EAAE,gBAAgB,CAAC;IAChC;;;;;;;OAOG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;CAC9B;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,QAAQ;IACvB,OAAO,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAC;IACnE;;;;;;;;;;;;;;OAcG;IACH,SAAS,CACP,YAAY,EAAE,YAAY,EAC1B,OAAO,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,GACjE,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAC;CAC1C;;AAED,qBAAa,WAAY,SAAQ,gBAEhC;CAAG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ports/event-bus.ts"],"sourcesContent":["import type {\n DomainEvent,\n EntifixConnError,\n EntifixError,\n} from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * How a subscriber's queue is shaped, which is a property of the *workload*\n * rather than of the transport
|
|
1
|
+
{"version":3,"sources":["../../src/ports/event-bus.ts"],"sourcesContent":["import type {\n DomainEvent,\n EntifixConnError,\n EntifixError,\n} from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * How a subscriber's queue is shaped, which is a property of the *workload*\n * rather than of the transport.\n *\n * - `work` — a named, durable queue that survives the consumer's restart and\n * accumulates while it is gone. Replicas share it, so each message reaches\n * exactly one of them. A projection writer, a fold and a settlement consumer\n * all want this.\n * - `broadcast` — a connection-scoped exclusive queue, so every replica\n * receives every message and nothing is retained across a restart. Correct\n * only when the replicas differ from one another — a socket push holding\n * different clients per process.\n *\n * The bus first built the exclusive queue for every subscriber, with a stated\n * reason: a shared queue delivers each event to one replica, \"which reads as\n * flakiness rather than as a design\". That reasoning is right for `broadcast`\n * and wrong for `work`; it picked broadcast semantics for a workload that is\n * work, at a time when the only subscriber made the difference invisible.\n */\nexport type SubscriptionMode = 'work' | 'broadcast';\n\n/**\n * A subscriber's declared interest, together with the delivery policy the\n * broker enforces for it.\n *\n * The shape mirrors `subscriptions` in `tools/slices/*.slice.ts`, so \"how does\n * this fail\" is answered where it can be checked rather than in a review\n * comment.\n */\nexport interface Subscription {\n /**\n * The **subscribing** slice — the `tools/slices/` key, and half of the queue\n * name.\n *\n * Deliberately not `EventSourceTag`, which is the *emitting* slice: one\n * deployment may host several slices, so a process-wide \"my slice\" would attribute a\n * consumer's queue to whichever slice happened to publish from the same\n * process.\n */\n readonly slice: string;\n /**\n * The event name pattern, used verbatim as the broker's binding —\n * `transaction.*`, `catalog.published`. Filtering in the handler instead is\n * what this exists to prevent: it makes every consumer pay for every\n * publisher's traffic, and it puts the routing rule where no register can\n * check it.\n */\n readonly pattern: string;\n readonly mode: SubscriptionMode;\n /**\n * How many times the broker may deliver a message before dead-lettering it.\n *\n * Enforced by the queue itself rather than by logic each consumer\n * reimplements, so it applies to a redelivery after a crash as well as to one\n * after a nack. `broadcast` queues have no dead-letter path, so the value is\n * carried but unenforced there.\n */\n readonly maxAttempts: number;\n}\n\n/**\n * The domain event bus (RabbitMQ in `@entifix/amqp`). Services publish\n * what happened; interested slices subscribe to the names they declared.\n *\n * Typed on {@link DomainEvent} rather than on any one publisher's payload: a bus\n * that only knew `TransactionEvent` had nothing for a publication event to\n * travel in, which would have meant a second framing and a second\n * transport for the same job.\n *\n * The port stays event-typed rather than envelope-typed — the adapter owns the\n * wire framing — so a handler receives the message and its metadata without\n * ever seeing the envelope that carried them.\n */\nexport interface EventBus {\n publish(event: DomainEvent): Effect.Effect<void, EntifixConnError>;\n /**\n * Register a consumer for the events matching `subscription.pattern`.\n *\n * The returned Effect completes once the subscription is established; the\n * handler then runs per delivered event. Delivery is at-least-once, so a\n * handler that is not idempotent must deduplicate on `event.id`.\n *\n * A handler failure is **transient**: the adapter requeues it and the broker\n * counts the redelivery against `maxAttempts`, dead-lettering at the limit. A\n * payload the adapter cannot read is **poison** and is quarantined with zero\n * retries — a message that cannot be deserialized never becomes\n * deserializable, and retrying it only spends the budget of the messages\n * behind it. A *business* failure is neither: that message was processed\n * successfully and already produced its own event.\n */\n subscribe(\n subscription: Subscription,\n handler: (event: DomainEvent) => Effect.Effect<void, EntifixError>,\n ): Effect.Effect<void, EntifixConnError>;\n}\n\nexport class EventBusTag extends Context.Service<EventBusTag, EventBus>()(\n 'EventBusTag',\n) {}\n"],"names":["Context","EventBusTag","Service"],"mappings":"AAKA,SAASA,OAAO,QAAqB,SAAS;AAkG9C,OAAO,MAAMC,oBAAoBD,QAAQE,OAAO,GAC9C;AACC"}
|
|
@@ -7,9 +7,9 @@ declare const EventSourceTag_base: Context.ServiceClass<EventSourceTag, "EventSo
|
|
|
7
7
|
* deployment: co-deploying two slices into one process is reversible, and a
|
|
8
8
|
* `source` that changed when a process moved would rewrite history for a fact
|
|
9
9
|
* that did not change. Not the domain either: a slice may hold several, so the
|
|
10
|
-
* domain does not identify the publisher. The slice is
|
|
11
|
-
*
|
|
12
|
-
*
|
|
10
|
+
* domain does not identify the publisher. The slice is the unit that owns a
|
|
11
|
+
* store, and a host that keeps a register of them can check it against what
|
|
12
|
+
* the bus actually carries.
|
|
13
13
|
*
|
|
14
14
|
* Provided at each composition root beside the other environment facts
|
|
15
15
|
* (`TenantDatabasePrefix`, `SagaDatabaseName`) rather than read from an
|
|
@@ -6,9 +6,9 @@ import { Context } from 'effect';
|
|
|
6
6
|
* deployment: co-deploying two slices into one process is reversible, and a
|
|
7
7
|
* `source` that changed when a process moved would rewrite history for a fact
|
|
8
8
|
* that did not change. Not the domain either: a slice may hold several, so the
|
|
9
|
-
* domain does not identify the publisher. The slice is
|
|
10
|
-
*
|
|
11
|
-
*
|
|
9
|
+
* domain does not identify the publisher. The slice is the unit that owns a
|
|
10
|
+
* store, and a host that keeps a register of them can check it against what
|
|
11
|
+
* the bus actually carries.
|
|
12
12
|
*
|
|
13
13
|
* Provided at each composition root beside the other environment facts
|
|
14
14
|
* (`TenantDatabasePrefix`, `SagaDatabaseName`) rather than read from an
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ports/event-source.ts"],"sourcesContent":["import { Context } from 'effect';\n\n/**\n * The name of the slice publishing an event — `marketplace-admin`, `order`.\n *\n * A **slice**, deliberately, and not one of the two nearer alternatives. Not the\n * deployment: co-deploying two slices into one process is reversible, and a\n * `source` that changed when a process moved would rewrite history for a fact\n * that did not change. Not the domain either: a slice may hold several, so the\n * domain does not identify the publisher. The slice is
|
|
1
|
+
{"version":3,"sources":["../../src/ports/event-source.ts"],"sourcesContent":["import { Context } from 'effect';\n\n/**\n * The name of the slice publishing an event — `marketplace-admin`, `order`.\n *\n * A **slice**, deliberately, and not one of the two nearer alternatives. Not the\n * deployment: co-deploying two slices into one process is reversible, and a\n * `source` that changed when a process moved would rewrite history for a fact\n * that did not change. Not the domain either: a slice may hold several, so the\n * domain does not identify the publisher. The slice is the unit that owns a\n * store, and a host that keeps a register of them can check it against what\n * the bus actually carries.\n *\n * Provided at each composition root beside the other environment facts\n * (`TenantDatabasePrefix`, `SagaDatabaseName`) rather than read from an\n * environment variable, so a service that forgets it fails to build its layer\n * instead of publishing events signed by nobody.\n */\nexport class EventSourceTag extends Context.Service<EventSourceTag, string>()(\n 'EventSourceTag',\n) {}\n"],"names":["Context","EventSourceTag","Service"],"mappings":"AAAA,SAASA,OAAO,QAAQ,SAAS;AAEjC;;;;;;;;;;;;;;;CAeC,GACD,OAAO,MAAMC,uBAAuBD,QAAQE,OAAO,GACjD;AACC"}
|
|
@@ -11,8 +11,8 @@ export interface SagaDispatch {
|
|
|
11
11
|
/**
|
|
12
12
|
* The organization this call acts for, when the participant is tenant-plane.
|
|
13
13
|
*
|
|
14
|
-
* Absent for a platform-plane participant. Present, it becomes
|
|
15
|
-
* `x-organization-id` — and it is safe only because the crossing token is
|
|
14
|
+
* Absent for a platform-plane participant. Present, it becomes the
|
|
15
|
+
* `x-organization-id` header — and it is safe only because the crossing token is
|
|
16
16
|
* checked first, so the input the caller controls is never the input that
|
|
17
17
|
* authorizes.
|
|
18
18
|
*/
|
|
@@ -26,8 +26,7 @@ export interface SagaDispatch {
|
|
|
26
26
|
* `409` from reserve is the business answer "not enough stock" and must fail the
|
|
27
27
|
* saga *forward* into compensation; a `503` is a participant that is down and
|
|
28
28
|
* the entry is retried. Collapsing the two either retries an out-of-stock line
|
|
29
|
-
* forever or permanently fails a checkout because a pod was restarting
|
|
30
|
-
* ([ADR 0052](../../../../../../docs/adr/0052-the-checkout-saga.md)).
|
|
29
|
+
* forever or permanently fails a checkout because a pod was restarting.
|
|
31
30
|
*
|
|
32
31
|
* So a `refused` response is a **success** of this port carrying `ok: false`,
|
|
33
32
|
* and only a transport or `5xx` failure is an `EntifixConnError`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"saga-dispatcher.d.ts","sourceRoot":"","sources":["../../src/ports/saga-dispatcher.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAEhE,sDAAsD;AACtD,MAAM,WAAW,YAAY;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Q,sBAGf;CAAG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ports/saga-dispatcher.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\nimport type { SagaCall } from '../contracts/saga-definition.js';\n\n/** One call the engine wants made, fully resolved. */\nexport interface SagaDispatch {\n /** The participant's configuration key — the dispatcher resolves the address. */\n readonly participant: string;\n readonly call: SagaCall;\n /** `<sagaId>:<stepId>[:<index>]`, which the participant claims. */\n readonly commandId: string;\n /**\n * The organization this call acts for, when the participant is tenant-plane.\n *\n * Absent for a platform-plane participant. Present, it becomes
|
|
1
|
+
{"version":3,"sources":["../../src/ports/saga-dispatcher.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\nimport type { SagaCall } from '../contracts/saga-definition.js';\n\n/** One call the engine wants made, fully resolved. */\nexport interface SagaDispatch {\n /** The participant's configuration key — the dispatcher resolves the address. */\n readonly participant: string;\n readonly call: SagaCall;\n /** `<sagaId>:<stepId>[:<index>]`, which the participant claims. */\n readonly commandId: string;\n /**\n * The organization this call acts for, when the participant is tenant-plane.\n *\n * Absent for a platform-plane participant. Present, it becomes the\n * `x-organization-id` header — and it is safe only because the crossing token is\n * checked first, so the input the caller controls is never the input that\n * authorizes.\n */\n readonly organizationId?: string;\n readonly body?: unknown;\n}\n\n/**\n * What a dispatched call answered.\n *\n * ⚠️ **A refusal is not a failure, and the split is the dispatcher's job.** A\n * `409` from reserve is the business answer \"not enough stock\" and must fail the\n * saga *forward* into compensation; a `503` is a participant that is down and\n * the entry is retried. Collapsing the two either retries an out-of-stock line\n * forever or permanently fails a checkout because a pod was restarting.\n *\n * So a `refused` response is a **success** of this port carrying `ok: false`,\n * and only a transport or `5xx` failure is an `EntifixConnError`.\n */\nexport interface SagaResponse {\n readonly ok: boolean;\n readonly status: number;\n readonly body: unknown;\n}\n\nexport interface SagaDispatcher {\n dispatch(\n dispatch: SagaDispatch,\n ): Effect.Effect<SagaResponse, EntifixConnError>;\n}\n\nexport class SagaDispatcherTag extends Context.Service<\n SagaDispatcherTag,\n SagaDispatcher\n>()('SagaDispatcherTag') {}\n"],"names":["Context","SagaDispatcherTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AA+C9C,OAAO,MAAMC,0BAA0BD,QAAQE,OAAO,GAGlD;AAAsB"}
|
|
@@ -7,8 +7,7 @@ import type { SagaInputs, SagaStepOutcome } from '../contracts/saga-definition.j
|
|
|
7
7
|
* `COMPENSATED` and `STRANDED` are deliberately different terminal states:
|
|
8
8
|
* "failed and reversed" and "failed with something still held" are the two
|
|
9
9
|
* outcomes an operator has to be able to tell apart, and a single `FAILED`
|
|
10
|
-
* would make the second look like the first
|
|
11
|
-
* ([ADR 0039](../../../../../../docs/adr/0039-multi-step-sagas-are-orchestrated.md)).
|
|
10
|
+
* would make the second look like the first.
|
|
12
11
|
*/
|
|
13
12
|
export declare const SAGA_STATES: readonly ["RUNNING", "COMPLETED", "COMPENSATING", "COMPENSATED", "STRANDED"];
|
|
14
13
|
export type SagaState = (typeof SAGA_STATES)[number];
|
|
@@ -29,15 +28,14 @@ export interface SagaInstance {
|
|
|
29
28
|
* than a report on one. Without it a resumed walk knows which step is next
|
|
30
29
|
* and has nothing to dispatch it with: a fan-out step's cardinality is its
|
|
31
30
|
* input's length, and a body template resolves against `inputs` before it
|
|
32
|
-
* resolves against earlier outcomes
|
|
33
|
-
* ([ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).
|
|
31
|
+
* resolves against earlier outcomes.
|
|
34
32
|
*/
|
|
35
33
|
readonly inputs: SagaInputs;
|
|
36
34
|
/**
|
|
37
35
|
* How many times a sweep has picked this instance up, which is the ceiling
|
|
38
36
|
* that stops a resume loop.
|
|
39
37
|
*
|
|
40
|
-
* It plays the part
|
|
38
|
+
* It plays the part `attempts` plays on an outbox entry, on the
|
|
41
39
|
* record that already exists rather than on a second one beside it. Past the
|
|
42
40
|
* ceiling the instance is settled `STRANDED` and logged — surfaced rather
|
|
43
41
|
* than retried forever, because a coordinator spinning on a permanent failure
|
|
@@ -54,14 +52,14 @@ export interface SagaInstance {
|
|
|
54
52
|
* A saga instance is a transaction's state with steps in it, so it belongs in
|
|
55
53
|
* the store that already holds transaction state — no new store, and the
|
|
56
54
|
* `transaction` slice keeps `domains: []`, because orchestration is a mechanism
|
|
57
|
-
* rather than a business domain
|
|
55
|
+
* rather than a business domain.
|
|
58
56
|
*/
|
|
59
57
|
export interface SagaStore {
|
|
60
58
|
start(instance: Omit<SagaInstance, 'updatedAt'>): Effect.Effect<void, EntifixConnError>;
|
|
61
59
|
/**
|
|
62
60
|
* Persist that a step is about to be dispatched.
|
|
63
61
|
*
|
|
64
|
-
* ⚠️ **Before the dispatch, never after.**
|
|
62
|
+
* ⚠️ **Before the dispatch, never after.** The outbox's rule extended from
|
|
65
63
|
* events to commands: a coordinator that marks a step in flight only after
|
|
66
64
|
* calling has the dual write that record exists to close, with the same
|
|
67
65
|
* consequence — a crash between the two leaves a step that either ran twice
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"saga-store.d.ts","sourceRoot":"","sources":["../../src/ports/saga-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C,OAAO,KAAK,EACV,UAAU,EACV,eAAe,EAChB,MAAM,iCAAiC,CAAC;AAEzC
|
|
1
|
+
{"version":3,"file":"saga-store.d.ts","sourceRoot":"","sources":["../../src/ports/saga-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C,OAAO,KAAK,EACV,UAAU,EACV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,EAChB,KAAK,CAAC,EAAE,MAAM,GACb,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAC;IACzC,GAAG,CACD,MAAM,EAAE,MAAM,GACb,MAAM,CAAC,MAAM,CAAC,YAAY,GAAG,SAAS,EAAE,gBAAgB,CAAC,CAAC;IAC7D,iFAAiF;IACjF,SAAS,CACP,WAAW,EAAE,MAAM,GAClB,MAAM,CAAC,MAAM,CAAC,SAAS,YAAY,EAAE,EAAE,gBAAgB,CAAC,CAAC;IAC5D;;;;;;;;;;;;;OAaG;IACH,cAAc,CACZ,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,GAClB,MAAM,CAAC,MAAM,CAAC,YAAY,GAAG,SAAS,EAAE,gBAAgB,CAAC,CAAC;IAC7D,2EAA2E;IAC3E,eAAe,CACb,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,GACb,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAC;CAC1C;;AAED,qBAAa,YAAa,SAAQ,iBAEjC;CAAG"}
|
package/dist/ports/saga-store.js
CHANGED
|
@@ -5,8 +5,7 @@ import { Context } from 'effect';
|
|
|
5
5
|
* `COMPENSATED` and `STRANDED` are deliberately different terminal states:
|
|
6
6
|
* "failed and reversed" and "failed with something still held" are the two
|
|
7
7
|
* outcomes an operator has to be able to tell apart, and a single `FAILED`
|
|
8
|
-
* would make the second look like the first
|
|
9
|
-
* ([ADR 0039](../../../../../../docs/adr/0039-multi-step-sagas-are-orchestrated.md)).
|
|
8
|
+
* would make the second look like the first.
|
|
10
9
|
*/ export const SAGA_STATES = [
|
|
11
10
|
'RUNNING',
|
|
12
11
|
'COMPLETED',
|