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