@entifix/transactions 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/contracts/command.d.ts +2 -2
- package/dist/contracts/command.d.ts.map +1 -1
- package/dist/contracts/command.js.map +1 -1
- package/dist/contracts/inbox.d.ts +2 -2
- package/dist/contracts/inbox.d.ts.map +1 -1
- package/dist/contracts/inbox.js.map +1 -1
- package/dist/contracts/outbox.d.ts +6 -6
- package/dist/contracts/outbox.d.ts.map +1 -1
- package/dist/contracts/outbox.js.map +1 -1
- package/dist/contracts/record.d.ts +4 -4
- package/dist/contracts/record.d.ts.map +1 -1
- package/dist/contracts/record.js.map +1 -1
- package/dist/contracts/unit-of-work.d.ts +5 -5
- package/dist/contracts/unit-of-work.d.ts.map +1 -1
- package/dist/contracts/unit-of-work.js +1 -1
- package/dist/contracts/unit-of-work.js.map +1 -1
- package/dist/engine/in-memory-retry-budget.d.ts +33 -0
- package/dist/engine/in-memory-retry-budget.d.ts.map +1 -0
- package/dist/engine/in-memory-retry-budget.js +84 -0
- package/dist/engine/in-memory-retry-budget.js.map +1 -0
- package/dist/engine/index.d.ts +1 -0
- package/dist/engine/index.d.ts.map +1 -1
- package/dist/engine/index.js +1 -0
- package/dist/engine/index.js.map +1 -1
- package/dist/engine/run-saga.d.ts +3 -3
- package/dist/engine/run-saga.d.ts.map +1 -1
- package/dist/engine/run-saga.js.map +1 -1
- package/dist/engine/run-transaction.d.ts +1 -1
- package/dist/engine/run-transaction.d.ts.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/ports/event-bus.d.ts +3 -3
- package/dist/ports/event-bus.d.ts.map +1 -1
- package/dist/ports/event-bus.js.map +1 -1
- package/dist/ports/lock-service.d.ts +4 -4
- package/dist/ports/lock-service.d.ts.map +1 -1
- package/dist/ports/lock-service.js.map +1 -1
- package/dist/ports/retry-budget.d.ts +51 -0
- package/dist/ports/retry-budget.d.ts.map +1 -0
- package/dist/ports/retry-budget.js +23 -0
- package/dist/ports/retry-budget.js.map +1 -0
- package/dist/ports/saga-store.d.ts +9 -9
- package/dist/ports/saga-store.d.ts.map +1 -1
- package/dist/ports/saga-store.js.map +1 -1
- package/dist/ports/sequence-service.d.ts +2 -2
- package/dist/ports/sequence-service.d.ts.map +1 -1
- package/dist/ports/sequence-service.js.map +1 -1
- package/dist/reactions/on.d.ts +53 -0
- package/dist/reactions/on.d.ts.map +1 -0
- package/dist/reactions/on.js +55 -0
- package/dist/reactions/on.js.map +1 -0
- package/dist/use-case/facade.uc.d.ts +2 -2
- package/dist/use-case/facade.uc.d.ts.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/engine/run-saga.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Effect } from 'effect';\n\nimport {\n type SagaCall,\n type SagaCallOutcome,\n sagaCommandId,\n type SagaDefinition,\n type SagaInputs,\n type SagaStep,\n type SagaStepInput,\n type SagaStepOutcome,\n} from '../contracts/saga-definition.js';\nimport { SagaDispatcherTag } from '../ports/saga-dispatcher.js';\nimport {\n type SagaInstance,\n type SagaStore,\n SagaStoreTag,\n} from '../ports/saga-store.js';\nimport { resolveBodyTemplate, resolveTemplate } from './resolve-template.js';\n\nexport type { SagaInputs, SagaStepInput };\n\n/**\n * The steps that have run, kept with their outcomes.\n *\n * Paired rather than looked back up by id, because a lookup introduces a\n * not-found branch that cannot happen — and an unreachable branch is a line\n * nothing can ever prove correct. A resumed walk rebuilds this from the stored\n * outcomes, which is the one place the lookup does happen and can genuinely\n * fail.\n */\ntype Taken = Array<{ step: SagaStep; outcome: SagaStepOutcome }>;\n\nexport interface RunSagaOptions {\n readonly sagaId: string;\n readonly definition: SagaDefinition;\n readonly inputs: SagaInputs;\n}\n\n/** How a run ended. */\nexport interface SagaResult {\n readonly state: 'COMPLETED' | 'COMPENSATED' | 'STRANDED';\n readonly outcomes: readonly SagaStepOutcome[];\n readonly error?: string;\n}\n\n/**\n * What one element of a `fanOutFrom` step is dispatched with.\n *\n * The earlier call's body travels as `outcome` rather than `input`, which is the\n * same scope a compensation resolves against and for the same reason: the id\n * being addressed was minted by the participant and is in its response.\n */\ninterface DerivedElement {\n readonly input: SagaStepInput;\n readonly scope: Record<string, unknown>;\n}\n\nconst inputsFor = (\n step: SagaStep,\n inputs: SagaInputs,\n): readonly SagaStepInput[] => {\n const declared = inputs[step.id] ?? [];\n // A non-fan-out step makes exactly one call whether or not it was given an\n // input, so an absent entry is an empty body rather than a skipped step.\n return step.fanOut ? declared : [declared[0] ?? {}];\n};\n\n/**\n * The elements a step actually dispatches: derived from an earlier step's\n * successful calls when it declares `fanOutFrom`, and from the caller's input\n * otherwise.\n *\n * ⚠️ **A `fanOutFrom` step ignores whatever the caller supplied for it.** The\n * cardinality is the earlier step's, and taking the caller's would let a\n * checkout convert a hold it never took — or, more likely, silently convert\n * none, which is how a saga reports COMPLETED with the goods still held.\n */\n/**\n * What every step can point at: the **first successful call** of each step that\n * has already run, by step id.\n *\n * First rather than all, because a template naming a fan-out step is ambiguous\n * by construction — \"the order id\" is one value and \"the reservation ids\" are\n * many, and the many case is what `fanOutFrom` exists for. Keeping this to the\n * unambiguous case is what stops `{steps.reserve.data.id}` quietly meaning\n * \"whichever hold happened to be first\".\n */\nconst stepsScope = (\n taken: ReadonlyArray<{ step: SagaStep; outcome: SagaStepOutcome }>,\n): Record<string, unknown> =>\n Object.fromEntries(\n taken\n .filter(entry => entry.outcome.calls.length > 0)\n .map(entry => [entry.step.id, entry.outcome.calls[0]?.body]),\n );\n\nconst elementsFor = (\n step: SagaStep,\n inputs: SagaInputs,\n taken: ReadonlyArray<{ step: SagaStep; outcome: SagaStepOutcome }>,\n): readonly DerivedElement[] => {\n const steps = stepsScope(taken);\n\n if (step.fanOutFrom === undefined) {\n return inputsFor(step, inputs).map(input => ({\n input,\n scope: { input: input.body, steps },\n }));\n }\n\n const source = taken.find(entry => entry.step.id === step.fanOutFrom);\n const body = inputs[step.id]?.[0]?.body;\n\n return (source?.outcome.calls ?? []).map(call => ({\n // ⚠️ The organization the *earlier call* acted for, never the caller's.\n // A tenant-plane participant resolves its handle from the header, so a\n // conversion dispatched without it is refused `400` and the hold expires\n // under a buyer who has already been charged.\n input: { body, organizationId: call.organizationId },\n scope: { outcome: call.body, input: body, steps },\n }));\n};\n\nconst dispatchCall = (\n step: SagaStep,\n call: SagaCall,\n sagaId: string,\n index: number,\n input: SagaStepInput,\n scope: Record<string, unknown>,\n) =>\n Effect.gen(function* () {\n const dispatcher = yield* SagaDispatcherTag;\n return yield* dispatcher.dispatch({\n participant: step.participant,\n call: { method: call.method, path: resolveTemplate(call.path, scope) },\n commandId: sagaCommandId(\n sagaId,\n step.id,\n step.fanOut ? index : undefined,\n ),\n organizationId: input.organizationId,\n body:\n call.method === 'GET' || call.method === 'DELETE'\n ? undefined\n : resolveBodyTemplate(input.body, scope),\n });\n });\n\n/**\n * Run one step: every call it makes, in order, stopping at the first refusal.\n *\n * Returns the calls that **succeeded** alongside the failure, because those are\n * exactly the calls a compensation has to undo — see {@link compensateStep}.\n */\nconst runStep = (\n step: SagaStep,\n sagaId: string,\n elements: readonly DerivedElement[],\n): Effect.Effect<\n { readonly calls: readonly SagaCallOutcome[]; readonly error?: string },\n EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n const calls: SagaCallOutcome[] = [];\n\n for (const [index, element] of elements.entries()) {\n const { input } = element;\n const response = yield* dispatchCall(\n step,\n step.command,\n sagaId,\n index,\n input,\n element.scope,\n );\n\n if (!response.ok) {\n // A business refusal. The saga fails *forward* into compensation, and\n // the calls already recorded are the ones that have to come back.\n return {\n calls,\n error: `step '${step.id}' call ${String(index)} refused with ${String(\n response.status,\n )}`,\n };\n }\n\n calls.push({\n index,\n status: response.status,\n body: response.body,\n // Carried so the compensation reaches the same tenant. Without it a\n // release is refused `400` and the saga strands holding stock.\n organizationId: input.organizationId,\n });\n }\n\n return { calls };\n });\n\n/**\n * Undo one step — **one compensation per successful call**, never one per step.\n *\n * ⚠️ This is the whole reason an outcome is kept per fan-out element. Five lines\n * with three holds taken and the fourth refused must release exactly three:\n * compensating the step as a unit would either release nothing or attempt to\n * release two holds that were never taken.\n *\n * Never fails: a compensation's own failure is reported by the caller and must\n * not stop the compensations after it, because a stranded saga nobody is told about is the same as a lost one.\n */\nconst compensateStep = (\n step: SagaStep,\n sagaId: string,\n outcome: SagaStepOutcome,\n): Effect.Effect<readonly string[], never, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const compensation = step.compensation;\n if (!compensation) {\n return [];\n }\n\n const failures: string[] = [];\n // Reverse order: the last thing done is the first thing undone, which is\n // what a reader expects of a stack of effects and what keeps a future\n // ordering dependency from being an accident.\n for (const call of [...outcome.calls].reverse()) {\n const result = yield* dispatchCall(\n step,\n compensation,\n sagaId,\n call.index,\n // ⚠️ The organization the *call* acted for, not an empty input. A\n // tenant-plane participant resolves its handle from the header, so a\n // compensation without it is refused before it reaches the hold.\n { organizationId: call.organizationId },\n { outcome: call.body },\n ).pipe(\n Effect.catch(error =>\n Effect.succeed({ ok: false, status: 0, body: error }),\n ),\n // A template that no longer matches the participant's response shape\n // throws rather than interpolating `undefined`; that is a defect, and\n // it is reported as a stranded compensation rather than crashing the\n // walk and leaving every later hold in place.\n Effect.catchDefect(defect =>\n Effect.succeed({ ok: false, status: 0, body: defect }),\n ),\n );\n\n // ⚠️ **A `404` is a compensation that has nothing left to undo**, and it\n // counts as success. Compensation is at-least-once the moment a resumed\n // coordinator can retry it, and a participant answering \"no such record\"\n // on the second delivery is describing a flow that *was* reversed. Left\n // as a refusal it strands exactly the sagas that were cleaned up\n // correctly — the same failure a conversion route that refuses a\n // redelivery has, from the other side.\n if (!result.ok && result.status !== 404) {\n failures.push(\n `compensation for '${step.id}' call ${String(call.index)} failed: ${String(\n result.body,\n )}`,\n );\n }\n }\n\n return failures;\n });\n\n/**\n * How many extra times a step is dispatched once the pivot has committed.\n *\n * Small and immediate on purpose. This is the in-process half of \"roll forward\",\n * and it exists to ride out the blip — a participant restarting, a connection\n * reset — not to be a retry policy. A step that is still refusing after these\n * strands the saga, loudly, because the alternative is a coordinator spinning on\n * a permanent failure while a customer's money sits captured.\n *\n * Durable retry across a coordinator restart is a different mechanism and is not\n * built: the alternative makes a step dispatch an outbox entry whose relay\n * performs the POST.\n */\nconst POST_PIVOT_RETRIES = 3;\n\n/**\n * Dispatch a step, retrying it `retries` more times while it refuses.\n *\n * ⚠️ **A retry re-dispatches the calls that already succeeded**, and that is\n * safe for exactly one reason: `sagaCommandId(sagaId, step.id, index)` is stable\n * across attempts, so a participant that is idempotent on the command id\n * recognises the replay. That is a requirement on every participant a saga may\n * retry; this is the code that depends on it.\n */\nconst runStepWithRetries = (\n step: SagaStep,\n sagaId: string,\n elements: readonly DerivedElement[],\n retries: number,\n): Effect.Effect<\n { readonly calls: readonly SagaCallOutcome[]; readonly error?: string },\n EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n let result = yield* runStep(step, sagaId, elements);\n\n for (\n let attempt = 1;\n attempt <= retries && result.error !== undefined;\n attempt += 1\n ) {\n yield* Effect.logWarning('retrying a saga step after the pivot').pipe(\n Effect.annotateLogs({\n sagaId,\n stepId: step.id,\n attempt,\n error: result.error,\n }),\n );\n result = yield* runStep(step, sagaId, elements);\n }\n\n return result;\n });\n\n/** Pair each recorded outcome with the step that produced it. */\nconst rebuildTaken = (\n definition: SagaDefinition,\n outcomes: readonly SagaStepOutcome[],\n): Taken | { readonly unknownStep: string } => {\n const taken: Taken = [];\n for (const outcome of outcomes) {\n const step = definition.steps.find(\n candidate => candidate.id === outcome.stepId,\n );\n // ⚠️ Not skipped. An outcome naming a step the definition no longer has\n // means the definition changed under a live instance, so the flow this\n // record describes and the flow the engine would walk are different flows.\n // Carrying on would compensate the wrong steps in the wrong order.\n if (!step) {\n return { unknownStep: outcome.stepId };\n }\n taken.push({ step, outcome });\n }\n return taken;\n};\n\n/** Whether the point of no return is behind us, read off what actually ran. */\nconst pivotCommittedIn = (taken: Taken): boolean =>\n taken.some(\n entry => entry.step.kind === 'pivot' && entry.outcome.error === undefined,\n );\n\n/**\n * Settle a saga that cannot go forward and cannot be reversed, loudly.\n *\n * ⚠️ The message is a parameter because these are **different operational\n * events** and each is grepped for on its own: money is captured behind a\n * pivot, a release was refused and stock is still held, a definition changed\n * under a live instance. Collapsing them into one string would make the log\n * line say only that something is wrong.\n */\nconst strand = (\n store: SagaStore,\n sagaId: string,\n outcomes: readonly SagaStepOutcome[],\n error: string,\n message: string,\n log: Record<string, unknown>,\n) =>\n Effect.gen(function* () {\n yield* Effect.logError(message).pipe(\n Effect.annotateLogs({ sagaId, error, ...log }),\n );\n yield* store.settle(sagaId, 'STRANDED', error);\n return { state: 'STRANDED', outcomes, error } as const;\n });\n\n/**\n * Unwind every compensatable step already taken, newest first.\n *\n * Shared by the in-process walk and by a resumed one, which is the whole reason\n * it is a function: a coordinator that died *while* compensating comes back\n * into exactly this loop, and the steps it already gave back carry\n * `compensated` so they are not given back twice.\n */\nconst unwind = (\n store: SagaStore,\n sagaId: string,\n definition: SagaDefinition,\n taken: Taken,\n error: string,\n): Effect.Effect<SagaResult, EntifixConnError, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const outcomes = taken.map(entry => entry.outcome);\n const failures: string[] = [];\n\n for (const done of [...taken].reverse()) {\n if (done.outcome.compensated === true) {\n continue;\n }\n const stepFailures = yield* compensateStep(\n done.step,\n sagaId,\n done.outcome,\n );\n failures.push(...stepFailures);\n // Marked only when the step came back whole. A partial failure stays\n // unmarked so a later resume retries it — safe because a compensation\n // with nothing left to undo answers `404`, which is a success above.\n if (stepFailures.length === 0) {\n yield* store.markCompensated(sagaId, done.step.id);\n }\n }\n\n if (failures.length > 0) {\n // ⚠️ Surfaced, never swallowed. This is the state that leaves a\n // reservation held and — once payment lands — a customer charged, and\n // it is the failure class nobody plans for.\n return yield* strand(\n store,\n sagaId,\n outcomes,\n error,\n 'saga compensation failed',\n { definition: definition.name, failures: failures.join('; ') },\n );\n }\n\n yield* store.settle(sagaId, 'COMPENSATED', error);\n return { state: 'COMPENSATED', outcomes, error };\n });\n\n/**\n * Dispatch the definition's steps from `startIndex` on, and unwind on a refusal.\n *\n * The state transition is persisted **before** each dispatch, so a crash leaves\n * a record that says what was actually attempted — the outbox's rule, extended\n * from events to commands.\n *\n * ⚠️ **Once the pivot has committed, nothing is unwound.** That is what a pivot\n * means, and the walk has to know it rather than the definition merely declaring\n * it: `compensateStep` no-ops on a step that declares no compensation, so an\n * unconditional unwind after a successful capture would skip the pivot in\n * silence and then delete the order behind it and release the holds behind that\n * — money taken, goods back on sale, every probe green. The step is retried\n * instead, and a saga that still cannot go forward is settled `STRANDED` and\n * logged, because a stranded saga nobody is told about is the same as a lost one.\n */\nconst walk = (\n store: SagaStore,\n options: RunSagaOptions,\n from: { readonly taken: Taken; readonly startIndex: number },\n): Effect.Effect<SagaResult, EntifixConnError, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const { sagaId, definition, inputs } = options;\n // Step and outcome are kept **together**: looking the step back up by id\n // would introduce a not-found branch that cannot happen, and an unreachable\n // branch is a line nothing can ever prove correct.\n const taken = from.taken;\n const outcomes = () => taken.map(entry => entry.outcome);\n\n // The point of no return, once it is behind us. Tracked rather than read off\n // the definition because what matters is not that a pivot exists but that it\n // *committed* — a pivot that refuses is still fully reversible, and is the\n // ordinary compensation case below.\n let pivotCommitted = pivotCommittedIn(taken);\n\n for (\n let index = from.startIndex;\n index < definition.steps.length;\n index++\n ) {\n const step = definition.steps[index];\n /* v8 ignore next 3 -- the loop bound makes this unreachable; it exists\n because `noUncheckedIndexedAccess` cannot see that. */\n if (!step) {\n continue;\n }\n\n yield* store.beginStep(sagaId, index);\n const { calls, error } = yield* runStepWithRetries(\n step,\n sagaId,\n elementsFor(step, inputs, taken),\n pivotCommitted ? POST_PIVOT_RETRIES : 0,\n );\n\n const outcome: SagaStepOutcome = {\n stepId: step.id,\n calls,\n ...(error === undefined ? {} : { error }),\n };\n taken.push({ step, outcome });\n yield* store.recordOutcome(sagaId, outcome);\n\n if (error === undefined) {\n if (step.kind === 'pivot') {\n pivotCommitted = true;\n }\n continue;\n }\n\n if (pivotCommitted) {\n // ⚠️ Forward or nowhere. Compensating from here would undo steps whose\n // effects the pivot has already been paid for.\n return yield* strand(\n store,\n sagaId,\n outcomes(),\n error,\n 'saga stranded after the pivot',\n { definition: definition.name, stepId: step.id },\n );\n }\n\n // Unwind. The failing step's own successful calls are compensated too —\n // a fan-out step that took three holds before its fourth was refused has\n // three to give back.\n yield* store.settle(sagaId, 'COMPENSATING', error);\n return yield* unwind(store, sagaId, definition, taken, error);\n }\n\n yield* store.settle(sagaId, 'COMPLETED');\n return { state: 'COMPLETED', outcomes: outcomes() };\n });\n\n/**\n * Start a flow and walk it to a terminal state.\n *\n * ⚠️ **Synchronous, and that is the buyer's requirement.** A checkout needs a\n * yes/no now, so this answers the settled result. What {@link resumeSaga} adds\n * is durability *behind* that answer: if this process dies mid-walk, the record\n * it has been writing all along is enough for another one to finish the flow.\n */\nexport const runSaga = (\n options: RunSagaOptions,\n): Effect.Effect<\n SagaResult,\n EntifixConnError,\n SagaDispatcherTag | SagaStoreTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const { sagaId, definition, inputs } = options;\n\n yield* store.start({\n sagaId,\n definition: definition.name,\n state: 'RUNNING',\n stepIndex: 0,\n outcomes: [],\n // ⚠️ Persisted, because a resume has nothing to dispatch without it: a\n // fan-out step's cardinality *is* its input's length.\n inputs,\n resumeAttempts: 0,\n createdAt: new Date().toISOString(),\n });\n\n return yield* walk(store, options, { taken: [], startIndex: 0 });\n });\n\nexport interface ResumeSagaOptions {\n readonly instance: SagaInstance;\n readonly definition: SagaDefinition;\n /** Past this many sweeps, the instance is surfaced instead of retried. */\n readonly maxResumeAttempts: number;\n}\n\n/**\n * Finish a flow another coordinator abandoned.\n *\n * ⚠️ **Where to re-enter is derived, never stored.** A resume point written\n * beside the outcomes would be a second record of the same fact, free to\n * disagree with them; the outcomes already say what happened, and\n * `beginStep`-before-dispatch means `stepIndex` says what was attempted. The\n * four cases are exhaustive:\n *\n * - the step at `stepIndex` recorded no outcome — the process died during the\n * dispatch, so **re-dispatch it**. Safe because `sagaCommandId` is stable\n * across attempts and every participant claims it in its own command inbox,\n * so calls that did land are recognised as replays rather than repeated.\n * - it recorded a successful outcome — the process died between\n * `recordOutcome` and the next `beginStep`, so **start at the one after**.\n * - it recorded a refusal — the process died deciding what to do about it, so\n * **re-enter that decision**: unwind, or strand if the pivot had committed.\n * - the instance is `COMPENSATING` — it died mid-unwind, so **continue the\n * unwind**, skipping steps already marked `compensated`.\n */\nexport const resumeSaga = (\n options: ResumeSagaOptions,\n): Effect.Effect<\n SagaResult,\n EntifixConnError,\n SagaDispatcherTag | SagaStoreTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const { instance, definition, maxResumeAttempts } = options;\n const { sagaId, outcomes } = instance;\n\n if (instance.resumeAttempts > maxResumeAttempts) {\n // Surfaced rather than retried forever. A coordinator spinning on a\n // permanent failure is how money stays captured with nobody told.\n return yield* strand(\n store,\n sagaId,\n outcomes,\n instance.error ??\n `resumed ${String(instance.resumeAttempts - 1)} times without settling`,\n 'saga abandoned after too many resumes',\n {\n definition: definition.name,\n resumeAttempts: instance.resumeAttempts,\n },\n );\n }\n\n const rebuilt = rebuildTaken(definition, outcomes);\n if ('unknownStep' in rebuilt) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n `recorded step '${rebuilt.unknownStep}' is not in definition '${definition.name}'`,\n 'saga instance does not match its definition',\n { definition: definition.name },\n );\n }\n\n const resumeOptions: RunSagaOptions = {\n sagaId,\n definition,\n inputs: instance.inputs,\n };\n\n if (instance.state === 'COMPENSATING') {\n return yield* unwind(\n store,\n sagaId,\n definition,\n rebuilt,\n instance.error ?? 'compensation resumed',\n );\n }\n\n const step = definition.steps[instance.stepIndex];\n if (!step) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n `step ${String(instance.stepIndex)} is not in definition '${definition.name}'`,\n 'saga instance does not match its definition',\n { definition: definition.name },\n );\n }\n\n const recorded = rebuilt.find(entry => entry.step.id === step.id);\n\n if (recorded === undefined) {\n return yield* walk(store, resumeOptions, {\n taken: rebuilt,\n startIndex: instance.stepIndex,\n });\n }\n\n if (recorded.outcome.error === undefined) {\n return yield* walk(store, resumeOptions, {\n taken: rebuilt,\n startIndex: instance.stepIndex + 1,\n });\n }\n\n const error = recorded.outcome.error;\n if (pivotCommittedIn(rebuilt)) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n error,\n 'saga stranded after the pivot',\n { definition: definition.name, stepId: step.id },\n );\n }\n\n yield* store.settle(sagaId, 'COMPENSATING', error);\n return yield* unwind(store, sagaId, definition, rebuilt, error);\n });\n"],"names":["Effect","sagaCommandId","SagaDispatcherTag","SagaStoreTag","resolveBodyTemplate","resolveTemplate","inputsFor","step","inputs","declared","id","fanOut","stepsScope","taken","Object","fromEntries","filter","entry","outcome","calls","length","map","body","elementsFor","steps","fanOutFrom","undefined","input","scope","source","find","call","organizationId","dispatchCall","sagaId","index","gen","dispatcher","dispatch","participant","method","path","commandId","runStep","elements","element","entries","response","command","ok","error","String","status","push","compensateStep","compensation","failures","reverse","result","pipe","catch","succeed","catchDefect","defect","POST_PIVOT_RETRIES","runStepWithRetries","retries","attempt","logWarning","annotateLogs","stepId","rebuildTaken","definition","outcomes","candidate","unknownStep","pivotCommittedIn","some","kind","strand","store","message","log","logError","settle","state","unwind","done","compensated","stepFailures","markCompensated","name","join","walk","options","from","pivotCommitted","startIndex","beginStep","recordOutcome","runSaga","start","stepIndex","resumeAttempts","createdAt","Date","toISOString","resumeSaga","instance","maxResumeAttempts","rebuilt","resumeOptions","recorded"],"mappings":";AACA,SAASA,MAAM,QAAQ,SAAS;AAEhC,S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G,aAAatF,WAAW;YAC1B,OAAO,OAAOmE,KAAKb,OAAO+B,eAAe;gBACvClG,OAAOiG;gBACPb,YAAYW,SAASN,SAAS;YAChC;QACF;QAEA,IAAIU,SAAS9F,OAAO,CAACgC,KAAK,KAAKxB,WAAW;YACxC,OAAO,OAAOmE,KAAKb,OAAO+B,eAAe;gBACvClG,OAAOiG;gBACPb,YAAYW,SAASN,SAAS,GAAG;YACnC;QACF;QAEA,MAAMpD,QAAQ8D,SAAS9F,OAAO,CAACgC,KAAK;QACpC,IAAI0B,iBAAiBkC,UAAU;YAC7B,OAAO,OAAO/B,OACZC,OACA9C,QACAuC,UACAvB,OACA,iCACA;gBAAEsB,YAAYA,WAAWmB,IAAI;gBAAErB,QAAQ/D,KAAKG,EAAE;YAAC;QAEnD;QAEA,OAAOsE,MAAMI,MAAM,CAAClD,QAAQ,gBAAgBgB;QAC5C,OAAO,OAAOoC,OAAON,OAAO9C,QAAQsC,YAAYsC,SAAS5D;IAC3D,GAAG"}
|
|
1
|
+
{"version":3,"sources":["../../src/engine/run-saga.ts"],"sourcesContent":["import type { EntifixConnError, StoreFailure } from '@entifix/core';\nimport { Effect } from 'effect';\n\nimport {\n type SagaCall,\n type SagaCallOutcome,\n sagaCommandId,\n type SagaDefinition,\n type SagaInputs,\n type SagaStep,\n type SagaStepInput,\n type SagaStepOutcome,\n} from '../contracts/saga-definition.js';\nimport { SagaDispatcherTag } from '../ports/saga-dispatcher.js';\nimport {\n type SagaInstance,\n type SagaStore,\n SagaStoreTag,\n} from '../ports/saga-store.js';\nimport { resolveBodyTemplate, resolveTemplate } from './resolve-template.js';\n\nexport type { SagaInputs, SagaStepInput };\n\n/**\n * The steps that have run, kept with their outcomes.\n *\n * Paired rather than looked back up by id, because a lookup introduces a\n * not-found branch that cannot happen — and an unreachable branch is a line\n * nothing can ever prove correct. A resumed walk rebuilds this from the stored\n * outcomes, which is the one place the lookup does happen and can genuinely\n * fail.\n */\ntype Taken = Array<{ step: SagaStep; outcome: SagaStepOutcome }>;\n\nexport interface RunSagaOptions {\n readonly sagaId: string;\n readonly definition: SagaDefinition;\n readonly inputs: SagaInputs;\n}\n\n/** How a run ended. */\nexport interface SagaResult {\n readonly state: 'COMPLETED' | 'COMPENSATED' | 'STRANDED';\n readonly outcomes: readonly SagaStepOutcome[];\n readonly error?: string;\n}\n\n/**\n * What one element of a `fanOutFrom` step is dispatched with.\n *\n * The earlier call's body travels as `outcome` rather than `input`, which is the\n * same scope a compensation resolves against and for the same reason: the id\n * being addressed was minted by the participant and is in its response.\n */\ninterface DerivedElement {\n readonly input: SagaStepInput;\n readonly scope: Record<string, unknown>;\n}\n\nconst inputsFor = (\n step: SagaStep,\n inputs: SagaInputs,\n): readonly SagaStepInput[] => {\n const declared = inputs[step.id] ?? [];\n // A non-fan-out step makes exactly one call whether or not it was given an\n // input, so an absent entry is an empty body rather than a skipped step.\n return step.fanOut ? declared : [declared[0] ?? {}];\n};\n\n/**\n * The elements a step actually dispatches: derived from an earlier step's\n * successful calls when it declares `fanOutFrom`, and from the caller's input\n * otherwise.\n *\n * ⚠️ **A `fanOutFrom` step ignores whatever the caller supplied for it.** The\n * cardinality is the earlier step's, and taking the caller's would let a\n * checkout convert a hold it never took — or, more likely, silently convert\n * none, which is how a saga reports COMPLETED with the goods still held.\n */\n/**\n * What every step can point at: the **first successful call** of each step that\n * has already run, by step id.\n *\n * First rather than all, because a template naming a fan-out step is ambiguous\n * by construction — \"the order id\" is one value and \"the reservation ids\" are\n * many, and the many case is what `fanOutFrom` exists for. Keeping this to the\n * unambiguous case is what stops `{steps.reserve.data.id}` quietly meaning\n * \"whichever hold happened to be first\".\n */\nconst stepsScope = (\n taken: ReadonlyArray<{ step: SagaStep; outcome: SagaStepOutcome }>,\n): Record<string, unknown> =>\n Object.fromEntries(\n taken\n .filter(entry => entry.outcome.calls.length > 0)\n .map(entry => [entry.step.id, entry.outcome.calls[0]?.body]),\n );\n\nconst elementsFor = (\n step: SagaStep,\n inputs: SagaInputs,\n taken: ReadonlyArray<{ step: SagaStep; outcome: SagaStepOutcome }>,\n): readonly DerivedElement[] => {\n const steps = stepsScope(taken);\n\n if (step.fanOutFrom === undefined) {\n return inputsFor(step, inputs).map(input => ({\n input,\n scope: { input: input.body, steps },\n }));\n }\n\n const source = taken.find(entry => entry.step.id === step.fanOutFrom);\n const body = inputs[step.id]?.[0]?.body;\n\n return (source?.outcome.calls ?? []).map(call => ({\n // ⚠️ The organization the *earlier call* acted for, never the caller's.\n // A tenant-plane participant resolves its handle from the header, so a\n // conversion dispatched without it is refused `400` and the hold expires\n // under a buyer who has already been charged.\n input: { body, organizationId: call.organizationId },\n scope: { outcome: call.body, input: body, steps },\n }));\n};\n\nconst dispatchCall = (\n step: SagaStep,\n call: SagaCall,\n sagaId: string,\n index: number,\n input: SagaStepInput,\n scope: Record<string, unknown>,\n) =>\n Effect.gen(function* () {\n const dispatcher = yield* SagaDispatcherTag;\n return yield* dispatcher.dispatch({\n participant: step.participant,\n call: { method: call.method, path: resolveTemplate(call.path, scope) },\n commandId: sagaCommandId(\n sagaId,\n step.id,\n step.fanOut ? index : undefined,\n ),\n organizationId: input.organizationId,\n body:\n call.method === 'GET' || call.method === 'DELETE'\n ? undefined\n : resolveBodyTemplate(input.body, scope),\n });\n });\n\n/**\n * Run one step: every call it makes, in order, stopping at the first refusal.\n *\n * Returns the calls that **succeeded** alongside the failure, because those are\n * exactly the calls a compensation has to undo — see {@link compensateStep}.\n */\nconst runStep = (\n step: SagaStep,\n sagaId: string,\n elements: readonly DerivedElement[],\n): Effect.Effect<\n { readonly calls: readonly SagaCallOutcome[]; readonly error?: string },\n EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n const calls: SagaCallOutcome[] = [];\n\n for (const [index, element] of elements.entries()) {\n const { input } = element;\n const response = yield* dispatchCall(\n step,\n step.command,\n sagaId,\n index,\n input,\n element.scope,\n );\n\n if (!response.ok) {\n // A business refusal. The saga fails *forward* into compensation, and\n // the calls already recorded are the ones that have to come back.\n return {\n calls,\n error: `step '${step.id}' call ${String(index)} refused with ${String(\n response.status,\n )}`,\n };\n }\n\n calls.push({\n index,\n status: response.status,\n body: response.body,\n // Carried so the compensation reaches the same tenant. Without it a\n // release is refused `400` and the saga strands holding stock.\n organizationId: input.organizationId,\n });\n }\n\n return { calls };\n });\n\n/**\n * Undo one step — **one compensation per successful call**, never one per step.\n *\n * ⚠️ This is the whole reason an outcome is kept per fan-out element. Five lines\n * with three holds taken and the fourth refused must release exactly three:\n * compensating the step as a unit would either release nothing or attempt to\n * release two holds that were never taken.\n *\n * Never fails: a compensation's own failure is reported by the caller and must\n * not stop the compensations after it, because a stranded saga nobody is told about is the same as a lost one.\n */\nconst compensateStep = (\n step: SagaStep,\n sagaId: string,\n outcome: SagaStepOutcome,\n): Effect.Effect<readonly string[], never, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const compensation = step.compensation;\n if (!compensation) {\n return [];\n }\n\n const failures: string[] = [];\n // Reverse order: the last thing done is the first thing undone, which is\n // what a reader expects of a stack of effects and what keeps a future\n // ordering dependency from being an accident.\n for (const call of [...outcome.calls].reverse()) {\n const result = yield* dispatchCall(\n step,\n compensation,\n sagaId,\n call.index,\n // ⚠️ The organization the *call* acted for, not an empty input. A\n // tenant-plane participant resolves its handle from the header, so a\n // compensation without it is refused before it reaches the hold.\n { organizationId: call.organizationId },\n { outcome: call.body },\n ).pipe(\n Effect.catch(error =>\n Effect.succeed({ ok: false, status: 0, body: error }),\n ),\n // A template that no longer matches the participant's response shape\n // throws rather than interpolating `undefined`; that is a defect, and\n // it is reported as a stranded compensation rather than crashing the\n // walk and leaving every later hold in place.\n Effect.catchDefect(defect =>\n Effect.succeed({ ok: false, status: 0, body: defect }),\n ),\n );\n\n // ⚠️ **A `404` is a compensation that has nothing left to undo**, and it\n // counts as success. Compensation is at-least-once the moment a resumed\n // coordinator can retry it, and a participant answering \"no such record\"\n // on the second delivery is describing a flow that *was* reversed. Left\n // as a refusal it strands exactly the sagas that were cleaned up\n // correctly — the same failure a conversion route that refuses a\n // redelivery has, from the other side.\n if (!result.ok && result.status !== 404) {\n failures.push(\n `compensation for '${step.id}' call ${String(call.index)} failed: ${String(\n result.body,\n )}`,\n );\n }\n }\n\n return failures;\n });\n\n/**\n * How many extra times a step is dispatched once the pivot has committed.\n *\n * Small and immediate on purpose. This is the in-process half of \"roll forward\",\n * and it exists to ride out the blip — a participant restarting, a connection\n * reset — not to be a retry policy. A step that is still refusing after these\n * strands the saga, loudly, because the alternative is a coordinator spinning on\n * a permanent failure while a customer's money sits captured.\n *\n * Durable retry across a coordinator restart is a different mechanism and is not\n * built: the alternative makes a step dispatch an outbox entry whose relay\n * performs the POST.\n */\nconst POST_PIVOT_RETRIES = 3;\n\n/**\n * Dispatch a step, retrying it `retries` more times while it refuses.\n *\n * ⚠️ **A retry re-dispatches the calls that already succeeded**, and that is\n * safe for exactly one reason: `sagaCommandId(sagaId, step.id, index)` is stable\n * across attempts, so a participant that is idempotent on the command id\n * recognises the replay. That is a requirement on every participant a saga may\n * retry; this is the code that depends on it.\n */\nconst runStepWithRetries = (\n step: SagaStep,\n sagaId: string,\n elements: readonly DerivedElement[],\n retries: number,\n): Effect.Effect<\n { readonly calls: readonly SagaCallOutcome[]; readonly error?: string },\n EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n let result = yield* runStep(step, sagaId, elements);\n\n for (\n let attempt = 1;\n attempt <= retries && result.error !== undefined;\n attempt += 1\n ) {\n yield* Effect.logWarning('retrying a saga step after the pivot').pipe(\n Effect.annotateLogs({\n sagaId,\n stepId: step.id,\n attempt,\n error: result.error,\n }),\n );\n result = yield* runStep(step, sagaId, elements);\n }\n\n return result;\n });\n\n/** Pair each recorded outcome with the step that produced it. */\nconst rebuildTaken = (\n definition: SagaDefinition,\n outcomes: readonly SagaStepOutcome[],\n): Taken | { readonly unknownStep: string } => {\n const taken: Taken = [];\n for (const outcome of outcomes) {\n const step = definition.steps.find(\n candidate => candidate.id === outcome.stepId,\n );\n // ⚠️ Not skipped. An outcome naming a step the definition no longer has\n // means the definition changed under a live instance, so the flow this\n // record describes and the flow the engine would walk are different flows.\n // Carrying on would compensate the wrong steps in the wrong order.\n if (!step) {\n return { unknownStep: outcome.stepId };\n }\n taken.push({ step, outcome });\n }\n return taken;\n};\n\n/** Whether the point of no return is behind us, read off what actually ran. */\nconst pivotCommittedIn = (taken: Taken): boolean =>\n taken.some(\n entry => entry.step.kind === 'pivot' && entry.outcome.error === undefined,\n );\n\n/**\n * Settle a saga that cannot go forward and cannot be reversed, loudly.\n *\n * ⚠️ The message is a parameter because these are **different operational\n * events** and each is grepped for on its own: money is captured behind a\n * pivot, a release was refused and stock is still held, a definition changed\n * under a live instance. Collapsing them into one string would make the log\n * line say only that something is wrong.\n */\nconst strand = (\n store: SagaStore,\n sagaId: string,\n outcomes: readonly SagaStepOutcome[],\n error: string,\n message: string,\n log: Record<string, unknown>,\n) =>\n Effect.gen(function* () {\n yield* Effect.logError(message).pipe(\n Effect.annotateLogs({ sagaId, error, ...log }),\n );\n yield* store.settle(sagaId, 'STRANDED', error);\n return { state: 'STRANDED', outcomes, error } as const;\n });\n\n/**\n * Unwind every compensatable step already taken, newest first.\n *\n * Shared by the in-process walk and by a resumed one, which is the whole reason\n * it is a function: a coordinator that died *while* compensating comes back\n * into exactly this loop, and the steps it already gave back carry\n * `compensated` so they are not given back twice.\n */\nconst unwind = (\n store: SagaStore,\n sagaId: string,\n definition: SagaDefinition,\n taken: Taken,\n error: string,\n): Effect.Effect<\n SagaResult,\n StoreFailure | EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n const outcomes = taken.map(entry => entry.outcome);\n const failures: string[] = [];\n\n for (const done of [...taken].reverse()) {\n if (done.outcome.compensated === true) {\n continue;\n }\n const stepFailures = yield* compensateStep(\n done.step,\n sagaId,\n done.outcome,\n );\n failures.push(...stepFailures);\n // Marked only when the step came back whole. A partial failure stays\n // unmarked so a later resume retries it — safe because a compensation\n // with nothing left to undo answers `404`, which is a success above.\n if (stepFailures.length === 0) {\n yield* store.markCompensated(sagaId, done.step.id);\n }\n }\n\n if (failures.length > 0) {\n // ⚠️ Surfaced, never swallowed. This is the state that leaves a\n // reservation held and — once payment lands — a customer charged, and\n // it is the failure class nobody plans for.\n return yield* strand(\n store,\n sagaId,\n outcomes,\n error,\n 'saga compensation failed',\n { definition: definition.name, failures: failures.join('; ') },\n );\n }\n\n yield* store.settle(sagaId, 'COMPENSATED', error);\n return { state: 'COMPENSATED', outcomes, error };\n });\n\n/**\n * Dispatch the definition's steps from `startIndex` on, and unwind on a refusal.\n *\n * The state transition is persisted **before** each dispatch, so a crash leaves\n * a record that says what was actually attempted — the outbox's rule, extended\n * from events to commands.\n *\n * ⚠️ **Once the pivot has committed, nothing is unwound.** That is what a pivot\n * means, and the walk has to know it rather than the definition merely declaring\n * it: `compensateStep` no-ops on a step that declares no compensation, so an\n * unconditional unwind after a successful capture would skip the pivot in\n * silence and then delete the order behind it and release the holds behind that\n * — money taken, goods back on sale, every probe green. The step is retried\n * instead, and a saga that still cannot go forward is settled `STRANDED` and\n * logged, because a stranded saga nobody is told about is the same as a lost one.\n */\nconst walk = (\n store: SagaStore,\n options: RunSagaOptions,\n from: { readonly taken: Taken; readonly startIndex: number },\n): Effect.Effect<\n SagaResult,\n StoreFailure | EntifixConnError,\n SagaDispatcherTag\n> =>\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 StoreFailure | EntifixConnError,\n SagaDispatcherTag | SagaStoreTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const { sagaId, definition, inputs } = options;\n\n yield* store.start({\n sagaId,\n definition: definition.name,\n state: 'RUNNING',\n stepIndex: 0,\n outcomes: [],\n // ⚠️ Persisted, because a resume has nothing to dispatch without it: a\n // fan-out step's cardinality *is* its input's length.\n inputs,\n resumeAttempts: 0,\n createdAt: new Date().toISOString(),\n });\n\n return yield* walk(store, options, { taken: [], startIndex: 0 });\n });\n\nexport interface ResumeSagaOptions {\n readonly instance: SagaInstance;\n readonly definition: SagaDefinition;\n /** Past this many sweeps, the instance is surfaced instead of retried. */\n readonly maxResumeAttempts: number;\n}\n\n/**\n * Finish a flow another coordinator abandoned.\n *\n * ⚠️ **Where to re-enter is derived, never stored.** A resume point written\n * beside the outcomes would be a second record of the same fact, free to\n * disagree with them; the outcomes already say what happened, and\n * `beginStep`-before-dispatch means `stepIndex` says what was attempted. The\n * four cases are exhaustive:\n *\n * - the step at `stepIndex` recorded no outcome — the process died during the\n * dispatch, so **re-dispatch it**. Safe because `sagaCommandId` is stable\n * across attempts and every participant claims it in its own command inbox,\n * so calls that did land are recognised as replays rather than repeated.\n * - it recorded a successful outcome — the process died between\n * `recordOutcome` and the next `beginStep`, so **start at the one after**.\n * - it recorded a refusal — the process died deciding what to do about it, so\n * **re-enter that decision**: unwind, or strand if the pivot had committed.\n * - the instance is `COMPENSATING` — it died mid-unwind, so **continue the\n * unwind**, skipping steps already marked `compensated`.\n */\nexport const resumeSaga = (\n options: ResumeSagaOptions,\n): Effect.Effect<\n SagaResult,\n StoreFailure | EntifixConnError,\n SagaDispatcherTag | SagaStoreTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const { instance, definition, maxResumeAttempts } = options;\n const { sagaId, outcomes } = instance;\n\n if (instance.resumeAttempts > maxResumeAttempts) {\n // Surfaced rather than retried forever. A coordinator spinning on a\n // permanent failure is how money stays captured with nobody told.\n return yield* strand(\n store,\n sagaId,\n outcomes,\n instance.error ??\n `resumed ${String(instance.resumeAttempts - 1)} times without settling`,\n 'saga abandoned after too many resumes',\n {\n definition: definition.name,\n resumeAttempts: instance.resumeAttempts,\n },\n );\n }\n\n const rebuilt = rebuildTaken(definition, outcomes);\n if ('unknownStep' in rebuilt) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n `recorded step '${rebuilt.unknownStep}' is not in definition '${definition.name}'`,\n 'saga instance does not match its definition',\n { definition: definition.name },\n );\n }\n\n const resumeOptions: RunSagaOptions = {\n sagaId,\n definition,\n inputs: instance.inputs,\n };\n\n if (instance.state === 'COMPENSATING') {\n return yield* unwind(\n store,\n sagaId,\n definition,\n rebuilt,\n instance.error ?? 'compensation resumed',\n );\n }\n\n const step = definition.steps[instance.stepIndex];\n if (!step) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n `step ${String(instance.stepIndex)} is not in definition '${definition.name}'`,\n 'saga instance does not match its definition',\n { definition: definition.name },\n );\n }\n\n const recorded = rebuilt.find(entry => entry.step.id === step.id);\n\n if (recorded === undefined) {\n return yield* walk(store, resumeOptions, {\n taken: rebuilt,\n startIndex: instance.stepIndex,\n });\n }\n\n if (recorded.outcome.error === undefined) {\n return yield* walk(store, resumeOptions, {\n taken: rebuilt,\n startIndex: instance.stepIndex + 1,\n });\n }\n\n const error = recorded.outcome.error;\n if (pivotCommittedIn(rebuilt)) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n error,\n 'saga stranded after the pivot',\n { definition: definition.name, stepId: step.id },\n );\n }\n\n yield* store.settle(sagaId, 'COMPENSATING', error);\n return yield* unwind(store, sagaId, definition, rebuilt, error);\n });\n"],"names":["Effect","sagaCommandId","SagaDispatcherTag","SagaStoreTag","resolveBodyTemplate","resolveTemplate","inputsFor","step","inputs","declared","id","fanOut","stepsScope","taken","Object","fromEntries","filter","entry","outcome","calls","length","map","body","elementsFor","steps","fanOutFrom","undefined","input","scope","source","find","call","organizationId","dispatchCall","sagaId","index","gen","dispatcher","dispatch","participant","method","path","commandId","runStep","elements","element","entries","response","command","ok","error","String","status","push","compensateStep","compensation","failures","reverse","result","pipe","catch","succeed","catchDefect","defect","POST_PIVOT_RETRIES","runStepWithRetries","retries","attempt","logWarning","annotateLogs","stepId","rebuildTaken","definition","outcomes","candidate","unknownStep","pivotCommittedIn","some","kind","strand","store","message","log","logError","settle","state","unwind","done","compensated","stepFailures","markCompensated","name","join","walk","options","from","pivotCommitted","startIndex","beginStep","recordOutcome","runSaga","start","stepIndex","resumeAttempts","createdAt","Date","toISOString","resumeSaga","instance","maxResumeAttempts","rebuilt","resumeOptions","recorded"],"mappings":";AACA,SAASA,MAAM,QAAQ,SAAS;AAEhC,SAGEC,aAAa,QAMR,kCAAkC;AACzC,SAASC,iBAAiB,QAAQ,8BAA8B;AAChE,SAGEC,YAAY,QACP,yBAAyB;AAChC,SAASC,mBAAmB,EAAEC,eAAe,QAAQ,wBAAwB;AAwC7E,MAAMC,YAAY,CAChBC,MACAC;QAEiBA,iBAGgBC;IAHjC,MAAMA,YAAWD,kBAAAA,MAAM,CAACD,KAAKG,EAAE,CAAC,YAAfF,kBAAmB,EAAE;IACtC,2EAA2E;IAC3E,yEAAyE;IACzE,OAAOD,KAAKI,MAAM,GAAGF,WAAW;SAACA,aAAAA,QAAQ,CAAC,EAAE,YAAXA,aAAe,CAAC;KAAE;AACrD;AAEA;;;;;;;;;CASC,GACD;;;;;;;;;CASC,GACD,MAAMG,aAAa,CACjBC,QAEAC,OAAOC,WAAW,CAChBF,MACGG,MAAM,CAACC,CAAAA,QAASA,MAAMC,OAAO,CAACC,KAAK,CAACC,MAAM,GAAG,GAC7CC,GAAG,CAACJ,CAAAA;YAAyBA;eAAhB;YAACA,MAAMV,IAAI,CAACG,EAAE;aAAEO,wBAAAA,MAAMC,OAAO,CAACC,KAAK,CAAC,EAAE,qBAAtBF,sBAAwBK,IAAI;SAAC;;AAGjE,MAAMC,cAAc,CAClBhB,MACAC,QACAK;;QAYaL,kBAAAA;IAVb,MAAMgB,QAAQZ,WAAWC;IAEzB,IAAIN,KAAKkB,UAAU,KAAKC,WAAW;QACjC,OAAOpB,UAAUC,MAAMC,QAAQa,GAAG,CAACM,CAAAA,QAAU,CAAA;gBAC3CA;gBACAC,OAAO;oBAAED,OAAOA,MAAML,IAAI;oBAAEE;gBAAM;YACpC,CAAA;IACF;IAEA,MAAMK,SAAShB,MA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AAC,CAAC,CAAC,EAC9E,+CACA;gBAAEnB,YAAYA,WAAWmB,IAAI;YAAC;QAElC;QAEA,MAAMqB,WAAWF,QAAQhF,IAAI,CAACb,CAAAA,QAASA,MAAMV,IAAI,CAACG,EAAE,KAAKH,KAAKG,EAAE;QAEhE,IAAIsG,aAAatF,WAAW;YAC1B,OAAO,OAAOmE,KAAKb,OAAO+B,eAAe;gBACvClG,OAAOiG;gBACPb,YAAYW,SAASN,SAAS;YAChC;QACF;QAEA,IAAIU,SAAS9F,OAAO,CAACgC,KAAK,KAAKxB,WAAW;YACxC,OAAO,OAAOmE,KAAKb,OAAO+B,eAAe;gBACvClG,OAAOiG;gBACPb,YAAYW,SAASN,SAAS,GAAG;YACnC;QACF;QAEA,MAAMpD,QAAQ8D,SAAS9F,OAAO,CAACgC,KAAK;QACpC,IAAI0B,iBAAiBkC,UAAU;YAC7B,OAAO,OAAO/B,OACZC,OACA9C,QACAuC,UACAvB,OACA,iCACA;gBAAEsB,YAAYA,WAAWmB,IAAI;gBAAErB,QAAQ/D,KAAKG,EAAE;YAAC;QAEnD;QAEA,OAAOsE,MAAMI,MAAM,CAAClD,QAAQ,gBAAgBgB;QAC5C,OAAO,OAAOoC,OAAON,OAAO9C,QAAQsC,YAAYsC,SAAS5D;IAC3D,GAAG"}
|
|
@@ -35,7 +35,7 @@ export declare function acceptTransaction(): Effect.Effect<{
|
|
|
35
35
|
} | {
|
|
36
36
|
readonly status: "accepted";
|
|
37
37
|
readonly handles: readonly LockHandle[];
|
|
38
|
-
}, import("@entifix/core").EntifixError, import("../index.js").TransactionHandlerTag | TransactionOutboxTag | import("../index.js").LockServiceTag | CommandTag | EventSourceTag>;
|
|
38
|
+
}, import("@entifix/core").EntifixError | import("@entifix/core").StoreFailure, import("../index.js").TransactionHandlerTag | TransactionOutboxTag | import("../index.js").LockServiceTag | CommandTag | EventSourceTag>;
|
|
39
39
|
/** What {@link acceptTransaction} decided — a fresh command, or a replay. */
|
|
40
40
|
export type AcceptOutcome = Effect.Success<ReturnType<typeof acceptTransaction>>;
|
|
41
41
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-transaction.d.ts","sourceRoot":"","sources":["../../src/engine/run-transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EACL,UAAU,EAGX,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAS3D;;;;;;;;;;;;;;;GAeG;AAEH;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB;;;;;;
|
|
1
|
+
{"version":3,"file":"run-transaction.d.ts","sourceRoot":"","sources":["../../src/engine/run-transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EACL,UAAU,EAGX,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAS3D;;;;;;;;;;;;;;;GAeG;AAEH;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB;;;;;;yNAgBhC;AAED,6EAA6E;AAC7E,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,CACxC,UAAU,CAAC,OAAO,iBAAiB,CAAC,CACrC,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,SAAS,UAAU,EAAE,uKA2DjE"}
|
package/dist/index.d.ts
CHANGED
|
@@ -9,11 +9,13 @@ export * from './mixins/transaction-mixins.js';
|
|
|
9
9
|
export * from './ports/event-bus.js';
|
|
10
10
|
export * from './ports/event-source.js';
|
|
11
11
|
export * from './ports/lock-service.js';
|
|
12
|
+
export * from './ports/retry-budget.js';
|
|
12
13
|
export * from './ports/saga-dispatcher.js';
|
|
13
14
|
export * from './ports/saga-store.js';
|
|
14
15
|
export * from './ports/sequence-service.js';
|
|
15
16
|
export * from './ports/transaction-handler.js';
|
|
16
17
|
export * from './ports/transaction-sink.js';
|
|
17
18
|
export * from './ports/transaction-stream-hub.js';
|
|
19
|
+
export * from './reactions/on.js';
|
|
18
20
|
export * from './use-case/facade.uc.js';
|
|
19
21
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -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,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,mCAAmC,CAAC;AAClD,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,6BAA6B,CAAC;AAC5C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,yBAAyB,CAAC;AACxC,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,mCAAmC,CAAC;AAClD,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -9,12 +9,14 @@ export * from './mixins/transaction-mixins.js';
|
|
|
9
9
|
export * from './ports/event-bus.js';
|
|
10
10
|
export * from './ports/event-source.js';
|
|
11
11
|
export * from './ports/lock-service.js';
|
|
12
|
+
export * from './ports/retry-budget.js';
|
|
12
13
|
export * from './ports/saga-dispatcher.js';
|
|
13
14
|
export * from './ports/saga-store.js';
|
|
14
15
|
export * from './ports/sequence-service.js';
|
|
15
16
|
export * from './ports/transaction-handler.js';
|
|
16
17
|
export * from './ports/transaction-sink.js';
|
|
17
18
|
export * from './ports/transaction-stream-hub.js';
|
|
19
|
+
export * from './reactions/on.js';
|
|
18
20
|
export * from './use-case/facade.uc.js';
|
|
19
21
|
|
|
20
22
|
//# sourceMappingURL=index.js.map
|
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 './contracts/unit-of-work.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 './ports/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,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,oCAAoC;AAClD,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 './contracts/unit-of-work.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/retry-budget.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 './ports/transaction-stream-hub.js';\nexport * from './reactions/on.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,8BAA8B;AAC5C,cAAc,iCAAiC;AAC/C,cAAc,uBAAuB;AACrC,cAAc,0BAA0B;AACxC,cAAc,0BAA0B;AACxC,cAAc,0BAA0B;AACxC,cAAc,6BAA6B;AAC3C,cAAc,wBAAwB;AACtC,cAAc,8BAA8B;AAC5C,cAAc,iCAAiC;AAC/C,cAAc,8BAA8B;AAC5C,cAAc,oCAAoC;AAClD,cAAc,oBAAoB;AAClC,cAAc,0BAA0B"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { DomainEvent,
|
|
1
|
+
import type { DomainEvent, StoreFailure, TransitionalFailure } from '@entifix/core';
|
|
2
2
|
import { Context, type Effect } from 'effect';
|
|
3
3
|
/**
|
|
4
4
|
* How a subscriber's queue is shaped, which is a property of the *workload*
|
|
@@ -72,7 +72,7 @@ export interface Subscription {
|
|
|
72
72
|
* ever seeing the envelope that carried them.
|
|
73
73
|
*/
|
|
74
74
|
export interface EventBus {
|
|
75
|
-
publish(event: DomainEvent): Effect.Effect<void,
|
|
75
|
+
publish(event: DomainEvent): Effect.Effect<void, StoreFailure>;
|
|
76
76
|
/**
|
|
77
77
|
* Register a consumer for the events matching `subscription.pattern`.
|
|
78
78
|
*
|
|
@@ -88,7 +88,7 @@ export interface EventBus {
|
|
|
88
88
|
* behind it. A *business* failure is neither: that message was processed
|
|
89
89
|
* successfully and already produced its own event.
|
|
90
90
|
*/
|
|
91
|
-
subscribe(subscription: Subscription, handler: (event: DomainEvent) => Effect.Effect<void,
|
|
91
|
+
subscribe(subscription: Subscription, handler: (event: DomainEvent) => Effect.Effect<void, TransitionalFailure>): Effect.Effect<void, StoreFailure>;
|
|
92
92
|
}
|
|
93
93
|
declare const EventBusTag_base: Context.ServiceClass<EventBusTag, "EventBusTag", EventBus>;
|
|
94
94
|
export declare class EventBusTag extends EventBusTag_base {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-bus.d.ts","sourceRoot":"","sources":["../../src/ports/event-bus.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,
|
|
1
|
+
{"version":3,"file":"event-bus.d.ts","sourceRoot":"","sources":["../../src/ports/event-bus.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,YAAY,EACZ,mBAAmB,EACpB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,WAAW,CAAC;AAEpD;;;;;;;GAOG;AACH,MAAM,WAAW,YAAY;IAC3B;;;;;;;;OAQG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB;;;;;;OAMG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,EAAE,gBAAgB,CAAC;IAChC;;;;;;;OAOG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;CAC9B;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,QAAQ;IACvB,OAAO,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;IAC/D;;;;;;;;;;;;;;OAcG;IACH,SAAS,CACP,YAAY,EAAE,YAAY,EAC1B,OAAO,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,mBAAmB,CAAC,GACxE,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;CACtC;;AAED,qBAAa,WAAY,SAAQ,gBAEhC;CAAG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ports/event-bus.ts"],"sourcesContent":["import type {\n DomainEvent,\n
|
|
1
|
+
{"version":3,"sources":["../../src/ports/event-bus.ts"],"sourcesContent":["import type {\n DomainEvent,\n StoreFailure,\n TransitionalFailure,\n} from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * How a subscriber's queue is shaped, which is a property of the *workload*\n * rather than of the transport.\n *\n * - `work` — a named, durable queue that survives the consumer's restart and\n * accumulates while it is gone. Replicas share it, so each message reaches\n * exactly one of them. A projection writer, a fold and a settlement consumer\n * all want this.\n * - `broadcast` — a connection-scoped exclusive queue, so every replica\n * receives every message and nothing is retained across a restart. Correct\n * only when the replicas differ from one another — a socket push holding\n * different clients per process.\n *\n * The bus first built the exclusive queue for every subscriber, with a stated\n * reason: a shared queue delivers each event to one replica, \"which reads as\n * flakiness rather than as a design\". That reasoning is right for `broadcast`\n * and wrong for `work`; it picked broadcast semantics for a workload that is\n * work, at a time when the only subscriber made the difference invisible.\n */\nexport type SubscriptionMode = 'work' | 'broadcast';\n\n/**\n * A subscriber's declared interest, together with the delivery policy the\n * broker enforces for it.\n *\n * The shape mirrors `subscriptions` in `tools/slices/*.slice.ts`, so \"how does\n * this fail\" is answered where it can be checked rather than in a review\n * comment.\n */\nexport interface Subscription {\n /**\n * The **subscribing** slice — the `tools/slices/` key, and half of the queue\n * name.\n *\n * Deliberately not `EventSourceTag`, which is the *emitting* slice: one\n * deployment may host several slices, so a process-wide \"my slice\" would attribute a\n * consumer's queue to whichever slice happened to publish from the same\n * process.\n */\n readonly slice: string;\n /**\n * The event name pattern, used verbatim as the broker's binding —\n * `transaction.*`, `catalog.published`. Filtering in the handler instead is\n * what this exists to prevent: it makes every consumer pay for every\n * publisher's traffic, and it puts the routing rule where no register can\n * check it.\n */\n readonly pattern: string;\n readonly mode: SubscriptionMode;\n /**\n * How many times the broker may deliver a message before dead-lettering it.\n *\n * Enforced by the queue itself rather than by logic each consumer\n * reimplements, so it applies to a redelivery after a crash as well as to one\n * after a nack. `broadcast` queues have no dead-letter path, so the value is\n * carried but unenforced there.\n */\n readonly maxAttempts: number;\n}\n\n/**\n * The domain event bus (RabbitMQ in `@entifix/amqp`). Services publish\n * what happened; interested slices subscribe to the names they declared.\n *\n * Typed on {@link DomainEvent} rather than on any one publisher's payload: a bus\n * that only knew `TransactionEvent` had nothing for a publication event to\n * travel in, which would have meant a second framing and a second\n * transport for the same job.\n *\n * The port stays event-typed rather than envelope-typed — the adapter owns the\n * wire framing — so a handler receives the message and its metadata without\n * ever seeing the envelope that carried them.\n */\nexport interface EventBus {\n publish(event: DomainEvent): Effect.Effect<void, StoreFailure>;\n /**\n * Register a consumer for the events matching `subscription.pattern`.\n *\n * The returned Effect completes once the subscription is established; the\n * handler then runs per delivered event. Delivery is at-least-once, so a\n * handler that is not idempotent must deduplicate on `event.id`.\n *\n * A handler failure is **transient**: the adapter requeues it and the broker\n * counts the redelivery against `maxAttempts`, dead-lettering at the limit. A\n * payload the adapter cannot read is **poison** and is quarantined with zero\n * retries — a message that cannot be deserialized never becomes\n * deserializable, and retrying it only spends the budget of the messages\n * behind it. A *business* failure is neither: that message was processed\n * successfully and already produced its own event.\n */\n subscribe(\n subscription: Subscription,\n handler: (event: DomainEvent) => Effect.Effect<void, TransitionalFailure>,\n ): Effect.Effect<void, StoreFailure>;\n}\n\nexport class EventBusTag extends Context.Service<EventBusTag, EventBus>()(\n 'EventBusTag',\n) {}\n"],"names":["Context","EventBusTag","Service"],"mappings":"AAKA,SAASA,OAAO,QAAqB,SAAS;AAkG9C,OAAO,MAAMC,oBAAoBD,QAAQE,OAAO,GAC9C;AACC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { StoreFailure } from '@entifix/core';
|
|
2
2
|
import { Context, type Effect } from 'effect';
|
|
3
3
|
/** A held lock; `token` proves ownership so release only frees our own lock. */
|
|
4
4
|
export interface LockHandle {
|
|
@@ -12,10 +12,10 @@ export interface LockHandle {
|
|
|
12
12
|
export interface LockService {
|
|
13
13
|
/**
|
|
14
14
|
* Acquire `key`, retrying up to the adapter's bounded budget. Fails with
|
|
15
|
-
* {@link
|
|
15
|
+
* {@link Contention} on contention (surfaced as `409`), not a `500`.
|
|
16
16
|
*/
|
|
17
|
-
acquire(key: string): Effect.Effect<LockHandle,
|
|
18
|
-
release(handle: LockHandle): Effect.Effect<void,
|
|
17
|
+
acquire(key: string): Effect.Effect<LockHandle, StoreFailure>;
|
|
18
|
+
release(handle: LockHandle): Effect.Effect<void, StoreFailure>;
|
|
19
19
|
}
|
|
20
20
|
declare const LockServiceTag_base: Context.ServiceClass<LockServiceTag, "LockServiceTag", LockService>;
|
|
21
21
|
export declare class LockServiceTag extends LockServiceTag_base {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lock-service.d.ts","sourceRoot":"","sources":["../../src/ports/lock-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"lock-service.d.ts","sourceRoot":"","sources":["../../src/ports/lock-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAc,YAAY,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C,gFAAgF;AAChF,MAAM,WAAW,UAAU;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC1B;;;OAGG;IACH,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;IAC9D,OAAO,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;CAChE;;AAED,qBAAa,cAAe,SAAQ,mBAGf;CAAG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ports/lock-service.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"sources":["../../src/ports/lock-service.ts"],"sourcesContent":["import type { Contention, StoreFailure } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/** A held lock; `token` proves ownership so release only frees our own lock. */\nexport interface LockHandle {\n key: string;\n token: string;\n}\n\n/**\n * Distributed mutual exclusion — the facade's `lock`/`free` steps. Implemented\n * over Redis (`SET NX PX` + bounded retry) in `@entifix/redis`.\n */\nexport interface LockService {\n /**\n * Acquire `key`, retrying up to the adapter's bounded budget. Fails with\n * {@link Contention} on contention (surfaced as `409`), not a `500`.\n */\n acquire(key: string): Effect.Effect<LockHandle, StoreFailure>;\n release(handle: LockHandle): Effect.Effect<void, StoreFailure>;\n}\n\nexport class LockServiceTag extends Context.Service<\n LockServiceTag,\n LockService\n>()('LockServiceTag') {}\n"],"names":["Context","LockServiceTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAqB9C,OAAO,MAAMC,uBAAuBD,QAAQE,OAAO,GAG/C;AAAmB"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { Context, type Effect, Metric } from 'effect';
|
|
2
|
+
/**
|
|
3
|
+
* Which budget a retry draws from: one per dependency, and per organization
|
|
4
|
+
* when the call acts for one, so a single tenant's outage cannot spend the
|
|
5
|
+
* retries every other tenant needs
|
|
6
|
+
* ([ADR 0014](../../../../../docs/adr/0014-retry-once-at-the-layer-above-under-a-budget.md)).
|
|
7
|
+
*/
|
|
8
|
+
export interface RetryKey {
|
|
9
|
+
readonly dependency: string;
|
|
10
|
+
readonly organizationId?: string;
|
|
11
|
+
}
|
|
12
|
+
/** The dials, with ADR 0014's defaults in {@link DEFAULT_RETRY_DIALS}. */
|
|
13
|
+
export interface RetryDials {
|
|
14
|
+
/** Attempts per call, the first included. */
|
|
15
|
+
readonly maxAttempts: number;
|
|
16
|
+
/** Retries may add at most this fraction to a dependency's first attempts. */
|
|
17
|
+
readonly budgetRatio: number;
|
|
18
|
+
/** Retries admitted per second regardless of the ratio. */
|
|
19
|
+
readonly budgetFloorPerSecond: number;
|
|
20
|
+
readonly backoffBaseMs: number;
|
|
21
|
+
readonly backoffCapMs: number;
|
|
22
|
+
/** Client-side throttling multiplier; `0` turns it off. */
|
|
23
|
+
readonly adaptiveThrottlingK: number;
|
|
24
|
+
readonly adaptiveThrottlingWindowMs: number;
|
|
25
|
+
}
|
|
26
|
+
export declare const DEFAULT_RETRY_DIALS: RetryDials;
|
|
27
|
+
/**
|
|
28
|
+
* The budget every in-process retry draws from. The port is here, in `.`, so
|
|
29
|
+
* anything that orchestrates calls can reach it; the engine is at `/engine`,
|
|
30
|
+
* where a cell cannot import it.
|
|
31
|
+
*/
|
|
32
|
+
export interface RetryBudget {
|
|
33
|
+
readonly dials: RetryDials;
|
|
34
|
+
/** A first attempt is about to be made. Returns `false` to throttle it locally. */
|
|
35
|
+
readonly admitAttempt: (key: RetryKey) => Effect.Effect<boolean>;
|
|
36
|
+
/** A retry wants to run. Returns `false` when the budget is spent. */
|
|
37
|
+
readonly admitRetry: (key: RetryKey) => Effect.Effect<boolean>;
|
|
38
|
+
/** The dependency answered — an answer, even a refusal, counts as accepted. */
|
|
39
|
+
readonly recordAccepted: (key: RetryKey) => Effect.Effect<void>;
|
|
40
|
+
}
|
|
41
|
+
declare const RetryBudgetTag_base: Context.ServiceClass<RetryBudgetTag, "@entifix/transactions/RetryBudget", RetryBudget>;
|
|
42
|
+
export declare class RetryBudgetTag extends RetryBudgetTag_base {
|
|
43
|
+
}
|
|
44
|
+
/** Retries started, by dependency. */
|
|
45
|
+
export declare const retryAttempts: Metric.Counter<number>;
|
|
46
|
+
/** Retries the budget refused, by dependency. */
|
|
47
|
+
export declare const retryBudgetRejections: Metric.Counter<number>;
|
|
48
|
+
/** First attempts throttled locally by adaptive throttling, by dependency. */
|
|
49
|
+
export declare const retryThrottled: Metric.Counter<number>;
|
|
50
|
+
export {};
|
|
51
|
+
//# sourceMappingURL=retry-budget.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retry-budget.d.ts","sourceRoot":"","sources":["../../src/ports/retry-budget.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEtD;;;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cAAc,wBAEzB,CAAC"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Context, Metric } from 'effect';
|
|
2
|
+
export const DEFAULT_RETRY_DIALS = {
|
|
3
|
+
maxAttempts: 3,
|
|
4
|
+
budgetRatio: 0.1,
|
|
5
|
+
budgetFloorPerSecond: 1,
|
|
6
|
+
backoffBaseMs: 50,
|
|
7
|
+
backoffCapMs: 2000,
|
|
8
|
+
adaptiveThrottlingK: 2,
|
|
9
|
+
adaptiveThrottlingWindowMs: 120000
|
|
10
|
+
};
|
|
11
|
+
export class RetryBudgetTag extends Context.Service()('@entifix/transactions/RetryBudget') {
|
|
12
|
+
}
|
|
13
|
+
/** Retries started, by dependency. */ export const retryAttempts = Metric.counter('entifix_retry_attempts_total', {
|
|
14
|
+
description: 'In-process retries started, by dependency.'
|
|
15
|
+
});
|
|
16
|
+
/** Retries the budget refused, by dependency. */ export const retryBudgetRejections = Metric.counter('entifix_retry_budget_rejections_total', {
|
|
17
|
+
description: 'Retries refused because the budget was spent, by dependency.'
|
|
18
|
+
});
|
|
19
|
+
/** First attempts throttled locally by adaptive throttling, by dependency. */ export const retryThrottled = Metric.counter('entifix_retry_throttled_total', {
|
|
20
|
+
description: 'First attempts rejected locally by adaptive throttling.'
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
//# sourceMappingURL=retry-budget.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/ports/retry-budget.ts"],"sourcesContent":["import { Context, type Effect, Metric } from 'effect';\n\n/**\n * Which budget a retry draws from: one per dependency, and per organization\n * when the call acts for one, so a single tenant's outage cannot spend the\n * retries every other tenant needs\n * ([ADR 0014](../../../../../docs/adr/0014-retry-once-at-the-layer-above-under-a-budget.md)).\n */\nexport interface RetryKey {\n readonly dependency: string;\n readonly organizationId?: string;\n}\n\n/** The dials, with ADR 0014's defaults in {@link DEFAULT_RETRY_DIALS}. */\nexport interface RetryDials {\n /** Attempts per call, the first included. */\n readonly maxAttempts: number;\n /** Retries may add at most this fraction to a dependency's first attempts. */\n readonly budgetRatio: number;\n /** Retries admitted per second regardless of the ratio. */\n readonly budgetFloorPerSecond: number;\n readonly backoffBaseMs: number;\n readonly backoffCapMs: number;\n /** Client-side throttling multiplier; `0` turns it off. */\n readonly adaptiveThrottlingK: number;\n readonly adaptiveThrottlingWindowMs: number;\n}\n\nexport const DEFAULT_RETRY_DIALS: RetryDials = {\n maxAttempts: 3,\n budgetRatio: 0.1,\n budgetFloorPerSecond: 1,\n backoffBaseMs: 50,\n backoffCapMs: 2000,\n adaptiveThrottlingK: 2,\n adaptiveThrottlingWindowMs: 120_000,\n};\n\n/**\n * The budget every in-process retry draws from. The port is here, in `.`, so\n * anything that orchestrates calls can reach it; the engine is at `/engine`,\n * where a cell cannot import it.\n */\nexport interface RetryBudget {\n readonly dials: RetryDials;\n /** A first attempt is about to be made. Returns `false` to throttle it locally. */\n readonly admitAttempt: (key: RetryKey) => Effect.Effect<boolean>;\n /** A retry wants to run. Returns `false` when the budget is spent. */\n readonly admitRetry: (key: RetryKey) => Effect.Effect<boolean>;\n /** The dependency answered — an answer, even a refusal, counts as accepted. */\n readonly recordAccepted: (key: RetryKey) => Effect.Effect<void>;\n}\n\nexport class RetryBudgetTag extends Context.Service<\n RetryBudgetTag,\n RetryBudget\n>()('@entifix/transactions/RetryBudget') {}\n\n/** Retries started, by dependency. */\nexport const retryAttempts = Metric.counter('entifix_retry_attempts_total', {\n description: 'In-process retries started, by dependency.',\n});\n\n/** Retries the budget refused, by dependency. */\nexport const retryBudgetRejections = Metric.counter(\n 'entifix_retry_budget_rejections_total',\n {\n description: 'Retries refused because the budget was spent, by dependency.',\n },\n);\n\n/** First attempts throttled locally by adaptive throttling, by dependency. */\nexport const retryThrottled = Metric.counter('entifix_retry_throttled_total', {\n description: 'First attempts rejected locally by adaptive throttling.',\n});\n"],"names":["Context","Metric","DEFAULT_RETRY_DIALS","maxAttempts","budgetRatio","budgetFloorPerSecond","backoffBaseMs","backoffCapMs","adaptiveThrottlingK","adaptiveThrottlingWindowMs","RetryBudgetTag","Service","retryAttempts","counter","description","retryBudgetRejections","retryThrottled"],"mappings":"AAAA,SAASA,OAAO,EAAeC,MAAM,QAAQ,SAAS;AA4BtD,OAAO,MAAMC,sBAAkC;IAC7CC,aAAa;IACbC,aAAa;IACbC,sBAAsB;IACtBC,eAAe;IACfC,cAAc;IACdC,qBAAqB;IACrBC,4BAA4B;AAC9B,EAAE;AAiBF,OAAO,MAAMC,uBAAuBV,QAAQW,OAAO,GAG/C;AAAsC;AAE1C,oCAAoC,GACpC,OAAO,MAAMC,gBAAgBX,OAAOY,OAAO,CAAC,gCAAgC;IAC1EC,aAAa;AACf,GAAG;AAEH,+CAA+C,GAC/C,OAAO,MAAMC,wBAAwBd,OAAOY,OAAO,CACjD,yCACA;IACEC,aAAa;AACf,GACA;AAEF,4EAA4E,GAC5E,OAAO,MAAME,iBAAiBf,OAAOY,OAAO,CAAC,iCAAiC;IAC5EC,aAAa;AACf,GAAG"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { StoreFailure } from '@entifix/core';
|
|
2
2
|
import { Context, type Effect } from 'effect';
|
|
3
3
|
import type { SagaInputs, SagaStepOutcome } from '../contracts/saga-definition.js';
|
|
4
4
|
/**
|
|
@@ -55,7 +55,7 @@ export interface SagaInstance {
|
|
|
55
55
|
* rather than a business domain.
|
|
56
56
|
*/
|
|
57
57
|
export interface SagaStore {
|
|
58
|
-
start(instance: Omit<SagaInstance, 'updatedAt'>): Effect.Effect<void,
|
|
58
|
+
start(instance: Omit<SagaInstance, 'updatedAt'>): Effect.Effect<void, StoreFailure>;
|
|
59
59
|
/**
|
|
60
60
|
* Persist that a step is about to be dispatched.
|
|
61
61
|
*
|
|
@@ -65,12 +65,12 @@ export interface SagaStore {
|
|
|
65
65
|
* consequence — a crash between the two leaves a step that either ran twice
|
|
66
66
|
* or never ran, and the record says the opposite of the truth.
|
|
67
67
|
*/
|
|
68
|
-
beginStep(sagaId: string, stepIndex: number): Effect.Effect<void,
|
|
69
|
-
recordOutcome(sagaId: string, outcome: SagaStepOutcome): Effect.Effect<void,
|
|
70
|
-
settle(sagaId: string, state: SagaState, error?: string): Effect.Effect<void,
|
|
71
|
-
get(sagaId: string): Effect.Effect<SagaInstance | undefined,
|
|
68
|
+
beginStep(sagaId: string, stepIndex: number): Effect.Effect<void, StoreFailure>;
|
|
69
|
+
recordOutcome(sagaId: string, outcome: SagaStepOutcome): Effect.Effect<void, StoreFailure>;
|
|
70
|
+
settle(sagaId: string, state: SagaState, error?: string): Effect.Effect<void, StoreFailure>;
|
|
71
|
+
get(sagaId: string): Effect.Effect<SagaInstance | undefined, StoreFailure>;
|
|
72
72
|
/** Instances left `RUNNING` or `COMPENSATING` past a deadline, for the sweep. */
|
|
73
|
-
findStale(olderThanMs: number): Effect.Effect<readonly SagaInstance[],
|
|
73
|
+
findStale(olderThanMs: number): Effect.Effect<readonly SagaInstance[], StoreFailure>;
|
|
74
74
|
/**
|
|
75
75
|
* Take ownership of a stale instance, or answer `undefined`.
|
|
76
76
|
*
|
|
@@ -85,9 +85,9 @@ export interface SagaStore {
|
|
|
85
85
|
* Re-stamping is also what stops *this* sweep's next tick finding the
|
|
86
86
|
* instance it is still working on.
|
|
87
87
|
*/
|
|
88
|
-
claimForResume(sagaId: string, olderThanMs: number): Effect.Effect<SagaInstance | undefined,
|
|
88
|
+
claimForResume(sagaId: string, olderThanMs: number): Effect.Effect<SagaInstance | undefined, StoreFailure>;
|
|
89
89
|
/** Mark one step's calls as given back, so a resumed unwind skips them. */
|
|
90
|
-
markCompensated(sagaId: string, stepId: string): Effect.Effect<void,
|
|
90
|
+
markCompensated(sagaId: string, stepId: string): Effect.Effect<void, StoreFailure>;
|
|
91
91
|
}
|
|
92
92
|
declare const SagaStoreTag_base: Context.ServiceClass<SagaStoreTag, "SagaStoreTag", SagaStore>;
|
|
93
93
|
export declare class SagaStoreTag extends SagaStoreTag_base {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"saga-store.d.ts","sourceRoot":"","sources":["../../src/ports/saga-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"saga-store.d.ts","sourceRoot":"","sources":["../../src/ports/saga-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C,OAAO,KAAK,EACV,UAAU,EACV,eAAe,EAChB,MAAM,iCAAiC,CAAC;AAEzC;;;;;;;GAOG;AACH,eAAO,MAAM,WAAW,8EAMd,CAAC;AAEX,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC;AAErD,iEAAiE;AACjE,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,2CAA2C;IAC3C,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC;IAC1B,6DAA6D;IAC7D,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,SAAS,eAAe,EAAE,CAAC;IAC9C;;;;;;;;;OASG;IACH,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B;;;;;;;;;OASG;IACH,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;CAC5B;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,SAAS;IACxB,KAAK,CACH,QAAQ,EAAE,IAAI,CAAC,YAAY,EAAE,WAAW,CAAC,GACxC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;IACrC;;;;;;;;OAQG;IACH,SAAS,CACP,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,GAChB,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;IACrC,aAAa,CACX,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,eAAe,GACvB,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;IACrC,MAAM,CACJ,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,SAAS,EAChB,KAAK,CAAC,EAAE,MAAM,GACb,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;IACrC,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,YAAY,GAAG,SAAS,EAAE,YAAY,CAAC,CAAC;IAC3E,iFAAiF;IACjF,SAAS,CACP,WAAW,EAAE,MAAM,GAClB,MAAM,CAAC,MAAM,CAAC,SAAS,YAAY,EAAE,EAAE,YAAY,CAAC,CAAC;IACxD;;;;;;;;;;;;;OAaG;IACH,cAAc,CACZ,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,GAClB,MAAM,CAAC,MAAM,CAAC,YAAY,GAAG,SAAS,EAAE,YAAY,CAAC,CAAC;IACzD,2EAA2E;IAC3E,eAAe,CACb,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,GACb,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;CACtC;;AAED,qBAAa,YAAa,SAAQ,iBAEjC;CAAG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ports/saga-store.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"sources":["../../src/ports/saga-store.ts"],"sourcesContent":["import type { StoreFailure } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\nimport type {\n SagaInputs,\n SagaStepOutcome,\n} from '../contracts/saga-definition.js';\n\n/**\n * Where a saga instance is.\n *\n * `COMPENSATED` and `STRANDED` are deliberately different terminal states:\n * \"failed and reversed\" and \"failed with something still held\" are the two\n * outcomes an operator has to be able to tell apart, and a single `FAILED`\n * would make the second look like the first.\n */\nexport const SAGA_STATES = [\n 'RUNNING',\n 'COMPLETED',\n 'COMPENSATING',\n 'COMPENSATED',\n 'STRANDED',\n] as const;\n\nexport type SagaState = (typeof SAGA_STATES)[number];\n\n/** One flow in progress, and what each of its steps returned. */\nexport interface SagaInstance {\n readonly sagaId: string;\n /** The {@link SagaDefinition}'s `name`. */\n readonly definition: string;\n readonly state: SagaState;\n /** The step being dispatched, or the last one dispatched. */\n readonly stepIndex: number;\n readonly outcomes: readonly SagaStepOutcome[];\n /**\n * What the caller supplied, kept so a **different process** can finish this\n * flow.\n *\n * ⚠️ This is the member that makes the instance a resumable record rather\n * than a report on one. Without it a resumed walk knows which step is next\n * and has nothing to dispatch it with: a fan-out step's cardinality is its\n * input's length, and a body template resolves against `inputs` before it\n * resolves against earlier outcomes.\n */\n readonly inputs: SagaInputs;\n /**\n * How many times a sweep has picked this instance up, which is the ceiling\n * that stops a resume loop.\n *\n * It plays the part `attempts` plays on an outbox entry, on the\n * record that already exists rather than on a second one beside it. Past the\n * ceiling the instance is settled `STRANDED` and logged — surfaced rather\n * than retried forever, because a coordinator spinning on a permanent failure\n * is how a customer's money stays captured with nobody told.\n */\n readonly resumeAttempts: number;\n readonly error?: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\n/**\n * The saga's own state, in the `saga` store.\n *\n * A saga instance is a transaction's state with steps in it, so it belongs in\n * the store that already holds transaction state — no new store, and the\n * `transaction` slice keeps `domains: []`, because orchestration is a mechanism\n * rather than a business domain.\n */\nexport interface SagaStore {\n start(\n instance: Omit<SagaInstance, 'updatedAt'>,\n ): Effect.Effect<void, StoreFailure>;\n /**\n * Persist that a step is about to be dispatched.\n *\n * ⚠️ **Before the dispatch, never after.** The outbox's rule extended from\n * events to commands: a coordinator that marks a step in flight only after\n * calling has the dual write that record exists to close, with the same\n * consequence — a crash between the two leaves a step that either ran twice\n * or never ran, and the record says the opposite of the truth.\n */\n beginStep(\n sagaId: string,\n stepIndex: number,\n ): Effect.Effect<void, StoreFailure>;\n recordOutcome(\n sagaId: string,\n outcome: SagaStepOutcome,\n ): Effect.Effect<void, StoreFailure>;\n settle(\n sagaId: string,\n state: SagaState,\n error?: string,\n ): Effect.Effect<void, StoreFailure>;\n get(sagaId: string): Effect.Effect<SagaInstance | undefined, StoreFailure>;\n /** Instances left `RUNNING` or `COMPENSATING` past a deadline, for the sweep. */\n findStale(\n olderThanMs: number,\n ): Effect.Effect<readonly SagaInstance[], StoreFailure>;\n /**\n * Take ownership of a stale instance, or answer `undefined`.\n *\n * ⚠️ **A claim, not a read**, and it is what makes the sweep safe to run in\n * more than one process: the same conditional write that increments\n * `resumeAttempts` also re-stamps `updatedAt`, so an instance already picked\n * up is no longer stale and the second sweeper gets nothing. Reading and then\n * resuming would have two coordinators dispatching one flow — survivable,\n * because every participant claims the command id, but it would double every\n * call and make the attempt ceiling meaningless.\n *\n * Re-stamping is also what stops *this* sweep's next tick finding the\n * instance it is still working on.\n */\n claimForResume(\n sagaId: string,\n olderThanMs: number,\n ): Effect.Effect<SagaInstance | undefined, StoreFailure>;\n /** Mark one step's calls as given back, so a resumed unwind skips them. */\n markCompensated(\n sagaId: string,\n stepId: string,\n ): Effect.Effect<void, StoreFailure>;\n}\n\nexport class SagaStoreTag extends Context.Service<SagaStoreTag, SagaStore>()(\n 'SagaStoreTag',\n) {}\n"],"names":["Context","SAGA_STATES","SagaStoreTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAO9C;;;;;;;CAOC,GACD,OAAO,MAAMC,cAAc;IACzB;IACA;IACA;IACA;IACA;CACD,CAAU;AAwGX,OAAO,MAAMC,qBAAqBF,QAAQG,OAAO,GAC/C;AACC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { StoreFailure } from '@entifix/core';
|
|
2
2
|
import { Context, type Effect } from 'effect';
|
|
3
3
|
/**
|
|
4
4
|
* A monotonic, gap-free-under-contention counter — the mechanism that makes
|
|
@@ -8,7 +8,7 @@ import { Context, type Effect } from 'effect';
|
|
|
8
8
|
*/
|
|
9
9
|
export interface SequenceService {
|
|
10
10
|
/** Atomically increments the named sequence and returns the new value. */
|
|
11
|
-
next(name: string): Effect.Effect<number,
|
|
11
|
+
next(name: string): Effect.Effect<number, StoreFailure>;
|
|
12
12
|
}
|
|
13
13
|
declare const SequenceServiceTag_base: Context.ServiceClass<SequenceServiceTag, "SequenceServiceTag", SequenceService>;
|
|
14
14
|
export declare class SequenceServiceTag extends SequenceServiceTag_base {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sequence-service.d.ts","sourceRoot":"","sources":["../../src/ports/sequence-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"sequence-service.d.ts","sourceRoot":"","sources":["../../src/ports/sequence-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C;;;;;GAKG;AACH,MAAM,WAAW,eAAe;IAC9B,0EAA0E;IAC1E,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;CACzD;;AAED,qBAAa,kBAAmB,SAAQ,uBAGf;CAAG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ports/sequence-service.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"sources":["../../src/ports/sequence-service.ts"],"sourcesContent":["import type { StoreFailure } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * A monotonic, gap-free-under-contention counter — the mechanism that makes\n * codes unique across service instances. Implemented as Redis `INCR` in\n * `@entifix/redis`; the atomicity of `INCR` is what guarantees no two\n * concurrent commands ever draw the same number.\n */\nexport interface SequenceService {\n /** Atomically increments the named sequence and returns the new value. */\n next(name: string): Effect.Effect<number, StoreFailure>;\n}\n\nexport class SequenceServiceTag extends Context.Service<\n SequenceServiceTag,\n SequenceService\n>()('SequenceServiceTag') {}\n"],"names":["Context","SequenceServiceTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAa9C,OAAO,MAAMC,2BAA2BD,QAAQE,OAAO,GAGnD;AAAuB"}
|