@entifix/transactions 0.1.1 → 0.1.3

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/README.md CHANGED
@@ -12,9 +12,9 @@ pnpm add @entifix/transactions effect
12
12
 
13
13
  ## Entry points
14
14
 
15
- | Import | What it holds |
16
- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
17
- | `@entifix/transactions` | Command envelopes, transaction events, inbox / outbox / event-bus / lock / sequence ports, `defineSaga`, `runSaga`, `resumeSaga`, the transaction stream hub |
15
+ | Import | What it holds |
16
+ | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
17
+ | `@entifix/transactions` | Command envelopes, transaction events, inbox / outbox / event-bus / lock / sequence ports, `defineSaga`, `runSaga`, `resumeSaga`, `resumeStaleSagas` / `startSagaResume`, `makeLocalSagaDispatcher` for a saga whose participants live in one service, the transaction stream hub |
18
18
 
19
19
  ---
20
20
 
@@ -94,7 +94,7 @@ export interface SagaDefinition {
94
94
  * does — and checkout writes an order.
95
95
  *
96
96
  * It is a plain string here rather than authz's `Permission`: this package is
97
- * `layer:entifix`, and `@entifix/authz` sits above it. The service that
97
+ * T2, and `@entifix/authz` sits above it at T4. The service that
98
98
  * mounts the route resolves the string against
99
99
  * `SERVICE_CROSSING_PERMISSIONS`, which is where the closed list belongs.
100
100
  */
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/saga-definition.ts"],"sourcesContent":["import { EntifixLogicError } from '@entifix/core';\n\n/**\n * Richardson's classification, and adopting the vocabulary is most of the answer\n * to \"which steps are compensable at all\"\n * ([ADR 0039](../../../../../../docs/adr/0039-multi-step-sagas-are-orchestrated.md)).\n *\n * - `compensatable` — before the point of no return; a failure downstream\n * reverses it.\n * - `pivot` — the point of no return. Once it commits, the saga goes forward.\n * - `retriable` — after the pivot; no compensation exists, so the only path is\n * to retry until it succeeds.\n */\nexport type SagaStepKind = 'compensatable' | 'pivot' | 'retriable';\n\n/** The HTTP verbs a step may be dispatched with. */\nexport type SagaMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * One call a step makes, as a template rather than a closure.\n *\n * `path` may carry `{…}` placeholders resolved by field path against the step's\n * recorded outcome — `/api/reservation/{outcome.data.id}`.\n *\n * ⚠️ **A template rather than a callback, and that is the constraint that\n * shaped the whole type.** A callback would have to name the participant's\n * types, and a `business:domain` package may not import another\n * (`docs/_shared/layering.md`) — which is exactly the import that has no legal\n * home and the reason ADR 0039 made a definition **data** in the first place.\n */\nexport interface SagaCall {\n readonly method: SagaMethod;\n readonly path: string;\n}\n\n/** One step of a flow. */\nexport interface SagaStep {\n /** Unique within the definition; half of the command id `<sagaId>:<stepId>`. */\n readonly id: string;\n /**\n * Which service answers it, as a **configuration key** — never a URI.\n *\n * A URI in a definition is a deployment fact written into a business\n * artifact, and it is what makes a definition untestable and un-relocatable.\n * The same lookup yields the crossing token for that participant, so a\n * definition carries no secret and never could\n * ([ADR 0052](../../../../../../docs/adr/0052-the-checkout-saga.md)).\n */\n readonly participant: string;\n readonly command: SagaCall;\n /** Required on a `compensatable` step, forbidden on every other kind. */\n readonly compensation?: SagaCall;\n readonly kind: SagaStepKind;\n /**\n * Dispatch one call per element of this step's input, rather than one call.\n *\n * ⚠️ **Cardinality is data, because it has to be.** Checkout reserves once per\n * vendor and how many vendors is known only from the cart, so writing that as\n * N steps would mean generating a definition per request — at which point it\n * is no longer data, and ADR 0039's whole construction collapses back into the\n * class that has no legal home.\n *\n * The consequence carried by {@link SagaStepOutcome}: **the unit of\n * compensation is the call, not the step.** Five lines with three holds taken\n * and the fourth refused must release exactly three.\n */\n readonly fanOut?: boolean;\n /**\n * Fan out over an **earlier step's successful calls** instead of over an\n * input the caller supplied.\n *\n * ⚠️ **Without this a later step cannot address what an earlier one created**,\n * and checkout is the case that proves it. `convert-reservation` needs one\n * call per hold, addressed by the reservation id — which stock-service mints,\n * so the caller cannot know it when it starts the flow. Supplying the ids as\n * input is impossible, and generating a definition per request is the thing\n * ADR 0039 exists to avoid.\n *\n * Each element inherits that call's `organizationId`, so a tenant-plane\n * participant reaches the same tenant it did the first time, and the `path`\n * template resolves against `{outcome.…}` — the same scope a compensation\n * gets, for the same reason: the id being addressed is in the response body.\n *\n * Implies {@link fanOut}. It names a step that must appear **before** this one,\n * and `defineSaga` refuses a forward or self reference at module load.\n */\n readonly fanOutFrom?: string;\n}\n\n/** A flow, as the data a generic engine walks. */\nexport interface SagaDefinition {\n readonly name: string;\n /**\n * What a caller must hold to run this flow, as a `<domain>:<entity>:<action>`\n * string.\n *\n * ⚠️ **On the definition rather than on the route**, so the route that runs a\n * flow stays generic. The alternative was one permission for every saga, which\n * would make \"may run a flow\" a single capability regardless of what the flow\n * does — and checkout writes an order.\n *\n * It is a plain string here rather than authz's `Permission`: this package is\n * `layer:entifix`, and `@entifix/authz` sits above it. The service that\n * mounts the route resolves the string against\n * `SERVICE_CROSSING_PERMISSIONS`, which is where the closed list belongs.\n */\n readonly permission: string;\n readonly steps: readonly SagaStep[];\n}\n\n/** What one dispatched call returned, kept so its compensation can read it. */\nexport interface SagaCallOutcome {\n /** The fan-out element this call was made for; `0` on a single-call step. */\n readonly index: number;\n readonly status: number;\n readonly body: unknown;\n /**\n * The organization this call acted for, carried so its compensation acts on\n * the same one.\n *\n * ⚠️ **Not derivable from the outcome, and its absence is silent.** A\n * tenant-plane participant resolves its storage handle from\n * `x-organization-id`, so a compensation dispatched without it is refused\n * `400` — and the saga strands with every hold still in place while the\n * engine reports it tried. Measured on the live lab: two holds taken, a third\n * line refused, and both releases rejected for a missing header\n * ([ADR 0023](../../../../../../docs/adr/0023-service-to-service-tenant-crossing.md)).\n */\n readonly organizationId?: string;\n}\n\n/**\n * What one step is given to work with — one element per call on a `fanOut` step,\n * exactly one otherwise.\n */\nexport interface SagaStepInput {\n /** The body to send. */\n readonly body?: unknown;\n /** ADR 0023's explicit organization, for a tenant-plane participant. */\n readonly organizationId?: string;\n}\n\n/**\n * The inputs each step needs, keyed by step id, supplied by the caller.\n *\n * ⚠️ **Here rather than in the engine**, because the durable instance carries\n * it: a resumed walk is a different process reading this off the store, so the\n * port that persists it may not reach up into the engine to name its type\n * ([ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).\n */\nexport type SagaInputs = Readonly<Record<string, readonly SagaStepInput[]>>;\n\n/** Every call one step made, in dispatch order. */\nexport interface SagaStepOutcome {\n readonly stepId: string;\n readonly calls: readonly SagaCallOutcome[];\n /**\n * Why this step stopped, when it did — absent on a step that succeeded.\n *\n * ⚠️ **Without it a resumed walk cannot tell a finished step from a refused\n * one.** `calls` holds what succeeded either way, so the two are\n * indistinguishable on the stored document, and the distinction is what\n * decides whether the pivot committed. Guessing it either compensates behind\n * a capture or walks past a refusal\n * ([ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).\n */\n readonly error?: string;\n /**\n * Whether this step's calls have already been given back.\n *\n * ⚠️ **What keeps a resumed unwind from compensating twice.** A second\n * `DELETE` of an order already deleted answers `404`, which the dispatcher\n * classifies as a refusal, which strands a flow that was in fact reversed.\n */\n readonly compensated?: boolean;\n}\n\nconst fail = (definition: string, detail: string): never => {\n throw new EntifixLogicError(\n `saga definition '${definition}' is invalid: ${detail}`,\n undefined,\n { definition },\n );\n};\n\n/**\n * Validate a definition and return it, or throw.\n *\n * ⚠️ **At load, not at the step.** A fault that only appears on the unlucky path\n * is a fault that ships — the same reasoning ADR 0035 used for `collection` +\n * `determining`. Every definition is therefore constructed through this\n * function at module scope, and loaded in a spec: a definition that never loads\n * is a definition that never fails.\n */\nexport function defineSaga(definition: SagaDefinition): SagaDefinition {\n const { name, steps } = definition;\n\n if (steps.length === 0) {\n fail(name, 'it declares no steps');\n }\n\n const seen = new Set<string>();\n for (const step of steps) {\n if (seen.has(step.id)) {\n // The command id is `<sagaId>:<stepId>`, so a duplicate id is two steps\n // sharing one idempotency key — the second would be dropped as a\n // redelivery of the first and never run at all.\n fail(name, `two steps share the id '${step.id}'`);\n }\n seen.add(step.id);\n }\n\n // `fanOutFrom` must name a step that has already run, or the outcomes it fans\n // out over do not exist yet. A forward reference would silently produce zero\n // calls — a step that looks like it ran and did nothing, which is exactly how\n // a conversion gets skipped while a saga reports COMPLETED.\n const before = new Set<string>();\n for (const step of steps) {\n if (step.fanOutFrom !== undefined && !before.has(step.fanOutFrom)) {\n fail(\n name,\n `step '${step.id}' fans out from '${step.fanOutFrom}', which is not a ` +\n 'step before it',\n );\n }\n before.add(step.id);\n }\n\n const pivots = steps.filter(step => step.kind === 'pivot');\n if (pivots.length > 1) {\n // A flow with two points of no return is a flow that has not been designed\n // yet, and the engine says so out loud (ADR 0039).\n fail(\n name,\n `it declares ${String(pivots.length)} pivots (${pivots\n .map(step => step.id)\n .join(', ')}); a flow has at most one point of no return`,\n );\n }\n\n // ⚠️ **Zero pivots is legal**, and checkout is the case that forced saying so.\n // Payment capture is M4; until it lands every step of checkout reverses. A\n // validator demanding exactly one would push the order write into a role it\n // would have to be removed from later — a wrong answer that passes\n // (ADR 0052). A definition with no pivot means the whole saga can be unwound,\n // which is a stronger property than a pivot rather than a missing one.\n const pivot = pivots[0];\n const pivotAt = pivot ? steps.indexOf(pivot) : -1;\n const afterPivot = (index: number) => pivot !== undefined && index > pivotAt;\n\n for (const [index, step] of steps.entries()) {\n switch (step.kind) {\n case 'compensatable': {\n if (afterPivot(index)) {\n fail(\n name,\n `step '${step.id}' is compensatable but sits after the pivot ` +\n `'${String(pivot?.id)}', where nothing can be reversed`,\n );\n }\n if (!step.compensation) {\n fail(\n name,\n `step '${step.id}' is compensatable but declares no compensation`,\n );\n }\n break;\n }\n case 'pivot':\n case 'retriable': {\n if (step.compensation) {\n // Not dead code — a *false assurance*. Such a compensation could\n // never run, so writing one says the step is reversible when it is\n // not (ADR 0039).\n fail(\n name,\n `step '${step.id}' is ${step.kind} and declares a compensation, ` +\n 'which could never run',\n );\n }\n if (step.kind === 'retriable' && !afterPivot(index)) {\n fail(\n name,\n `step '${step.id}' is retriable but sits before the pivot; a step ` +\n 'that cannot be reversed must not run while the saga can still ' +\n 'be unwound',\n );\n }\n break;\n }\n }\n }\n\n return definition;\n}\n\n/**\n * The command id one call is dispatched under.\n *\n * `<sagaId>:<stepId>` — the shape `transactionEventId` already uses for events,\n * so #178's `TransactionInbox` serves saga steps with no second dedup store and\n * no second key. A fan-out step appends the element index, because its calls are\n * separate side effects that must each be claimed on their own.\n */\nexport const sagaCommandId = (\n sagaId: string,\n stepId: string,\n index?: number,\n): string =>\n index === undefined\n ? `${sagaId}:${stepId}`\n : `${sagaId}:${stepId}:${String(index)}`;\n"],"names":["EntifixLogicError","fail","definition","detail","undefined","defineSaga","name","steps","length","seen","Set","step","has","id","add","before","fanOutFrom","pivots","filter","kind","String","map","join","pivot","pivotAt","indexOf","afterPivot","index","entries","compensation","sagaCommandId","sagaId","stepId"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,gBAAgB;AAiLlD,MAAMC,OAAO,CAACC,YAAoBC;IAChC,MAAM,IAAIH,kBACR,CAAC,iBAAiB,EAAEE,WAAW,cAAc,EAAEC,QAAQ,EACvDC,WACA;QAAEF;IAAW;AAEjB;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASG,WAAWH,UAA0B;IACnD,MAAM,EAAEI,IAAI,EAAEC,KAAK,EAAE,GAAGL;IAExB,IAAIK,MAAMC,MAAM,KAAK,GAAG;QACtBP,KAAKK,MAAM;IACb;IAEA,MAAMG,OAAO,IAAIC;IACjB,KAAK,MAAMC,QAAQJ,MAAO;QACxB,IAAIE,KAAKG,GAAG,CAACD,KAAKE,EAAE,GAAG;YACrB,wEAAwE;YACxE,iEAAiE;YACjE,gDAAgD;YAChDZ,KAAKK,MAAM,CAAC,wBAAwB,EAAEK,KAAKE,EAAE,CAAC,CAAC,CAAC;QAClD;QACAJ,KAAKK,GAAG,CAACH,KAAKE,EAAE;IAClB;IAEA,8EAA8E;IAC9E,6EAA6E;IAC7E,8EAA8E;IAC9E,4DAA4D;IAC5D,MAAME,SAAS,IAAIL;IACnB,KAAK,MAAMC,QAAQJ,MAAO;QACxB,IAAII,KAAKK,UAAU,KAAKZ,aAAa,CAACW,OAAOH,GAAG,CAACD,KAAKK,UAAU,GAAG;YACjEf,KACEK,MACA,CAAC,MAAM,EAAEK,KAAKE,EAAE,CAAC,iBAAiB,EAAEF,KAAKK,UAAU,CAAC,kBAAkB,CAAC,GACrE;QAEN;QACAD,OAAOD,GAAG,CAACH,KAAKE,EAAE;IACpB;IAEA,MAAMI,SAASV,MAAMW,MAAM,CAACP,CAAAA,OAAQA,KAAKQ,IAAI,KAAK;IAClD,IAAIF,OAAOT,MAAM,GAAG,GAAG;QACrB,2EAA2E;QAC3E,mDAAmD;QACnDP,KACEK,MACA,CAAC,YAAY,EAAEc,OAAOH,OAAOT,MAAM,EAAE,SAAS,EAAES,OAC7CI,GAAG,CAACV,CAAAA,OAAQA,KAAKE,EAAE,EACnBS,IAAI,CAAC,MAAM,4CAA4C,CAAC;IAE/D;IAEA,+EAA+E;IAC/E,2EAA2E;IAC3E,4EAA4E;IAC5E,mEAAmE;IACnE,8EAA8E;IAC9E,uEAAuE;IACvE,MAAMC,QAAQN,MAAM,CAAC,EAAE;IACvB,MAAMO,UAAUD,QAAQhB,MAAMkB,OAAO,CAACF,SAAS,CAAC;IAChD,MAAMG,aAAa,CAACC,QAAkBJ,UAAUnB,aAAauB,QAAQH;IAErE,KAAK,MAAM,CAACG,OAAOhB,KAAK,IAAIJ,MAAMqB,OAAO,GAAI;QAC3C,OAAQjB,KAAKQ,IAAI;YACf,KAAK;gBAAiB;oBACpB,IAAIO,WAAWC,QAAQ;wBACrB1B,KACEK,MACA,CAAC,MAAM,EAAEK,KAAKE,EAAE,CAAC,4CAA4C,CAAC,GAC5D,CAAC,CAAC,EAAEO,OAAOG,yBAAAA,MAAOV,EAAE,EAAE,gCAAgC,CAAC;oBAE7D;oBACA,IAAI,CAACF,KAAKkB,YAAY,EAAE;wBACtB5B,KACEK,MACA,CAAC,MAAM,EAAEK,KAAKE,EAAE,CAAC,+CAA+C,CAAC;oBAErE;oBACA;gBACF;YACA,KAAK;YACL,KAAK;gBAAa;oBAChB,IAAIF,KAAKkB,YAAY,EAAE;wBACrB,iEAAiE;wBACjE,mEAAmE;wBACnE,kBAAkB;wBAClB5B,KACEK,MACA,CAAC,MAAM,EAAEK,KAAKE,EAAE,CAAC,KAAK,EAAEF,KAAKQ,IAAI,CAAC,8BAA8B,CAAC,GAC/D;oBAEN;oBACA,IAAIR,KAAKQ,IAAI,KAAK,eAAe,CAACO,WAAWC,QAAQ;wBACnD1B,KACEK,MACA,CAAC,MAAM,EAAEK,KAAKE,EAAE,CAAC,iDAAiD,CAAC,GACjE,mEACA;oBAEN;oBACA;gBACF;QACF;IACF;IAEA,OAAOX;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,MAAM4B,gBAAgB,CAC3BC,QACAC,QACAL,QAEAA,UAAUvB,YACN,GAAG2B,OAAO,CAAC,EAAEC,QAAQ,GACrB,GAAGD,OAAO,CAAC,EAAEC,OAAO,CAAC,EAAEZ,OAAOO,QAAQ,CAAC"}
1
+ {"version":3,"sources":["../../src/contracts/saga-definition.ts"],"sourcesContent":["import { EntifixLogicError } from '@entifix/core';\n\n/**\n * Richardson's classification, and adopting the vocabulary is most of the answer\n * to \"which steps are compensable at all\"\n * ([ADR 0039](../../../../../../docs/adr/0039-multi-step-sagas-are-orchestrated.md)).\n *\n * - `compensatable` — before the point of no return; a failure downstream\n * reverses it.\n * - `pivot` — the point of no return. Once it commits, the saga goes forward.\n * - `retriable` — after the pivot; no compensation exists, so the only path is\n * to retry until it succeeds.\n */\nexport type SagaStepKind = 'compensatable' | 'pivot' | 'retriable';\n\n/** The HTTP verbs a step may be dispatched with. */\nexport type SagaMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * One call a step makes, as a template rather than a closure.\n *\n * `path` may carry `{…}` placeholders resolved by field path against the step's\n * recorded outcome — `/api/reservation/{outcome.data.id}`.\n *\n * ⚠️ **A template rather than a callback, and that is the constraint that\n * shaped the whole type.** A callback would have to name the participant's\n * types, and a `business:domain` package may not import another\n * (`docs/_shared/layering.md`) — which is exactly the import that has no legal\n * home and the reason ADR 0039 made a definition **data** in the first place.\n */\nexport interface SagaCall {\n readonly method: SagaMethod;\n readonly path: string;\n}\n\n/** One step of a flow. */\nexport interface SagaStep {\n /** Unique within the definition; half of the command id `<sagaId>:<stepId>`. */\n readonly id: string;\n /**\n * Which service answers it, as a **configuration key** — never a URI.\n *\n * A URI in a definition is a deployment fact written into a business\n * artifact, and it is what makes a definition untestable and un-relocatable.\n * The same lookup yields the crossing token for that participant, so a\n * definition carries no secret and never could\n * ([ADR 0052](../../../../../../docs/adr/0052-the-checkout-saga.md)).\n */\n readonly participant: string;\n readonly command: SagaCall;\n /** Required on a `compensatable` step, forbidden on every other kind. */\n readonly compensation?: SagaCall;\n readonly kind: SagaStepKind;\n /**\n * Dispatch one call per element of this step's input, rather than one call.\n *\n * ⚠️ **Cardinality is data, because it has to be.** Checkout reserves once per\n * vendor and how many vendors is known only from the cart, so writing that as\n * N steps would mean generating a definition per request — at which point it\n * is no longer data, and ADR 0039's whole construction collapses back into the\n * class that has no legal home.\n *\n * The consequence carried by {@link SagaStepOutcome}: **the unit of\n * compensation is the call, not the step.** Five lines with three holds taken\n * and the fourth refused must release exactly three.\n */\n readonly fanOut?: boolean;\n /**\n * Fan out over an **earlier step's successful calls** instead of over an\n * input the caller supplied.\n *\n * ⚠️ **Without this a later step cannot address what an earlier one created**,\n * and checkout is the case that proves it. `convert-reservation` needs one\n * call per hold, addressed by the reservation id — which stock-service mints,\n * so the caller cannot know it when it starts the flow. Supplying the ids as\n * input is impossible, and generating a definition per request is the thing\n * ADR 0039 exists to avoid.\n *\n * Each element inherits that call's `organizationId`, so a tenant-plane\n * participant reaches the same tenant it did the first time, and the `path`\n * template resolves against `{outcome.…}` — the same scope a compensation\n * gets, for the same reason: the id being addressed is in the response body.\n *\n * Implies {@link fanOut}. It names a step that must appear **before** this one,\n * and `defineSaga` refuses a forward or self reference at module load.\n */\n readonly fanOutFrom?: string;\n}\n\n/** A flow, as the data a generic engine walks. */\nexport interface SagaDefinition {\n readonly name: string;\n /**\n * What a caller must hold to run this flow, as a `<domain>:<entity>:<action>`\n * string.\n *\n * ⚠️ **On the definition rather than on the route**, so the route that runs a\n * flow stays generic. The alternative was one permission for every saga, which\n * would make \"may run a flow\" a single capability regardless of what the flow\n * does — and checkout writes an order.\n *\n * It is a plain string here rather than authz's `Permission`: this package is\n * T2, and `@entifix/authz` sits above it at T4. The service that\n * mounts the route resolves the string against\n * `SERVICE_CROSSING_PERMISSIONS`, which is where the closed list belongs.\n */\n readonly permission: string;\n readonly steps: readonly SagaStep[];\n}\n\n/** What one dispatched call returned, kept so its compensation can read it. */\nexport interface SagaCallOutcome {\n /** The fan-out element this call was made for; `0` on a single-call step. */\n readonly index: number;\n readonly status: number;\n readonly body: unknown;\n /**\n * The organization this call acted for, carried so its compensation acts on\n * the same one.\n *\n * ⚠️ **Not derivable from the outcome, and its absence is silent.** A\n * tenant-plane participant resolves its storage handle from\n * `x-organization-id`, so a compensation dispatched without it is refused\n * `400` — and the saga strands with every hold still in place while the\n * engine reports it tried. Measured on the live lab: two holds taken, a third\n * line refused, and both releases rejected for a missing header\n * ([ADR 0023](../../../../../../docs/adr/0023-service-to-service-tenant-crossing.md)).\n */\n readonly organizationId?: string;\n}\n\n/**\n * What one step is given to work with — one element per call on a `fanOut` step,\n * exactly one otherwise.\n */\nexport interface SagaStepInput {\n /** The body to send. */\n readonly body?: unknown;\n /** ADR 0023's explicit organization, for a tenant-plane participant. */\n readonly organizationId?: string;\n}\n\n/**\n * The inputs each step needs, keyed by step id, supplied by the caller.\n *\n * ⚠️ **Here rather than in the engine**, because the durable instance carries\n * it: a resumed walk is a different process reading this off the store, so the\n * port that persists it may not reach up into the engine to name its type\n * ([ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).\n */\nexport type SagaInputs = Readonly<Record<string, readonly SagaStepInput[]>>;\n\n/** Every call one step made, in dispatch order. */\nexport interface SagaStepOutcome {\n readonly stepId: string;\n readonly calls: readonly SagaCallOutcome[];\n /**\n * Why this step stopped, when it did — absent on a step that succeeded.\n *\n * ⚠️ **Without it a resumed walk cannot tell a finished step from a refused\n * one.** `calls` holds what succeeded either way, so the two are\n * indistinguishable on the stored document, and the distinction is what\n * decides whether the pivot committed. Guessing it either compensates behind\n * a capture or walks past a refusal\n * ([ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).\n */\n readonly error?: string;\n /**\n * Whether this step's calls have already been given back.\n *\n * ⚠️ **What keeps a resumed unwind from compensating twice.** A second\n * `DELETE` of an order already deleted answers `404`, which the dispatcher\n * classifies as a refusal, which strands a flow that was in fact reversed.\n */\n readonly compensated?: boolean;\n}\n\nconst fail = (definition: string, detail: string): never => {\n throw new EntifixLogicError(\n `saga definition '${definition}' is invalid: ${detail}`,\n undefined,\n { definition },\n );\n};\n\n/**\n * Validate a definition and return it, or throw.\n *\n * ⚠️ **At load, not at the step.** A fault that only appears on the unlucky path\n * is a fault that ships — the same reasoning ADR 0035 used for `collection` +\n * `determining`. Every definition is therefore constructed through this\n * function at module scope, and loaded in a spec: a definition that never loads\n * is a definition that never fails.\n */\nexport function defineSaga(definition: SagaDefinition): SagaDefinition {\n const { name, steps } = definition;\n\n if (steps.length === 0) {\n fail(name, 'it declares no steps');\n }\n\n const seen = new Set<string>();\n for (const step of steps) {\n if (seen.has(step.id)) {\n // The command id is `<sagaId>:<stepId>`, so a duplicate id is two steps\n // sharing one idempotency key — the second would be dropped as a\n // redelivery of the first and never run at all.\n fail(name, `two steps share the id '${step.id}'`);\n }\n seen.add(step.id);\n }\n\n // `fanOutFrom` must name a step that has already run, or the outcomes it fans\n // out over do not exist yet. A forward reference would silently produce zero\n // calls — a step that looks like it ran and did nothing, which is exactly how\n // a conversion gets skipped while a saga reports COMPLETED.\n const before = new Set<string>();\n for (const step of steps) {\n if (step.fanOutFrom !== undefined && !before.has(step.fanOutFrom)) {\n fail(\n name,\n `step '${step.id}' fans out from '${step.fanOutFrom}', which is not a ` +\n 'step before it',\n );\n }\n before.add(step.id);\n }\n\n const pivots = steps.filter(step => step.kind === 'pivot');\n if (pivots.length > 1) {\n // A flow with two points of no return is a flow that has not been designed\n // yet, and the engine says so out loud (ADR 0039).\n fail(\n name,\n `it declares ${String(pivots.length)} pivots (${pivots\n .map(step => step.id)\n .join(', ')}); a flow has at most one point of no return`,\n );\n }\n\n // ⚠️ **Zero pivots is legal**, and checkout is the case that forced saying so.\n // Payment capture is M4; until it lands every step of checkout reverses. A\n // validator demanding exactly one would push the order write into a role it\n // would have to be removed from later — a wrong answer that passes\n // (ADR 0052). A definition with no pivot means the whole saga can be unwound,\n // which is a stronger property than a pivot rather than a missing one.\n const pivot = pivots[0];\n const pivotAt = pivot ? steps.indexOf(pivot) : -1;\n const afterPivot = (index: number) => pivot !== undefined && index > pivotAt;\n\n for (const [index, step] of steps.entries()) {\n switch (step.kind) {\n case 'compensatable': {\n if (afterPivot(index)) {\n fail(\n name,\n `step '${step.id}' is compensatable but sits after the pivot ` +\n `'${String(pivot?.id)}', where nothing can be reversed`,\n );\n }\n if (!step.compensation) {\n fail(\n name,\n `step '${step.id}' is compensatable but declares no compensation`,\n );\n }\n break;\n }\n case 'pivot':\n case 'retriable': {\n if (step.compensation) {\n // Not dead code — a *false assurance*. Such a compensation could\n // never run, so writing one says the step is reversible when it is\n // not (ADR 0039).\n fail(\n name,\n `step '${step.id}' is ${step.kind} and declares a compensation, ` +\n 'which could never run',\n );\n }\n if (step.kind === 'retriable' && !afterPivot(index)) {\n fail(\n name,\n `step '${step.id}' is retriable but sits before the pivot; a step ` +\n 'that cannot be reversed must not run while the saga can still ' +\n 'be unwound',\n );\n }\n break;\n }\n }\n }\n\n return definition;\n}\n\n/**\n * The command id one call is dispatched under.\n *\n * `<sagaId>:<stepId>` — the shape `transactionEventId` already uses for events,\n * so #178's `TransactionInbox` serves saga steps with no second dedup store and\n * no second key. A fan-out step appends the element index, because its calls are\n * separate side effects that must each be claimed on their own.\n */\nexport const sagaCommandId = (\n sagaId: string,\n stepId: string,\n index?: number,\n): string =>\n index === undefined\n ? `${sagaId}:${stepId}`\n : `${sagaId}:${stepId}:${String(index)}`;\n"],"names":["EntifixLogicError","fail","definition","detail","undefined","defineSaga","name","steps","length","seen","Set","step","has","id","add","before","fanOutFrom","pivots","filter","kind","String","map","join","pivot","pivotAt","indexOf","afterPivot","index","entries","compensation","sagaCommandId","sagaId","stepId"],"mappings":"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"}
@@ -0,0 +1,35 @@
1
+ import { type EntifixConnError } from '@entifix/core';
2
+ import { Effect, Layer } from 'effect';
3
+ import type { SagaCall } from '../contracts/saga-definition.js';
4
+ import { type SagaDispatch, type SagaDispatcher, SagaDispatcherTag, type SagaResponse } from '../ports/saga-dispatcher.js';
5
+ /** What a local participant is handed: the dispatch, minus whom it is for. */
6
+ export type LocalSagaRequest = Omit<SagaDispatch, 'participant'>;
7
+ /**
8
+ * One participant answered in-process.
9
+ *
10
+ * The same contract an HTTP participant keeps: a business refusal is a response
11
+ * with `ok: false` — the engine compensates on it — and only a failure to reach
12
+ * the participant at all is an {@link EntifixConnError}. Key the side effect on
13
+ * `commandId` (an inbox), because a resumed flow dispatches the same command
14
+ * again.
15
+ */
16
+ export type LocalSagaParticipant = (request: LocalSagaRequest) => Effect.Effect<SagaResponse, EntifixConnError>;
17
+ /**
18
+ * A {@link SagaDispatcher} that calls participants in this process.
19
+ *
20
+ * The saga engine never does HTTP itself: a step is a `{ method, path }` handed
21
+ * to the dispatcher port. So a flow whose every step belongs to one service needs
22
+ * no transport, no crossing token and no second process — only this, with each
23
+ * participant name mapped to the Effect that performs its commands. A handler
24
+ * that serves several commands routes on `request.call`.
25
+ *
26
+ * ⚠️ A participant the definition names and this map lacks is a **defect**, not
27
+ * a failed step: it is a wiring mistake the flow cannot recover from, and
28
+ * reporting it as a refusal would compensate a flow for a bug.
29
+ */
30
+ export declare const makeLocalSagaDispatcher: (participants: Readonly<Record<string, LocalSagaParticipant>>) => SagaDispatcher;
31
+ /** Provides {@link SagaDispatcherTag} from local participants. */
32
+ export declare const LocalSagaDispatcherLayer: (participants: Readonly<Record<string, LocalSagaParticipant>>) => Layer.Layer<SagaDispatcherTag>;
33
+ /** True when a request is the given command, for a participant routing on it. */
34
+ export declare const isSagaCall: (request: LocalSagaRequest, call: SagaCall) => boolean;
35
+ //# sourceMappingURL=local-saga-dispatcher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"local-saga-dispatcher.d.ts","sourceRoot":"","sources":["../../src/engine/local-saga-dispatcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,gBAAgB,EAAqB,MAAM,eAAe,CAAC;AACzE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAEvC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAChE,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,iBAAiB,EACjB,KAAK,YAAY,EAClB,MAAM,6BAA6B,CAAC;AAErC,8EAA8E;AAC9E,MAAM,MAAM,gBAAgB,GAAG,IAAI,CAAC,YAAY,EAAE,aAAa,CAAC,CAAC;AAEjE;;;;;;;;GAQG;AACH,MAAM,MAAM,oBAAoB,GAAG,CACjC,OAAO,EAAE,gBAAgB,KACtB,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,gBAAgB,CAAC,CAAC;AAEnD;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,uBAAuB,GAClC,cAAc,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAC,KAC3D,cAaD,CAAC;AAEH,kEAAkE;AAClE,eAAO,MAAM,wBAAwB,GACnC,cAAc,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAC,KAC3D,KAAK,CAAC,KAAK,CAAC,iBAAiB,CACyC,CAAC;AAE1E,iFAAiF;AACjF,eAAO,MAAM,UAAU,GACrB,SAAS,gBAAgB,EACzB,MAAM,QAAQ,KACb,OACqE,CAAC"}
@@ -0,0 +1,32 @@
1
+ import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
2
+ import { EntifixLogicError } from '@entifix/core';
3
+ import { Effect, Layer } from 'effect';
4
+ import { SagaDispatcherTag } from '../ports/saga-dispatcher.js';
5
+ /**
6
+ * A {@link SagaDispatcher} that calls participants in this process.
7
+ *
8
+ * The saga engine never does HTTP itself: a step is a `{ method, path }` handed
9
+ * to the dispatcher port. So a flow whose every step belongs to one service needs
10
+ * no transport, no crossing token and no second process — only this, with each
11
+ * participant name mapped to the Effect that performs its commands. A handler
12
+ * that serves several commands routes on `request.call`.
13
+ *
14
+ * ⚠️ A participant the definition names and this map lacks is a **defect**, not
15
+ * a failed step: it is a wiring mistake the flow cannot recover from, and
16
+ * reporting it as a refusal would compensate a flow for a bug.
17
+ */ export const makeLocalSagaDispatcher = (participants)=>({
18
+ dispatch: (_0)=>{
19
+ let { participant } = _0, request = _object_without_properties_loose(_0, [
20
+ "participant"
21
+ ]);
22
+ const handle = participants[participant];
23
+ return handle === undefined ? Effect.die(new EntifixLogicError(`The saga dispatched to participant "${participant}", which this service registered no local handler for.`, undefined, {
24
+ participant,
25
+ call: request.call
26
+ })) : handle(request);
27
+ }
28
+ });
29
+ /** Provides {@link SagaDispatcherTag} from local participants. */ export const LocalSagaDispatcherLayer = (participants)=>Layer.succeed(SagaDispatcherTag, makeLocalSagaDispatcher(participants));
30
+ /** True when a request is the given command, for a participant routing on it. */ export const isSagaCall = (request, call)=>request.call.method === call.method && request.call.path === call.path;
31
+
32
+ //# sourceMappingURL=local-saga-dispatcher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/engine/local-saga-dispatcher.ts"],"sourcesContent":["import { type EntifixConnError, EntifixLogicError } from '@entifix/core';\nimport { Effect, Layer } from 'effect';\n\nimport type { SagaCall } from '../contracts/saga-definition.js';\nimport {\n type SagaDispatch,\n type SagaDispatcher,\n SagaDispatcherTag,\n type SagaResponse,\n} from '../ports/saga-dispatcher.js';\n\n/** What a local participant is handed: the dispatch, minus whom it is for. */\nexport type LocalSagaRequest = Omit<SagaDispatch, 'participant'>;\n\n/**\n * One participant answered in-process.\n *\n * The same contract an HTTP participant keeps: a business refusal is a response\n * with `ok: false` — the engine compensates on it — and only a failure to reach\n * the participant at all is an {@link EntifixConnError}. Key the side effect on\n * `commandId` (an inbox), because a resumed flow dispatches the same command\n * again.\n */\nexport type LocalSagaParticipant = (\n request: LocalSagaRequest,\n) => Effect.Effect<SagaResponse, EntifixConnError>;\n\n/**\n * A {@link SagaDispatcher} that calls participants in this process.\n *\n * The saga engine never does HTTP itself: a step is a `{ method, path }` handed\n * to the dispatcher port. So a flow whose every step belongs to one service needs\n * no transport, no crossing token and no second process — only this, with each\n * participant name mapped to the Effect that performs its commands. A handler\n * that serves several commands routes on `request.call`.\n *\n * ⚠️ A participant the definition names and this map lacks is a **defect**, not\n * a failed step: it is a wiring mistake the flow cannot recover from, and\n * reporting it as a refusal would compensate a flow for a bug.\n */\nexport const makeLocalSagaDispatcher = (\n participants: Readonly<Record<string, LocalSagaParticipant>>,\n): SagaDispatcher => ({\n dispatch: ({ participant, ...request }) => {\n const handle = participants[participant];\n return handle === undefined\n ? Effect.die(\n new EntifixLogicError(\n `The saga dispatched to participant \"${participant}\", which this service registered no local handler for.`,\n undefined,\n { participant, call: request.call },\n ),\n )\n : handle(request);\n },\n});\n\n/** Provides {@link SagaDispatcherTag} from local participants. */\nexport const LocalSagaDispatcherLayer = (\n participants: Readonly<Record<string, LocalSagaParticipant>>,\n): Layer.Layer<SagaDispatcherTag> =>\n Layer.succeed(SagaDispatcherTag, makeLocalSagaDispatcher(participants));\n\n/** True when a request is the given command, for a participant routing on it. */\nexport const isSagaCall = (\n request: LocalSagaRequest,\n call: SagaCall,\n): boolean =>\n request.call.method === call.method && request.call.path === call.path;\n"],"names":["EntifixLogicError","Effect","Layer","SagaDispatcherTag","makeLocalSagaDispatcher","participants","dispatch","participant","request","handle","undefined","die","call","LocalSagaDispatcherLayer","succeed","isSagaCall","method","path"],"mappings":";AAAA,SAAgCA,iBAAiB,QAAQ,gBAAgB;AACzE,SAASC,MAAM,EAAEC,KAAK,QAAQ,SAAS;AAGvC,SAGEC,iBAAiB,QAEZ,8BAA8B;AAkBrC;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,0BAA0B,CACrCC,eACoB,CAAA;QACpBC,UAAU;gBAAC,EAAEC,WAAW,EAAc,OAATC;;;YAC3B,MAAMC,SAASJ,YAAY,CAACE,YAAY;YACxC,OAAOE,WAAWC,YACdT,OAAOU,GAAG,CACR,IAAIX,kBACF,CAAC,oCAAoC,EAAEO,YAAY,sDAAsD,CAAC,EAC1GG,WACA;gBAAEH;gBAAaK,MAAMJ,QAAQI,IAAI;YAAC,MAGtCH,OAAOD;QACb;IACF,CAAA,EAAG;AAEH,gEAAgE,GAChE,OAAO,MAAMK,2BAA2B,CACtCR,eAEAH,MAAMY,OAAO,CAACX,mBAAmBC,wBAAwBC,eAAe;AAE1E,+EAA+E,GAC/E,OAAO,MAAMU,aAAa,CACxBP,SACAI,OAEAJ,QAAQI,IAAI,CAACI,MAAM,KAAKJ,KAAKI,MAAM,IAAIR,QAAQI,IAAI,CAACK,IAAI,KAAKL,KAAKK,IAAI,CAAC"}
@@ -0,0 +1,46 @@
1
+ import { ShutdownRegistryTag } from '@entifix/business';
2
+ import { Effect } from 'effect';
3
+ import type { SagaDefinition } from '../contracts/saga-definition.js';
4
+ import { SagaDispatcherTag } from '../ports/saga-dispatcher.js';
5
+ import { SagaStoreTag } from '../ports/saga-store.js';
6
+ export interface ResumeSweepOptions {
7
+ /** Every flow this process can finish, by `definition.name`. */
8
+ readonly definitions: readonly SagaDefinition[];
9
+ /**
10
+ * How long an instance may sit untouched before its coordinator is presumed
11
+ * gone.
12
+ *
13
+ * ⚠️ **Must stay above the longest a step legitimately takes.** `updatedAt`
14
+ * is re-stamped before every dispatch, so a slow participant keeps an instance
15
+ * fresh — but a step slower than this window is resumed underneath the
16
+ * coordinator still waiting on it, and only the participants' inboxes stop
17
+ * that from being two side effects.
18
+ */
19
+ readonly staleAfterMs: number;
20
+ /** Past this many sweeps, an instance settles `STRANDED` instead. */
21
+ readonly maxResumeAttempts: number;
22
+ }
23
+ /**
24
+ * One pass: find the instances nobody finished, claim each, and finish it.
25
+ *
26
+ * ⚠️ **`findStale` then `claimForResume`, never `findStale` then resume.** The
27
+ * claim is a conditional write, so an instance another replica already took no
28
+ * longer matches and is skipped. Without it two sweepers would walk one flow
29
+ * together, and the attempt ceiling would count two attempts per tick.
30
+ *
31
+ * Failures are logged, per instance and around the pass, never raised: one flow
32
+ * that cannot be resumed must not abandon the flows behind it, and a store that
33
+ * is briefly unreachable must not kill the daemon that calls this.
34
+ */
35
+ export declare const resumeStaleSagas: ({ definitions, staleAfterMs, maxResumeAttempts, }: ResumeSweepOptions) => Effect.Effect<void, never, SagaStoreTag | SagaDispatcherTag>;
36
+ /**
37
+ * Runs {@link resumeStaleSagas} every `intervalMs` as a daemon, and stops it on
38
+ * shutdown.
39
+ *
40
+ * `stop-intake`, not `flush`: the sweep writes the store and dispatches, so it
41
+ * has to stop before the clients it goes through do.
42
+ */
43
+ export declare const startSagaResume: (options: ResumeSweepOptions & {
44
+ readonly intervalMs: number;
45
+ }) => Effect.Effect<void, never, SagaStoreTag | SagaDispatcherTag | ShutdownRegistryTag>;
46
+ //# sourceMappingURL=resume-sweep.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resume-sweep.d.ts","sourceRoot":"","sources":["../../src/engine/resume-sweep.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAY,MAAM,EAAS,MAAM,QAAQ,CAAC;AAEjD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAGtD,MAAM,WAAW,kBAAkB;IACjC,gEAAgE;IAChE,QAAQ,CAAC,WAAW,EAAE,SAAS,cAAc,EAAE,CAAC;IAChD;;;;;;;;;OASG;IACH,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,qEAAqE;IACrE,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;CACpC;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,gBAAgB,GAAI,mDAI9B,kBAAkB,KAAG,MAAM,CAAC,MAAM,CACnC,IAAI,EACJ,KAAK,EACL,YAAY,GAAG,iBAAiB,CAwD/B,CAAC;AAEJ;;;;;;GAMG;AACH,eAAO,MAAM,eAAe,GAC1B,SAAS,kBAAkB,GAAG;IAAE,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;CAAE,KAC5D,MAAM,CAAC,MAAM,CACd,IAAI,EACJ,KAAK,EACL,YAAY,GAAG,iBAAiB,GAAG,mBAAmB,CA0BpD,CAAC"}
@@ -0,0 +1,74 @@
1
+ import { ShutdownRegistryTag } from '@entifix/business';
2
+ import { Duration, Effect, Fiber } from 'effect';
3
+ import { SagaDispatcherTag } from '../ports/saga-dispatcher.js';
4
+ import { SagaStoreTag } from '../ports/saga-store.js';
5
+ import { resumeSaga } from './run-saga.js';
6
+ /**
7
+ * One pass: find the instances nobody finished, claim each, and finish it.
8
+ *
9
+ * ⚠️ **`findStale` then `claimForResume`, never `findStale` then resume.** The
10
+ * claim is a conditional write, so an instance another replica already took no
11
+ * longer matches and is skipped. Without it two sweepers would walk one flow
12
+ * together, and the attempt ceiling would count two attempts per tick.
13
+ *
14
+ * Failures are logged, per instance and around the pass, never raised: one flow
15
+ * that cannot be resumed must not abandon the flows behind it, and a store that
16
+ * is briefly unreachable must not kill the daemon that calls this.
17
+ */ export const resumeStaleSagas = ({ definitions, staleAfterMs, maxResumeAttempts })=>Effect.gen(function*() {
18
+ const store = yield* SagaStoreTag;
19
+ const byName = new Map(definitions.map((definition)=>[
20
+ definition.name,
21
+ definition
22
+ ]));
23
+ for (const found of yield* store.findStale(staleAfterMs)){
24
+ const definition = byName.get(found.definition);
25
+ if (definition === undefined) {
26
+ // Nothing here can finish a flow it cannot read, and settling it would
27
+ // be a guess about its steps — so it is surfaced and left alone.
28
+ yield* Effect.logError('stale saga names an unknown definition').pipe(Effect.annotateLogs({
29
+ sagaId: found.sagaId,
30
+ definition: found.definition
31
+ }));
32
+ continue;
33
+ }
34
+ const claimed = yield* store.claimForResume(found.sagaId, staleAfterMs);
35
+ if (claimed === undefined) continue;
36
+ yield* resumeSaga({
37
+ instance: claimed,
38
+ definition,
39
+ maxResumeAttempts
40
+ }).pipe(Effect.tap((result)=>Effect.logInfo('resumed a saga instance').pipe(Effect.annotateLogs({
41
+ sagaId: claimed.sagaId,
42
+ definition: claimed.definition,
43
+ resumedFrom: claimed.state,
44
+ settled: result.state
45
+ }))), Effect.catchAll((error)=>Effect.logError('resuming a saga instance failed').pipe(Effect.annotateLogs({
46
+ sagaId: claimed.sagaId,
47
+ error: String(error)
48
+ }))));
49
+ }
50
+ }).pipe(Effect.catchAll((error)=>Effect.logError('saga resume sweep failed').pipe(Effect.annotateLogs({
51
+ error: String(error)
52
+ }))));
53
+ /**
54
+ * Runs {@link resumeStaleSagas} every `intervalMs` as a daemon, and stops it on
55
+ * shutdown.
56
+ *
57
+ * `stop-intake`, not `flush`: the sweep writes the store and dispatches, so it
58
+ * has to stop before the clients it goes through do.
59
+ */ export const startSagaResume = (options)=>Effect.gen(function*() {
60
+ const store = yield* SagaStoreTag;
61
+ const dispatcher = yield* SagaDispatcherTag;
62
+ const shutdown = yield* ShutdownRegistryTag;
63
+ // Resolved once at boot and provided to every pass, so the daemon needs
64
+ // nothing from the context it outlives.
65
+ const pass = resumeStaleSagas(options).pipe(Effect.provideService(SagaStoreTag, store), Effect.provideService(SagaDispatcherTag, dispatcher));
66
+ const daemon = yield* Effect.forkDaemon(pass.pipe(Effect.delay(Duration.millis(options.intervalMs)), Effect.forever));
67
+ yield* shutdown.register({
68
+ name: 'saga-resume-sweep',
69
+ phase: 'stop-intake',
70
+ run: Fiber.interrupt(daemon).pipe(Effect.asVoid)
71
+ });
72
+ });
73
+
74
+ //# sourceMappingURL=resume-sweep.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/engine/resume-sweep.ts"],"sourcesContent":["import { ShutdownRegistryTag } from '@entifix/business';\nimport { Duration, Effect, Fiber } from 'effect';\n\nimport type { SagaDefinition } from '../contracts/saga-definition.js';\nimport { SagaDispatcherTag } from '../ports/saga-dispatcher.js';\nimport { SagaStoreTag } from '../ports/saga-store.js';\nimport { resumeSaga } from './run-saga.js';\n\nexport interface ResumeSweepOptions {\n /** Every flow this process can finish, by `definition.name`. */\n readonly definitions: readonly SagaDefinition[];\n /**\n * How long an instance may sit untouched before its coordinator is presumed\n * gone.\n *\n * ⚠️ **Must stay above the longest a step legitimately takes.** `updatedAt`\n * is re-stamped before every dispatch, so a slow participant keeps an instance\n * fresh — but a step slower than this window is resumed underneath the\n * coordinator still waiting on it, and only the participants' inboxes stop\n * that from being two side effects.\n */\n readonly staleAfterMs: number;\n /** Past this many sweeps, an instance settles `STRANDED` instead. */\n readonly maxResumeAttempts: number;\n}\n\n/**\n * One pass: find the instances nobody finished, claim each, and finish it.\n *\n * ⚠️ **`findStale` then `claimForResume`, never `findStale` then resume.** The\n * claim is a conditional write, so an instance another replica already took no\n * longer matches and is skipped. Without it two sweepers would walk one flow\n * together, and the attempt ceiling would count two attempts per tick.\n *\n * Failures are logged, per instance and around the pass, never raised: one flow\n * that cannot be resumed must not abandon the flows behind it, and a store that\n * is briefly unreachable must not kill the daemon that calls this.\n */\nexport const resumeStaleSagas = ({\n definitions,\n staleAfterMs,\n maxResumeAttempts,\n}: ResumeSweepOptions): Effect.Effect<\n void,\n never,\n SagaStoreTag | SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const byName = new Map(\n definitions.map(definition => [definition.name, definition]),\n );\n\n for (const found of yield* store.findStale(staleAfterMs)) {\n const definition = byName.get(found.definition);\n if (definition === undefined) {\n // Nothing here can finish a flow it cannot read, and settling it would\n // be a guess about its steps — so it is surfaced and left alone.\n yield* Effect.logError('stale saga names an unknown definition').pipe(\n Effect.annotateLogs({\n sagaId: found.sagaId,\n definition: found.definition,\n }),\n );\n continue;\n }\n\n const claimed = yield* store.claimForResume(found.sagaId, staleAfterMs);\n if (claimed === undefined) continue;\n\n yield* resumeSaga({\n instance: claimed,\n definition,\n maxResumeAttempts,\n }).pipe(\n Effect.tap(result =>\n Effect.logInfo('resumed a saga instance').pipe(\n Effect.annotateLogs({\n sagaId: claimed.sagaId,\n definition: claimed.definition,\n resumedFrom: claimed.state,\n settled: result.state,\n }),\n ),\n ),\n Effect.catchAll(error =>\n Effect.logError('resuming a saga instance failed').pipe(\n Effect.annotateLogs({\n sagaId: claimed.sagaId,\n error: String(error),\n }),\n ),\n ),\n );\n }\n }).pipe(\n Effect.catchAll(error =>\n Effect.logError('saga resume sweep failed').pipe(\n Effect.annotateLogs({ error: String(error) }),\n ),\n ),\n );\n\n/**\n * Runs {@link resumeStaleSagas} every `intervalMs` as a daemon, and stops it on\n * shutdown.\n *\n * `stop-intake`, not `flush`: the sweep writes the store and dispatches, so it\n * has to stop before the clients it goes through do.\n */\nexport const startSagaResume = (\n options: ResumeSweepOptions & { readonly intervalMs: number },\n): Effect.Effect<\n void,\n never,\n SagaStoreTag | SagaDispatcherTag | ShutdownRegistryTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const dispatcher = yield* SagaDispatcherTag;\n const shutdown = yield* ShutdownRegistryTag;\n\n // Resolved once at boot and provided to every pass, so the daemon needs\n // nothing from the context it outlives.\n const pass = resumeStaleSagas(options).pipe(\n Effect.provideService(SagaStoreTag, store),\n Effect.provideService(SagaDispatcherTag, dispatcher),\n );\n\n const daemon = yield* Effect.forkDaemon(\n pass.pipe(\n Effect.delay(Duration.millis(options.intervalMs)),\n Effect.forever,\n ),\n );\n\n yield* shutdown.register({\n name: 'saga-resume-sweep',\n phase: 'stop-intake',\n run: Fiber.interrupt(daemon).pipe(Effect.asVoid),\n });\n });\n"],"names":["ShutdownRegistryTag","Duration","Effect","Fiber","SagaDispatcherTag","SagaStoreTag","resumeSaga","resumeStaleSagas","definitions","staleAfterMs","maxResumeAttempts","gen","store","byName","Map","map","definition","name","found","findStale","get","undefined","logError","pipe","annotateLogs","sagaId","claimed","claimForResume","instance","tap","result","logInfo","resumedFrom","state","settled","catchAll","error","String","startSagaResume","options","dispatcher","shutdown","pass","provideService","daemon","forkDaemon","delay","millis","intervalMs","forever","register","phase","run","interrupt","asVoid"],"mappings":"AAAA,SAASA,mBAAmB,QAAQ,oBAAoB;AACxD,SAASC,QAAQ,EAAEC,MAAM,EAAEC,KAAK,QAAQ,SAAS;AAGjD,SAASC,iBAAiB,QAAQ,8BAA8B;AAChE,SAASC,YAAY,QAAQ,yBAAyB;AACtD,SAASC,UAAU,QAAQ,gBAAgB;AAoB3C;;;;;;;;;;;CAWC,GACD,OAAO,MAAMC,mBAAmB,CAAC,EAC/BC,WAAW,EACXC,YAAY,EACZC,iBAAiB,EACE,GAKnBR,OAAOS,GAAG,CAAC;QACT,MAAMC,QAAQ,OAAOP;QACrB,MAAMQ,SAAS,IAAIC,IACjBN,YAAYO,GAAG,CAACC,CAAAA,aAAc;gBAACA,WAAWC,IAAI;gBAAED;aAAW;QAG7D,KAAK,MAAME,SAAS,OAAON,MAAMO,SAAS,CAACV,cAAe;YACxD,MAAMO,aAAaH,OAAOO,GAAG,CAACF,MAAMF,UAAU;YAC9C,IAAIA,eAAeK,WAAW;gBAC5B,uEAAuE;gBACvE,iEAAiE;gBACjE,OAAOnB,OAAOoB,QAAQ,CAAC,0CAA0CC,IAAI,CACnErB,OAAOsB,YAAY,CAAC;oBAClBC,QAAQP,MAAMO,MAAM;oBACpBT,YAAYE,MAAMF,UAAU;gBAC9B;gBAEF;YACF;YAEA,MAAMU,UAAU,OAAOd,MAAMe,cAAc,CAACT,MAAMO,MAAM,EAAEhB;YAC1D,IAAIiB,YAAYL,WAAW;YAE3B,OAAOf,WAAW;gBAChBsB,UAAUF;gBACVV;gBACAN;YACF,GAAGa,IAAI,CACLrB,OAAO2B,GAAG,CAACC,CAAAA,SACT5B,OAAO6B,OAAO,CAAC,2BAA2BR,IAAI,CAC5CrB,OAAOsB,YAAY,CAAC;oBAClBC,QAAQC,QAAQD,MAAM;oBACtBT,YAAYU,QAAQV,UAAU;oBAC9BgB,aAAaN,QAAQO,KAAK;oBAC1BC,SAASJ,OAAOG,KAAK;gBACvB,MAGJ/B,OAAOiC,QAAQ,CAACC,CAAAA,QACdlC,OAAOoB,QAAQ,CAAC,mCAAmCC,IAAI,CACrDrB,OAAOsB,YAAY,CAAC;oBAClBC,QAAQC,QAAQD,MAAM;oBACtBW,OAAOC,OAAOD;gBAChB;QAIR;IACF,GAAGb,IAAI,CACLrB,OAAOiC,QAAQ,CAACC,CAAAA,QACdlC,OAAOoB,QAAQ,CAAC,4BAA4BC,IAAI,CAC9CrB,OAAOsB,YAAY,CAAC;YAAEY,OAAOC,OAAOD;QAAO,MAG/C;AAEJ;;;;;;CAMC,GACD,OAAO,MAAME,kBAAkB,CAC7BC,UAMArC,OAAOS,GAAG,CAAC;QACT,MAAMC,QAAQ,OAAOP;QACrB,MAAMmC,aAAa,OAAOpC;QAC1B,MAAMqC,WAAW,OAAOzC;QAExB,wEAAwE;QACxE,wCAAwC;QACxC,MAAM0C,OAAOnC,iBAAiBgC,SAAShB,IAAI,CACzCrB,OAAOyC,cAAc,CAACtC,cAAcO,QACpCV,OAAOyC,cAAc,CAACvC,mBAAmBoC;QAG3C,MAAMI,SAAS,OAAO1C,OAAO2C,UAAU,CACrCH,KAAKnB,IAAI,CACPrB,OAAO4C,KAAK,CAAC7C,SAAS8C,MAAM,CAACR,QAAQS,UAAU,IAC/C9C,OAAO+C,OAAO;QAIlB,OAAOR,SAASS,QAAQ,CAAC;YACvBjC,MAAM;YACNkC,OAAO;YACPC,KAAKjD,MAAMkD,SAAS,CAACT,QAAQrB,IAAI,CAACrB,OAAOoD,MAAM;QACjD;IACF,GAAG"}
package/dist/index.d.ts CHANGED
@@ -4,7 +4,9 @@ export * from './contracts/inbox.js';
4
4
  export * from './contracts/outbox.js';
5
5
  export * from './contracts/record.js';
6
6
  export * from './contracts/saga-definition.js';
7
+ export * from './engine/local-saga-dispatcher.js';
7
8
  export * from './engine/resolve-template.js';
9
+ export * from './engine/resume-sweep.js';
8
10
  export * from './engine/run-saga.js';
9
11
  export * from './engine/run-transaction.js';
10
12
  export * from './mixins/transaction-mixins.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,wBAAwB,CAAC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC;AACrC,cAAc,uBAAuB,CAAC;AACtC,cAAc,uBAAuB,CAAC;AACtC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,8BAA8B,CAAC;AAC7C,cAAc,sBAAsB,CAAC;AACrC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,yBAAyB,CAAC;AACxC,cAAc,yBAAyB,CAAC;AACxC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,uBAAuB,CAAC;AACtC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,oCAAoC,CAAC;AACnD,cAAc,yBAAyB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,wBAAwB,CAAC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC;AACrC,cAAc,uBAAuB,CAAC;AACtC,cAAc,uBAAuB,CAAC;AACtC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,mCAAmC,CAAC;AAClD,cAAc,8BAA8B,CAAC;AAC7C,cAAc,0BAA0B,CAAC;AACzC,cAAc,sBAAsB,CAAC;AACrC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,yBAAyB,CAAC;AACxC,cAAc,yBAAyB,CAAC;AACxC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,uBAAuB,CAAC;AACtC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,oCAAoC,CAAC;AACnD,cAAc,yBAAyB,CAAC"}
package/dist/index.js CHANGED
@@ -4,7 +4,9 @@ export * from './contracts/inbox.js';
4
4
  export * from './contracts/outbox.js';
5
5
  export * from './contracts/record.js';
6
6
  export * from './contracts/saga-definition.js';
7
+ export * from './engine/local-saga-dispatcher.js';
7
8
  export * from './engine/resolve-template.js';
9
+ export * from './engine/resume-sweep.js';
8
10
  export * from './engine/run-saga.js';
9
11
  export * from './engine/run-transaction.js';
10
12
  export * from './mixins/transaction-mixins.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './contracts/command.js';\nexport * from './contracts/event.js';\nexport * from './contracts/inbox.js';\nexport * from './contracts/outbox.js';\nexport * from './contracts/record.js';\nexport * from './contracts/saga-definition.js';\nexport * from './engine/resolve-template.js';\nexport * from './engine/run-saga.js';\nexport * from './engine/run-transaction.js';\nexport * from './mixins/transaction-mixins.js';\nexport * from './ports/event-bus.js';\nexport * from './ports/event-source.js';\nexport * from './ports/lock-service.js';\nexport * from './ports/saga-dispatcher.js';\nexport * from './ports/saga-store.js';\nexport * from './ports/sequence-service.js';\nexport * from './ports/transaction-handler.js';\nexport * from './ports/transaction-sink.js';\nexport * from './stream/transaction-stream-hub.js';\nexport * from './use-case/facade.uc.js';\n"],"names":[],"mappings":"AAAA,cAAc,yBAAyB;AACvC,cAAc,uBAAuB;AACrC,cAAc,uBAAuB;AACrC,cAAc,wBAAwB;AACtC,cAAc,wBAAwB;AACtC,cAAc,iCAAiC;AAC/C,cAAc,+BAA+B;AAC7C,cAAc,uBAAuB;AACrC,cAAc,8BAA8B;AAC5C,cAAc,iCAAiC;AAC/C,cAAc,uBAAuB;AACrC,cAAc,0BAA0B;AACxC,cAAc,0BAA0B;AACxC,cAAc,6BAA6B;AAC3C,cAAc,wBAAwB;AACtC,cAAc,8BAA8B;AAC5C,cAAc,iCAAiC;AAC/C,cAAc,8BAA8B;AAC5C,cAAc,qCAAqC;AACnD,cAAc,0BAA0B"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './contracts/command.js';\nexport * from './contracts/event.js';\nexport * from './contracts/inbox.js';\nexport * from './contracts/outbox.js';\nexport * from './contracts/record.js';\nexport * from './contracts/saga-definition.js';\nexport * from './engine/local-saga-dispatcher.js';\nexport * from './engine/resolve-template.js';\nexport * from './engine/resume-sweep.js';\nexport * from './engine/run-saga.js';\nexport * from './engine/run-transaction.js';\nexport * from './mixins/transaction-mixins.js';\nexport * from './ports/event-bus.js';\nexport * from './ports/event-source.js';\nexport * from './ports/lock-service.js';\nexport * from './ports/saga-dispatcher.js';\nexport * from './ports/saga-store.js';\nexport * from './ports/sequence-service.js';\nexport * from './ports/transaction-handler.js';\nexport * from './ports/transaction-sink.js';\nexport * from './stream/transaction-stream-hub.js';\nexport * from './use-case/facade.uc.js';\n"],"names":[],"mappings":"AAAA,cAAc,yBAAyB;AACvC,cAAc,uBAAuB;AACrC,cAAc,uBAAuB;AACrC,cAAc,wBAAwB;AACtC,cAAc,wBAAwB;AACtC,cAAc,iCAAiC;AAC/C,cAAc,oCAAoC;AAClD,cAAc,+BAA+B;AAC7C,cAAc,2BAA2B;AACzC,cAAc,uBAAuB;AACrC,cAAc,8BAA8B;AAC5C,cAAc,iCAAiC;AAC/C,cAAc,uBAAuB;AACrC,cAAc,0BAA0B;AACxC,cAAc,0BAA0B;AACxC,cAAc,6BAA6B;AAC3C,cAAc,wBAAwB;AACtC,cAAc,8BAA8B;AAC5C,cAAc,iCAAiC;AAC/C,cAAc,8BAA8B;AAC5C,cAAc,qCAAqC;AACnD,cAAc,0BAA0B"}
@@ -48,7 +48,7 @@ export type PendingEntry = PendingTransaction & {
48
48
  * takes it from there.
49
49
  *
50
50
  * Framework-free and synchronous on purpose: the implementation is a React store
51
- * action, and keeping that behind a port is what stops `entifix:transactions`
51
+ * action, and keeping that behind a port is what stops `@entifix/transactions`
52
52
  * knowing anything about React or about where the pending set is persisted.
53
53
  */
54
54
  export interface TransactionSink {
@@ -86,7 +86,7 @@ export declare const NoopTransactionSink: TransactionSink;
86
86
  * It extends {@link TransactionSink} because one store is behind both: the
87
87
  * adapter needs only `began`, and the settlement side needs to read entries and
88
88
  * retire them. Two interfaces rather than one because they are consumed from
89
- * opposite sides of a layer boundary — `entifix:react` may not import a shell,
89
+ * opposite sides of a tier boundary — a T3 package may not import a T4 shell,
90
90
  * so the store is handed in as a prop, the way `EntityDraftStore` already is for
91
91
  * autosave (ADR 0032).
92
92
  */
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ports/transaction-sink.ts"],"sourcesContent":["import { Context } from 'effect';\n\n/**\n * A write the browser has started and the server has not finished.\n *\n * The `transactionId` is also the stored entity's id — ADR 0028 makes the\n * client's minted id the primary key — so this is enough to find the record\n * later without holding a copy of it.\n */\nexport interface PendingTransaction {\n readonly transactionId: string;\n /** The target entity's `key`, so a settle knows which query scope to refresh. */\n readonly entity: string;\n /** ISO-8601, when the `202` came back. Drives the oldest-first eviction. */\n readonly at: string;\n}\n\n/** A pending write, plus what reconciliation has since learned about it. */\nexport type PendingEntry = PendingTransaction & {\n readonly state: 'pending' | 'failed';\n /**\n * The record as the browser holds it, so a list can show it before the server\n * has one.\n *\n * ⚠️ **In memory only — never persisted.** The store's `partialize` strips it,\n * for ADR 0032's reason: a class instance does not survive a JSON round trip,\n * it comes back as something else. So a refresh keeps the *watch* and loses\n * the row, which is the documented behaviour — past a refresh, server truth\n * plus an honest notice beats a record rebuilt from a blob.\n *\n * Typed `unknown` because this package must not care what an entity is; the\n * shell that put it here is the only thing that reads it back.\n */\n readonly record?: unknown;\n /**\n * Free text from whatever threw, in whatever language it was written in.\n *\n * ⚠️ Diagnostic only — never the headline of anything a user reads. A\n * transaction's failure carries no error *code*, so the message shown has to\n * be a catalog key and this is the detail beside it (ADR 0043's residual).\n */\n readonly reason?: string;\n};\n\n/**\n * How a transactional write announces itself to whoever is watching.\n *\n * The save adapter is the only place that knows a create went out as a command\n * rather than as a plain `POST`, and it learns nothing back — the `202`\n * describes a transaction, not an entity. So it tells this port, and the browser\n * takes it from there.\n *\n * Framework-free and synchronous on purpose: the implementation is a React store\n * action, and keeping that behind a port is what stops `entifix:transactions`\n * knowing anything about React or about where the pending set is persisted.\n */\nexport interface TransactionSink {\n began(pending: PendingTransaction): void;\n}\n\n/**\n * ⚠️ Read with `Effect.serviceOption`, never `yield*`.\n *\n * That keeps the tag out of the save adapter's `R`, so the storefront, the plain\n * REST adapters and every existing spec compile and run with no layer to\n * provide — an optional capability must not become a build break for callers\n * that will never want it.\n *\n * The cost of that erasure is that **nothing forces a composition root to\n * provide it**: forget to, and the read returns `None`, everything compiles, and\n * the feature is silently dead. A spec pins the one place that must\n * (`mergeContext`), because an invariant the compiler cannot hold is one a test\n * has to.\n */\nexport class TransactionSinkTag extends Context.Tag('TransactionSinkTag')<\n TransactionSinkTag,\n TransactionSink\n>() {}\n\n/**\n * The sink where nothing is watching — outside a mounted provider, and in every\n * caller that never opted into command creates.\n *\n * A create on a plain route still works exactly as it did; it simply gets no\n * optimistic treatment, which is an honest boundary rather than a write into an\n * unscoped store.\n */\nexport const NoopTransactionSink: TransactionSink = {\n began: () => undefined,\n};\n\n/**\n * The full view of the pending set, for the side that reconciles it.\n *\n * It extends {@link TransactionSink} because one store is behind both: the\n * adapter needs only `began`, and the settlement side needs to read entries and\n * retire them. Two interfaces rather than one because they are consumed from\n * opposite sides of a layer boundary — `entifix:react` may not import a shell,\n * so the store is handed in as a prop, the way `EntityDraftStore` already is for\n * autosave (ADR 0032).\n */\nexport interface PendingTransactionStore extends TransactionSink {\n readonly entries: readonly PendingEntry[];\n /** The write landed. Drop it; the server's copy is the truth now. */\n settle(transactionId: string): void;\n /**\n * Holds the record the browser already has, so the list can render it while\n * the write is still in flight — and answers whether this id was being\n * watched at all.\n *\n * ⚠️ **The return value is why this is one call and not two.** A caller that\n * asked `entries.some(...)` first would be reading a React render closure\n * captured *before* its own `await`, so the announcement the save adapter made\n * during that await is invisible to it and every transactional write reads as\n * a plain one. Answering from the store's current state is the only version\n * without that race.\n *\n * Separate from `began` because the save adapter announces before it returns\n * and has no reason to know about lists.\n */\n attach(transactionId: string, record: unknown): boolean;\n /** The write failed terminally. Keep it, marked, until it is dismissed. */\n fail(transactionId: string, reason?: string): void;\n /** The operator has read the failure. */\n dismiss(transactionId: string): void;\n}\n"],"names":["Context","TransactionSinkTag","Tag","NoopTransactionSink","began","undefined"],"mappings":"AAAA,SAASA,OAAO,QAAQ,SAAS;AA4DjC;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,2BAA2BD,QAAQE,GAAG,CAAC;AAG/C;AAEL;;;;;;;CAOC,GACD,OAAO,MAAMC,sBAAuC;IAClDC,OAAO,IAAMC;AACf,EAAE"}
1
+ {"version":3,"sources":["../../src/ports/transaction-sink.ts"],"sourcesContent":["import { Context } from 'effect';\n\n/**\n * A write the browser has started and the server has not finished.\n *\n * The `transactionId` is also the stored entity's id — ADR 0028 makes the\n * client's minted id the primary key — so this is enough to find the record\n * later without holding a copy of it.\n */\nexport interface PendingTransaction {\n readonly transactionId: string;\n /** The target entity's `key`, so a settle knows which query scope to refresh. */\n readonly entity: string;\n /** ISO-8601, when the `202` came back. Drives the oldest-first eviction. */\n readonly at: string;\n}\n\n/** A pending write, plus what reconciliation has since learned about it. */\nexport type PendingEntry = PendingTransaction & {\n readonly state: 'pending' | 'failed';\n /**\n * The record as the browser holds it, so a list can show it before the server\n * has one.\n *\n * ⚠️ **In memory only — never persisted.** The store's `partialize` strips it,\n * for ADR 0032's reason: a class instance does not survive a JSON round trip,\n * it comes back as something else. So a refresh keeps the *watch* and loses\n * the row, which is the documented behaviour — past a refresh, server truth\n * plus an honest notice beats a record rebuilt from a blob.\n *\n * Typed `unknown` because this package must not care what an entity is; the\n * shell that put it here is the only thing that reads it back.\n */\n readonly record?: unknown;\n /**\n * Free text from whatever threw, in whatever language it was written in.\n *\n * ⚠️ Diagnostic only — never the headline of anything a user reads. A\n * transaction's failure carries no error *code*, so the message shown has to\n * be a catalog key and this is the detail beside it (ADR 0043's residual).\n */\n readonly reason?: string;\n};\n\n/**\n * How a transactional write announces itself to whoever is watching.\n *\n * The save adapter is the only place that knows a create went out as a command\n * rather than as a plain `POST`, and it learns nothing back — the `202`\n * describes a transaction, not an entity. So it tells this port, and the browser\n * takes it from there.\n *\n * Framework-free and synchronous on purpose: the implementation is a React store\n * action, and keeping that behind a port is what stops `@entifix/transactions`\n * knowing anything about React or about where the pending set is persisted.\n */\nexport interface TransactionSink {\n began(pending: PendingTransaction): void;\n}\n\n/**\n * ⚠️ Read with `Effect.serviceOption`, never `yield*`.\n *\n * That keeps the tag out of the save adapter's `R`, so the storefront, the plain\n * REST adapters and every existing spec compile and run with no layer to\n * provide — an optional capability must not become a build break for callers\n * that will never want it.\n *\n * The cost of that erasure is that **nothing forces a composition root to\n * provide it**: forget to, and the read returns `None`, everything compiles, and\n * the feature is silently dead. A spec pins the one place that must\n * (`mergeContext`), because an invariant the compiler cannot hold is one a test\n * has to.\n */\nexport class TransactionSinkTag extends Context.Tag('TransactionSinkTag')<\n TransactionSinkTag,\n TransactionSink\n>() {}\n\n/**\n * The sink where nothing is watching — outside a mounted provider, and in every\n * caller that never opted into command creates.\n *\n * A create on a plain route still works exactly as it did; it simply gets no\n * optimistic treatment, which is an honest boundary rather than a write into an\n * unscoped store.\n */\nexport const NoopTransactionSink: TransactionSink = {\n began: () => undefined,\n};\n\n/**\n * The full view of the pending set, for the side that reconciles it.\n *\n * It extends {@link TransactionSink} because one store is behind both: the\n * adapter needs only `began`, and the settlement side needs to read entries and\n * retire them. Two interfaces rather than one because they are consumed from\n * opposite sides of a tier boundary — a T3 package may not import a T4 shell,\n * so the store is handed in as a prop, the way `EntityDraftStore` already is for\n * autosave (ADR 0032).\n */\nexport interface PendingTransactionStore extends TransactionSink {\n readonly entries: readonly PendingEntry[];\n /** The write landed. Drop it; the server's copy is the truth now. */\n settle(transactionId: string): void;\n /**\n * Holds the record the browser already has, so the list can render it while\n * the write is still in flight — and answers whether this id was being\n * watched at all.\n *\n * ⚠️ **The return value is why this is one call and not two.** A caller that\n * asked `entries.some(...)` first would be reading a React render closure\n * captured *before* its own `await`, so the announcement the save adapter made\n * during that await is invisible to it and every transactional write reads as\n * a plain one. Answering from the store's current state is the only version\n * without that race.\n *\n * Separate from `began` because the save adapter announces before it returns\n * and has no reason to know about lists.\n */\n attach(transactionId: string, record: unknown): boolean;\n /** The write failed terminally. Keep it, marked, until it is dismissed. */\n fail(transactionId: string, reason?: string): void;\n /** The operator has read the failure. */\n dismiss(transactionId: string): void;\n}\n"],"names":["Context","TransactionSinkTag","Tag","NoopTransactionSink","began","undefined"],"mappings":"AAAA,SAASA,OAAO,QAAQ,SAAS;AA4DjC;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,2BAA2BD,QAAQE,GAAG,CAAC;AAG/C;AAEL;;;;;;;CAOC,GACD,OAAO,MAAMC,sBAAuC;IAClDC,OAAO,IAAMC;AACf,EAAE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/transactions",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Commands, transactions and sagas: inbox and outbox ports, an event bus, locks, and a declarative saga runner.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -31,9 +31,6 @@
31
31
  ],
32
32
  "nx": {
33
33
  "tags": [
34
- "layer:entifix",
35
- "scope:shared",
36
- "entifix:transactions",
37
34
  "tier:2"
38
35
  ],
39
36
  "sourceRoot": "packages/ts/transactions/src",
@@ -55,7 +52,8 @@
55
52
  },
56
53
  "dependencies": {
57
54
  "@swc/helpers": "0.5.23",
58
- "@entifix/core": "0.1.1"
55
+ "@entifix/business": "0.1.3",
56
+ "@entifix/core": "0.1.3"
59
57
  },
60
58
  "peerDependencies": {
61
59
  "effect": ">=3.22 <4"