@entifix/transactions 0.1.0-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 (86) hide show
  1. package/LICENSE +21 -0
  2. package/dist/contracts/command.d.ts +59 -0
  3. package/dist/contracts/command.d.ts.map +1 -0
  4. package/dist/contracts/command.js +42 -0
  5. package/dist/contracts/command.js.map +1 -0
  6. package/dist/contracts/event.d.ts +84 -0
  7. package/dist/contracts/event.d.ts.map +1 -0
  8. package/dist/contracts/event.js +67 -0
  9. package/dist/contracts/event.js.map +1 -0
  10. package/dist/contracts/inbox.d.ts +80 -0
  11. package/dist/contracts/inbox.d.ts.map +1 -0
  12. package/dist/contracts/inbox.js +5 -0
  13. package/dist/contracts/inbox.js.map +1 -0
  14. package/dist/contracts/outbox.d.ts +137 -0
  15. package/dist/contracts/outbox.d.ts.map +1 -0
  16. package/dist/contracts/outbox.js +5 -0
  17. package/dist/contracts/outbox.js.map +1 -0
  18. package/dist/contracts/record.d.ts +108 -0
  19. package/dist/contracts/record.d.ts.map +1 -0
  20. package/dist/contracts/record.js +27 -0
  21. package/dist/contracts/record.js.map +1 -0
  22. package/dist/contracts/saga-definition.d.ts +186 -0
  23. package/dist/contracts/saga-definition.d.ts.map +1 -0
  24. package/dist/contracts/saga-definition.js +95 -0
  25. package/dist/contracts/saga-definition.js.map +1 -0
  26. package/dist/engine/resolve-template.d.ts +49 -0
  27. package/dist/engine/resolve-template.d.ts.map +1 -0
  28. package/dist/engine/resolve-template.js +106 -0
  29. package/dist/engine/resolve-template.js.map +1 -0
  30. package/dist/engine/run-saga.d.ts +55 -0
  31. package/dist/engine/run-saga.d.ts.map +1 -0
  32. package/dist/engine/run-saga.js +467 -0
  33. package/dist/engine/run-saga.js.map +1 -0
  34. package/dist/engine/run-transaction.d.ts +55 -0
  35. package/dist/engine/run-transaction.d.ts.map +1 -0
  36. package/dist/engine/run-transaction.js +101 -0
  37. package/dist/engine/run-transaction.js.map +1 -0
  38. package/dist/index.d.ts +21 -0
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +22 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/mixins/transaction-mixins.d.ts +20 -0
  43. package/dist/mixins/transaction-mixins.d.ts.map +1 -0
  44. package/dist/mixins/transaction-mixins.js +13 -0
  45. package/dist/mixins/transaction-mixins.js.map +1 -0
  46. package/dist/ports/event-bus.d.ts +98 -0
  47. package/dist/ports/event-bus.d.ts.map +1 -0
  48. package/dist/ports/event-bus.js +5 -0
  49. package/dist/ports/event-bus.js.map +1 -0
  50. package/dist/ports/event-source.d.ts +22 -0
  51. package/dist/ports/event-source.d.ts.map +1 -0
  52. package/dist/ports/event-source.js +20 -0
  53. package/dist/ports/event-source.js.map +1 -0
  54. package/dist/ports/lock-service.d.ts +24 -0
  55. package/dist/ports/lock-service.d.ts.map +1 -0
  56. package/dist/ports/lock-service.js +5 -0
  57. package/dist/ports/lock-service.js.map +1 -0
  58. package/dist/ports/saga-dispatcher.d.ts +47 -0
  59. package/dist/ports/saga-dispatcher.d.ts.map +1 -0
  60. package/dist/ports/saga-dispatcher.js +5 -0
  61. package/dist/ports/saga-dispatcher.js.map +1 -0
  62. package/dist/ports/saga-store.d.ts +98 -0
  63. package/dist/ports/saga-store.d.ts.map +1 -0
  64. package/dist/ports/saga-store.js +20 -0
  65. package/dist/ports/saga-store.js.map +1 -0
  66. package/dist/ports/sequence-service.d.ts +17 -0
  67. package/dist/ports/sequence-service.d.ts.map +1 -0
  68. package/dist/ports/sequence-service.js +5 -0
  69. package/dist/ports/sequence-service.js.map +1 -0
  70. package/dist/ports/transaction-handler.d.ts +68 -0
  71. package/dist/ports/transaction-handler.d.ts.map +1 -0
  72. package/dist/ports/transaction-handler.js +5 -0
  73. package/dist/ports/transaction-handler.js.map +1 -0
  74. package/dist/ports/transaction-sink.d.ts +119 -0
  75. package/dist/ports/transaction-sink.d.ts.map +1 -0
  76. package/dist/ports/transaction-sink.js +28 -0
  77. package/dist/ports/transaction-sink.js.map +1 -0
  78. package/dist/stream/transaction-stream-hub.d.ts +41 -0
  79. package/dist/stream/transaction-stream-hub.d.ts.map +1 -0
  80. package/dist/stream/transaction-stream-hub.js +53 -0
  81. package/dist/stream/transaction-stream-hub.js.map +1 -0
  82. package/dist/use-case/facade.uc.d.ts +22 -0
  83. package/dist/use-case/facade.uc.d.ts.map +1 -0
  84. package/dist/use-case/facade.uc.js +55 -0
  85. package/dist/use-case/facade.uc.js.map +1 -0
  86. package/package.json +65 -0
@@ -0,0 +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 ADR 0039 says nobody\n * 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 ADR 0039's 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;;;;;;;;;;;;;;;;CAgBC,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"}
@@ -0,0 +1,55 @@
1
+ import type { EntifixConnError } from '@entifix/core';
2
+ import { Effect } from 'effect';
3
+ import { type SagaDefinition, type SagaInputs, type SagaStepInput, type SagaStepOutcome } from '../contracts/saga-definition.js';
4
+ import { SagaDispatcherTag } from '../ports/saga-dispatcher.js';
5
+ import { type SagaInstance, SagaStoreTag } from '../ports/saga-store.js';
6
+ export type { SagaInputs, SagaStepInput };
7
+ export interface RunSagaOptions {
8
+ readonly sagaId: string;
9
+ readonly definition: SagaDefinition;
10
+ readonly inputs: SagaInputs;
11
+ }
12
+ /** How a run ended. */
13
+ export interface SagaResult {
14
+ readonly state: 'COMPLETED' | 'COMPENSATED' | 'STRANDED';
15
+ readonly outcomes: readonly SagaStepOutcome[];
16
+ readonly error?: string;
17
+ }
18
+ /**
19
+ * Start a flow and walk it to a terminal state.
20
+ *
21
+ * ⚠️ **Synchronous, and that is the buyer's requirement.** A checkout needs a
22
+ * yes/no now, so this answers the settled result. What {@link resumeSaga} adds
23
+ * is durability *behind* that answer: if this process dies mid-walk, the record
24
+ * it has been writing all along is enough for another one to finish the flow.
25
+ */
26
+ export declare const runSaga: (options: RunSagaOptions) => Effect.Effect<SagaResult, EntifixConnError, SagaDispatcherTag | SagaStoreTag>;
27
+ export interface ResumeSagaOptions {
28
+ readonly instance: SagaInstance;
29
+ readonly definition: SagaDefinition;
30
+ /** Past this many sweeps, the instance is surfaced instead of retried. */
31
+ readonly maxResumeAttempts: number;
32
+ }
33
+ /**
34
+ * Finish a flow another coordinator abandoned.
35
+ *
36
+ * ⚠️ **Where to re-enter is derived, never stored.** A resume point written
37
+ * beside the outcomes would be a second record of the same fact, free to
38
+ * disagree with them; the outcomes already say what happened, and
39
+ * `beginStep`-before-dispatch means `stepIndex` says what was attempted. The
40
+ * four cases are exhaustive:
41
+ *
42
+ * - the step at `stepIndex` recorded no outcome — the process died during the
43
+ * dispatch, so **re-dispatch it**. Safe because `sagaCommandId` is stable
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).
47
+ * - it recorded a successful outcome — the process died between
48
+ * `recordOutcome` and the next `beginStep`, so **start at the one after**.
49
+ * - it recorded a refusal — the process died deciding what to do about it, so
50
+ * **re-enter that decision**: unwind, or strand if the pivot had committed.
51
+ * - the instance is `COMPENSATING` — it died mid-unwind, so **continue the
52
+ * unwind**, skipping steps already marked `compensated`.
53
+ */
54
+ export declare const resumeSaga: (options: ResumeSagaOptions) => Effect.Effect<SagaResult, EntifixConnError, SagaDispatcherTag | SagaStoreTag>;
55
+ //# sourceMappingURL=run-saga.d.ts.map
@@ -0,0 +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;AAyeD;;;;;;;GAOG;AACH,eAAO,MAAM,OAAO,GAClB,SAAS,cAAc,KACtB,MAAM,CAAC,MAAM,CACd,UAAU,EACV,gBAAgB,EAChB,iBAAiB,GAAG,YAAY,CAoB9B,CAAC;AAEL,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,QAAQ,EAAE,YAAY,CAAC;IAChC,QAAQ,CAAC,UAAU,EAAE,cAAc,CAAC;IACpC,0EAA0E;IAC1E,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;CACpC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,UAAU,GACrB,SAAS,iBAAiB,KACzB,MAAM,CAAC,MAAM,CACd,UAAU,EACV,gBAAgB,EAChB,iBAAiB,GAAG,YAAY,CA8F9B,CAAC"}
@@ -0,0 +1,467 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ import { Effect } from 'effect';
3
+ import { sagaCommandId } from '../contracts/saga-definition.js';
4
+ import { SagaDispatcherTag } from '../ports/saga-dispatcher.js';
5
+ import { SagaStoreTag } from '../ports/saga-store.js';
6
+ import { resolveBodyTemplate, resolveTemplate } from './resolve-template.js';
7
+ const inputsFor = (step, inputs)=>{
8
+ var _inputs_step_id, _declared_;
9
+ const declared = (_inputs_step_id = inputs[step.id]) != null ? _inputs_step_id : [];
10
+ // A non-fan-out step makes exactly one call whether or not it was given an
11
+ // input, so an absent entry is an empty body rather than a skipped step.
12
+ return step.fanOut ? declared : [
13
+ (_declared_ = declared[0]) != null ? _declared_ : {}
14
+ ];
15
+ };
16
+ /**
17
+ * The elements a step actually dispatches: derived from an earlier step's
18
+ * successful calls when it declares `fanOutFrom`, and from the caller's input
19
+ * otherwise.
20
+ *
21
+ * ⚠️ **A `fanOutFrom` step ignores whatever the caller supplied for it.** The
22
+ * cardinality is the earlier step's, and taking the caller's would let a
23
+ * checkout convert a hold it never took — or, more likely, silently convert
24
+ * none, which is how a saga reports COMPLETED with the goods still held.
25
+ */ /**
26
+ * What every step can point at: the **first successful call** of each step that
27
+ * has already run, by step id.
28
+ *
29
+ * First rather than all, because a template naming a fan-out step is ambiguous
30
+ * by construction — "the order id" is one value and "the reservation ids" are
31
+ * many, and the many case is what `fanOutFrom` exists for. Keeping this to the
32
+ * unambiguous case is what stops `{steps.reserve.data.id}` quietly meaning
33
+ * "whichever hold happened to be first".
34
+ */ const stepsScope = (taken)=>Object.fromEntries(taken.filter((entry)=>entry.outcome.calls.length > 0).map((entry)=>{
35
+ var _entry_outcome_calls_;
36
+ return [
37
+ entry.step.id,
38
+ (_entry_outcome_calls_ = entry.outcome.calls[0]) == null ? void 0 : _entry_outcome_calls_.body
39
+ ];
40
+ }));
41
+ const elementsFor = (step, inputs, taken)=>{
42
+ var _ref;
43
+ var _inputs_step_id_, _inputs_step_id;
44
+ const steps = stepsScope(taken);
45
+ if (step.fanOutFrom === undefined) {
46
+ return inputsFor(step, inputs).map((input)=>({
47
+ input,
48
+ scope: {
49
+ input: input.body,
50
+ steps
51
+ }
52
+ }));
53
+ }
54
+ const source = taken.find((entry)=>entry.step.id === step.fanOutFrom);
55
+ const body = (_inputs_step_id = inputs[step.id]) == null ? void 0 : (_inputs_step_id_ = _inputs_step_id[0]) == null ? void 0 : _inputs_step_id_.body;
56
+ return ((_ref = source == null ? void 0 : source.outcome.calls) != null ? _ref : []).map((call)=>({
57
+ // ⚠️ The organization the *earlier call* acted for, never the caller's.
58
+ // A tenant-plane participant resolves its handle from the header, so a
59
+ // conversion dispatched without it is refused `400` and the hold expires
60
+ // under a buyer who has already been charged.
61
+ input: {
62
+ body,
63
+ organizationId: call.organizationId
64
+ },
65
+ scope: {
66
+ outcome: call.body,
67
+ input: body,
68
+ steps
69
+ }
70
+ }));
71
+ };
72
+ const dispatchCall = (step, call, sagaId, index, input, scope)=>Effect.gen(function*() {
73
+ const dispatcher = yield* SagaDispatcherTag;
74
+ return yield* dispatcher.dispatch({
75
+ participant: step.participant,
76
+ call: {
77
+ method: call.method,
78
+ path: resolveTemplate(call.path, scope)
79
+ },
80
+ commandId: sagaCommandId(sagaId, step.id, step.fanOut ? index : undefined),
81
+ organizationId: input.organizationId,
82
+ body: call.method === 'GET' || call.method === 'DELETE' ? undefined : resolveBodyTemplate(input.body, scope)
83
+ });
84
+ });
85
+ /**
86
+ * Run one step: every call it makes, in order, stopping at the first refusal.
87
+ *
88
+ * Returns the calls that **succeeded** alongside the failure, because those are
89
+ * exactly the calls a compensation has to undo — see {@link compensateStep}.
90
+ */ const runStep = (step, sagaId, elements)=>Effect.gen(function*() {
91
+ const calls = [];
92
+ for (const [index, element] of elements.entries()){
93
+ const { input } = element;
94
+ const response = yield* dispatchCall(step, step.command, sagaId, index, input, element.scope);
95
+ if (!response.ok) {
96
+ // A business refusal. The saga fails *forward* into compensation, and
97
+ // the calls already recorded are the ones that have to come back.
98
+ return {
99
+ calls,
100
+ error: `step '${step.id}' call ${String(index)} refused with ${String(response.status)}`
101
+ };
102
+ }
103
+ calls.push({
104
+ index,
105
+ status: response.status,
106
+ body: response.body,
107
+ // Carried so the compensation reaches the same tenant. Without it a
108
+ // release is refused `400` and the saga strands holding stock.
109
+ organizationId: input.organizationId
110
+ });
111
+ }
112
+ return {
113
+ calls
114
+ };
115
+ });
116
+ /**
117
+ * Undo one step — **one compensation per successful call**, never one per step.
118
+ *
119
+ * ⚠️ This is the whole reason an outcome is kept per fan-out element. Five lines
120
+ * with three holds taken and the fourth refused must release exactly three:
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)).
124
+ *
125
+ * Never fails: a compensation's own failure is reported by the caller and must
126
+ * not stop the compensations after it, for the reason ADR 0039 gives — a
127
+ * stranded saga nobody is told about is the same as a lost one.
128
+ */ const compensateStep = (step, sagaId, outcome)=>Effect.gen(function*() {
129
+ const compensation = step.compensation;
130
+ if (!compensation) {
131
+ return [];
132
+ }
133
+ const failures = [];
134
+ // Reverse order: the last thing done is the first thing undone, which is
135
+ // what a reader expects of a stack of effects and what keeps a future
136
+ // ordering dependency from being an accident.
137
+ for (const call of [
138
+ ...outcome.calls
139
+ ].reverse()){
140
+ const result = yield* dispatchCall(step, compensation, sagaId, call.index, // ⚠️ The organization the *call* acted for, not an empty input. A
141
+ // tenant-plane participant resolves its handle from the header, so a
142
+ // compensation without it is refused before it reaches the hold.
143
+ {
144
+ organizationId: call.organizationId
145
+ }, {
146
+ outcome: call.body
147
+ }).pipe(Effect.catchAll((error)=>Effect.succeed({
148
+ ok: false,
149
+ status: 0,
150
+ body: error
151
+ })), // A template that no longer matches the participant's response shape
152
+ // throws rather than interpolating `undefined`; that is a defect, and
153
+ // it is reported as a stranded compensation rather than crashing the
154
+ // walk and leaving every later hold in place.
155
+ Effect.catchAllDefect((defect)=>Effect.succeed({
156
+ ok: false,
157
+ status: 0,
158
+ body: defect
159
+ })));
160
+ // ⚠️ **A `404` is a compensation that has nothing left to undo**, and it
161
+ // counts as success. Compensation is at-least-once the moment a resumed
162
+ // coordinator can retry it, and a participant answering "no such record"
163
+ // on the second delivery is describing a flow that *was* reversed. Left
164
+ // as a refusal it strands exactly the sagas that were cleaned up
165
+ // correctly, which is the failure ADR 0054 named on the conversion route
166
+ // and is the same one from the other side.
167
+ if (!result.ok && result.status !== 404) {
168
+ failures.push(`compensation for '${step.id}' call ${String(call.index)} failed: ${String(result.body)}`);
169
+ }
170
+ }
171
+ return failures;
172
+ });
173
+ /**
174
+ * How many extra times a step is dispatched once the pivot has committed.
175
+ *
176
+ * Small and immediate on purpose. This is the in-process half of "roll forward",
177
+ * and it exists to ride out the blip — a participant restarting, a connection
178
+ * reset — not to be a retry policy. A step that is still refusing after these
179
+ * strands the saga, loudly, because the alternative is a coordinator spinning on
180
+ * a permanent failure while a customer's money sits captured.
181
+ *
182
+ * Durable retry across a coordinator restart is a different mechanism and is not
183
+ * built: see #233, which makes a step dispatch an outbox entry whose relay
184
+ * performs the POST.
185
+ */ const POST_PIVOT_RETRIES = 3;
186
+ /**
187
+ * Dispatch a step, retrying it `retries` more times while it refuses.
188
+ *
189
+ * ⚠️ **A retry re-dispatches the calls that already succeeded**, and that is
190
+ * safe for exactly one reason: `sagaCommandId(sagaId, step.id, index)` is stable
191
+ * across attempts, so a participant that is idempotent on the command id
192
+ * recognises the replay. ADR 0052 states that requirement on the participant;
193
+ * this is the code that depends on it.
194
+ */ const runStepWithRetries = (step, sagaId, elements, retries)=>Effect.gen(function*() {
195
+ let result = yield* runStep(step, sagaId, elements);
196
+ for(let attempt = 1; attempt <= retries && result.error !== undefined; attempt += 1){
197
+ yield* Effect.logWarning('retrying a saga step after the pivot').pipe(Effect.annotateLogs({
198
+ sagaId,
199
+ stepId: step.id,
200
+ attempt,
201
+ error: result.error
202
+ }));
203
+ result = yield* runStep(step, sagaId, elements);
204
+ }
205
+ return result;
206
+ });
207
+ /** Pair each recorded outcome with the step that produced it. */ const rebuildTaken = (definition, outcomes)=>{
208
+ const taken = [];
209
+ for (const outcome of outcomes){
210
+ const step = definition.steps.find((candidate)=>candidate.id === outcome.stepId);
211
+ // ⚠️ Not skipped. An outcome naming a step the definition no longer has
212
+ // means the definition changed under a live instance, so the flow this
213
+ // record describes and the flow the engine would walk are different flows.
214
+ // Carrying on would compensate the wrong steps in the wrong order.
215
+ if (!step) {
216
+ return {
217
+ unknownStep: outcome.stepId
218
+ };
219
+ }
220
+ taken.push({
221
+ step,
222
+ outcome
223
+ });
224
+ }
225
+ return taken;
226
+ };
227
+ /** Whether the point of no return is behind us, read off what actually ran. */ const pivotCommittedIn = (taken)=>taken.some((entry)=>entry.step.kind === 'pivot' && entry.outcome.error === undefined);
228
+ /**
229
+ * Settle a saga that cannot go forward and cannot be reversed, loudly.
230
+ *
231
+ * ⚠️ The message is a parameter because these are **different operational
232
+ * events** and each is grepped for on its own: money is captured behind a
233
+ * pivot, a release was refused and stock is still held, a definition changed
234
+ * under a live instance. Collapsing them into one string would make the log
235
+ * line say only that something is wrong.
236
+ */ const strand = (store, sagaId, outcomes, error, message, log)=>Effect.gen(function*() {
237
+ yield* Effect.logError(message).pipe(Effect.annotateLogs(_extends({
238
+ sagaId,
239
+ error
240
+ }, log)));
241
+ yield* store.settle(sagaId, 'STRANDED', error);
242
+ return {
243
+ state: 'STRANDED',
244
+ outcomes,
245
+ error
246
+ };
247
+ });
248
+ /**
249
+ * Unwind every compensatable step already taken, newest first.
250
+ *
251
+ * Shared by the in-process walk and by a resumed one, which is the whole reason
252
+ * it is a function: a coordinator that died *while* compensating comes back
253
+ * into exactly this loop, and the steps it already gave back carry
254
+ * `compensated` so they are not given back twice.
255
+ */ const unwind = (store, sagaId, definition, taken, error)=>Effect.gen(function*() {
256
+ const outcomes = taken.map((entry)=>entry.outcome);
257
+ const failures = [];
258
+ for (const done of [
259
+ ...taken
260
+ ].reverse()){
261
+ if (done.outcome.compensated === true) {
262
+ continue;
263
+ }
264
+ const stepFailures = yield* compensateStep(done.step, sagaId, done.outcome);
265
+ failures.push(...stepFailures);
266
+ // Marked only when the step came back whole. A partial failure stays
267
+ // unmarked so a later resume retries it — safe because a compensation
268
+ // with nothing left to undo answers `404`, which is a success above.
269
+ if (stepFailures.length === 0) {
270
+ yield* store.markCompensated(sagaId, done.step.id);
271
+ }
272
+ }
273
+ if (failures.length > 0) {
274
+ // ⚠️ Surfaced, never swallowed. This is the state that leaves a
275
+ // reservation held and — once payment lands — a customer charged, and
276
+ // ADR 0039 names it as the failure class nobody plans for.
277
+ return yield* strand(store, sagaId, outcomes, error, 'saga compensation failed', {
278
+ definition: definition.name,
279
+ failures: failures.join('; ')
280
+ });
281
+ }
282
+ yield* store.settle(sagaId, 'COMPENSATED', error);
283
+ return {
284
+ state: 'COMPENSATED',
285
+ outcomes,
286
+ error
287
+ };
288
+ });
289
+ /**
290
+ * Dispatch the definition's steps from `startIndex` on, and unwind on a refusal.
291
+ *
292
+ * The state transition is persisted **before** each dispatch, so a crash leaves
293
+ * a record that says what was actually attempted (ADR 0028, extended to
294
+ * commands by ADR 0039).
295
+ *
296
+ * ⚠️ **Once the pivot has committed, nothing is unwound.** That is what a pivot
297
+ * means, and the walk has to know it rather than the definition merely declaring
298
+ * it: `compensateStep` no-ops on a step that declares no compensation, so an
299
+ * unconditional unwind after a successful capture would skip the pivot in
300
+ * silence and then delete the order behind it and release the holds behind that
301
+ * — money taken, goods back on sale, every probe green. The step is retried
302
+ * instead, and a saga that still cannot go forward is settled `STRANDED` and
303
+ * logged, because ADR 0039 is explicit that a stranded saga nobody is told about
304
+ * is the same as a lost one.
305
+ */ const walk = (store, options, from)=>Effect.gen(function*() {
306
+ const { sagaId, definition, inputs } = options;
307
+ // Step and outcome are kept **together**: looking the step back up by id
308
+ // would introduce a not-found branch that cannot happen, and an unreachable
309
+ // branch is a line nothing can ever prove correct.
310
+ const taken = from.taken;
311
+ const outcomes = ()=>taken.map((entry)=>entry.outcome);
312
+ // The point of no return, once it is behind us. Tracked rather than read off
313
+ // the definition because what matters is not that a pivot exists but that it
314
+ // *committed* — a pivot that refuses is still fully reversible, and is the
315
+ // ordinary compensation case below.
316
+ let pivotCommitted = pivotCommittedIn(taken);
317
+ for(let index = from.startIndex; index < definition.steps.length; index++){
318
+ const step = definition.steps[index];
319
+ /* v8 ignore next 3 -- the loop bound makes this unreachable; it exists
320
+ because `noUncheckedIndexedAccess` cannot see that. */ if (!step) {
321
+ continue;
322
+ }
323
+ yield* store.beginStep(sagaId, index);
324
+ const { calls, error } = yield* runStepWithRetries(step, sagaId, elementsFor(step, inputs, taken), pivotCommitted ? POST_PIVOT_RETRIES : 0);
325
+ const outcome = _extends({
326
+ stepId: step.id,
327
+ calls
328
+ }, error === undefined ? {} : {
329
+ error
330
+ });
331
+ taken.push({
332
+ step,
333
+ outcome
334
+ });
335
+ yield* store.recordOutcome(sagaId, outcome);
336
+ if (error === undefined) {
337
+ if (step.kind === 'pivot') {
338
+ pivotCommitted = true;
339
+ }
340
+ continue;
341
+ }
342
+ if (pivotCommitted) {
343
+ // ⚠️ Forward or nowhere. Compensating from here would undo steps whose
344
+ // effects the pivot has already been paid for.
345
+ return yield* strand(store, sagaId, outcomes(), error, 'saga stranded after the pivot', {
346
+ definition: definition.name,
347
+ stepId: step.id
348
+ });
349
+ }
350
+ // Unwind. The failing step's own successful calls are compensated too —
351
+ // a fan-out step that took three holds before its fourth was refused has
352
+ // three to give back.
353
+ yield* store.settle(sagaId, 'COMPENSATING', error);
354
+ return yield* unwind(store, sagaId, definition, taken, error);
355
+ }
356
+ yield* store.settle(sagaId, 'COMPLETED');
357
+ return {
358
+ state: 'COMPLETED',
359
+ outcomes: outcomes()
360
+ };
361
+ });
362
+ /**
363
+ * Start a flow and walk it to a terminal state.
364
+ *
365
+ * ⚠️ **Synchronous, and that is the buyer's requirement.** A checkout needs a
366
+ * yes/no now, so this answers the settled result. What {@link resumeSaga} adds
367
+ * is durability *behind* that answer: if this process dies mid-walk, the record
368
+ * it has been writing all along is enough for another one to finish the flow.
369
+ */ export const runSaga = (options)=>Effect.gen(function*() {
370
+ const store = yield* SagaStoreTag;
371
+ const { sagaId, definition, inputs } = options;
372
+ yield* store.start({
373
+ sagaId,
374
+ definition: definition.name,
375
+ state: 'RUNNING',
376
+ stepIndex: 0,
377
+ outcomes: [],
378
+ // ⚠️ Persisted, because a resume has nothing to dispatch without it: a
379
+ // fan-out step's cardinality *is* its input's length (ADR 0055).
380
+ inputs,
381
+ resumeAttempts: 0,
382
+ createdAt: new Date().toISOString()
383
+ });
384
+ return yield* walk(store, options, {
385
+ taken: [],
386
+ startIndex: 0
387
+ });
388
+ });
389
+ /**
390
+ * Finish a flow another coordinator abandoned.
391
+ *
392
+ * ⚠️ **Where to re-enter is derived, never stored.** A resume point written
393
+ * beside the outcomes would be a second record of the same fact, free to
394
+ * disagree with them; the outcomes already say what happened, and
395
+ * `beginStep`-before-dispatch means `stepIndex` says what was attempted. The
396
+ * four cases are exhaustive:
397
+ *
398
+ * - the step at `stepIndex` recorded no outcome — the process died during the
399
+ * dispatch, so **re-dispatch it**. Safe because `sagaCommandId` is stable
400
+ * 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).
403
+ * - it recorded a successful outcome — the process died between
404
+ * `recordOutcome` and the next `beginStep`, so **start at the one after**.
405
+ * - it recorded a refusal — the process died deciding what to do about it, so
406
+ * **re-enter that decision**: unwind, or strand if the pivot had committed.
407
+ * - the instance is `COMPENSATING` — it died mid-unwind, so **continue the
408
+ * unwind**, skipping steps already marked `compensated`.
409
+ */ export const resumeSaga = (options)=>Effect.gen(function*() {
410
+ const store = yield* SagaStoreTag;
411
+ const { instance, definition, maxResumeAttempts } = options;
412
+ const { sagaId, outcomes } = instance;
413
+ if (instance.resumeAttempts > maxResumeAttempts) {
414
+ var _instance_error;
415
+ // Surfaced rather than retried forever. A coordinator spinning on a
416
+ // permanent failure is how money stays captured with nobody told.
417
+ return yield* strand(store, sagaId, outcomes, (_instance_error = instance.error) != null ? _instance_error : `resumed ${String(instance.resumeAttempts - 1)} times without settling`, 'saga abandoned after too many resumes', {
418
+ definition: definition.name,
419
+ resumeAttempts: instance.resumeAttempts
420
+ });
421
+ }
422
+ const rebuilt = rebuildTaken(definition, outcomes);
423
+ if ('unknownStep' in rebuilt) {
424
+ return yield* strand(store, sagaId, outcomes, `recorded step '${rebuilt.unknownStep}' is not in definition '${definition.name}'`, 'saga instance does not match its definition', {
425
+ definition: definition.name
426
+ });
427
+ }
428
+ const resumeOptions = {
429
+ sagaId,
430
+ definition,
431
+ inputs: instance.inputs
432
+ };
433
+ if (instance.state === 'COMPENSATING') {
434
+ var _instance_error1;
435
+ return yield* unwind(store, sagaId, definition, rebuilt, (_instance_error1 = instance.error) != null ? _instance_error1 : 'compensation resumed');
436
+ }
437
+ const step = definition.steps[instance.stepIndex];
438
+ if (!step) {
439
+ return yield* strand(store, sagaId, outcomes, `step ${String(instance.stepIndex)} is not in definition '${definition.name}'`, 'saga instance does not match its definition', {
440
+ definition: definition.name
441
+ });
442
+ }
443
+ const recorded = rebuilt.find((entry)=>entry.step.id === step.id);
444
+ if (recorded === undefined) {
445
+ return yield* walk(store, resumeOptions, {
446
+ taken: rebuilt,
447
+ startIndex: instance.stepIndex
448
+ });
449
+ }
450
+ if (recorded.outcome.error === undefined) {
451
+ return yield* walk(store, resumeOptions, {
452
+ taken: rebuilt,
453
+ startIndex: instance.stepIndex + 1
454
+ });
455
+ }
456
+ const error = recorded.outcome.error;
457
+ if (pivotCommittedIn(rebuilt)) {
458
+ return yield* strand(store, sagaId, outcomes, error, 'saga stranded after the pivot', {
459
+ definition: definition.name,
460
+ stepId: step.id
461
+ });
462
+ }
463
+ yield* store.settle(sagaId, 'COMPENSATING', error);
464
+ return yield* unwind(store, sagaId, definition, rebuilt, error);
465
+ });
466
+
467
+ //# sourceMappingURL=run-saga.js.map
@@ -0,0 +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.catchAll(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.catchAllDefect(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","catchAll","succeed","catchAllDefect","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,iBAAi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