@entifix/workflow 0.0.0-stage → 0.12.1
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/LICENSE +21 -0
- package/README.md +24 -2
- package/dist/engine/make-flow-engine.d.ts +23 -0
- package/dist/engine/make-flow-engine.d.ts.map +1 -0
- package/dist/engine/make-flow-engine.js +97 -0
- package/dist/engine/make-flow-engine.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/interpreter/slip-workflow.d.ts +114 -0
- package/dist/interpreter/slip-workflow.d.ts.map +1 -0
- package/dist/interpreter/slip-workflow.js +316 -0
- package/dist/interpreter/slip-workflow.js.map +1 -0
- package/dist/postgres/index.d.ts +9 -0
- package/dist/postgres/index.d.ts.map +1 -0
- package/dist/postgres/index.js +9 -0
- package/dist/postgres/index.js.map +1 -0
- package/dist/postgres/single-runner.d.ts +9 -0
- package/dist/postgres/single-runner.d.ts.map +1 -0
- package/dist/postgres/single-runner.js +13 -0
- package/dist/postgres/single-runner.js.map +1 -0
- package/dist/postgres/sql-flow-status-store.d.ts +14 -0
- package/dist/postgres/sql-flow-status-store.d.ts.map +1 -0
- package/dist/postgres/sql-flow-status-store.js +68 -0
- package/dist/postgres/sql-flow-status-store.js.map +1 -0
- package/dist/socket-runner/index.d.ts +2 -0
- package/dist/socket-runner/index.d.ts.map +1 -0
- package/dist/socket-runner/index.js +3 -0
- package/dist/socket-runner/index.js.map +1 -0
- package/dist/socket-runner/socket-runner.d.ts +24 -0
- package/dist/socket-runner/socket-runner.d.ts.map +1 -0
- package/dist/socket-runner/socket-runner.js +20 -0
- package/dist/socket-runner/socket-runner.js.map +1 -0
- package/dist/status/flow-status-store.d.ts +59 -0
- package/dist/status/flow-status-store.d.ts.map +1 -0
- package/dist/status/flow-status-store.js +50 -0
- package/dist/status/flow-status-store.js.map +1 -0
- package/package.json +109 -3
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
import { Slip, slipSteps } from '@entifix/business/flow';
|
|
3
|
+
import { decodeProblem, Failure, isFailure, JsonBody, problemOf, Timeout } from '@entifix/core';
|
|
4
|
+
import { BulkheadTag, CircuitBreakerTag, flowEvent, On, OutboxTag, ParticipantClientTag } from '@entifix/transactions';
|
|
5
|
+
import { Context, Effect, Exit, Metric, Schedule, Schema, SchemaTransformation } from 'effect';
|
|
6
|
+
import { Activity, DurableClock, DurableDeferred, Workflow } from 'effect/workflow';
|
|
7
|
+
import { flowStates, FlowStatusStoreTag } from '../status/flow-status-store.js';
|
|
8
|
+
/**
|
|
9
|
+
* A failure as an Activity journals it: the problem body on the way in, the
|
|
10
|
+
* failure its code names on the way out, so a resumed flow sees the typed
|
|
11
|
+
* refusal a participant sent rather than a cast.
|
|
12
|
+
*/ export const JournaledFailure = Schema.Unknown.pipe(Schema.decodeTo(Schema.declare((value)=>isFailure(value)), SchemaTransformation.transform({
|
|
13
|
+
decode: (body)=>decodeProblem(body),
|
|
14
|
+
encode: (failure)=>problemOf(failure)
|
|
15
|
+
})));
|
|
16
|
+
/**
|
|
17
|
+
* How a flow ended, as the workflow's own result: every step ran, or a
|
|
18
|
+
* refusal before the commit point was undone, or an undoing itself failed and
|
|
19
|
+
* the flow stopped where it was — which a person has to look at.
|
|
20
|
+
*/ export const FlowOutcome = Schema.Literals([
|
|
21
|
+
'completed',
|
|
22
|
+
'compensated',
|
|
23
|
+
'failed'
|
|
24
|
+
]);
|
|
25
|
+
/** A durable wait that outlived its timeout before its signal came. */ export class FlowWaitTimedOut extends Failure.timeout()('FlowWaitTimedOut', 'flowWaitTimedOut', {
|
|
26
|
+
step: Schema.String
|
|
27
|
+
}, {
|
|
28
|
+
message: ({ step })=>`the wait at '${step}' timed out`
|
|
29
|
+
}) {
|
|
30
|
+
}
|
|
31
|
+
export const DEFAULT_FLOW_DIALS = {
|
|
32
|
+
attemptTimeoutMs: 10000,
|
|
33
|
+
stepTimeoutMs: 60000,
|
|
34
|
+
concurrency: 4
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* The interpreter's options, provided to the workflow it is registered with —
|
|
38
|
+
* the payload is the slip; the catalog and dials are the deployment's.
|
|
39
|
+
*/ export class InterpreterOptionsTag extends Context.Service()('@entifix/workflow/InterpreterOptions') {
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The one workflow every flow runs as: its payload is the pinned slip and the
|
|
43
|
+
* idempotency key that started it
|
|
44
|
+
* ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)).
|
|
45
|
+
* The execution id derives from the key, so the same key is the same flow.
|
|
46
|
+
*
|
|
47
|
+
* A flow suspended past its commit point is resumed on the retry schedule:
|
|
48
|
+
* a participant that comes back gets the step again, idempotently.
|
|
49
|
+
*/ export const SlipWorkflow = Workflow.make('entifix/slip', {
|
|
50
|
+
payload: {
|
|
51
|
+
key: Schema.String,
|
|
52
|
+
slip: Slip
|
|
53
|
+
},
|
|
54
|
+
idempotencyKey: (payload)=>payload.key,
|
|
55
|
+
success: FlowOutcome,
|
|
56
|
+
// Its failure is what suspends it past the commit point; it is never the
|
|
57
|
+
// flow's result.
|
|
58
|
+
error: JournaledFailure,
|
|
59
|
+
// Doubling from a second, never more than a minute apart.
|
|
60
|
+
suspendedRetrySchedule: Schedule.min([
|
|
61
|
+
Schedule.exponential('1 second'),
|
|
62
|
+
Schedule.spaced('1 minute')
|
|
63
|
+
])
|
|
64
|
+
});
|
|
65
|
+
/** The durable wait a `wait` step parks on, addressed by the step's name. */ export const waitFor = (step)=>DurableDeferred.make(`wait:${step}`, {
|
|
66
|
+
success: Schema.Unknown
|
|
67
|
+
});
|
|
68
|
+
const segmentOf = (step)=>step.segment === undefined ? undefined : [
|
|
69
|
+
step.segment.vendor,
|
|
70
|
+
step.segment.paymentMethod
|
|
71
|
+
].filter(Boolean).join('/');
|
|
72
|
+
/**
|
|
73
|
+
* A stage's steps as the groups that run at once: one group per segment when
|
|
74
|
+
* every step names one — a basket's vendors, joined before the shared pivot —
|
|
75
|
+
* and otherwise one group, in order.
|
|
76
|
+
*/ const groupsOf = (steps)=>{
|
|
77
|
+
if (steps.some((step)=>segmentOf(step) === undefined)) return [
|
|
78
|
+
[
|
|
79
|
+
...steps
|
|
80
|
+
]
|
|
81
|
+
];
|
|
82
|
+
const groups = new Map();
|
|
83
|
+
for (const step of steps){
|
|
84
|
+
var _groups_get;
|
|
85
|
+
const key = segmentOf(step);
|
|
86
|
+
groups.set(key, [
|
|
87
|
+
...(_groups_get = groups.get(key)) != null ? _groups_get : [],
|
|
88
|
+
step
|
|
89
|
+
]);
|
|
90
|
+
}
|
|
91
|
+
return [
|
|
92
|
+
...groups.values()
|
|
93
|
+
];
|
|
94
|
+
};
|
|
95
|
+
/**
|
|
96
|
+
* Interprets a pinned slip of grammar version 1
|
|
97
|
+
* ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)):
|
|
98
|
+
* each step is an Activity named after it and keyed `<flowId>:<step>`, so a
|
|
99
|
+
* resumed flow replays what already ran and calls a participant at most once
|
|
100
|
+
* per step. Inside the Activity the call runs under the participant's
|
|
101
|
+
* breaker and bulkhead and the retry budget, each attempt bounded and the
|
|
102
|
+
* step as a whole bounded; nothing retries outside it.
|
|
103
|
+
*
|
|
104
|
+
* - Before and at the commit point, a failure — a breaker already open
|
|
105
|
+
* included, which fails fast — compensates what succeeded, in reverse, and
|
|
106
|
+
* the flow ends `compensated`.
|
|
107
|
+
* - After it, a failure suspends the flow at that step: the money is taken,
|
|
108
|
+
* so the flow rolls forward when the participant comes back, never back.
|
|
109
|
+
* - A `wait` step parks the flow on a durable deferred its signal completes,
|
|
110
|
+
* raced with a durable clock when it names `timeoutMs`; it may name a
|
|
111
|
+
* `correlation`, so a sender that knows the order rather than the flow can
|
|
112
|
+
* complete it.
|
|
113
|
+
* - The segments of a stage run at once, bounded, and join before the next.
|
|
114
|
+
*
|
|
115
|
+
* Every transition is announced as a `flow.*` event through the outbox, by an
|
|
116
|
+
* Activity, so it is written once whatever replays. Compensation is explicit
|
|
117
|
+
* rather than a workflow finalizer, so the record says `compensated` only
|
|
118
|
+
* after the last undoing has run — and an undoing that fails stops the flow
|
|
119
|
+
* `failed` at that step instead of pretending.
|
|
120
|
+
*/ const interpretV1 = (slip)=>Effect.gen(function*() {
|
|
121
|
+
const options = yield* InterpreterOptionsTag;
|
|
122
|
+
const dials = _extends({}, DEFAULT_FLOW_DIALS, options.dials);
|
|
123
|
+
const { catalog } = options;
|
|
124
|
+
const steps = slipSteps(slip);
|
|
125
|
+
const ordinalOf = (step)=>steps.indexOf(step) + 1;
|
|
126
|
+
const commitPoint = steps.findIndex((step)=>{
|
|
127
|
+
var _catalog_get;
|
|
128
|
+
return ((_catalog_get = catalog.get(step.ref)) == null ? void 0 : _catalog_get.kind) === 'pivot';
|
|
129
|
+
});
|
|
130
|
+
const outputs = {};
|
|
131
|
+
const done = [];
|
|
132
|
+
const record = (name, patch)=>Activity.make({
|
|
133
|
+
name,
|
|
134
|
+
execute: Effect.flatMap(FlowStatusStoreTag, (store)=>store.update(slip.flowId, patch)).pipe(Effect.andThen(Metric.update(Metric.withAttributes(flowStates, {
|
|
135
|
+
state: patch.state,
|
|
136
|
+
source: options.source
|
|
137
|
+
}), 1)), Effect.orDie)
|
|
138
|
+
});
|
|
139
|
+
const announce = (name, step, ordinal, failure)=>Activity.make({
|
|
140
|
+
name: `announce:${name}:${step}`,
|
|
141
|
+
execute: Effect.flatMap(OutboxTag, (outbox)=>{
|
|
142
|
+
var _slip_audience;
|
|
143
|
+
return outbox.enqueue(flowEvent({
|
|
144
|
+
name,
|
|
145
|
+
source: options.source,
|
|
146
|
+
at: new Date().toISOString(),
|
|
147
|
+
step: `${name}:${step}`,
|
|
148
|
+
ordinal,
|
|
149
|
+
audience: [
|
|
150
|
+
{
|
|
151
|
+
kind: 'flow',
|
|
152
|
+
id: slip.flowId
|
|
153
|
+
},
|
|
154
|
+
...(_slip_audience = slip.audience) != null ? _slip_audience : []
|
|
155
|
+
],
|
|
156
|
+
data: _extends({
|
|
157
|
+
flowId: slip.flowId,
|
|
158
|
+
definition: slip.recipe,
|
|
159
|
+
slipVersion: slip.slipVersion,
|
|
160
|
+
step
|
|
161
|
+
}, failure === undefined ? {} : {
|
|
162
|
+
failure: {
|
|
163
|
+
code: failure.code,
|
|
164
|
+
category: failure.category
|
|
165
|
+
}
|
|
166
|
+
})
|
|
167
|
+
}));
|
|
168
|
+
}).pipe(Effect.orDie)
|
|
169
|
+
});
|
|
170
|
+
/** One call, bounded, under the participant's breaker, bulkhead and budget. */ const guarded = (step, attempt)=>Effect.gen(function*() {
|
|
171
|
+
var _step_participant;
|
|
172
|
+
const key = (_step_participant = step.participant) != null ? _step_participant : 'participant';
|
|
173
|
+
const bounds = _extends({}, dials, options.dialsFor == null ? void 0 : options.dialsFor.call(options, key));
|
|
174
|
+
const breaker = yield* CircuitBreakerTag;
|
|
175
|
+
const bulkhead = yield* BulkheadTag;
|
|
176
|
+
const timedOut = ()=>Effect.fail(new Timeout({
|
|
177
|
+
dependency: key
|
|
178
|
+
}));
|
|
179
|
+
return yield* breaker.guard(key)(bulkhead.withPermit(key)(attempt.pipe(Effect.timeoutOrElse({
|
|
180
|
+
duration: bounds.attemptTimeoutMs,
|
|
181
|
+
orElse: timedOut
|
|
182
|
+
})))).pipe(On(Failure.isFamily('technical')).retry({
|
|
183
|
+
key: {
|
|
184
|
+
dependency: key
|
|
185
|
+
},
|
|
186
|
+
idempotent: true
|
|
187
|
+
}), Effect.timeoutOrElse({
|
|
188
|
+
duration: bounds.stepTimeoutMs,
|
|
189
|
+
orElse: timedOut
|
|
190
|
+
}));
|
|
191
|
+
});
|
|
192
|
+
const call = (step, kind)=>Activity.make({
|
|
193
|
+
name: `${step.step}:${kind}`,
|
|
194
|
+
// Whatever the participant answered, as JSON — `undefined` included,
|
|
195
|
+
// which a journal cannot otherwise hold.
|
|
196
|
+
success: JsonBody,
|
|
197
|
+
error: JournaledFailure,
|
|
198
|
+
execute: Effect.flatMap(ParticipantClientTag, (participant)=>guarded(step, participant.call({
|
|
199
|
+
step,
|
|
200
|
+
kind,
|
|
201
|
+
idempotencyKey: kind === 'action' ? `${slip.flowId}:${step.step}` : `${slip.flowId}:${step.step}:compensation`,
|
|
202
|
+
outputs
|
|
203
|
+
})))
|
|
204
|
+
});
|
|
205
|
+
const wait = (step)=>Effect.gen(function*() {
|
|
206
|
+
var _step_parameters, _step_parameters1;
|
|
207
|
+
const correlation = (_step_parameters = step.parameters) == null ? void 0 : _step_parameters['correlation'];
|
|
208
|
+
yield* record(`status:${step.step}:waiting`, _extends({
|
|
209
|
+
state: 'waiting',
|
|
210
|
+
step: step.step,
|
|
211
|
+
waitingFor: step.step
|
|
212
|
+
}, typeof correlation === 'string' ? {
|
|
213
|
+
correlation
|
|
214
|
+
} : {}));
|
|
215
|
+
const signalled = DurableDeferred.await(waitFor(step.step));
|
|
216
|
+
const timeoutMs = (_step_parameters1 = step.parameters) == null ? void 0 : _step_parameters1['timeoutMs'];
|
|
217
|
+
// A durable race, so a replay answers the branch that won rather than
|
|
218
|
+
// racing again.
|
|
219
|
+
outputs[step.step] = typeof timeoutMs === 'number' ? yield* DurableDeferred.raceAll({
|
|
220
|
+
name: `race:${step.step}`,
|
|
221
|
+
success: Schema.Unknown,
|
|
222
|
+
error: FlowWaitTimedOut,
|
|
223
|
+
effects: [
|
|
224
|
+
signalled,
|
|
225
|
+
DurableClock.sleep({
|
|
226
|
+
name: `timeout:${step.step}`,
|
|
227
|
+
duration: timeoutMs
|
|
228
|
+
}).pipe(Effect.andThen(Effect.fail(new FlowWaitTimedOut({
|
|
229
|
+
step: step.step
|
|
230
|
+
}))))
|
|
231
|
+
]
|
|
232
|
+
}) : yield* signalled;
|
|
233
|
+
yield* record(`status:${step.step}:resumed`, {
|
|
234
|
+
state: 'running',
|
|
235
|
+
step: step.step
|
|
236
|
+
});
|
|
237
|
+
});
|
|
238
|
+
/** One step, its failure tagged with where it happened. */ const run = (step)=>Effect.gen(function*() {
|
|
239
|
+
var _catalog_get, _catalog_get1;
|
|
240
|
+
if (((_catalog_get = catalog.get(step.ref)) == null ? void 0 : _catalog_get.kind) === 'wait') return yield* wait(step).pipe(Effect.mapError((failure)=>({
|
|
241
|
+
step,
|
|
242
|
+
failure
|
|
243
|
+
})));
|
|
244
|
+
yield* record(`status:${step.step}:running`, {
|
|
245
|
+
state: 'running',
|
|
246
|
+
step: step.step
|
|
247
|
+
});
|
|
248
|
+
outputs[step.step] = yield* call(step, 'action').pipe(Effect.mapError((failure)=>({
|
|
249
|
+
step,
|
|
250
|
+
failure
|
|
251
|
+
})));
|
|
252
|
+
if (((_catalog_get1 = catalog.get(step.ref)) == null ? void 0 : _catalog_get1.kind) === 'compensatable') done.push(step);
|
|
253
|
+
});
|
|
254
|
+
yield* announce('flow.started', 'started', 0);
|
|
255
|
+
for (const stage of slip.stages){
|
|
256
|
+
const exits = yield* Effect.forEach(groupsOf(stage.steps), (group)=>Effect.exit(Effect.forEach(group, run, {
|
|
257
|
+
discard: true
|
|
258
|
+
})), {
|
|
259
|
+
concurrency: dials.concurrency
|
|
260
|
+
});
|
|
261
|
+
// The earliest step that failed decides; a group's failure is its own.
|
|
262
|
+
const [first] = exits.flatMap((exit)=>Exit.isFailure(exit) ? exit.cause.reasons.flatMap((reason)=>// A durable race fails with its losers' interruptions beside
|
|
263
|
+
// the failure that won, so the failure is looked for.
|
|
264
|
+
reason._tag === 'Fail' ? [
|
|
265
|
+
reason.error
|
|
266
|
+
] : []) : []).sort((a, b)=>ordinalOf(a.step) - ordinalOf(b.step));
|
|
267
|
+
if (first === undefined) continue;
|
|
268
|
+
const { step, failure } = first;
|
|
269
|
+
if (commitPoint === -1 || steps.indexOf(step) <= commitPoint) {
|
|
270
|
+
for (const undone of [
|
|
271
|
+
...done
|
|
272
|
+
].reverse()){
|
|
273
|
+
const undoing = yield* Effect.exit(call(undone, 'compensation'));
|
|
274
|
+
if (Exit.isFailure(undoing)) {
|
|
275
|
+
yield* record(`status:${undone.step}:failed`, {
|
|
276
|
+
state: 'failed',
|
|
277
|
+
step: undone.step
|
|
278
|
+
});
|
|
279
|
+
yield* announce('flow.failed', undone.step, ordinalOf(undone), failure);
|
|
280
|
+
return 'failed';
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
yield* record(`status:${step.step}:compensated`, {
|
|
284
|
+
state: 'compensated',
|
|
285
|
+
step: step.step
|
|
286
|
+
});
|
|
287
|
+
yield* announce('flow.failed', step.step, ordinalOf(step), failure);
|
|
288
|
+
return 'compensated';
|
|
289
|
+
}
|
|
290
|
+
yield* record(`status:${step.step}:suspended`, {
|
|
291
|
+
state: 'suspended',
|
|
292
|
+
step: step.step
|
|
293
|
+
});
|
|
294
|
+
yield* announce('flow.suspended', step.step, ordinalOf(step), failure);
|
|
295
|
+
return yield* Effect.fail(failure).pipe(Effect.provideService(Workflow.SuspendOnFailure, true));
|
|
296
|
+
}
|
|
297
|
+
yield* record('status:completed', {
|
|
298
|
+
state: 'completed'
|
|
299
|
+
});
|
|
300
|
+
yield* announce('flow.completed', 'completed', steps.length + 1);
|
|
301
|
+
return 'completed';
|
|
302
|
+
});
|
|
303
|
+
/**
|
|
304
|
+
* One interpreter per grammar version a slip can be written in. A flow runs
|
|
305
|
+
* to its end under the grammar it started with, so a change to how steps are
|
|
306
|
+
* walked — their order, their Activity names — is a new entry here, never an
|
|
307
|
+
* edit to an existing one; the journal replay holds every entry to its
|
|
308
|
+
* recorded command sequence.
|
|
309
|
+
*/ const INTERPRETERS = {
|
|
310
|
+
1: interpretV1
|
|
311
|
+
};
|
|
312
|
+
/** Every `slipVersion` the interpreter walks — each must have a journal. */ export const interpretedSlipVersions = Object.keys(INTERPRETERS).map(Number);
|
|
313
|
+
export const interpretSlip = (slip)=>INTERPRETERS[slip.slipVersion](slip);
|
|
314
|
+
/** The interpreter registered with the workflow engine, with its options. */ export const SlipWorkflowLayer = (options)=>SlipWorkflow.toLayer((payload)=>interpretSlip(payload.slip).pipe(Effect.provideService(InterpreterOptionsTag, options)));
|
|
315
|
+
|
|
316
|
+
//# sourceMappingURL=slip-workflow.js.map
|
|
@@ -0,0 +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 OutboxTag,\n ParticipantClientTag,\n} from '@entifix/transactions';\nimport {\n Context,\n Effect,\n Exit,\n Metric,\n Schedule,\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';\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.\n */\nexport const FlowOutcome = Schema.Literals([\n 'completed',\n 'compensated',\n 'failed',\n]);\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 /** Every attempt at a step together, retries included. */\n readonly stepTimeoutMs: 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 concurrency: 4,\n};\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 and step 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 * A flow suspended past its commit point is resumed on the retry schedule:\n * a participant that comes back gets the step again, idempotently.\n */\nexport const SlipWorkflow = Workflow.make('entifix/slip', {\n payload: { key: Schema.String, slip: Slip },\n idempotencyKey: payload => payload.key,\n success: FlowOutcome,\n // Its failure is what suspends it past the commit point; it is never the\n // flow's result.\n error: JournaledFailure,\n // Doubling from a second, never more than a minute apart.\n suspendedRetrySchedule: Schedule.min([\n Schedule.exponential('1 second'),\n Schedule.spaced('1 minute'),\n ]),\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, a failure suspends the flow at that step: the money is taken,\n * so the flow rolls forward when the participant comes back, never back.\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 */\nconst interpretV1 = (slip: Slip) =>\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 outputs: Record<string, unknown> = {};\n const done: SlipStep[] = [];\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(Effect.orDie),\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 = (step: SlipStep, kind: 'action' | 'compensation') =>\n Activity.make({\n name: `${step.step}:${kind}`,\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 outputs,\n }),\n ),\n ),\n });\n\n const wait = (step: SlipStep) =>\n Effect.gen(function* () {\n const correlation = step.parameters?.['correlation'];\n yield* record(`status:${step.step}:waiting`, {\n state: 'waiting',\n step: step.step,\n waitingFor: step.step,\n ...(typeof correlation === 'string' ? { correlation } : {}),\n });\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 outputs[step.step] =\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 Effect.fail(new FlowWaitTimedOut({ step: step.step })),\n ),\n ),\n ],\n })\n : yield* signalled;\n yield* record(`status:${step.step}:resumed`, {\n state: 'running',\n step: step.step,\n });\n });\n\n /** One step, its failure tagged with where it happened. */\n const run = (step: SlipStep) =>\n Effect.gen(function* () {\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 outputs[step.step] = yield* call(step, 'action').pipe(\n Effect.mapError((failure): StepFailed => ({ step, failure })),\n );\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 ? exit.cause.reasons.flatMap(reason =>\n // A durable race fails with its losers' interruptions beside\n // the failure that won, so the failure is looked for.\n reason._tag === 'Fail' ? [reason.error] : [],\n )\n : [],\n )\n .sort((a, b) => ordinalOf(a.step) - ordinalOf(b.step));\n if (first === undefined) continue;\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 = { 1: interpretV1 } as const satisfies Record<\n Slip['slipVersion'],\n (slip: Slip) => unknown\n>;\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","OutboxTag","ParticipantClientTag","Context","Effect","Exit","Metric","Schedule","Schema","SchemaTransformation","Activity","DurableClock","DurableDeferred","Workflow","flowStates","FlowStatusStoreTag","JournaledFailure","Unknown","pipe","decodeTo","declare","value","transform","decode","body","encode","failure","FlowOutcome","Literals","FlowWaitTimedOut","timeout","step","String","message","DEFAULT_FLOW_DIALS","attemptTimeoutMs","stepTimeoutMs","concurrency","InterpreterOptionsTag","Service","SlipWorkflow","make","payload","key","slip","idempotencyKey","success","error","suspendedRetrySchedule","min","exponential","spaced","waitFor","segmentOf","segment","undefined","vendor","paymentMethod","filter","Boolean","join","groupsOf","steps","some","groups","Map","set","get","values","interpretV1","gen","options","dials","catalog","ordinalOf","indexOf","commitPoint","findIndex","ref","kind","outputs","done","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","category","guarded","attempt","participant","bounds","dialsFor","breaker","bulkhead","timedOut","fail","dependency","guard","withPermit","timeoutOrElse","duration","orElse","isFamily","retry","idempotent","call","wait","correlation","parameters","waitingFor","signalled","await","timeoutMs","raceAll","effects","sleep","run","mapError","push","stage","stages","exits","forEach","group","exit","discard","first","cause","reasons","reason","_tag","sort","a","b","undone","reverse","undoing","provideService","SuspendOnFailure","length","INTERPRETERS","interpretedSlipVersions","Object","keys","map","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,SAAS,EACTC,oBAAoB,QACf,wBAAwB;AAC/B,SACEC,OAAO,EACPC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,QAAQ,EACRC,MAAM,EACNC,oBAAoB,QACf,SAAS;AAChB,SACEC,QAAQ,EACRC,YAAY,EACZC,eAAe,EACfC,QAAQ,QACH,kBAAkB;AAEzB,SAEEC,UAAU,EACVC,kBAAkB,QACb,iCAAiC;AAExC;;;;CAIC,GACD,OAAO,MAAMC,mBACXR,OAAOS,OAAO,CAACC,IAAI,CACjBV,OAAOW,QAAQ,CACbX,OAAOY,OAAO,CAAC,CAACC,QAAmC5B,UAAU4B,SAC7DZ,qBAAqBa,SAAS,CAAC;IAC7BC,QAAQC,CAAAA,OAAQjC,cAAciC;IAC9BC,QAAQC,CAAAA,UAAW/B,UAAU+B;AAC/B,KAEF;AAEJ;;;;CAIC,GACD,OAAO,MAAMC,cAAcnB,OAAOoB,QAAQ,CAAC;IACzC;IACA;IACA;CACD,EAAE;AAEH,qEAAqE,GACrE,OAAO,MAAMC,yBAAyBrC,QAAQsC,OAAO,GACnD,oBACA,oBACA;IAAEC,MAAMvB,OAAOwB,MAAM;AAAC,GACtB;IAAEC,SAAS,CAAC,EAAEF,IAAI,EAAE,GAAK,CAAC,aAAa,EAAEA,KAAK,WAAW,CAAC;AAAC;AAC1D;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,OAAO;oBACT;gBACF;gBACA,OAAOwD,OAAO,CAAC,OAAO,EAAEnD,KAAKA,IAAI,CAAC,YAAY,CAAC,EAAE;oBAC/C6D,OAAO;oBACP7D,MAAMA,KAAKA,IAAI;gBACjB;gBACA,OAAOgE,SAAS,eAAehE,KAAKA,IAAI,EAAE2C,UAAU3C,OAAOL;gBAC3D,OAAO;YACT;YAEA,OAAOwD,OAAO,CAAC,OAAO,EAAEnD,KAAKA,IAAI,CAAC,UAAU,CAAC,EAAE;gBAC7C6D,OAAO;gBACP7D,MAAMA,KAAKA,IAAI;YACjB;YACA,OAAOgE,SAAS,kBAAkBhE,KAAKA,IAAI,EAAE2C,UAAU3C,OAAOL;YAC9D,OAAO,OAAOtB,OAAOkH,IAAI,CAAC5F,SAASR,IAAI,CACrCd,OAAO4J,cAAc,CAACnJ,SAASoJ,gBAAgB,EAAE;QAErD;QAEA,OAAO/E,OAAO,oBAAoB;YAAEU,OAAO;QAAY;QACvD,OAAOG,SAAS,kBAAkB,aAAajC,MAAMoG,MAAM,GAAG;QAC9D,OAAO;IACT;AAEF;;;;;;CAMC,GACD,MAAMC,eAAe;IAAE,GAAG9F;AAAY;AAKtC,0EAA0E,GAC1E,OAAO,MAAM+F,0BACXC,OAAOC,IAAI,CAACH,cAAcI,GAAG,CAACC,QAAQ;AAExC,OAAO,MAAMC,gBAAgB,CAAC7H,OAC5BuH,YAAY,CAACvH,KAAK+D,WAAW,CAAC,CAAC/D,MAAM;AAEvC,2EAA2E,GAC3E,OAAO,MAAM8H,oBAAoB,CAACnG,UAChC/B,aAAamI,OAAO,CAACjI,CAAAA,UACnB+H,cAAc/H,QAAQE,IAAI,EAAE1B,IAAI,CAC9Bd,OAAO4J,cAAc,CAAC1H,uBAAuBiC,WAE/C"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The flow engine's durable half over the host's SQL database: the cluster
|
|
3
|
+
* workflow engine's journal, a status store beside it, and a single runner.
|
|
4
|
+
* Postgres dialect. A deployment of several runners adds
|
|
5
|
+
* `@entifix/workflow/socket-runner`.
|
|
6
|
+
*/
|
|
7
|
+
export * from './single-runner.js';
|
|
8
|
+
export * from './sql-flow-status-store.js';
|
|
9
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/postgres/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAc,oBAAoB,CAAC;AACnC,cAAc,4BAA4B,CAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The flow engine's durable half over the host's SQL database: the cluster
|
|
3
|
+
* workflow engine's journal, a status store beside it, and a single runner.
|
|
4
|
+
* Postgres dialect. A deployment of several runners adds
|
|
5
|
+
* `@entifix/workflow/socket-runner`.
|
|
6
|
+
*/ export * from './single-runner.js';
|
|
7
|
+
export * from './sql-flow-status-store.js';
|
|
8
|
+
|
|
9
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/postgres/index.ts"],"sourcesContent":["/**\n * The flow engine's durable half over the host's SQL database: the cluster\n * workflow engine's journal, a status store beside it, and a single runner.\n * Postgres dialect. A deployment of several runners adds\n * `@entifix/workflow/socket-runner`.\n */\nexport * from './single-runner.js';\nexport * from './sql-flow-status-store.js';\n"],"names":[],"mappings":"AAAA;;;;;CAKC,GACD,cAAc,qBAAqB;AACnC,cAAc,6BAA6B"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { Layer } from 'effect';
|
|
2
|
+
import type { InterpreterOptions } from '../interpreter/slip-workflow.js';
|
|
3
|
+
/**
|
|
4
|
+
* The flow engine on one runner in this process, its journal and its status
|
|
5
|
+
* in the host's SQL database — for a deployment of one replica, and for specs.
|
|
6
|
+
* Needs the host's `SqlClient` and `Crypto` and a participant client.
|
|
7
|
+
*/
|
|
8
|
+
export declare const SingleRunnerFlowEngineLayer: (options: InterpreterOptions) => Layer.Layer<import("@entifix/transactions").FlowEngineTag, import("@entifix/core").StoreFailure | import("effect/Config").ConfigError, import("@entifix/transactions").OutboxTag | import("@entifix/transactions").BulkheadTag | import("@entifix/transactions").CircuitBreakerTag | import("@entifix/transactions").ParticipantClientTag | import("@entifix/transactions").RetryBudgetTag | import("effect/sql/SqlClient").SqlClient | import("effect/Crypto").Crypto>;
|
|
9
|
+
//# sourceMappingURL=single-runner.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"single-runner.d.ts","sourceRoot":"","sources":["../../src/postgres/single-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAI/B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AAG1E;;;;GAIG;AACH,eAAO,MAAM,2BAA2B,GAAI,SAAS,kBAAkB,4cAQpE,CAAC"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Layer } from 'effect';
|
|
2
|
+
import { ClusterWorkflowEngine, SingleRunner } from 'effect/cluster';
|
|
3
|
+
import { FlowEngineLayer } from '../engine/make-flow-engine.js';
|
|
4
|
+
import { SqlFlowStatusStoreLayer } from './sql-flow-status-store.js';
|
|
5
|
+
/**
|
|
6
|
+
* The flow engine on one runner in this process, its journal and its status
|
|
7
|
+
* in the host's SQL database — for a deployment of one replica, and for specs.
|
|
8
|
+
* Needs the host's `SqlClient` and `Crypto` and a participant client.
|
|
9
|
+
*/ export const SingleRunnerFlowEngineLayer = (options)=>FlowEngineLayer(options).pipe(Layer.provide(SqlFlowStatusStoreLayer), Layer.provide(ClusterWorkflowEngine.layer.pipe(Layer.provide(SingleRunner.layer({
|
|
10
|
+
runnerStorage: 'sql'
|
|
11
|
+
})))));
|
|
12
|
+
|
|
13
|
+
//# sourceMappingURL=single-runner.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/postgres/single-runner.ts"],"sourcesContent":["import { Layer } from 'effect';\nimport { ClusterWorkflowEngine, SingleRunner } from 'effect/cluster';\n\nimport { FlowEngineLayer } from '../engine/make-flow-engine.js';\nimport type { InterpreterOptions } from '../interpreter/slip-workflow.js';\nimport { SqlFlowStatusStoreLayer } from './sql-flow-status-store.js';\n\n/**\n * The flow engine on one runner in this process, its journal and its status\n * in the host's SQL database — for a deployment of one replica, and for specs.\n * Needs the host's `SqlClient` and `Crypto` and a participant client.\n */\nexport const SingleRunnerFlowEngineLayer = (options: InterpreterOptions) =>\n FlowEngineLayer(options).pipe(\n Layer.provide(SqlFlowStatusStoreLayer),\n Layer.provide(\n ClusterWorkflowEngine.layer.pipe(\n Layer.provide(SingleRunner.layer({ runnerStorage: 'sql' })),\n ),\n ),\n );\n"],"names":["Layer","ClusterWorkflowEngine","SingleRunner","FlowEngineLayer","SqlFlowStatusStoreLayer","SingleRunnerFlowEngineLayer","options","pipe","provide","layer","runnerStorage"],"mappings":"AAAA,SAASA,KAAK,QAAQ,SAAS;AAC/B,SAASC,qBAAqB,EAAEC,YAAY,QAAQ,iBAAiB;AAErE,SAASC,eAAe,QAAQ,gCAAgC;AAEhE,SAASC,uBAAuB,QAAQ,6BAA6B;AAErE;;;;CAIC,GACD,OAAO,MAAMC,8BAA8B,CAACC,UAC1CH,gBAAgBG,SAASC,IAAI,CAC3BP,MAAMQ,OAAO,CAACJ,0BACdJ,MAAMQ,OAAO,CACXP,sBAAsBQ,KAAK,CAACF,IAAI,CAC9BP,MAAMQ,OAAO,CAACN,aAAaO,KAAK,CAAC;QAAEC,eAAe;IAAM,OAG5D"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Effect, Layer } from 'effect';
|
|
2
|
+
import { SqlClient } from 'effect/sql';
|
|
3
|
+
import { type FlowStatusStore, FlowStatusStoreTag } from '../status/flow-status-store.js';
|
|
4
|
+
/** Creates the flow status table if it is missing. Idempotent. */
|
|
5
|
+
export declare const ensureFlowStatusTable: (sql: SqlClient.SqlClient) => Effect.Effect<void, import("@entifix/core").StoreFailure, never>;
|
|
6
|
+
/**
|
|
7
|
+
* The flow status store over SQL, beside the workflow engine's own tables. A
|
|
8
|
+
* registration inserts under the key or answers the flow already there, in one
|
|
9
|
+
* statement and a read.
|
|
10
|
+
*/
|
|
11
|
+
export declare const makeSqlFlowStatusStore: (sql: SqlClient.SqlClient) => FlowStatusStore;
|
|
12
|
+
/** The SQL status store, its table ensured as the layer builds. */
|
|
13
|
+
export declare const SqlFlowStatusStoreLayer: Layer.Layer<FlowStatusStoreTag, import("@entifix/core").StoreFailure, SqlClient.SqlClient>;
|
|
14
|
+
//# sourceMappingURL=sql-flow-status-store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sql-flow-status-store.d.ts","sourceRoot":"","sources":["../../src/postgres/sql-flow-status-store.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,KAAK,EAAU,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC,OAAO,EAEL,KAAK,eAAe,EACpB,kBAAkB,EACnB,MAAM,gCAAgC,CAAC;AAwBxC,kEAAkE;AAClE,eAAO,MAAM,qBAAqB,GAAI,KAAK,SAAS,CAAC,SAAS,qEAUZ,CAAC;AAEnD;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,GACjC,KAAK,SAAS,CAAC,SAAS,KACvB,eA2CD,CAAC;AAEH,mEAAmE;AACnE,eAAO,MAAM,uBAAuB,4FAOnC,CAAC"}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
import { translateSqlError } from '@entifix/sql';
|
|
3
|
+
import { Effect, Layer, Option } from 'effect';
|
|
4
|
+
import { SqlClient } from 'effect/sql';
|
|
5
|
+
import { FlowStatusStoreTag } from '../status/flow-status-store.js';
|
|
6
|
+
const recordOf = (row)=>_extends({
|
|
7
|
+
flowId: row.flow_id,
|
|
8
|
+
executionId: row.execution_id,
|
|
9
|
+
state: row.state
|
|
10
|
+
}, row.step === null ? {} : {
|
|
11
|
+
step: row.step
|
|
12
|
+
}, row.waiting_for === null ? {} : {
|
|
13
|
+
waitingFor: row.waiting_for
|
|
14
|
+
}, row.correlation === null ? {} : {
|
|
15
|
+
correlation: row.correlation
|
|
16
|
+
});
|
|
17
|
+
const fault = (error)=>translateSqlError(error);
|
|
18
|
+
/** Creates the flow status table if it is missing. Idempotent. */ export const ensureFlowStatusTable = (sql)=>sql`
|
|
19
|
+
CREATE TABLE IF NOT EXISTS entifix_flow_status (
|
|
20
|
+
flow_id text PRIMARY KEY,
|
|
21
|
+
idempotency_key text NOT NULL UNIQUE,
|
|
22
|
+
execution_id text NOT NULL,
|
|
23
|
+
state text NOT NULL,
|
|
24
|
+
step text,
|
|
25
|
+
waiting_for text,
|
|
26
|
+
correlation text
|
|
27
|
+
)`.pipe(Effect.asVoid, Effect.mapError(fault));
|
|
28
|
+
/**
|
|
29
|
+
* The flow status store over SQL, beside the workflow engine's own tables. A
|
|
30
|
+
* registration inserts under the key or answers the flow already there, in one
|
|
31
|
+
* statement and a read.
|
|
32
|
+
*/ export const makeSqlFlowStatusStore = (sql)=>({
|
|
33
|
+
register: (key, record)=>Effect.gen(function*() {
|
|
34
|
+
const [inserted] = yield* sql`
|
|
35
|
+
INSERT INTO entifix_flow_status
|
|
36
|
+
(flow_id, idempotency_key, execution_id, state)
|
|
37
|
+
VALUES (${record.flowId}, ${key}, ${record.executionId}, ${record.state})
|
|
38
|
+
ON CONFLICT DO NOTHING
|
|
39
|
+
RETURNING *`;
|
|
40
|
+
if (inserted !== undefined) return recordOf(inserted);
|
|
41
|
+
const [existing] = yield* sql`
|
|
42
|
+
SELECT * FROM entifix_flow_status
|
|
43
|
+
WHERE idempotency_key = ${key} OR flow_id = ${record.flowId}`;
|
|
44
|
+
// Gone between the two statements cannot happen: nothing deletes a flow.
|
|
45
|
+
return recordOf(existing);
|
|
46
|
+
}).pipe(Effect.mapError(fault)),
|
|
47
|
+
find: (flowId)=>sql`
|
|
48
|
+
SELECT * FROM entifix_flow_status WHERE flow_id = ${flowId}`.pipe(Effect.map(([row])=>row === undefined ? Option.none() : Option.some(recordOf(row))), Effect.mapError(fault)),
|
|
49
|
+
findByCorrelation: (correlation)=>sql`
|
|
50
|
+
SELECT * FROM entifix_flow_status
|
|
51
|
+
WHERE correlation = ${correlation}`.pipe(Effect.map(([row])=>row === undefined ? Option.none() : Option.some(recordOf(row))), Effect.mapError(fault)),
|
|
52
|
+
update: (flowId, patch)=>{
|
|
53
|
+
var _patch_step, _patch_waitingFor, _patch_correlation;
|
|
54
|
+
return sql`
|
|
55
|
+
UPDATE entifix_flow_status
|
|
56
|
+
SET state = ${patch.state}, step = ${(_patch_step = patch.step) != null ? _patch_step : null},
|
|
57
|
+
waiting_for = ${(_patch_waitingFor = patch.waitingFor) != null ? _patch_waitingFor : null},
|
|
58
|
+
correlation = ${(_patch_correlation = patch.correlation) != null ? _patch_correlation : null}
|
|
59
|
+
WHERE flow_id = ${flowId}`.pipe(Effect.asVoid, Effect.mapError(fault));
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
/** The SQL status store, its table ensured as the layer builds. */ export const SqlFlowStatusStoreLayer = Layer.effect(FlowStatusStoreTag, Effect.gen(function*() {
|
|
63
|
+
const sql = yield* SqlClient.SqlClient;
|
|
64
|
+
yield* ensureFlowStatusTable(sql);
|
|
65
|
+
return makeSqlFlowStatusStore(sql);
|
|
66
|
+
}));
|
|
67
|
+
|
|
68
|
+
//# sourceMappingURL=sql-flow-status-store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/postgres/sql-flow-status-store.ts"],"sourcesContent":["import { translateSqlError } from '@entifix/sql';\nimport type { FlowState } from '@entifix/transactions';\nimport { Effect, Layer, Option } from 'effect';\nimport { SqlClient } from 'effect/sql';\n\nimport {\n type FlowRecord,\n type FlowStatusStore,\n FlowStatusStoreTag,\n} from '../status/flow-status-store.js';\n\n// A type alias, not an interface: a row must be assignable to the record a\n// driver hands back, and an interface has no index signature.\ntype FlowStatusRow = {\n readonly flow_id: string;\n readonly execution_id: string;\n readonly state: FlowState;\n readonly step: string | null;\n readonly waiting_for: string | null;\n readonly correlation: string | null;\n};\n\nconst recordOf = (row: FlowStatusRow): FlowRecord => ({\n flowId: row.flow_id,\n executionId: row.execution_id,\n state: row.state,\n ...(row.step === null ? {} : { step: row.step }),\n ...(row.waiting_for === null ? {} : { waitingFor: row.waiting_for }),\n ...(row.correlation === null ? {} : { correlation: row.correlation }),\n});\n\nconst fault = (error: unknown) => translateSqlError(error);\n\n/** Creates the flow status table if it is missing. Idempotent. */\nexport const ensureFlowStatusTable = (sql: SqlClient.SqlClient) =>\n sql`\n CREATE TABLE IF NOT EXISTS entifix_flow_status (\n flow_id text PRIMARY KEY,\n idempotency_key text NOT NULL UNIQUE,\n execution_id text NOT NULL,\n state text NOT NULL,\n step text,\n waiting_for text,\n correlation text\n )`.pipe(Effect.asVoid, Effect.mapError(fault));\n\n/**\n * The flow status store over SQL, beside the workflow engine's own tables. A\n * registration inserts under the key or answers the flow already there, in one\n * statement and a read.\n */\nexport const makeSqlFlowStatusStore = (\n sql: SqlClient.SqlClient,\n): FlowStatusStore => ({\n register: (key, record) =>\n Effect.gen(function* () {\n const [inserted] = yield* sql<FlowStatusRow>`\n INSERT INTO entifix_flow_status\n (flow_id, idempotency_key, execution_id, state)\n VALUES (${record.flowId}, ${key}, ${record.executionId}, ${record.state})\n ON CONFLICT DO NOTHING\n RETURNING *`;\n if (inserted !== undefined) return recordOf(inserted);\n const [existing] = yield* sql<FlowStatusRow>`\n SELECT * FROM entifix_flow_status\n WHERE idempotency_key = ${key} OR flow_id = ${record.flowId}`;\n // Gone between the two statements cannot happen: nothing deletes a flow.\n return recordOf(existing as FlowStatusRow);\n }).pipe(Effect.mapError(fault)),\n\n find: flowId =>\n sql<FlowStatusRow>`\n SELECT * FROM entifix_flow_status WHERE flow_id = ${flowId}`.pipe(\n Effect.map(([row]) =>\n row === undefined ? Option.none() : Option.some(recordOf(row)),\n ),\n Effect.mapError(fault),\n ),\n\n findByCorrelation: correlation =>\n sql<FlowStatusRow>`\n SELECT * FROM entifix_flow_status\n WHERE correlation = ${correlation}`.pipe(\n Effect.map(([row]) =>\n row === undefined ? Option.none() : Option.some(recordOf(row)),\n ),\n Effect.mapError(fault),\n ),\n\n update: (flowId, patch) =>\n sql`\n UPDATE entifix_flow_status\n SET state = ${patch.state}, step = ${patch.step ?? null},\n waiting_for = ${patch.waitingFor ?? null},\n correlation = ${patch.correlation ?? null}\n WHERE flow_id = ${flowId}`.pipe(Effect.asVoid, Effect.mapError(fault)),\n});\n\n/** The SQL status store, its table ensured as the layer builds. */\nexport const SqlFlowStatusStoreLayer = Layer.effect(\n FlowStatusStoreTag,\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n yield* ensureFlowStatusTable(sql);\n return makeSqlFlowStatusStore(sql);\n }),\n);\n"],"names":["translateSqlError","Effect","Layer","Option","SqlClient","FlowStatusStoreTag","recordOf","row","flowId","flow_id","executionId","execution_id","state","step","waiting_for","waitingFor","correlation","fault","error","ensureFlowStatusTable","sql","pipe","asVoid","mapError","makeSqlFlowStatusStore","register","key","record","gen","inserted","undefined","existing","find","map","none","some","findByCorrelation","update","patch","SqlFlowStatusStoreLayer","effect"],"mappings":";AAAA,SAASA,iBAAiB,QAAQ,eAAe;AAEjD,SAASC,MAAM,EAAEC,KAAK,EAAEC,MAAM,QAAQ,SAAS;AAC/C,SAASC,SAAS,QAAQ,aAAa;AAEvC,SAGEC,kBAAkB,QACb,iCAAiC;AAaxC,MAAMC,WAAW,CAACC,MAAoC;QACpDC,QAAQD,IAAIE,OAAO;QACnBC,aAAaH,IAAII,YAAY;QAC7BC,OAAOL,IAAIK,KAAK;OACZL,IAAIM,IAAI,KAAK,OAAO,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cACjBI,GAAkB,CAAC;;0BAEG,EAAEJ,YAAY,CAAC,CAACK,IAAI,CACxCpB,OAAOgC,GAAG,CAAC,CAAC,CAAC1B,IAAI,GACfA,QAAQuB,YAAY3B,OAAO+B,IAAI,KAAK/B,OAAOgC,IAAI,CAAC7B,SAASC,QAE3DN,OAAOsB,QAAQ,CAACN;QAGpBoB,QAAQ,CAAC7B,QAAQ8B;gBAGwBA,aACjBA,mBACAA;mBAJtBlB,GAAG,CAAC;;kBAEU,EAAEkB,MAAM1B,KAAK,CAAC,SAAS,GAAE0B,cAAAA,MAAMzB,IAAI,YAAVyB,cAAc,KAAK;wBACtC,GAAEA,oBAAAA,MAAMvB,UAAU,YAAhBuB,oBAAoB,KAAK;wBAC3B,GAAEA,qBAAAA,MAAMtB,WAAW,YAAjBsB,qBAAqB,KAAK;sBAC9B,EAAE9B,OAAO,CAAC,CAACa,IAAI,CAACpB,OAAOqB,MAAM,EAAErB,OAAOsB,QAAQ,CAACN;;IACrE,CAAA,EAAG;AAEH,iEAAiE,GACjE,OAAO,MAAMsB,0BAA0BrC,MAAMsC,MAAM,CACjDnC,oBACAJ,OAAO2B,GAAG,CAAC;IACT,MAAMR,MAAM,OAAOhB,UAAUA,SAAS;IACtC,OAAOe,sBAAsBC;IAC7B,OAAOI,uBAAuBJ;AAChC,IACA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/socket-runner/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/socket-runner/index.ts"],"sourcesContent":["export * from './socket-runner.js';\n"],"names":[],"mappings":"AAAA,cAAc,qBAAqB"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { Layer } from 'effect';
|
|
2
|
+
import { type ShardingConfig } from 'effect/cluster';
|
|
3
|
+
import type { InterpreterOptions } from '../interpreter/slip-workflow.js';
|
|
4
|
+
export interface SocketRunnerOptions {
|
|
5
|
+
/** Where the other runners reach this one, and where it listens. */
|
|
6
|
+
readonly host: string;
|
|
7
|
+
readonly port: number;
|
|
8
|
+
/**
|
|
9
|
+
* How quickly the runner notices a dead peer and takes its shards over —
|
|
10
|
+
* the lock expiry, the assignment refresh, the storage polls. The cluster
|
|
11
|
+
* defaults are tuned for a fleet that rarely loses a runner; a host may
|
|
12
|
+
* shorten them, and the chaos suite does.
|
|
13
|
+
*/
|
|
14
|
+
readonly sharding?: Partial<Omit<ShardingConfig.ShardingConfig['Service'], 'runnerAddress'>>;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The flow engine as one runner among several
|
|
18
|
+
* ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)):
|
|
19
|
+
* runners register in the shared SQL database, shards are spread between
|
|
20
|
+
* them, and a runner that dies has its flows resumed by another. Every
|
|
21
|
+
* replica runs this with its own port.
|
|
22
|
+
*/
|
|
23
|
+
export declare const SocketRunnerFlowEngineLayer: (options: InterpreterOptions, runner: SocketRunnerOptions) => Layer.Layer<import("@entifix/transactions").FlowEngineTag, import("@entifix/core").StoreFailure | import("effect/Config").ConfigError | import("effect/socket/SocketServer").SocketServerError, import("@entifix/transactions").OutboxTag | import("@entifix/transactions").BulkheadTag | import("@entifix/transactions").CircuitBreakerTag | import("@entifix/transactions").ParticipantClientTag | import("@entifix/transactions").RetryBudgetTag | import("effect/sql/SqlClient").SqlClient>;
|
|
24
|
+
//# sourceMappingURL=socket-runner.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket-runner.d.ts","sourceRoot":"","sources":["../../src/socket-runner/socket-runner.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAU,MAAM,QAAQ,CAAC;AACvC,OAAO,EAGL,KAAK,cAAc,EACpB,MAAM,gBAAgB,CAAC;AAGxB,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AAG1E,MAAM,WAAW,mBAAmB;IAClC,oEAAoE;IACpE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB;;;;;OAKG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CACzB,IAAI,CAAC,cAAc,CAAC,cAAc,CAAC,SAAS,CAAC,EAAE,eAAe,CAAC,CAChE,CAAC;CACH;AAED;;;;;;GAMG;AACH,eAAO,MAAM,2BAA2B,GACtC,SAAS,kBAAkB,EAC3B,QAAQ,mBAAmB,oeAmB1B,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
import { NodeClusterSocket } from '@effect/platform-node';
|
|
3
|
+
import { Layer, Option } from 'effect';
|
|
4
|
+
import { ClusterWorkflowEngine, RunnerAddress } from 'effect/cluster';
|
|
5
|
+
import { FlowEngineLayer } from '../engine/make-flow-engine.js';
|
|
6
|
+
import { SqlFlowStatusStoreLayer } from '../postgres/sql-flow-status-store.js';
|
|
7
|
+
/**
|
|
8
|
+
* The flow engine as one runner among several
|
|
9
|
+
* ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)):
|
|
10
|
+
* runners register in the shared SQL database, shards are spread between
|
|
11
|
+
* them, and a runner that dies has its flows resumed by another. Every
|
|
12
|
+
* replica runs this with its own port.
|
|
13
|
+
*/ export const SocketRunnerFlowEngineLayer = (options, runner)=>FlowEngineLayer(options).pipe(Layer.provide(SqlFlowStatusStoreLayer), Layer.provide(ClusterWorkflowEngine.layer.pipe(Layer.provide(NodeClusterSocket.layer({
|
|
14
|
+
storage: 'sql',
|
|
15
|
+
shardingConfig: _extends({}, runner.sharding, {
|
|
16
|
+
runnerAddress: Option.some(RunnerAddress.make(runner.host, runner.port))
|
|
17
|
+
})
|
|
18
|
+
})))));
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=socket-runner.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/socket-runner/socket-runner.ts"],"sourcesContent":["import { NodeClusterSocket } from '@effect/platform-node';\nimport { Layer, Option } from 'effect';\nimport {\n ClusterWorkflowEngine,\n RunnerAddress,\n type ShardingConfig,\n} from 'effect/cluster';\n\nimport { FlowEngineLayer } from '../engine/make-flow-engine.js';\nimport type { InterpreterOptions } from '../interpreter/slip-workflow.js';\nimport { SqlFlowStatusStoreLayer } from '../postgres/sql-flow-status-store.js';\n\nexport interface SocketRunnerOptions {\n /** Where the other runners reach this one, and where it listens. */\n readonly host: string;\n readonly port: number;\n /**\n * How quickly the runner notices a dead peer and takes its shards over —\n * the lock expiry, the assignment refresh, the storage polls. The cluster\n * defaults are tuned for a fleet that rarely loses a runner; a host may\n * shorten them, and the chaos suite does.\n */\n readonly sharding?: Partial<\n Omit<ShardingConfig.ShardingConfig['Service'], 'runnerAddress'>\n >;\n}\n\n/**\n * The flow engine as one runner among several\n * ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)):\n * runners register in the shared SQL database, shards are spread between\n * them, and a runner that dies has its flows resumed by another. Every\n * replica runs this with its own port.\n */\nexport const SocketRunnerFlowEngineLayer = (\n options: InterpreterOptions,\n runner: SocketRunnerOptions,\n) =>\n FlowEngineLayer(options).pipe(\n Layer.provide(SqlFlowStatusStoreLayer),\n Layer.provide(\n ClusterWorkflowEngine.layer.pipe(\n Layer.provide(\n NodeClusterSocket.layer({\n storage: 'sql',\n shardingConfig: {\n ...runner.sharding,\n runnerAddress: Option.some(\n RunnerAddress.make(runner.host, runner.port),\n ),\n },\n }),\n ),\n ),\n ),\n );\n"],"names":["NodeClusterSocket","Layer","Option","ClusterWorkflowEngine","RunnerAddress","FlowEngineLayer","SqlFlowStatusStoreLayer","SocketRunnerFlowEngineLayer","options","runner","pipe","provide","layer","storage","shardingConfig","sharding","runnerAddress","some","make","host","port"],"mappings":";AAAA,SAASA,iBAAiB,QAAQ,wBAAwB;AAC1D,SAASC,KAAK,EAAEC,MAAM,QAAQ,SAAS;AACvC,SACEC,qBAAqB,EACrBC,aAAa,QAER,iBAAiB;AAExB,SAASC,eAAe,QAAQ,gCAAgC;AAEhE,SAASC,uBAAuB,QAAQ,uCAAuC;AAiB/E;;;;;;CAMC,GACD,OAAO,MAAMC,8BAA8B,CACzCC,SACAC,SAEAJ,gBAAgBG,SAASE,IAAI,CAC3BT,MAAMU,OAAO,CAACL,0BACdL,MAAMU,OAAO,CACXR,sBAAsBS,KAAK,CAACF,IAAI,CAC9BT,MAAMU,OAAO,CACXX,kBAAkBY,KAAK,CAAC;QACtBC,SAAS;QACTC,gBAAgB,aACXL,OAAOM,QAAQ;YAClBC,eAAed,OAAOe,IAAI,CACxBb,cAAcc,IAAI,CAACT,OAAOU,IAAI,EAAEV,OAAOW,IAAI;;IAGjD,OAIN"}
|