@entifix/workflow 0.23.22 → 0.23.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @entifix/workflow
2
2
 
3
- Durable flows. A flow is a pinned routing slip, and this package interprets it on Effect Workflow behind the `FlowEngineTag` port from `@entifix/transactions`: each step an Activity keyed `<flowId>:<step>`, a refusal before the commit point compensated in reverse, a failure after it rolled forward on a durable clock until the participant answers or the step's bound is spent, and a `wait` step parked on a durable deferred its signal completes.
3
+ Durable flows. A flow is a pinned routing slip, and this package interprets it on Effect Workflow behind the `FlowEngineTag` port from `@entifix/transactions`: each step an Activity keyed `<flowId>:<step>`, a refusal before the commit point compensated in reverse — a call whose answer was lost asked again under its own key and the walk continued from its answer, and an undoing whose participant is away tried again — a failure after it rolled forward on a durable clock until the participant answers or the step's bound is spent, and a `wait` step parked on a durable deferred its signal completes.
4
4
 
5
5
  `effect/workflow` and `effect/cluster` are imported here and nowhere else in entifix — their APIs are unstable, and the chaos suite pins what this package relies on.
6
6
 
@@ -84,7 +84,7 @@ export declare class InterpreterOptionsTag extends InterpreterOptionsTag_base {
84
84
  export declare const SlipWorkflow: Workflow.Workflow<"entifix/slip", Schema.Struct<{
85
85
  key: Schema.String;
86
86
  slip: Schema.Struct<{
87
- readonly slipVersion: Schema.Literals<readonly [1, 2, 3]>;
87
+ readonly slipVersion: Schema.Literals<readonly [1, 2, 3, 4]>;
88
88
  readonly flowId: Schema.String;
89
89
  readonly recipe: Schema.String;
90
90
  readonly requiresCommitPoint: Schema.optionalKey<Schema.Boolean>;
@@ -1 +1 @@
1
- {"version":3,"file":"slip-workflow.d.ts","sourceRoot":"","sources":["../../src/interpreter/slip-workflow.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,eAAe,EACpB,IAAI,EAGL,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAEL,KAAK,cAAc,EAMpB,MAAM,eAAe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;AAC5E,eAAO,MAAM,uBAAuB,EAAE,SAAS,MAAM,EACd,CAAC;AAExC,eAAO,MAAM,aAAa,GAAI,MAAM,IAAI,waACF,CAAC;AAEvC,6EAA6E;AAC7E,eAAO,MAAM,iBAAiB,GAAI,SAAS,kBAAkB,mPAK1D,CAAC"}
@@ -137,6 +137,7 @@ const walkSlip = (slip, grammar)=>Effect.gen(function*() {
137
137
  /** What each wait was answered with, by step name — what a guard reads. */ const answered = new Map();
138
138
  /** Steps a guard passed over; a step guarded on one of them is skipped too. */ const skipped = new Set();
139
139
  /** The wait whose timeout stranded the flow, once one has. */ let stranded;
140
+ /** A step whose outcome its participant never told, once one is (v4). */ let inDoubt;
140
141
  const record = (name, patch)=>Activity.make({
141
142
  name,
142
143
  execute: Effect.flatMap(FlowStatusStoreTag, (store)=>store.update(slip.flowId, patch)).pipe(Effect.andThen(Metric.update(Metric.withAttributes(flowStates, {
@@ -313,6 +314,41 @@ const walkSlip = (slip, grammar)=>Effect.gen(function*() {
313
314
  });
314
315
  }
315
316
  });
317
+ /**
318
+ * Dispatches `step` again on a durable clock while it fails for a
319
+ * technical reason, within its bound (v4): an action whose answer was lost
320
+ * replays what the participant did under the same idempotency key, and an
321
+ * undoing is tried until its participant is back. Answers how it ended —
322
+ * `answered`, `refused` with a typed failure waiting does not fix, or
323
+ * `unresolved` once the bound is spent.
324
+ */ const retried = (step, kind, first)=>Effect.gen(function*() {
325
+ var _step_participant;
326
+ const key = (_step_participant = step.participant) != null ? _step_participant : 'participant';
327
+ const bounds = _extends({}, dials, options.dialsFor == null ? void 0 : options.dialsFor.call(options, key));
328
+ const resumes = resumesWithin(bounds);
329
+ for(let resume = first;; resume++){
330
+ if (resume > first || first > 0) yield* DurableClock.sleep({
331
+ name: `${kind === 'action' ? 'resolve' : 'undo'}:${step.step}#${String(resume)}`,
332
+ duration: bounds.resumeAfterMs
333
+ });
334
+ const exit = yield* Effect.exit(call(step, kind, resume));
335
+ if (Exit.isSuccess(exit)) return {
336
+ answered: exit.value
337
+ };
338
+ const failure = Cause.findErrorOption(exit.cause);
339
+ if (Option.isNone(failure) || !waitingCanFix(failure.value)) return {
340
+ refused: Option.getOrUndefined(failure)
341
+ };
342
+ if (resume >= resumes) return {
343
+ unresolved: failure.value
344
+ };
345
+ }
346
+ });
347
+ /**
348
+ * Undoes one step that ran. Under v4 an undoing that fails for a technical
349
+ * reason is tried again on a durable clock, within the step's bound, so a
350
+ * participant away for a moment does not leave its write behind.
351
+ */ const undo = (step)=>grammar.resolvesDoubt ? retried(step, 'compensation', 0).pipe(Effect.map((ended)=>'answered' in ended)) : Effect.exit(call(step, 'compensation')).pipe(Effect.map(Exit.isSuccess));
316
352
  /** Why the flow stranded, when a step's failure is what stranded it. */ let strandedBy;
317
353
  /** One step, its failure tagged with where it happened. */ const run = (step)=>Effect.gen(function*() {
318
354
  var _catalog_get, _catalog_get1;
@@ -343,14 +379,39 @@ const walkSlip = (slip, grammar)=>Effect.gen(function*() {
343
379
  bindings.record(step, catalog.get(step.ref), rolled.answer);
344
380
  return;
345
381
  }
346
- const answer = yield* call(step, 'action').pipe(Effect.mapError((failure)=>({
382
+ const compensatable = ((_catalog_get1 = catalog.get(step.ref)) == null ? void 0 : _catalog_get1.kind) === 'compensatable';
383
+ const exit = yield* Effect.exit(call(step, 'action').pipe(Effect.mapError((failure)=>({
347
384
  step,
348
385
  failure
349
- })));
350
- bindings.record(step, catalog.get(step.ref), answer);
351
- if (((_catalog_get1 = catalog.get(step.ref)) == null ? void 0 : _catalog_get1.kind) === 'compensatable') done.push(step);
386
+ }))));
387
+ if (Exit.isSuccess(exit)) {
388
+ bindings.record(step, catalog.get(step.ref), exit.value);
389
+ if (compensatable) done.push(step);
390
+ return;
391
+ }
392
+ const failed = Cause.findErrorOption(exit.cause);
393
+ // The call failed with its outcome unknown: the participant may have
394
+ // done it and lost the answer. Asked again under the same key, it says
395
+ // which — and the walk goes on from its answer, so a write that landed
396
+ // is never undone as if it had not, nor a pivot rolled back (v4).
397
+ if (grammar.resolvesDoubt && Option.isSome(failed) && waitingCanFix(failed.value.failure)) {
398
+ const resolved = yield* retried(step, 'action', 1);
399
+ if ('answered' in resolved) {
400
+ bindings.record(step, catalog.get(step.ref), resolved.answered);
401
+ if (compensatable) done.push(step);
402
+ return;
403
+ }
404
+ if ('unresolved' in resolved) inDoubt = step;
405
+ }
406
+ return yield* Effect.failCause(exit.cause);
352
407
  });
353
408
  yield* announce('flow.started', 'started', 0);
409
+ /**
410
+ * The version a flow's one ending is announced at: past every step's, so
411
+ * a reader that keeps the newest version takes it over the `waiting` or
412
+ * `suspended` its last step announced first — which shared that step's
413
+ * ordinal, and left a stranded flow reading `suspended` forever.
414
+ */ const ending = steps.length + 1;
354
415
  for (const stage of slip.stages){
355
416
  const exits = yield* Effect.forEach(groupsOf(stage.steps), (group)=>Effect.exit(Effect.forEach(group, run, {
356
417
  discard: true
@@ -366,29 +427,35 @@ const walkSlip = (slip, grammar)=>Effect.gen(function*() {
366
427
  state: 'stranded',
367
428
  step: stranded.step
368
429
  });
369
- yield* announce('flow.stranded', stranded.step, ordinalOf(stranded), strandedBy);
430
+ yield* announce('flow.stranded', stranded.step, ending, strandedBy);
370
431
  return 'stranded';
371
432
  }
372
433
  const { step, failure } = first;
373
434
  if (commitPoint === -1 || steps.indexOf(step) <= commitPoint) {
435
+ // A step still in doubt may have landed, and nothing can undo what is
436
+ // not known: the flow stops there, for a person to look at.
437
+ const unresolved = inDoubt === undefined ? [] : [
438
+ inDoubt
439
+ ];
374
440
  for (const undone of [
375
- ...done
376
- ].reverse()){
377
- const undoing = yield* Effect.exit(call(undone, 'compensation'));
378
- if (Exit.isFailure(undoing)) {
379
- yield* record(`status:${undone.step}:failed`, {
380
- state: 'failed',
381
- step: undone.step
382
- });
383
- yield* announce('flow.failed', undone.step, ordinalOf(undone), failure);
384
- return 'failed';
385
- }
441
+ ...unresolved,
442
+ ...[
443
+ ...done
444
+ ].reverse()
445
+ ]){
446
+ if (undone !== inDoubt && (yield* undo(undone))) continue;
447
+ yield* record(`status:${undone.step}:failed`, {
448
+ state: 'failed',
449
+ step: undone.step
450
+ });
451
+ yield* announce('flow.failed', undone.step, ending, failure);
452
+ return 'failed';
386
453
  }
387
454
  yield* record(`status:${step.step}:compensated`, {
388
455
  state: 'compensated',
389
456
  step: step.step
390
457
  });
391
- yield* announce('flow.failed', step.step, ordinalOf(step), failure);
458
+ yield* announce('flow.failed', step.step, ending, failure);
392
459
  return 'compensated';
393
460
  }
394
461
  yield* record(`status:${step.step}:suspended`, {
@@ -401,7 +468,7 @@ const walkSlip = (slip, grammar)=>Effect.gen(function*() {
401
468
  yield* record('status:completed', {
402
469
  state: 'completed'
403
470
  });
404
- yield* announce('flow.completed', 'completed', steps.length + 1);
471
+ yield* announce('flow.completed', 'completed', ending);
405
472
  return 'completed';
406
473
  });
407
474
  /**
@@ -413,15 +480,23 @@ const walkSlip = (slip, grammar)=>Effect.gen(function*() {
413
480
  */ const INTERPRETERS = {
414
481
  1: (slip)=>walkSlip(slip, {
415
482
  announcesCommittedWaits: false,
416
- rollsForward: false
483
+ rollsForward: false,
484
+ resolvesDoubt: false
417
485
  }),
418
486
  2: (slip)=>walkSlip(slip, {
419
487
  announcesCommittedWaits: true,
420
- rollsForward: false
488
+ rollsForward: false,
489
+ resolvesDoubt: false
421
490
  }),
422
491
  3: (slip)=>walkSlip(slip, {
423
492
  announcesCommittedWaits: true,
424
- rollsForward: true
493
+ rollsForward: true,
494
+ resolvesDoubt: false
495
+ }),
496
+ 4: (slip)=>walkSlip(slip, {
497
+ announcesCommittedWaits: true,
498
+ rollsForward: true,
499
+ resolvesDoubt: true
425
500
  })
426
501
  };
427
502
  /** Every `slipVersion` the interpreter walks — each must have a journal. */ export const interpretedSlipVersions = Object.keys(INTERPRETERS).map(Number);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/interpreter/slip-workflow.ts"],"sourcesContent":["import {\n type FragmentCatalog,\n Slip,\n type SlipStep,\n slipSteps,\n} from '@entifix/business/flow';\nimport {\n decodeProblem,\n type EntifixFailure,\n Failure,\n isFailure,\n JsonBody,\n problemOf,\n Timeout,\n} from '@entifix/core';\nimport {\n BulkheadTag,\n CircuitBreakerTag,\n flowEvent,\n type FlowEventName,\n On,\n OutboxDrainTag,\n OutboxTag,\n ParticipantClientTag,\n} from '@entifix/transactions';\nimport {\n Cause,\n Context,\n Effect,\n Exit,\n Metric,\n Option,\n Schema,\n SchemaTransformation,\n} from 'effect';\nimport {\n Activity,\n DurableClock,\n DurableDeferred,\n Workflow,\n} from 'effect/workflow';\n\nimport {\n type FlowRecordPatch,\n flowStates,\n FlowStatusStoreTag,\n} from '../status/flow-status-store.js';\nimport { makeBindings } from './bindings.js';\n\n/**\n * A failure as an Activity journals it: the problem body on the way in, the\n * failure its code names on the way out, so a resumed flow sees the typed\n * refusal a participant sent rather than a cast.\n */\nexport const JournaledFailure: Schema.Codec<EntifixFailure, unknown> =\n Schema.Unknown.pipe(\n Schema.decodeTo(\n Schema.declare((value): value is EntifixFailure => isFailure(value)),\n SchemaTransformation.transform({\n decode: body => decodeProblem(body),\n encode: failure => problemOf(failure),\n }),\n ),\n );\n\n/**\n * How a flow ended, as the workflow's own result: every step ran, or a\n * refusal before the commit point was undone, or an undoing itself failed and\n * the flow stopped where it was — which a person has to look at — or a wait\n * that strands on its timeout ran out, which a person has to look at too.\n */\nexport const FlowOutcome = Schema.Literals([\n 'completed',\n 'compensated',\n 'failed',\n 'stranded',\n]);\n\n/**\n * What a wait does when its `timeoutMs` runs out, from its `onTimeout`\n * parameter: answer as if signalled with an outcome a later guard branches\n * on, strand the flow for an operator, or — named neither — fail as any step\n * does, which past the commit point suspends it.\n */\ntype OnTimeout =\n | { readonly kind: 'outcome'; readonly outcome: string }\n | { readonly kind: 'strand' }\n | { readonly kind: 'fail' };\n\nconst onTimeoutOf = (step: SlipStep): OnTimeout => {\n const named = step.parameters?.['onTimeout'];\n if (named === 'strand') return { kind: 'strand' };\n const outcome =\n typeof named === 'object' && named !== null\n ? (named as { readonly outcome?: unknown }).outcome\n : undefined;\n return typeof outcome === 'string'\n ? { kind: 'outcome', outcome }\n : { kind: 'fail' };\n};\n\n/** The outcome a wait was answered with: its signal's `outcome`, when a string. */\nconst outcomeOf = (answer: unknown): string | undefined => {\n const named =\n typeof answer === 'object' && answer !== null\n ? (answer as { readonly outcome?: unknown }).outcome\n : undefined;\n return typeof named === 'string' ? named : undefined;\n};\n\n/** The race's answer when a wait that strands on its timeout ran out. */\nconst STRANDED = Symbol.for('@entifix/workflow/stranded');\n\n/** A durable wait that outlived its timeout before its signal came. */\nexport class FlowWaitTimedOut extends Failure.timeout<FlowWaitTimedOut>()(\n 'FlowWaitTimedOut',\n 'flowWaitTimedOut',\n { step: Schema.String },\n { message: ({ step }) => `the wait at '${step}' timed out` },\n) {}\n\n/** How long a flow gives each participant call, and each step as a whole. */\nexport interface FlowDials {\n /** One attempt at a call. */\n readonly attemptTimeoutMs: number;\n /** One run of a step: every attempt together, retries included. */\n readonly stepTimeoutMs: number;\n /**\n * Past the commit point, how long a step keeps being dispatched again after\n * a technical failure before the flow strands (grammar 3). Counted in\n * waits of `resumeAfterMs`, so a replay walks the same number of them.\n */\n readonly stepBoundMs: number;\n /**\n * Past the commit point, how long a suspended step waits on a durable clock\n * before it is dispatched again — no shorter than the participant's breaker\n * stays open, or the next run only meets the same open breaker.\n */\n readonly resumeAfterMs: number;\n /** Segments of one stage run at once. */\n readonly concurrency: number;\n}\n\nexport const DEFAULT_FLOW_DIALS: FlowDials = {\n attemptTimeoutMs: 10_000,\n stepTimeoutMs: 60_000,\n stepBoundMs: 300_000,\n resumeAfterMs: 10_000,\n concurrency: 4,\n};\n\n/**\n * How many times a step suspended past the commit point is dispatched again\n * before the flow strands: the waits that fit in its bound, and at least one.\n */\nexport const resumesWithin = (\n dials: Pick<FlowDials, 'stepBoundMs' | 'resumeAfterMs'>,\n): number =>\n Math.max(1, Math.floor(dials.stepBoundMs / Math.max(1, dials.resumeAfterMs)));\n\n/**\n * Whether waiting can fix a failure past the commit point: a technical one —\n * a breaker open, a bulkhead full, a timeout, a participant down — can; a\n * business refusal, or a protocol failure, which is a bug, cannot.\n */\nconst waitingCanFix = (failure: EntifixFailure): boolean =>\n Failure.isFamily('technical')(failure) && failure.category !== 'protocol';\n\n/** What the interpreter runs a slip with: the catalog, who announces, the dials. */\nexport interface InterpreterOptions {\n readonly catalog: FragmentCatalog;\n /** The slice the `flow.*` events are announced from. */\n readonly source: string;\n readonly dials?: Partial<FlowDials>;\n /**\n * One participant's own attempt, step and resume bounds, over `dials` — the same\n * shape the breaker's `dialsFor` and the bulkhead's `permitsFor` take, so a\n * participant's dials are one row set however many guards read them.\n */\n readonly dialsFor?: (\n participant: string,\n ) => Partial<Omit<FlowDials, 'concurrency'>> | undefined;\n}\n\n/**\n * The interpreter's options, provided to the workflow it is registered with —\n * the payload is the slip; the catalog and dials are the deployment's.\n */\nexport class InterpreterOptionsTag extends Context.Service<\n InterpreterOptionsTag,\n InterpreterOptions\n>()('@entifix/workflow/InterpreterOptions') {}\n\n/**\n * The one workflow every flow runs as: its payload is the pinned slip and the\n * idempotency key that started it\n * ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)).\n * The execution id derives from the key, so the same key is the same flow.\n *\n * Under grammars 1 and 2, a failure past the commit point fails the run and\n * leaves the record `suspended`; nothing dispatches the step again. Grammar 3\n * rolls forward inside the walk instead — a durable clock, then the step\n * again — and strands when its bound runs out.\n */\nexport const SlipWorkflow = Workflow.make('entifix/slip', {\n payload: { key: Schema.String, slip: Slip },\n idempotencyKey: payload => payload.key,\n success: FlowOutcome,\n // Grammars 1 and 2 end a run with a failure past the commit point; it is\n // never the flow's result.\n error: JournaledFailure,\n});\n\n/** The durable wait a `wait` step parks on, addressed by the step's name. */\nexport const waitFor = (step: string) =>\n DurableDeferred.make(`wait:${step}`, { success: Schema.Unknown });\n\n/** A step's failure, with the step it happened at. */\ninterface StepFailed {\n readonly step: SlipStep;\n readonly failure: EntifixFailure;\n}\n\nconst segmentOf = (step: SlipStep) =>\n step.segment === undefined\n ? undefined\n : [step.segment.vendor, step.segment.paymentMethod]\n .filter(Boolean)\n .join('/');\n\n/**\n * A stage's steps as the groups that run at once: one group per segment when\n * every step names one — a basket's vendors, joined before the shared pivot —\n * and otherwise one group, in order.\n */\nconst groupsOf = (steps: readonly SlipStep[]): readonly SlipStep[][] => {\n if (steps.some(step => segmentOf(step) === undefined)) return [[...steps]];\n const groups = new Map<string, SlipStep[]>();\n for (const step of steps) {\n const key = segmentOf(step) as string;\n groups.set(key, [...(groups.get(key) ?? []), step]);\n }\n return [...groups.values()];\n};\n\n/**\n * Interprets a pinned slip of grammar version 1\n * ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)):\n * each step is an Activity named after it and keyed `<flowId>:<step>`, so a\n * resumed flow replays what already ran and calls a participant at most once\n * per step. Inside the Activity the call runs under the participant's\n * breaker and bulkhead and the retry budget, each attempt bounded and the\n * step as a whole bounded; nothing retries outside it.\n *\n * - Before and at the commit point, a failure — a breaker already open\n * included, which fails fast — compensates what succeeded, in reverse, and\n * the flow ends `compensated`.\n * - After it, the money is taken, so the flow rolls forward, never back.\n * Under grammar 3 a technical failure suspends the step, a durable clock\n * waits `resumeAfterMs`, and the step is dispatched again under the same\n * idempotency key, until it answers or `stepBoundMs` is spent and the flow\n * strands; a business refusal strands it at once. Under grammars 1 and 2 a\n * failure there ends the run with the record left `suspended`.\n * - A `wait` step parks the flow on a durable deferred its signal completes,\n * raced with a durable clock when it names `timeoutMs`; it may name a\n * `correlation`, so a sender that knows the order rather than the flow can\n * complete it.\n * - The segments of a stage run at once, bounded, and join before the next.\n *\n * Every transition is announced as a `flow.*` event through the outbox, by an\n * Activity, so it is written once whatever replays. Compensation is explicit\n * rather than a workflow finalizer, so the record says `compensated` only\n * after the last undoing has run — and an undoing that fails stops the flow\n * `failed` at that step instead of pretending.\n */\n/** What differs between grammar versions as the walk is interpreted. */\ninterface Grammar {\n /** Whether a wait past the commit point announces `flow.waiting` (v2). */\n readonly announcesCommittedWaits: boolean;\n /**\n * Whether a step that fails past the commit point is dispatched again on a\n * durable clock, and the flow strands when that stops helping (v3).\n */\n readonly rollsForward: boolean;\n}\n\nconst walkSlip = (slip: Slip, grammar: Grammar) =>\n Effect.gen(function* () {\n const options = yield* InterpreterOptionsTag;\n const dials = { ...DEFAULT_FLOW_DIALS, ...options.dials };\n const { catalog } = options;\n const steps = slipSteps(slip);\n const ordinalOf = (step: SlipStep) => steps.indexOf(step) + 1;\n const commitPoint = steps.findIndex(\n step => catalog.get(step.ref)?.kind === 'pivot',\n );\n const bindings = makeBindings();\n const done: SlipStep[] = [];\n /** What each wait was answered with, by step name — what a guard reads. */\n const answered = new Map<string, string | undefined>();\n /** Steps a guard passed over; a step guarded on one of them is skipped too. */\n const skipped = new Set<string>();\n /** The wait whose timeout stranded the flow, once one has. */\n let stranded: SlipStep | undefined;\n\n const record = (name: string, patch: FlowRecordPatch) =>\n Activity.make({\n name,\n execute: Effect.flatMap(FlowStatusStoreTag, store =>\n store.update(slip.flowId, patch),\n ).pipe(\n Effect.andThen(\n Metric.update(\n Metric.withAttributes(flowStates, {\n state: patch.state,\n source: options.source,\n }),\n 1,\n ),\n ),\n Effect.orDie,\n ),\n });\n\n const announce = (\n name: FlowEventName,\n step: string,\n ordinal: number,\n failure?: EntifixFailure,\n ) =>\n Activity.make({\n name: `announce:${name}:${step}`,\n execute: Effect.flatMap(OutboxTag, outbox =>\n outbox.enqueue(\n flowEvent({\n name,\n source: options.source,\n at: new Date().toISOString(),\n step: `${name}:${step}`,\n ordinal,\n audience: [\n { kind: 'flow', id: slip.flowId },\n ...(slip.audience ?? []),\n ],\n data: {\n flowId: slip.flowId,\n definition: slip.recipe,\n slipVersion: slip.slipVersion,\n step,\n ...(failure === undefined\n ? {}\n : {\n failure: {\n code: failure.code,\n category: failure.category,\n },\n }),\n },\n }),\n ),\n ).pipe(\n Effect.orDie,\n // On the bus now rather than at the relay's next sweep, where the\n // host provides a drain; inside the activity, so a replay that skips\n // the announcement skips the drain with it.\n Effect.andThen(\n Effect.flatMap(Effect.serviceOption(OutboxDrainTag), drain =>\n Option.isSome(drain) ? drain.value.now : Effect.void,\n ),\n ),\n ),\n });\n\n /** One call, bounded, under the participant's breaker, bulkhead and budget. */\n const guarded = (\n step: SlipStep,\n attempt: Effect.Effect<unknown, EntifixFailure>,\n ) =>\n Effect.gen(function* () {\n const key = step.participant ?? 'participant';\n const bounds = { ...dials, ...options.dialsFor?.(key) };\n const breaker = yield* CircuitBreakerTag;\n const bulkhead = yield* BulkheadTag;\n const timedOut = () => Effect.fail(new Timeout({ dependency: key }));\n return yield* breaker\n .guard(key)(\n bulkhead.withPermit(key)(\n attempt.pipe(\n Effect.timeoutOrElse({\n duration: bounds.attemptTimeoutMs,\n orElse: timedOut,\n }),\n ),\n ),\n )\n .pipe(\n On(Failure.isFamily('technical')).retry({\n key: { dependency: key },\n idempotent: true,\n }),\n Effect.timeoutOrElse({\n duration: bounds.stepTimeoutMs,\n orElse: timedOut,\n }),\n );\n });\n\n const call = (\n step: SlipStep,\n kind: 'action' | 'compensation',\n resume = 0,\n ) =>\n Activity.make({\n // A step dispatched again past the commit point is a new Activity, so\n // a replay reads each run's own answer rather than the first failure.\n name:\n resume === 0\n ? `${step.step}:${kind}`\n : `${step.step}:${kind}#${String(resume)}`,\n // Whatever the participant answered, as JSON — `undefined` included,\n // which a journal cannot otherwise hold.\n success: JsonBody,\n error: JournaledFailure,\n execute: Effect.flatMap(ParticipantClientTag, participant =>\n guarded(\n step,\n participant.call({\n step,\n kind,\n idempotencyKey:\n kind === 'action'\n ? `${slip.flowId}:${step.step}`\n : `${slip.flowId}:${step.step}:compensation`,\n inputs: bindings.inputsFor(step, catalog.get(step.ref), kind),\n }),\n ),\n ),\n });\n\n const wait = (step: SlipStep) =>\n Effect.gen(function* () {\n const correlation = step.parameters?.['correlation'];\n const accepts = catalog.get(step.ref)?.outcomes;\n const onTimeout = onTimeoutOf(step);\n yield* record(`status:${step.step}:waiting`, {\n state: 'waiting',\n step: step.step,\n waitingFor: step.step,\n ...(typeof correlation === 'string' ? { correlation } : {}),\n ...(accepts === undefined ? {} : { accepts }),\n });\n // Past the commit point the caller's write has landed, and the wait is\n // for someone else — a courier, a person — so the flow says so and a\n // browser holding the write pending can let it go. Before it, nothing\n // has landed, and the flow stays silent.\n if (\n grammar.announcesCommittedWaits &&\n commitPoint !== -1 &&\n steps.indexOf(step) > commitPoint\n )\n yield* announce('flow.waiting', step.step, ordinalOf(step));\n const signalled = DurableDeferred.await(waitFor(step.step));\n const timeoutMs = step.parameters?.['timeoutMs'];\n // A durable race, so a replay answers the branch that won rather than\n // racing again.\n const answer =\n typeof timeoutMs === 'number'\n ? yield* DurableDeferred.raceAll({\n name: `race:${step.step}`,\n success: Schema.Unknown,\n error: FlowWaitTimedOut,\n effects: [\n signalled,\n DurableClock.sleep({\n name: `timeout:${step.step}`,\n duration: timeoutMs,\n }).pipe(\n Effect.andThen(\n // An outcome answers as a signal would; a strand and a\n // plain failure both fail the race, and are told apart\n // below — so the journaled race is the same either way.\n onTimeout.kind === 'outcome'\n ? Effect.succeed<unknown>({\n outcome: onTimeout.outcome,\n })\n : Effect.fail(\n new FlowWaitTimedOut({ step: step.step }),\n ),\n ),\n ),\n ],\n }).pipe(\n Effect.catchTag('FlowWaitTimedOut', timedOut =>\n onTimeout.kind === 'strand'\n ? Effect.succeed<unknown>(STRANDED)\n : Effect.fail(timedOut),\n ),\n )\n : yield* signalled;\n if (answer === STRANDED) {\n stranded = step;\n return;\n }\n answered.set(step.step, outcomeOf(answer));\n bindings.record(step, catalog.get(step.ref), answer);\n yield* record(`status:${step.step}:resumed`, {\n state: 'running',\n step: step.step,\n });\n });\n\n const pastCommit = (step: SlipStep) =>\n commitPoint !== -1 && steps.indexOf(step) > commitPoint;\n\n /**\n * A step past the commit point under grammar 3: a technical failure\n * suspends it, a durable clock waits, and it is dispatched again — the\n * participant answers the same idempotency key — until it answers or its\n * bound runs out, when the flow strands. A business refusal strands at\n * once, since waiting does not change an answer.\n */\n const rollForward = (step: SlipStep) =>\n Effect.gen(function* () {\n const key = step.participant ?? 'participant';\n const bounds = { ...dials, ...options.dialsFor?.(key) };\n const resumes = resumesWithin(bounds);\n for (let resume = 0; ; resume++) {\n const exit = yield* Effect.exit(call(step, 'action', resume));\n if (Exit.isSuccess(exit)) {\n if (resume > 0)\n yield* record(`status:${step.step}:resumed`, {\n state: 'running',\n step: step.step,\n });\n return { answer: exit.value } as const;\n }\n const failure = Cause.findErrorOption(exit.cause);\n // No typed failure — a defect, which is a bug that waiting does\n // not fix — strands as a refusal does, with nothing to name.\n if (\n Option.isNone(failure) ||\n !waitingCanFix(failure.value) ||\n resume >= resumes\n ) {\n stranded = step;\n return {\n stranded: Option.getOrUndefined(failure),\n } as const;\n }\n if (resume === 0) {\n yield* record(`status:${step.step}:suspended`, {\n state: 'suspended',\n step: step.step,\n });\n yield* announce(\n 'flow.suspended',\n step.step,\n ordinalOf(step),\n failure.value,\n );\n }\n yield* DurableClock.sleep({\n name: `resume:${step.step}#${String(resume + 1)}`,\n duration: bounds.resumeAfterMs,\n });\n }\n });\n\n /** Why the flow stranded, when a step's failure is what stranded it. */\n let strandedBy: EntifixFailure | undefined;\n\n /** One step, its failure tagged with where it happened. */\n const run = (step: SlipStep) =>\n Effect.gen(function* () {\n // A stranded flow runs nothing more, in any group of the stage.\n if (stranded !== undefined) return;\n if (step.guard !== undefined) {\n const { wait: guardedOn, outcomes } = step.guard;\n const outcome = answered.get(guardedOn);\n if (\n skipped.has(guardedOn) ||\n outcome === undefined ||\n !outcomes.includes(outcome)\n ) {\n skipped.add(step.step);\n return;\n }\n }\n if (catalog.get(step.ref)?.kind === 'wait')\n return yield* wait(step).pipe(\n Effect.mapError((failure): StepFailed => ({ step, failure })),\n );\n yield* record(`status:${step.step}:running`, {\n state: 'running',\n step: step.step,\n });\n if (grammar.rollsForward && pastCommit(step)) {\n const rolled = yield* rollForward(step);\n if ('stranded' in rolled) {\n strandedBy = rolled.stranded;\n return;\n }\n bindings.record(step, catalog.get(step.ref), rolled.answer);\n return;\n }\n const answer = yield* call(step, 'action').pipe(\n Effect.mapError((failure): StepFailed => ({ step, failure })),\n );\n bindings.record(step, catalog.get(step.ref), answer);\n if (catalog.get(step.ref)?.kind === 'compensatable') done.push(step);\n });\n\n yield* announce('flow.started', 'started', 0);\n\n for (const stage of slip.stages) {\n const exits = yield* Effect.forEach(\n groupsOf(stage.steps),\n group => Effect.exit(Effect.forEach(group, run, { discard: true })),\n { concurrency: dials.concurrency },\n );\n // The earliest step that failed decides; a group's failure is its own.\n const [first] = exits\n .flatMap(exit =>\n Exit.isFailure(exit)\n ? // A durable race fails with its losers' interruptions beside\n // the failure that won, so the failure is looked for.\n exit.cause.reasons\n .filter(Cause.isFailReason)\n .map(reason => reason.error)\n : [],\n )\n .sort((a, b) => ordinalOf(a.step) - ordinalOf(b.step));\n if (first === undefined) {\n if (stranded === undefined) continue;\n yield* record(`status:${stranded.step}:stranded`, {\n state: 'stranded',\n step: stranded.step,\n });\n yield* announce(\n 'flow.stranded',\n stranded.step,\n ordinalOf(stranded),\n strandedBy,\n );\n return 'stranded' as const;\n }\n\n const { step, failure } = first;\n if (commitPoint === -1 || steps.indexOf(step) <= commitPoint) {\n for (const undone of [...done].reverse()) {\n const undoing = yield* Effect.exit(call(undone, 'compensation'));\n if (Exit.isFailure(undoing)) {\n yield* record(`status:${undone.step}:failed`, {\n state: 'failed',\n step: undone.step,\n });\n yield* announce(\n 'flow.failed',\n undone.step,\n ordinalOf(undone),\n failure,\n );\n return 'failed' as const;\n }\n }\n yield* record(`status:${step.step}:compensated`, {\n state: 'compensated',\n step: step.step,\n });\n yield* announce('flow.failed', step.step, ordinalOf(step), failure);\n return 'compensated' as const;\n }\n\n yield* record(`status:${step.step}:suspended`, {\n state: 'suspended',\n step: step.step,\n });\n yield* announce('flow.suspended', step.step, ordinalOf(step), failure);\n return yield* Effect.fail(failure).pipe(\n Effect.provideService(Workflow.SuspendOnFailure, true),\n );\n }\n\n yield* record('status:completed', { state: 'completed' });\n yield* announce('flow.completed', 'completed', steps.length + 1);\n return 'completed' as const;\n });\n\n/**\n * One interpreter per grammar version a slip can be written in. A flow runs\n * to its end under the grammar it started with, so a change to how steps are\n * walked — their order, their Activity names — is a new entry here, never an\n * edit to an existing one; the journal replay holds every entry to its\n * recorded command sequence.\n */\nconst INTERPRETERS = {\n 1: (slip: Slip) =>\n walkSlip(slip, { announcesCommittedWaits: false, rollsForward: false }),\n 2: (slip: Slip) =>\n walkSlip(slip, { announcesCommittedWaits: true, rollsForward: false }),\n 3: (slip: Slip) =>\n walkSlip(slip, { announcesCommittedWaits: true, rollsForward: true }),\n} as const satisfies Record<Slip['slipVersion'], (slip: Slip) => unknown>;\n\n/** Every `slipVersion` the interpreter walks — each must have a journal. */\nexport const interpretedSlipVersions: readonly number[] =\n Object.keys(INTERPRETERS).map(Number);\n\nexport const interpretSlip = (slip: Slip) =>\n INTERPRETERS[slip.slipVersion](slip);\n\n/** The interpreter registered with the workflow engine, with its options. */\nexport const SlipWorkflowLayer = (options: InterpreterOptions) =>\n SlipWorkflow.toLayer(payload =>\n interpretSlip(payload.slip).pipe(\n Effect.provideService(InterpreterOptionsTag, options),\n ),\n );\n"],"names":["Slip","slipSteps","decodeProblem","Failure","isFailure","JsonBody","problemOf","Timeout","BulkheadTag","CircuitBreakerTag","flowEvent","On","OutboxDrainTag","OutboxTag","ParticipantClientTag","Cause","Context","Effect","Exit","Metric","Option","Schema","SchemaTransformation","Activity","DurableClock","DurableDeferred","Workflow","flowStates","FlowStatusStoreTag","makeBindings","JournaledFailure","Unknown","pipe","decodeTo","declare","value","transform","decode","body","encode","failure","FlowOutcome","Literals","onTimeoutOf","step","named","parameters","kind","outcome","undefined","outcomeOf","answer","STRANDED","Symbol","for","FlowWaitTimedOut","timeout","String","message","DEFAULT_FLOW_DIALS","attemptTimeoutMs","stepTimeoutMs","stepBoundMs","resumeAfterMs","concurrency","resumesWithin","dials","Math","max","floor","waitingCanFix","isFamily","category","InterpreterOptionsTag","Service","SlipWorkflow","make","payload","key","slip","idempotencyKey","success","error","waitFor","segmentOf","segment","vendor","paymentMethod","filter","Boolean","join","groupsOf","steps","some","groups","Map","set","get","values","walkSlip","grammar","gen","options","catalog","ordinalOf","indexOf","commitPoint","findIndex","ref","bindings","done","answered","skipped","Set","stranded","record","name","patch","execute","flatMap","store","update","flowId","andThen","withAttributes","state","source","orDie","announce","ordinal","outbox","enqueue","at","Date","toISOString","audience","id","data","definition","recipe","slipVersion","code","serviceOption","drain","isSome","now","void","guarded","attempt","participant","bounds","dialsFor","breaker","bulkhead","timedOut","fail","dependency","guard","withPermit","timeoutOrElse","duration","orElse","retry","idempotent","call","resume","inputs","inputsFor","wait","correlation","accepts","outcomes","onTimeout","waitingFor","announcesCommittedWaits","signalled","await","timeoutMs","raceAll","effects","sleep","succeed","catchTag","pastCommit","rollForward","resumes","exit","isSuccess","findErrorOption","cause","isNone","getOrUndefined","strandedBy","run","guardedOn","has","includes","add","mapError","rollsForward","rolled","push","stage","stages","exits","forEach","group","discard","first","reasons","isFailReason","map","reason","sort","a","b","undone","reverse","undoing","provideService","SuspendOnFailure","length","INTERPRETERS","interpretedSlipVersions","Object","keys","Number","interpretSlip","SlipWorkflowLayer","toLayer"],"mappings":";AAAA,SAEEA,IAAI,EAEJC,SAAS,QACJ,yBAAyB;AAChC,SACEC,aAAa,EAEbC,OAAO,EACPC,SAAS,EACTC,QAAQ,EACRC,SAAS,EACTC,OAAO,QACF,gBAAgB;AACvB,SACEC,WAAW,EACXC,iBAAiB,EACjBC,SAAS,EAETC,EAAE,EACFC,cAAc,EACdC,SAAS,EACTC,oBAAoB,QACf,wBAAwB;AAC/B,SACEC,KAAK,EACLC,OAAO,EACPC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,MAAM,EACNC,MAAM,EACNC,oBAAoB,QACf,SAAS;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AAyB;YAAMyB,cAAc;QAAK;AACvE;AAEA,0EAA0E,GAC1E,OAAO,MAAMwB,0BACXC,OAAOC,IAAI,CAACH,cAAcX,GAAG,CAACe,QAAQ;AAExC,OAAO,MAAMC,gBAAgB,CAACpJ,OAC5B+I,YAAY,CAAC/I,KAAK6D,WAAW,CAAC,CAAC7D,MAAM;AAEvC,2EAA2E,GAC3E,OAAO,MAAMqJ,oBAAoB,CAAC9H,UAChC3B,aAAa0J,OAAO,CAACxJ,CAAAA,UACnBsJ,cAActJ,QAAQE,IAAI,EAAE/C,IAAI,CAC9Bf,OAAO0M,cAAc,CAAClJ,uBAAuB6B,WAE/C"}
1
+ {"version":3,"sources":["../../src/interpreter/slip-workflow.ts"],"sourcesContent":["import {\n type FragmentCatalog,\n Slip,\n type SlipStep,\n slipSteps,\n} from '@entifix/business/flow';\nimport {\n decodeProblem,\n type EntifixFailure,\n Failure,\n isFailure,\n JsonBody,\n problemOf,\n Timeout,\n} from '@entifix/core';\nimport {\n BulkheadTag,\n CircuitBreakerTag,\n flowEvent,\n type FlowEventName,\n On,\n OutboxDrainTag,\n OutboxTag,\n ParticipantClientTag,\n} from '@entifix/transactions';\nimport {\n Cause,\n Context,\n Effect,\n Exit,\n Metric,\n Option,\n Schema,\n SchemaTransformation,\n} from 'effect';\nimport {\n Activity,\n DurableClock,\n DurableDeferred,\n Workflow,\n} from 'effect/workflow';\n\nimport {\n type FlowRecordPatch,\n flowStates,\n FlowStatusStoreTag,\n} from '../status/flow-status-store.js';\nimport { makeBindings } from './bindings.js';\n\n/**\n * A failure as an Activity journals it: the problem body on the way in, the\n * failure its code names on the way out, so a resumed flow sees the typed\n * refusal a participant sent rather than a cast.\n */\nexport const JournaledFailure: Schema.Codec<EntifixFailure, unknown> =\n Schema.Unknown.pipe(\n Schema.decodeTo(\n Schema.declare((value): value is EntifixFailure => isFailure(value)),\n SchemaTransformation.transform({\n decode: body => decodeProblem(body),\n encode: failure => problemOf(failure),\n }),\n ),\n );\n\n/**\n * How a flow ended, as the workflow's own result: every step ran, or a\n * refusal before the commit point was undone, or an undoing itself failed and\n * the flow stopped where it was — which a person has to look at — or a wait\n * that strands on its timeout ran out, which a person has to look at too.\n */\nexport const FlowOutcome = Schema.Literals([\n 'completed',\n 'compensated',\n 'failed',\n 'stranded',\n]);\n\n/**\n * What a wait does when its `timeoutMs` runs out, from its `onTimeout`\n * parameter: answer as if signalled with an outcome a later guard branches\n * on, strand the flow for an operator, or — named neither — fail as any step\n * does, which past the commit point suspends it.\n */\ntype OnTimeout =\n | { readonly kind: 'outcome'; readonly outcome: string }\n | { readonly kind: 'strand' }\n | { readonly kind: 'fail' };\n\nconst onTimeoutOf = (step: SlipStep): OnTimeout => {\n const named = step.parameters?.['onTimeout'];\n if (named === 'strand') return { kind: 'strand' };\n const outcome =\n typeof named === 'object' && named !== null\n ? (named as { readonly outcome?: unknown }).outcome\n : undefined;\n return typeof outcome === 'string'\n ? { kind: 'outcome', outcome }\n : { kind: 'fail' };\n};\n\n/** The outcome a wait was answered with: its signal's `outcome`, when a string. */\nconst outcomeOf = (answer: unknown): string | undefined => {\n const named =\n typeof answer === 'object' && answer !== null\n ? (answer as { readonly outcome?: unknown }).outcome\n : undefined;\n return typeof named === 'string' ? named : undefined;\n};\n\n/** The race's answer when a wait that strands on its timeout ran out. */\nconst STRANDED = Symbol.for('@entifix/workflow/stranded');\n\n/** A durable wait that outlived its timeout before its signal came. */\nexport class FlowWaitTimedOut extends Failure.timeout<FlowWaitTimedOut>()(\n 'FlowWaitTimedOut',\n 'flowWaitTimedOut',\n { step: Schema.String },\n { message: ({ step }) => `the wait at '${step}' timed out` },\n) {}\n\n/** How long a flow gives each participant call, and each step as a whole. */\nexport interface FlowDials {\n /** One attempt at a call. */\n readonly attemptTimeoutMs: number;\n /** One run of a step: every attempt together, retries included. */\n readonly stepTimeoutMs: number;\n /**\n * Past the commit point, how long a step keeps being dispatched again after\n * a technical failure before the flow strands (grammar 3). Counted in\n * waits of `resumeAfterMs`, so a replay walks the same number of them.\n */\n readonly stepBoundMs: number;\n /**\n * Past the commit point, how long a suspended step waits on a durable clock\n * before it is dispatched again — no shorter than the participant's breaker\n * stays open, or the next run only meets the same open breaker.\n */\n readonly resumeAfterMs: number;\n /** Segments of one stage run at once. */\n readonly concurrency: number;\n}\n\nexport const DEFAULT_FLOW_DIALS: FlowDials = {\n attemptTimeoutMs: 10_000,\n stepTimeoutMs: 60_000,\n stepBoundMs: 300_000,\n resumeAfterMs: 10_000,\n concurrency: 4,\n};\n\n/**\n * How many times a step suspended past the commit point is dispatched again\n * before the flow strands: the waits that fit in its bound, and at least one.\n */\nexport const resumesWithin = (\n dials: Pick<FlowDials, 'stepBoundMs' | 'resumeAfterMs'>,\n): number =>\n Math.max(1, Math.floor(dials.stepBoundMs / Math.max(1, dials.resumeAfterMs)));\n\n/**\n * Whether waiting can fix a failure past the commit point: a technical one —\n * a breaker open, a bulkhead full, a timeout, a participant down — can; a\n * business refusal, or a protocol failure, which is a bug, cannot.\n */\nconst waitingCanFix = (failure: EntifixFailure): boolean =>\n Failure.isFamily('technical')(failure) && failure.category !== 'protocol';\n\n/** What the interpreter runs a slip with: the catalog, who announces, the dials. */\nexport interface InterpreterOptions {\n readonly catalog: FragmentCatalog;\n /** The slice the `flow.*` events are announced from. */\n readonly source: string;\n readonly dials?: Partial<FlowDials>;\n /**\n * One participant's own attempt, step and resume bounds, over `dials` — the same\n * shape the breaker's `dialsFor` and the bulkhead's `permitsFor` take, so a\n * participant's dials are one row set however many guards read them.\n */\n readonly dialsFor?: (\n participant: string,\n ) => Partial<Omit<FlowDials, 'concurrency'>> | undefined;\n}\n\n/**\n * The interpreter's options, provided to the workflow it is registered with —\n * the payload is the slip; the catalog and dials are the deployment's.\n */\nexport class InterpreterOptionsTag extends Context.Service<\n InterpreterOptionsTag,\n InterpreterOptions\n>()('@entifix/workflow/InterpreterOptions') {}\n\n/**\n * The one workflow every flow runs as: its payload is the pinned slip and the\n * idempotency key that started it\n * ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)).\n * The execution id derives from the key, so the same key is the same flow.\n *\n * Under grammars 1 and 2, a failure past the commit point fails the run and\n * leaves the record `suspended`; nothing dispatches the step again. Grammar 3\n * rolls forward inside the walk instead — a durable clock, then the step\n * again — and strands when its bound runs out.\n */\nexport const SlipWorkflow = Workflow.make('entifix/slip', {\n payload: { key: Schema.String, slip: Slip },\n idempotencyKey: payload => payload.key,\n success: FlowOutcome,\n // Grammars 1 and 2 end a run with a failure past the commit point; it is\n // never the flow's result.\n error: JournaledFailure,\n});\n\n/** The durable wait a `wait` step parks on, addressed by the step's name. */\nexport const waitFor = (step: string) =>\n DurableDeferred.make(`wait:${step}`, { success: Schema.Unknown });\n\n/** A step's failure, with the step it happened at. */\ninterface StepFailed {\n readonly step: SlipStep;\n readonly failure: EntifixFailure;\n}\n\nconst segmentOf = (step: SlipStep) =>\n step.segment === undefined\n ? undefined\n : [step.segment.vendor, step.segment.paymentMethod]\n .filter(Boolean)\n .join('/');\n\n/**\n * A stage's steps as the groups that run at once: one group per segment when\n * every step names one — a basket's vendors, joined before the shared pivot —\n * and otherwise one group, in order.\n */\nconst groupsOf = (steps: readonly SlipStep[]): readonly SlipStep[][] => {\n if (steps.some(step => segmentOf(step) === undefined)) return [[...steps]];\n const groups = new Map<string, SlipStep[]>();\n for (const step of steps) {\n const key = segmentOf(step) as string;\n groups.set(key, [...(groups.get(key) ?? []), step]);\n }\n return [...groups.values()];\n};\n\n/**\n * Interprets a pinned slip of grammar version 1\n * ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)):\n * each step is an Activity named after it and keyed `<flowId>:<step>`, so a\n * resumed flow replays what already ran and calls a participant at most once\n * per step. Inside the Activity the call runs under the participant's\n * breaker and bulkhead and the retry budget, each attempt bounded and the\n * step as a whole bounded; nothing retries outside it.\n *\n * - Before and at the commit point, a failure — a breaker already open\n * included, which fails fast — compensates what succeeded, in reverse, and\n * the flow ends `compensated`.\n * - After it, the money is taken, so the flow rolls forward, never back.\n * Under grammar 3 a technical failure suspends the step, a durable clock\n * waits `resumeAfterMs`, and the step is dispatched again under the same\n * idempotency key, until it answers or `stepBoundMs` is spent and the flow\n * strands; a business refusal strands it at once. Under grammars 1 and 2 a\n * failure there ends the run with the record left `suspended`.\n * - Under grammar 4, a step whose call failed for a technical reason before\n * or at the commit point is dispatched again under its own key on a\n * durable clock until its participant answers, and the walk goes on from\n * that answer; one that refuses is compensated as any refusal is, and one\n * that never answers stops the flow `failed` there, undoing nothing. An\n * undoing that fails that way is tried again before the flow stops.\n * - A `wait` step parks the flow on a durable deferred its signal completes,\n * raced with a durable clock when it names `timeoutMs`; it may name a\n * `correlation`, so a sender that knows the order rather than the flow can\n * complete it.\n * - The segments of a stage run at once, bounded, and join before the next.\n *\n * Every transition is announced as a `flow.*` event through the outbox, by an\n * Activity, so it is written once whatever replays. Compensation is explicit\n * rather than a workflow finalizer, so the record says `compensated` only\n * after the last undoing has run — and an undoing that fails stops the flow\n * `failed` at that step instead of pretending.\n */\n/** What differs between grammar versions as the walk is interpreted. */\ninterface Grammar {\n /** Whether a wait past the commit point announces `flow.waiting` (v2). */\n readonly announcesCommittedWaits: boolean;\n /**\n * Whether a step that fails past the commit point is dispatched again on a\n * durable clock, and the flow strands when that stops helping (v3).\n */\n readonly rollsForward: boolean;\n /**\n * Whether a step before or at the commit point whose call failed for a\n * technical reason — an answer lost, a participant gone mid-call — is asked\n * again under its own idempotency key until it answers, and the walk goes\n * on from that answer; and whether an undoing that fails that way is tried\n * again on a durable clock before the flow stops `failed` (v4).\n */\n readonly resolvesDoubt: boolean;\n}\n\nconst walkSlip = (slip: Slip, grammar: Grammar) =>\n Effect.gen(function* () {\n const options = yield* InterpreterOptionsTag;\n const dials = { ...DEFAULT_FLOW_DIALS, ...options.dials };\n const { catalog } = options;\n const steps = slipSteps(slip);\n const ordinalOf = (step: SlipStep) => steps.indexOf(step) + 1;\n const commitPoint = steps.findIndex(\n step => catalog.get(step.ref)?.kind === 'pivot',\n );\n const bindings = makeBindings();\n const done: SlipStep[] = [];\n /** What each wait was answered with, by step name — what a guard reads. */\n const answered = new Map<string, string | undefined>();\n /** Steps a guard passed over; a step guarded on one of them is skipped too. */\n const skipped = new Set<string>();\n /** The wait whose timeout stranded the flow, once one has. */\n let stranded: SlipStep | undefined;\n /** A step whose outcome its participant never told, once one is (v4). */\n let inDoubt: SlipStep | undefined;\n\n const record = (name: string, patch: FlowRecordPatch) =>\n Activity.make({\n name,\n execute: Effect.flatMap(FlowStatusStoreTag, store =>\n store.update(slip.flowId, patch),\n ).pipe(\n Effect.andThen(\n Metric.update(\n Metric.withAttributes(flowStates, {\n state: patch.state,\n source: options.source,\n }),\n 1,\n ),\n ),\n Effect.orDie,\n ),\n });\n\n const announce = (\n name: FlowEventName,\n step: string,\n ordinal: number,\n failure?: EntifixFailure,\n ) =>\n Activity.make({\n name: `announce:${name}:${step}`,\n execute: Effect.flatMap(OutboxTag, outbox =>\n outbox.enqueue(\n flowEvent({\n name,\n source: options.source,\n at: new Date().toISOString(),\n step: `${name}:${step}`,\n ordinal,\n audience: [\n { kind: 'flow', id: slip.flowId },\n ...(slip.audience ?? []),\n ],\n data: {\n flowId: slip.flowId,\n definition: slip.recipe,\n slipVersion: slip.slipVersion,\n step,\n ...(failure === undefined\n ? {}\n : {\n failure: {\n code: failure.code,\n category: failure.category,\n },\n }),\n },\n }),\n ),\n ).pipe(\n Effect.orDie,\n // On the bus now rather than at the relay's next sweep, where the\n // host provides a drain; inside the activity, so a replay that skips\n // the announcement skips the drain with it.\n Effect.andThen(\n Effect.flatMap(Effect.serviceOption(OutboxDrainTag), drain =>\n Option.isSome(drain) ? drain.value.now : Effect.void,\n ),\n ),\n ),\n });\n\n /** One call, bounded, under the participant's breaker, bulkhead and budget. */\n const guarded = (\n step: SlipStep,\n attempt: Effect.Effect<unknown, EntifixFailure>,\n ) =>\n Effect.gen(function* () {\n const key = step.participant ?? 'participant';\n const bounds = { ...dials, ...options.dialsFor?.(key) };\n const breaker = yield* CircuitBreakerTag;\n const bulkhead = yield* BulkheadTag;\n const timedOut = () => Effect.fail(new Timeout({ dependency: key }));\n return yield* breaker\n .guard(key)(\n bulkhead.withPermit(key)(\n attempt.pipe(\n Effect.timeoutOrElse({\n duration: bounds.attemptTimeoutMs,\n orElse: timedOut,\n }),\n ),\n ),\n )\n .pipe(\n On(Failure.isFamily('technical')).retry({\n key: { dependency: key },\n idempotent: true,\n }),\n Effect.timeoutOrElse({\n duration: bounds.stepTimeoutMs,\n orElse: timedOut,\n }),\n );\n });\n\n const call = (\n step: SlipStep,\n kind: 'action' | 'compensation',\n resume = 0,\n ) =>\n Activity.make({\n // A step dispatched again past the commit point is a new Activity, so\n // a replay reads each run's own answer rather than the first failure.\n name:\n resume === 0\n ? `${step.step}:${kind}`\n : `${step.step}:${kind}#${String(resume)}`,\n // Whatever the participant answered, as JSON — `undefined` included,\n // which a journal cannot otherwise hold.\n success: JsonBody,\n error: JournaledFailure,\n execute: Effect.flatMap(ParticipantClientTag, participant =>\n guarded(\n step,\n participant.call({\n step,\n kind,\n idempotencyKey:\n kind === 'action'\n ? `${slip.flowId}:${step.step}`\n : `${slip.flowId}:${step.step}:compensation`,\n inputs: bindings.inputsFor(step, catalog.get(step.ref), kind),\n }),\n ),\n ),\n });\n\n const wait = (step: SlipStep) =>\n Effect.gen(function* () {\n const correlation = step.parameters?.['correlation'];\n const accepts = catalog.get(step.ref)?.outcomes;\n const onTimeout = onTimeoutOf(step);\n yield* record(`status:${step.step}:waiting`, {\n state: 'waiting',\n step: step.step,\n waitingFor: step.step,\n ...(typeof correlation === 'string' ? { correlation } : {}),\n ...(accepts === undefined ? {} : { accepts }),\n });\n // Past the commit point the caller's write has landed, and the wait is\n // for someone else — a courier, a person — so the flow says so and a\n // browser holding the write pending can let it go. Before it, nothing\n // has landed, and the flow stays silent.\n if (\n grammar.announcesCommittedWaits &&\n commitPoint !== -1 &&\n steps.indexOf(step) > commitPoint\n )\n yield* announce('flow.waiting', step.step, ordinalOf(step));\n const signalled = DurableDeferred.await(waitFor(step.step));\n const timeoutMs = step.parameters?.['timeoutMs'];\n // A durable race, so a replay answers the branch that won rather than\n // racing again.\n const answer =\n typeof timeoutMs === 'number'\n ? yield* DurableDeferred.raceAll({\n name: `race:${step.step}`,\n success: Schema.Unknown,\n error: FlowWaitTimedOut,\n effects: [\n signalled,\n DurableClock.sleep({\n name: `timeout:${step.step}`,\n duration: timeoutMs,\n }).pipe(\n Effect.andThen(\n // An outcome answers as a signal would; a strand and a\n // plain failure both fail the race, and are told apart\n // below — so the journaled race is the same either way.\n onTimeout.kind === 'outcome'\n ? Effect.succeed<unknown>({\n outcome: onTimeout.outcome,\n })\n : Effect.fail(\n new FlowWaitTimedOut({ step: step.step }),\n ),\n ),\n ),\n ],\n }).pipe(\n Effect.catchTag('FlowWaitTimedOut', timedOut =>\n onTimeout.kind === 'strand'\n ? Effect.succeed<unknown>(STRANDED)\n : Effect.fail(timedOut),\n ),\n )\n : yield* signalled;\n if (answer === STRANDED) {\n stranded = step;\n return;\n }\n answered.set(step.step, outcomeOf(answer));\n bindings.record(step, catalog.get(step.ref), answer);\n yield* record(`status:${step.step}:resumed`, {\n state: 'running',\n step: step.step,\n });\n });\n\n const pastCommit = (step: SlipStep) =>\n commitPoint !== -1 && steps.indexOf(step) > commitPoint;\n\n /**\n * A step past the commit point under grammar 3: a technical failure\n * suspends it, a durable clock waits, and it is dispatched again — the\n * participant answers the same idempotency key — until it answers or its\n * bound runs out, when the flow strands. A business refusal strands at\n * once, since waiting does not change an answer.\n */\n const rollForward = (step: SlipStep) =>\n Effect.gen(function* () {\n const key = step.participant ?? 'participant';\n const bounds = { ...dials, ...options.dialsFor?.(key) };\n const resumes = resumesWithin(bounds);\n for (let resume = 0; ; resume++) {\n const exit = yield* Effect.exit(call(step, 'action', resume));\n if (Exit.isSuccess(exit)) {\n if (resume > 0)\n yield* record(`status:${step.step}:resumed`, {\n state: 'running',\n step: step.step,\n });\n return { answer: exit.value } as const;\n }\n const failure = Cause.findErrorOption(exit.cause);\n // No typed failure — a defect, which is a bug that waiting does\n // not fix — strands as a refusal does, with nothing to name.\n if (\n Option.isNone(failure) ||\n !waitingCanFix(failure.value) ||\n resume >= resumes\n ) {\n stranded = step;\n return {\n stranded: Option.getOrUndefined(failure),\n } as const;\n }\n if (resume === 0) {\n yield* record(`status:${step.step}:suspended`, {\n state: 'suspended',\n step: step.step,\n });\n yield* announce(\n 'flow.suspended',\n step.step,\n ordinalOf(step),\n failure.value,\n );\n }\n yield* DurableClock.sleep({\n name: `resume:${step.step}#${String(resume + 1)}`,\n duration: bounds.resumeAfterMs,\n });\n }\n });\n\n /**\n * Dispatches `step` again on a durable clock while it fails for a\n * technical reason, within its bound (v4): an action whose answer was lost\n * replays what the participant did under the same idempotency key, and an\n * undoing is tried until its participant is back. Answers how it ended —\n * `answered`, `refused` with a typed failure waiting does not fix, or\n * `unresolved` once the bound is spent.\n */\n const retried = (\n step: SlipStep,\n kind: 'action' | 'compensation',\n first: number,\n ) =>\n Effect.gen(function* () {\n const key = step.participant ?? 'participant';\n const bounds = { ...dials, ...options.dialsFor?.(key) };\n const resumes = resumesWithin(bounds);\n for (let resume = first; ; resume++) {\n if (resume > first || first > 0)\n yield* DurableClock.sleep({\n name: `${kind === 'action' ? 'resolve' : 'undo'}:${step.step}#${String(resume)}`,\n duration: bounds.resumeAfterMs,\n });\n const exit = yield* Effect.exit(call(step, kind, resume));\n if (Exit.isSuccess(exit)) return { answered: exit.value } as const;\n const failure = Cause.findErrorOption(exit.cause);\n if (Option.isNone(failure) || !waitingCanFix(failure.value))\n return { refused: Option.getOrUndefined(failure) } as const;\n if (resume >= resumes) return { unresolved: failure.value } as const;\n }\n });\n\n /**\n * Undoes one step that ran. Under v4 an undoing that fails for a technical\n * reason is tried again on a durable clock, within the step's bound, so a\n * participant away for a moment does not leave its write behind.\n */\n const undo = (step: SlipStep) =>\n grammar.resolvesDoubt\n ? retried(step, 'compensation', 0).pipe(\n Effect.map(ended => 'answered' in ended),\n )\n : Effect.exit(call(step, 'compensation')).pipe(\n Effect.map(Exit.isSuccess),\n );\n\n /** Why the flow stranded, when a step's failure is what stranded it. */\n let strandedBy: EntifixFailure | undefined;\n\n /** One step, its failure tagged with where it happened. */\n const run = (step: SlipStep) =>\n Effect.gen(function* () {\n // A stranded flow runs nothing more, in any group of the stage.\n if (stranded !== undefined) return;\n if (step.guard !== undefined) {\n const { wait: guardedOn, outcomes } = step.guard;\n const outcome = answered.get(guardedOn);\n if (\n skipped.has(guardedOn) ||\n outcome === undefined ||\n !outcomes.includes(outcome)\n ) {\n skipped.add(step.step);\n return;\n }\n }\n if (catalog.get(step.ref)?.kind === 'wait')\n return yield* wait(step).pipe(\n Effect.mapError((failure): StepFailed => ({ step, failure })),\n );\n yield* record(`status:${step.step}:running`, {\n state: 'running',\n step: step.step,\n });\n if (grammar.rollsForward && pastCommit(step)) {\n const rolled = yield* rollForward(step);\n if ('stranded' in rolled) {\n strandedBy = rolled.stranded;\n return;\n }\n bindings.record(step, catalog.get(step.ref), rolled.answer);\n return;\n }\n const compensatable = catalog.get(step.ref)?.kind === 'compensatable';\n const exit = yield* Effect.exit(\n call(step, 'action').pipe(\n Effect.mapError((failure): StepFailed => ({ step, failure })),\n ),\n );\n if (Exit.isSuccess(exit)) {\n bindings.record(step, catalog.get(step.ref), exit.value);\n if (compensatable) done.push(step);\n return;\n }\n const failed = Cause.findErrorOption(exit.cause);\n // The call failed with its outcome unknown: the participant may have\n // done it and lost the answer. Asked again under the same key, it says\n // which — and the walk goes on from its answer, so a write that landed\n // is never undone as if it had not, nor a pivot rolled back (v4).\n if (\n grammar.resolvesDoubt &&\n Option.isSome(failed) &&\n waitingCanFix(failed.value.failure)\n ) {\n const resolved = yield* retried(step, 'action', 1);\n if ('answered' in resolved) {\n bindings.record(step, catalog.get(step.ref), resolved.answered);\n if (compensatable) done.push(step);\n return;\n }\n if ('unresolved' in resolved) inDoubt = step;\n }\n return yield* Effect.failCause(exit.cause);\n });\n\n yield* announce('flow.started', 'started', 0);\n /**\n * The version a flow's one ending is announced at: past every step's, so\n * a reader that keeps the newest version takes it over the `waiting` or\n * `suspended` its last step announced first — which shared that step's\n * ordinal, and left a stranded flow reading `suspended` forever.\n */\n const ending = steps.length + 1;\n\n for (const stage of slip.stages) {\n const exits = yield* Effect.forEach(\n groupsOf(stage.steps),\n group => Effect.exit(Effect.forEach(group, run, { discard: true })),\n { concurrency: dials.concurrency },\n );\n // The earliest step that failed decides; a group's failure is its own.\n const [first] = exits\n .flatMap(exit =>\n Exit.isFailure(exit)\n ? // A durable race fails with its losers' interruptions beside\n // the failure that won, so the failure is looked for.\n exit.cause.reasons\n .filter(Cause.isFailReason)\n .map(reason => reason.error)\n : [],\n )\n .sort((a, b) => ordinalOf(a.step) - ordinalOf(b.step));\n if (first === undefined) {\n if (stranded === undefined) continue;\n yield* record(`status:${stranded.step}:stranded`, {\n state: 'stranded',\n step: stranded.step,\n });\n yield* announce('flow.stranded', stranded.step, ending, strandedBy);\n return 'stranded' as const;\n }\n\n const { step, failure } = first;\n if (commitPoint === -1 || steps.indexOf(step) <= commitPoint) {\n // A step still in doubt may have landed, and nothing can undo what is\n // not known: the flow stops there, for a person to look at.\n const unresolved = inDoubt === undefined ? [] : [inDoubt];\n for (const undone of [...unresolved, ...[...done].reverse()]) {\n if (undone !== inDoubt && (yield* undo(undone))) continue;\n yield* record(`status:${undone.step}:failed`, {\n state: 'failed',\n step: undone.step,\n });\n yield* announce('flow.failed', undone.step, ending, failure);\n return 'failed' as const;\n }\n yield* record(`status:${step.step}:compensated`, {\n state: 'compensated',\n step: step.step,\n });\n yield* announce('flow.failed', step.step, ending, failure);\n return 'compensated' as const;\n }\n\n yield* record(`status:${step.step}:suspended`, {\n state: 'suspended',\n step: step.step,\n });\n yield* announce('flow.suspended', step.step, ordinalOf(step), failure);\n return yield* Effect.fail(failure).pipe(\n Effect.provideService(Workflow.SuspendOnFailure, true),\n );\n }\n\n yield* record('status:completed', { state: 'completed' });\n yield* announce('flow.completed', 'completed', ending);\n return 'completed' as const;\n });\n\n/**\n * One interpreter per grammar version a slip can be written in. A flow runs\n * to its end under the grammar it started with, so a change to how steps are\n * walked — their order, their Activity names — is a new entry here, never an\n * edit to an existing one; the journal replay holds every entry to its\n * recorded command sequence.\n */\nconst INTERPRETERS = {\n 1: (slip: Slip) =>\n walkSlip(slip, {\n announcesCommittedWaits: false,\n rollsForward: false,\n resolvesDoubt: false,\n }),\n 2: (slip: Slip) =>\n walkSlip(slip, {\n announcesCommittedWaits: true,\n rollsForward: false,\n resolvesDoubt: false,\n }),\n 3: (slip: Slip) =>\n walkSlip(slip, {\n announcesCommittedWaits: true,\n rollsForward: true,\n resolvesDoubt: false,\n }),\n 4: (slip: Slip) =>\n walkSlip(slip, {\n announcesCommittedWaits: true,\n rollsForward: true,\n resolvesDoubt: true,\n }),\n} as const satisfies Record<Slip['slipVersion'], (slip: Slip) => unknown>;\n\n/** Every `slipVersion` the interpreter walks — each must have a journal. */\nexport const interpretedSlipVersions: readonly number[] =\n Object.keys(INTERPRETERS).map(Number);\n\nexport const interpretSlip = (slip: Slip) =>\n INTERPRETERS[slip.slipVersion](slip);\n\n/** The interpreter registered with the workflow engine, with its options. */\nexport const SlipWorkflowLayer = (options: InterpreterOptions) =>\n SlipWorkflow.toLayer(payload =>\n interpretSlip(payload.slip).pipe(\n Effect.provideService(InterpreterOptionsTag, options),\n ),\n );\n"],"names":["Slip","slipSteps","decodeProblem","Failure","isFailure","JsonBody","problemOf","Timeout","BulkheadTag","CircuitBreakerTag","flowEvent","On","OutboxDrainTag","OutboxTag","ParticipantClientTag","Cause","Context","Effect","Exit","Metric","Option","Schema","SchemaTransformation","Activity","DurableClock","DurableDeferred","Workflow","flowStates","FlowStatusStoreTag","makeBindings","JournaledFailure","Unknown","pipe","decodeTo","declare","value","transform","decode","body","encode","failure","FlowOutcome","Literals","onTimeoutOf","step","named","parameters","kind","outcome","undefined","outcomeOf","answer","STRANDED","Symbol","for","FlowWaitTimedOut","timeout","String","message","DEFAULT_FLOW_DIALS","attemptTimeoutMs","stepTimeoutMs","stepBoundMs","resumeAfterMs","concurrency","resumesWithin","dials","Math","max","floor","waitingCanFix","isFamily","category","InterpreterOptionsTag","Service","SlipWorkflow","make","payload","key","slip","idempotencyKey","success","error","waitFor","segmentOf","segment","vendor","paymentMethod","filter","Boolean","join","groupsOf","steps","some","groups","Map","set","get","values","walkSlip","grammar","gen","options","catalog","ordinalOf","indexOf","commitPoint","findIndex","ref","bindings","done","answered","skipped","Set","stranded","inDoubt","record","name","patch","execute","flatMap","store","update","flowId","andThen","withAttributes","state","source","orDie","announce","ordinal","outbox","enqueue","at","Date","toISOString","audience","id","data","definition","recipe","slipVersion","code","serviceOption","drain","isSome","now","void","guarded","attempt","participant","bounds","dialsFor","breaker","bulkhead","timedOut","fail","dependency","guard","withPermit","timeoutOrElse","duration","orElse","retry","idempotent","call","resume","inputs","inputsFor","wait","correlation","accepts","outcomes","onTimeout","waitingFor","announcesCommittedWaits","signalled","await","timeoutMs","raceAll","effects","sleep","succeed","catchTag","pastCommit","rollForward","resumes","exit","isSuccess","findErrorOption","cause","isNone","getOrUndefined","retried","first","refused","unresolved","undo","resolvesDoubt","map","ended","strandedBy","run","guardedOn","has","includes","add","mapError","rollsForward","rolled","compensatable","push","failed","resolved","failCause","ending","length","stage","stages","exits","forEach","group","discard","reasons","isFailReason","reason","sort","a","b","undone","reverse","provideService","SuspendOnFailure","INTERPRETERS","interpretedSlipVersions","Object","keys","Number","interpretSlip","SlipWorkflowLayer","toLayer"],"mappings":";AAAA,SAEEA,IAAI,EAEJC,SAAS,QACJ,yBAAyB;AAChC,SACEC,aAAa,EAEbC,OAAO,EACPC,SAAS,EACTC,QAAQ,EACRC,SAAS,EACTC,OAAO,QACF,gBAAgB;AACvB,SACEC,WAAW,EACXC,iBAAiB,EACjBC,SAAS,EAETC,EAAE,EACFC,cAAc,EACdC,S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CAACsC,QAAQ;AAExC,OAAO,MAAMC,gBAAgB,CAAC/J,OAC5B0J,YAAY,CAAC1J,KAAK8D,WAAW,CAAC,CAAC9D,MAAM;AAEvC,2EAA2E,GAC3E,OAAO,MAAMgK,oBAAoB,CAACzI,UAChC3B,aAAaqK,OAAO,CAACnK,CAAAA,UACnBiK,cAAcjK,QAAQE,IAAI,EAAE/C,IAAI,CAC9Bf,OAAOsN,cAAc,CAAC9J,uBAAuB6B,WAE/C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/workflow",
3
- "version": "0.23.22",
3
+ "version": "0.23.24",
4
4
  "description": "Durable flows: the slip interpreter on Effect Workflow, behind the flow engine port, with Postgres storage and socket runners.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -89,16 +89,16 @@
89
89
  },
90
90
  "dependencies": {
91
91
  "@swc/helpers": "0.5.23",
92
- "@entifix/business": "0.23.22",
93
- "@entifix/core": "0.23.22",
94
- "@entifix/sql": "0.23.22",
95
- "@entifix/transactions": "0.23.22"
92
+ "@entifix/business": "0.23.24",
93
+ "@entifix/core": "0.23.24",
94
+ "@entifix/sql": "0.23.24",
95
+ "@entifix/transactions": "0.23.24"
96
96
  },
97
97
  "devDependencies": {
98
98
  "@effect/platform-node": "4.0.7",
99
99
  "@effect/sql-pg": "4.0.7",
100
100
  "effect": "4.0.7",
101
- "@entifix/testing-unit": "0.23.22"
101
+ "@entifix/testing-unit": "0.23.24"
102
102
  },
103
103
  "peerDependencies": {
104
104
  "@effect/platform-node": "^4.0.7",