@entifix/workflow 0.21.0 → 0.22.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/README.md +8 -0
- package/dist/engine/make-flow-engine.d.ts.map +1 -1
- package/dist/engine/make-flow-engine.js +7 -2
- package/dist/engine/make-flow-engine.js.map +1 -1
- package/dist/postgres/index.d.ts +3 -1
- package/dist/postgres/index.d.ts.map +1 -1
- package/dist/postgres/index.js +4 -2
- package/dist/postgres/index.js.map +1 -1
- package/dist/postgres/journal-retention.d.ts +61 -0
- package/dist/postgres/journal-retention.d.ts.map +1 -0
- package/dist/postgres/journal-retention.js +97 -0
- package/dist/postgres/journal-retention.js.map +1 -0
- package/dist/postgres/single-runner.d.ts +5 -2
- package/dist/postgres/single-runner.d.ts.map +1 -1
- package/dist/postgres/single-runner.js +5 -2
- package/dist/postgres/single-runner.js.map +1 -1
- package/dist/postgres/sql-flow-status-store.d.ts.map +1 -1
- package/dist/postgres/sql-flow-status-store.js +21 -4
- package/dist/postgres/sql-flow-status-store.js.map +1 -1
- package/dist/socket-runner/socket-runner.d.ts +4 -2
- package/dist/socket-runner/socket-runner.d.ts.map +1 -1
- package/dist/socket-runner/socket-runner.js +4 -2
- package/dist/socket-runner/socket-runner.js.map +1 -1
- package/dist/status/flow-status-store.d.ts +7 -0
- package/dist/status/flow-status-store.d.ts.map +1 -1
- package/dist/status/flow-status-store.js +11 -0
- package/dist/status/flow-status-store.js.map +1 -1
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -20,6 +20,14 @@ pnpm add @effect/platform-node
|
|
|
20
20
|
| `@entifix/workflow/postgres` | `SingleRunnerFlowEngineLayer` and the SQL status store, over the host's `SqlClient` |
|
|
21
21
|
| `@entifix/workflow/socket-runner` | `SocketRunnerFlowEngineLayer`, one runner among several; needs `@effect/platform-node` |
|
|
22
22
|
|
|
23
|
+
Both runner layers take `journalRetention` beside the interpreter's options:
|
|
24
|
+
how long a finished flow keeps its journal (`'30 days'`, any `Duration`
|
|
25
|
+
input). There is no default — a layer without it fails to build with
|
|
26
|
+
`JournalRetentionUnset` — because the journal holds every flow's inputs. A
|
|
27
|
+
purge runs beside the runner every `purgeInterval` (an hour by default) and
|
|
28
|
+
empties the journal of flows that ended more than that long ago, keeping their
|
|
29
|
+
status row; `onPurge` hears what each pass did.
|
|
30
|
+
|
|
23
31
|
---
|
|
24
32
|
|
|
25
33
|
Tier 2 (adapters) of entifix — a package depends only on its own tier or below. See [the tiers](https://github.com/r10c-technologies/entifix#the-tiers-and-what-you-are-allowed-to-install). MIT licensed.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"make-flow-engine.d.ts","sourceRoot":"","sources":["../../src/engine/make-flow-engine.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,UAAU,EACf,aAAa,EAGd,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAW,MAAM,EAAE,KAAK,EAAU,MAAM,QAAQ,CAAC;AACxD,OAAO,EAAmB,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAElE,OAAO,EACL,KAAK,kBAAkB,EAIxB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,
|
|
1
|
+
{"version":3,"file":"make-flow-engine.d.ts","sourceRoot":"","sources":["../../src/engine/make-flow-engine.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,UAAU,EACf,aAAa,EAGd,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAW,MAAM,EAAE,KAAK,EAAU,MAAM,QAAQ,CAAC;AACxD,OAAO,EAAmB,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAElE,OAAO,EACL,KAAK,kBAAkB,EAIxB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EACL,kBAAkB,EAEnB,MAAM,gCAAgC,CAAC;AAExC;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,sFA2HzB,CAAC;AAEH;;;;;;GAMG;AACH,eAAO,MAAM,eAAe,GAAI,SAAS,kBAAkB,gVAGxD,CAAC;AAEJ;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,GAAI,SAAS,kBAAkB,gTACS,CAAC"}
|
|
@@ -3,7 +3,7 @@ import { FlowEngineTag, FlowNotFound, FlowSignalRejected } from '@entifix/transa
|
|
|
3
3
|
import { Context, Effect, Layer, Option } from 'effect';
|
|
4
4
|
import { DurableDeferred, WorkflowEngine } from 'effect/workflow';
|
|
5
5
|
import { SlipWorkflow, SlipWorkflowLayer, waitFor } from '../interpreter/slip-workflow.js';
|
|
6
|
-
import { FlowStatusStoreTag } from '../status/flow-status-store.js';
|
|
6
|
+
import { FlowStatusStoreTag, isTerminalFlowState } from '../status/flow-status-store.js';
|
|
7
7
|
/**
|
|
8
8
|
* The flow engine port over Effect Workflow
|
|
9
9
|
* ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)).
|
|
@@ -62,7 +62,9 @@ import { FlowStatusStoreTag } from '../status/flow-status-store.js';
|
|
|
62
62
|
executionId,
|
|
63
63
|
state: 'running'
|
|
64
64
|
});
|
|
65
|
-
|
|
65
|
+
// A flow that already ended is answered, never executed again: its
|
|
66
|
+
// journal may have been purged, and executing it would run it anew.
|
|
67
|
+
if (record.executionId === executionId && record.flowId === slip.flowId && !isTerminalFlowState(record.state)) yield* within(SlipWorkflow.execute(payload, {
|
|
66
68
|
discard: true
|
|
67
69
|
}));
|
|
68
70
|
return {
|
|
@@ -93,6 +95,9 @@ import { FlowStatusStoreTag } from '../status/flow-status-store.js';
|
|
|
93
95
|
}),
|
|
94
96
|
interrupt: (flowId)=>Effect.gen(function*() {
|
|
95
97
|
const record = yield* known(flowId);
|
|
98
|
+
// An ended flow has nothing to interrupt, and its state stays the
|
|
99
|
+
// one it ended in.
|
|
100
|
+
if (isTerminalFlowState(record.state)) return;
|
|
96
101
|
yield* within(SlipWorkflow.interrupt(record.executionId));
|
|
97
102
|
yield* store.update(flowId, _extends({
|
|
98
103
|
state: 'interrupted'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/engine/make-flow-engine.ts"],"sourcesContent":["import {\n type FlowEngine,\n FlowEngineTag,\n FlowNotFound,\n FlowSignalRejected,\n} from '@entifix/transactions';\nimport { Context, Effect, Layer, Option } from 'effect';\nimport { DurableDeferred, WorkflowEngine } from 'effect/workflow';\n\nimport {\n type InterpreterOptions,\n SlipWorkflow,\n SlipWorkflowLayer,\n waitFor,\n} from '../interpreter/slip-workflow.js';\nimport type { FlowRecord } from '../status/flow-status-store.js';\nimport { FlowStatusStoreTag } from '../status/flow-status-store.js';\n\n/**\n * The flow engine port over Effect Workflow\n * ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)).\n * A start records the flow under its key and executes the slip detached — it\n * answers the flow id, never the outcome, which arrives as `flow.*` events and\n * in the status record. A signal is accepted only by a flow parked on exactly\n * that wait.\n */\nexport const makeFlowEngine = Effect.gen(function* () {\n const context = yield* Effect.context<\n WorkflowEngine.WorkflowEngine | FlowStatusStoreTag\n >();\n const store = Context.get(context, FlowStatusStoreTag);\n const within = <A, E>(\n effect: Effect.Effect<A, E, WorkflowEngine.WorkflowEngine>,\n ) => Effect.provideContext(effect, context);\n\n const known = (flowId: string) =>\n Effect.flatMap(store.find(flowId), found =>\n Option.match(found, {\n onNone: () => Effect.fail(new FlowNotFound({ flowId })),\n onSome: Effect.succeed,\n }),\n );\n\n /** Completes the wait `record` is parked on, if `token` names it. */\n const complete = (token: string, outcome: unknown) => (record: FlowRecord) =>\n Effect.gen(function* () {\n // Claimed before the wait is resumed, never after: the resumed flow\n // records its own states, and a `running` written behind them would put\n // a finished flow back to running with nothing left to correct it. The\n // claim is conditional, so a second signal racing this one is refused.\n const claimed = yield* store.claimWait(record.flowId, token);\n if (!claimed)\n return yield* Effect.fail(\n new FlowSignalRejected({ flowId: record.flowId, token }),\n );\n const deferred = waitFor(token);\n yield* within(\n DurableDeferred.succeed(deferred, {\n token: DurableDeferred.tokenFromExecutionId(deferred, {\n workflow: SlipWorkflow,\n executionId: record.executionId,\n }),\n value: outcome,\n }),\n ).pipe(\n // The wait was not resumed, so it is parked again and a retried signal\n // can claim it.\n Effect.onError(() =>\n store\n .update(record.flowId, {\n state: 'waiting',\n step: token,\n waitingFor: token,\n ...(record.correlation === undefined\n ? {}\n : { correlation: record.correlation }),\n ...(record.accepts === undefined\n ? {}\n : { accepts: record.accepts }),\n })\n .pipe(Effect.ignore),\n ),\n );\n });\n\n const engine: FlowEngine = {\n start: (slip, idempotencyKey) =>\n Effect.gen(function* () {\n const payload = { key: idempotencyKey, slip };\n const executionId = yield* SlipWorkflow.executionId(payload);\n const record = yield* store.register(idempotencyKey, {\n flowId: slip.flowId,\n executionId,\n state: 'running',\n });\n if (record.executionId === executionId && record.flowId === slip.flowId)\n yield* within(SlipWorkflow.execute(payload, { discard: true }));\n return { flowId: record.flowId };\n }),\n\n status: flowId =>\n Effect.map(known(flowId), record => ({\n flowId: record.flowId,\n state: record.state,\n ...(record.step === undefined ? {} : { step: record.step }),\n })),\n\n signal: (flowId, token, outcome) =>\n Effect.flatMap(known(flowId), complete(token, outcome)),\n\n signalCorrelated: (correlation, signal) =>\n Effect.gen(function* () {\n // Only a parked flow carries its correlation: one still on its way to\n // the wait has none yet, and is not found — the sender retries.\n const found = yield* store.findByCorrelation(correlation);\n if (Option.isNone(found) || found.value.waitingFor === undefined)\n return yield* Effect.fail(new FlowNotFound({ flowId: correlation }));\n const record = found.value;\n const token = record.waitingFor as string;\n if (\n record.accepts !== undefined &&\n !record.accepts.includes(signal.outcome)\n )\n return yield* Effect.fail(\n new FlowSignalRejected({ flowId: record.flowId, token }),\n );\n return yield* complete(token, signal)(record);\n }),\n\n interrupt: flowId =>\n Effect.gen(function* () {\n const record = yield* known(flowId);\n yield* within(SlipWorkflow.interrupt(record.executionId));\n yield* store.update(flowId, {\n state: 'interrupted',\n ...(record.step === undefined ? {} : { step: record.step }),\n });\n }),\n };\n return engine;\n});\n\n/**\n * The flow engine with the interpreter registered. Needs a workflow engine —\n * the in-memory one, or the cluster engine over Postgres from\n * `@entifix/workflow/postgres` — a status store, a participant client, the\n * outbox its events go through, and the breaker, bulkhead and retry budget\n * every call runs under.\n */\nexport const FlowEngineLayer = (options: InterpreterOptions) =>\n Layer.effect(FlowEngineTag, makeFlowEngine).pipe(\n Layer.provideMerge(SlipWorkflowLayer(options)),\n );\n\n/**\n * The flow engine over Effect's in-memory workflow engine: every flow lives and\n * dies with the process. For a single-process host — an example, a test, a\n * tool — whose flows need the interpreter's semantics but not its durability;\n * a fleet takes `@entifix/workflow/postgres`'s engines instead, and nothing\n * else in its composition changes.\n */\nexport const MemoryFlowEngineLayer = (options: InterpreterOptions) =>\n FlowEngineLayer(options).pipe(Layer.provide(WorkflowEngine.layerMemory));\n"],"names":["FlowEngineTag","FlowNotFound","FlowSignalRejected","Context","Effect","Layer","Option","DurableDeferred","WorkflowEngine","SlipWorkflow","SlipWorkflowLayer","waitFor","FlowStatusStoreTag","makeFlowEngine","gen","context","store","get","within","effect","provideContext","known","flowId","flatMap","find","found","match","onNone","fail","onSome","succeed","complete","token","outcome","record","claimed","claimWait","deferred","tokenFromExecutionId","workflow","executionId","value","pipe","onError","update","state","step","waitingFor","correlation","undefined","accepts","ignore","engine","start","slip","idempotencyKey","payload","key","register","execute","discard","status","map","signal","signalCorrelated","findByCorrelation","isNone","includes","interrupt","FlowEngineLayer","options","provideMerge","MemoryFlowEngineLayer","provide","layerMemory"],"mappings":";AAAA,SAEEA,aAAa,EACbC,YAAY,EACZC,kBAAkB,QACb,wBAAwB;AAC/B,SAASC,OAAO,EAAEC,MAAM,EAAEC,KAAK,EAAEC,MAAM,QAAQ,SAAS;AACxD,SAASC,eAAe,EAAEC,cAAc,QAAQ,kBAAkB;AAElE,SAEEC,YAAY,EACZC,iBAAiB,EACjBC,OAAO,QACF,kCAAkC;AAEzC,SAASC,kBAAkB,QAAQ,iCAAiC;AAEpE;;;;;;;CAOC,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0B;gBAAY;gBACnE,MAAMd,SAAST,MAAMgB,KAAK;gBAC1B,MAAMT,QAAQE,OAAOa,UAAU;gBAC/B,IACEb,OAAOgB,OAAO,KAAKD,aACnB,CAACf,OAAOgB,OAAO,CAACiB,QAAQ,CAACJ,OAAO9B,OAAO,GAEvC,OAAO,OAAO7B,OAAOwB,IAAI,CACvB,IAAI1B,mBAAmB;oBAAEoB,QAAQY,OAAOZ,MAAM;oBAAEU;gBAAM;gBAE1D,OAAO,OAAOD,SAASC,OAAO+B,QAAQ7B;YACxC;QAEFkC,WAAW9C,CAAAA,SACTlB,OAAOU,GAAG,CAAC;gBACT,MAAMoB,SAAS,OAAOb,MAAMC;gBAC5B,OAAOJ,OAAOT,aAAa2D,SAAS,CAAClC,OAAOM,WAAW;gBACvD,OAAOxB,MAAM4B,MAAM,CAACtB,QAAQ;oBAC1BuB,OAAO;mBACHX,OAAOY,IAAI,KAAKG,YAAY,CAAC,IAAI;oBAAEH,MAAMZ,OAAOY,IAAI;gBAAC;YAE7D;IACJ;IACA,OAAOM;AACT,GAAG;AAEH;;;;;;CAMC,GACD,OAAO,MAAMiB,kBAAkB,CAACC,UAC9BjE,MAAMc,MAAM,CAACnB,eAAea,gBAAgB6B,IAAI,CAC9CrC,MAAMkE,YAAY,CAAC7D,kBAAkB4D,WACrC;AAEJ;;;;;;CAMC,GACD,OAAO,MAAME,wBAAwB,CAACF,UACpCD,gBAAgBC,SAAS5B,IAAI,CAACrC,MAAMoE,OAAO,CAACjE,eAAekE,WAAW,GAAG"}
|
|
1
|
+
{"version":3,"sources":["../../src/engine/make-flow-engine.ts"],"sourcesContent":["import {\n type FlowEngine,\n FlowEngineTag,\n FlowNotFound,\n FlowSignalRejected,\n} from '@entifix/transactions';\nimport { Context, Effect, Layer, Option } from 'effect';\nimport { DurableDeferred, WorkflowEngine } from 'effect/workflow';\n\nimport {\n type InterpreterOptions,\n SlipWorkflow,\n SlipWorkflowLayer,\n waitFor,\n} from '../interpreter/slip-workflow.js';\nimport type { FlowRecord } from '../status/flow-status-store.js';\nimport {\n FlowStatusStoreTag,\n isTerminalFlowState,\n} from '../status/flow-status-store.js';\n\n/**\n * The flow engine port over Effect Workflow\n * ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)).\n * A start records the flow under its key and executes the slip detached — it\n * answers the flow id, never the outcome, which arrives as `flow.*` events and\n * in the status record. A signal is accepted only by a flow parked on exactly\n * that wait.\n */\nexport const makeFlowEngine = Effect.gen(function* () {\n const context = yield* Effect.context<\n WorkflowEngine.WorkflowEngine | FlowStatusStoreTag\n >();\n const store = Context.get(context, FlowStatusStoreTag);\n const within = <A, E>(\n effect: Effect.Effect<A, E, WorkflowEngine.WorkflowEngine>,\n ) => Effect.provideContext(effect, context);\n\n const known = (flowId: string) =>\n Effect.flatMap(store.find(flowId), found =>\n Option.match(found, {\n onNone: () => Effect.fail(new FlowNotFound({ flowId })),\n onSome: Effect.succeed,\n }),\n );\n\n /** Completes the wait `record` is parked on, if `token` names it. */\n const complete = (token: string, outcome: unknown) => (record: FlowRecord) =>\n Effect.gen(function* () {\n // Claimed before the wait is resumed, never after: the resumed flow\n // records its own states, and a `running` written behind them would put\n // a finished flow back to running with nothing left to correct it. The\n // claim is conditional, so a second signal racing this one is refused.\n const claimed = yield* store.claimWait(record.flowId, token);\n if (!claimed)\n return yield* Effect.fail(\n new FlowSignalRejected({ flowId: record.flowId, token }),\n );\n const deferred = waitFor(token);\n yield* within(\n DurableDeferred.succeed(deferred, {\n token: DurableDeferred.tokenFromExecutionId(deferred, {\n workflow: SlipWorkflow,\n executionId: record.executionId,\n }),\n value: outcome,\n }),\n ).pipe(\n // The wait was not resumed, so it is parked again and a retried signal\n // can claim it.\n Effect.onError(() =>\n store\n .update(record.flowId, {\n state: 'waiting',\n step: token,\n waitingFor: token,\n ...(record.correlation === undefined\n ? {}\n : { correlation: record.correlation }),\n ...(record.accepts === undefined\n ? {}\n : { accepts: record.accepts }),\n })\n .pipe(Effect.ignore),\n ),\n );\n });\n\n const engine: FlowEngine = {\n start: (slip, idempotencyKey) =>\n Effect.gen(function* () {\n const payload = { key: idempotencyKey, slip };\n const executionId = yield* SlipWorkflow.executionId(payload);\n const record = yield* store.register(idempotencyKey, {\n flowId: slip.flowId,\n executionId,\n state: 'running',\n });\n // A flow that already ended is answered, never executed again: its\n // journal may have been purged, and executing it would run it anew.\n if (\n record.executionId === executionId &&\n record.flowId === slip.flowId &&\n !isTerminalFlowState(record.state)\n )\n yield* within(SlipWorkflow.execute(payload, { discard: true }));\n return { flowId: record.flowId };\n }),\n\n status: flowId =>\n Effect.map(known(flowId), record => ({\n flowId: record.flowId,\n state: record.state,\n ...(record.step === undefined ? {} : { step: record.step }),\n })),\n\n signal: (flowId, token, outcome) =>\n Effect.flatMap(known(flowId), complete(token, outcome)),\n\n signalCorrelated: (correlation, signal) =>\n Effect.gen(function* () {\n // Only a parked flow carries its correlation: one still on its way to\n // the wait has none yet, and is not found — the sender retries.\n const found = yield* store.findByCorrelation(correlation);\n if (Option.isNone(found) || found.value.waitingFor === undefined)\n return yield* Effect.fail(new FlowNotFound({ flowId: correlation }));\n const record = found.value;\n const token = record.waitingFor as string;\n if (\n record.accepts !== undefined &&\n !record.accepts.includes(signal.outcome)\n )\n return yield* Effect.fail(\n new FlowSignalRejected({ flowId: record.flowId, token }),\n );\n return yield* complete(token, signal)(record);\n }),\n\n interrupt: flowId =>\n Effect.gen(function* () {\n const record = yield* known(flowId);\n // An ended flow has nothing to interrupt, and its state stays the\n // one it ended in.\n if (isTerminalFlowState(record.state)) return;\n yield* within(SlipWorkflow.interrupt(record.executionId));\n yield* store.update(flowId, {\n state: 'interrupted',\n ...(record.step === undefined ? {} : { step: record.step }),\n });\n }),\n };\n return engine;\n});\n\n/**\n * The flow engine with the interpreter registered. Needs a workflow engine —\n * the in-memory one, or the cluster engine over Postgres from\n * `@entifix/workflow/postgres` — a status store, a participant client, the\n * outbox its events go through, and the breaker, bulkhead and retry budget\n * every call runs under.\n */\nexport const FlowEngineLayer = (options: InterpreterOptions) =>\n Layer.effect(FlowEngineTag, makeFlowEngine).pipe(\n Layer.provideMerge(SlipWorkflowLayer(options)),\n );\n\n/**\n * The flow engine over Effect's in-memory workflow engine: every flow lives and\n * dies with the process. For a single-process host — an example, a test, a\n * tool — whose flows need the interpreter's semantics but not its durability;\n * a fleet takes `@entifix/workflow/postgres`'s engines instead, and nothing\n * else in its composition changes.\n */\nexport const MemoryFlowEngineLayer = (options: InterpreterOptions) =>\n FlowEngineLayer(options).pipe(Layer.provide(WorkflowEngine.layerMemory));\n"],"names":["FlowEngineTag","FlowNotFound","FlowSignalRejected","Context","Effect","Layer","Option","DurableDeferred","WorkflowEngine","SlipWorkflow","SlipWorkflowLayer","waitFor","FlowStatusStoreTag","isTerminalFlowState","makeFlowEngine","gen","context","store","get","within","effect","provideContext","known","flowId","flatMap","find","found","match","onNone","fail","onSome","succeed","complete","token","outcome","record","claimed","claimWait","deferred","tokenFromExecutionId","workflow","executionId","value","pipe","onError","update","state","step","waitingFor","correlation","undefined","accepts","ignore","engine","start","slip","idempotencyKey","payload","key","register","execute","discard","status","map","signal","signalCorrelated","findByCorrelation","isNone","includes","interrupt","FlowEngineLayer","options","provideMerge","MemoryFlowEngineLayer","provide","layerMemory"],"mappings":";AAAA,SAEEA,aAAa,EACbC,YAAY,EACZC,kBAAkB,QACb,wBAAwB;AAC/B,SAASC,OAAO,EAAEC,MAAM,EAAEC,KAAK,EAAEC,MAAM,QAAQ,SAAS;AACxD,SAASC,eAAe,EAAEC,cAAc,QAAQ,kBAAkB;AAElE,SAEEC,YAAY,EACZC,iBAAiB,EACjBC,OAAO,QACF,kCAAkC;AAEzC,SACEC,kBAAkB,EAClBC,mBAAmB,QACd,iCAAiC;AAExC;;;;;;;CAOC,GACD,OAAO,MAAMC,iBAAiBV,OAAOW,GAAG,CAAC;IACvC,MAAMC,UAAU,OAAOZ,OAAOY,OAAO;IAGrC,MAAMC,QAAQd,QAAQe,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AK;gBAC1B,MAAMT,QAAQE,OAAOa,UAAU;gBAC/B,IACEb,OAAOgB,OAAO,KAAKD,aACnB,CAACf,OAAOgB,OAAO,CAACiB,QAAQ,CAACJ,OAAO9B,OAAO,GAEvC,OAAO,OAAO9B,OAAOyB,IAAI,CACvB,IAAI3B,mBAAmB;oBAAEqB,QAAQY,OAAOZ,MAAM;oBAAEU;gBAAM;gBAE1D,OAAO,OAAOD,SAASC,OAAO+B,QAAQ7B;YACxC;QAEFkC,WAAW9C,CAAAA,SACTnB,OAAOW,GAAG,CAAC;gBACT,MAAMoB,SAAS,OAAOb,MAAMC;gBAC5B,kEAAkE;gBAClE,mBAAmB;gBACnB,IAAIV,oBAAoBsB,OAAOW,KAAK,GAAG;gBACvC,OAAO3B,OAAOV,aAAa4D,SAAS,CAAClC,OAAOM,WAAW;gBACvD,OAAOxB,MAAM4B,MAAM,CAACtB,QAAQ;oBAC1BuB,OAAO;mBACHX,OAAOY,IAAI,KAAKG,YAAY,CAAC,IAAI;oBAAEH,MAAMZ,OAAOY,IAAI;gBAAC;YAE7D;IACJ;IACA,OAAOM;AACT,GAAG;AAEH;;;;;;CAMC,GACD,OAAO,MAAMiB,kBAAkB,CAACC,UAC9BlE,MAAMe,MAAM,CAACpB,eAAec,gBAAgB6B,IAAI,CAC9CtC,MAAMmE,YAAY,CAAC9D,kBAAkB6D,WACrC;AAEJ;;;;;;CAMC,GACD,OAAO,MAAME,wBAAwB,CAACF,UACpCD,gBAAgBC,SAAS5B,IAAI,CAACtC,MAAMqE,OAAO,CAAClE,eAAemE,WAAW,GAAG"}
|
package/dist/postgres/index.d.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
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,
|
|
3
|
+
* workflow engine's journal, a status store beside it, the purge that empties
|
|
4
|
+
* a finished flow's journal after its retention, and a single runner.
|
|
4
5
|
* Postgres dialect. A deployment of several runners adds
|
|
5
6
|
* `@entifix/workflow/socket-runner`.
|
|
6
7
|
*/
|
|
8
|
+
export * from './journal-retention.js';
|
|
7
9
|
export * from './single-runner.js';
|
|
8
10
|
export * from './sql-flow-status-store.js';
|
|
9
11
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/postgres/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/postgres/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,cAAc,wBAAwB,CAAC;AACvC,cAAc,oBAAoB,CAAC;AACnC,cAAc,4BAA4B,CAAC"}
|
package/dist/postgres/index.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
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,
|
|
3
|
+
* workflow engine's journal, a status store beside it, the purge that empties
|
|
4
|
+
* a finished flow's journal after its retention, and a single runner.
|
|
4
5
|
* Postgres dialect. A deployment of several runners adds
|
|
5
6
|
* `@entifix/workflow/socket-runner`.
|
|
6
|
-
*/ export * from './
|
|
7
|
+
*/ export * from './journal-retention.js';
|
|
8
|
+
export * from './single-runner.js';
|
|
7
9
|
export * from './sql-flow-status-store.js';
|
|
8
10
|
|
|
9
11
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +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
|
|
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, the purge that empties\n * a finished flow's journal after its retention, and a single runner.\n * Postgres dialect. A deployment of several runners adds\n * `@entifix/workflow/socket-runner`.\n */\nexport * from './journal-retention.js';\nexport * from './single-runner.js';\nexport * from './sql-flow-status-store.js';\n"],"names":[],"mappings":"AAAA;;;;;;CAMC,GACD,cAAc,yBAAyB;AACvC,cAAc,qBAAqB;AACnC,cAAc,6BAA6B"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { Duration, Effect, Layer } from 'effect';
|
|
2
|
+
import { SqlClient } from 'effect/sql';
|
|
3
|
+
/** How often the purge looks for journals past their retention, by default. */
|
|
4
|
+
export declare const JOURNAL_PURGE_INTERVAL: Duration.Duration;
|
|
5
|
+
/** Flows purged per statement, by default. */
|
|
6
|
+
export declare const JOURNAL_PURGE_BATCH = 100;
|
|
7
|
+
/** What one purge pass did, for the host to log; the package logs nothing. */
|
|
8
|
+
export type JournalPurgeOutcome = {
|
|
9
|
+
readonly _tag: 'purged';
|
|
10
|
+
readonly flows: number;
|
|
11
|
+
} | {
|
|
12
|
+
readonly _tag: 'purgeFailed';
|
|
13
|
+
readonly failure: unknown;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* How long a finished flow's journal is kept. The journal holds every flow's
|
|
17
|
+
* start input and step inputs, which can carry personal data, so retention is
|
|
18
|
+
* the store owner's — the engine's — and the host must state it: there is no
|
|
19
|
+
* default that silently keeps everything forever.
|
|
20
|
+
*/
|
|
21
|
+
export interface JournalRetention {
|
|
22
|
+
/** How long after a flow ends its journal is purged. Required, and positive. */
|
|
23
|
+
readonly journalRetention: Duration.Input;
|
|
24
|
+
/** How often the purge runs. Defaults to {@link JOURNAL_PURGE_INTERVAL}. */
|
|
25
|
+
readonly purgeInterval?: Duration.Input;
|
|
26
|
+
/** Flows purged per statement. Defaults to {@link JOURNAL_PURGE_BATCH}. */
|
|
27
|
+
readonly purgeBatch?: number;
|
|
28
|
+
/** Told what each pass did. */
|
|
29
|
+
readonly onPurge?: (outcome: JournalPurgeOutcome) => Effect.Effect<void>;
|
|
30
|
+
}
|
|
31
|
+
declare const JournalRetentionUnset_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
32
|
+
readonly _tag: "JournalRetentionUnset";
|
|
33
|
+
} & Readonly<A>;
|
|
34
|
+
/** The engine was started without a usable retention for its journal. */
|
|
35
|
+
export declare class JournalRetentionUnset extends JournalRetentionUnset_base<{
|
|
36
|
+
readonly dial: 'journalRetention';
|
|
37
|
+
readonly reason: string;
|
|
38
|
+
}> {
|
|
39
|
+
get message(): string;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Purges one batch: the flows that ended more than `retention` ago and still
|
|
43
|
+
* hold a journal lose their messages and replies — every one the workflow and
|
|
44
|
+
* its clock entity recorded under the flow's execution id — and their status
|
|
45
|
+
* row keeps its state, step and timestamps but drops its payload columns and
|
|
46
|
+
* is stamped purged. One statement, so a batch is all or nothing; rows locked
|
|
47
|
+
* by a concurrent pass are skipped, never waited on. Answers how many flows it
|
|
48
|
+
* purged.
|
|
49
|
+
*/
|
|
50
|
+
export declare const purgeFinishedJournals: (sql: SqlClient.SqlClient, retention: Duration.Duration, batch?: number) => Effect.Effect<number, import("@entifix/core").StoreFailure, never>;
|
|
51
|
+
/**
|
|
52
|
+
* The purge as a daemon beside the runner, for as long as the engine's layer
|
|
53
|
+
* lives: one pass every interval, the first an interval after start — by then
|
|
54
|
+
* the engine has created the tables it purges. A failed pass is reported and
|
|
55
|
+
* the next one runs — a purge that stopped would look exactly like one with
|
|
56
|
+
* nothing to do. Fails to build with {@link JournalRetentionUnset} when the
|
|
57
|
+
* retention is not stated.
|
|
58
|
+
*/
|
|
59
|
+
export declare const JournalPurgeLayer: (options: JournalRetention) => Layer.Layer<never, JournalRetentionUnset, SqlClient.SqlClient>;
|
|
60
|
+
export {};
|
|
61
|
+
//# sourceMappingURL=journal-retention.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"journal-retention.d.ts","sourceRoot":"","sources":["../../src/postgres/journal-retention.ts"],"names":[],"mappings":"AACA,OAAO,EAAQ,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAU,MAAM,QAAQ,CAAC;AAC/D,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAIvC,+EAA+E;AAC/E,eAAO,MAAM,sBAAsB,mBAAoB,CAAC;AACxD,8CAA8C;AAC9C,eAAO,MAAM,mBAAmB,MAAM,CAAC;AAEvC,8EAA8E;AAC9E,MAAM,MAAM,mBAAmB,GAC3B;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GACnD;IAAE,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAA;CAAE,CAAC;AAEhE;;;;;GAKG;AACH,MAAM,WAAW,gBAAgB;IAC/B,gFAAgF;IAChF,QAAQ,CAAC,gBAAgB,EAAE,QAAQ,CAAC,KAAK,CAAC;IAC1C,4EAA4E;IAC5E,QAAQ,CAAC,aAAa,CAAC,EAAE,QAAQ,CAAC,KAAK,CAAC;IACxC,2EAA2E;IAC3E,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,+BAA+B;IAC/B,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,mBAAmB,KAAK,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;CAC1E;;;;AAED,yEAAyE;AACzE,qBAAa,qBAAsB,SAAQ,2BAEzC;IAAE,QAAQ,CAAC,IAAI,EAAE,kBAAkB,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;IAC/D,IAAa,OAAO,IAAI,MAAM,CAE7B;CACF;AAyCD;;;;;;;;GAQG;AACH,eAAO,MAAM,qBAAqB,GAChC,KAAK,SAAS,CAAC,SAAS,EACxB,WAAW,QAAQ,CAAC,QAAQ,EAC5B,QAAO,MAA4B,uEA4BlC,CAAC;AAiBJ;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB,GAAI,SAAS,gBAAgB,mEAgBxD,CAAC"}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { translateSqlError } from '@entifix/sql';
|
|
2
|
+
import { Data, Duration, Effect, Layer, Option } from 'effect';
|
|
3
|
+
import { SqlClient } from 'effect/sql';
|
|
4
|
+
import { TERMINAL_FLOW_STATES } from '../status/flow-status-store.js';
|
|
5
|
+
/** How often the purge looks for journals past their retention, by default. */ export const JOURNAL_PURGE_INTERVAL = Duration.hours(1);
|
|
6
|
+
/** Flows purged per statement, by default. */ export const JOURNAL_PURGE_BATCH = 100;
|
|
7
|
+
/** The engine was started without a usable retention for its journal. */ export class JournalRetentionUnset extends Data.TaggedError('JournalRetentionUnset') {
|
|
8
|
+
get message() {
|
|
9
|
+
return this.reason;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
const positive = (input)=>Option.match(input === undefined ? Option.none() : Duration.fromInput(input), {
|
|
13
|
+
onNone: ()=>Duration.zero,
|
|
14
|
+
onSome: (duration)=>duration
|
|
15
|
+
});
|
|
16
|
+
/** The dials, checked; a retention that is missing, unreadable or not positive fails. */ const readRetention = (options)=>Effect.gen(function*() {
|
|
17
|
+
const retention = positive(options.journalRetention);
|
|
18
|
+
if (!Duration.isGreaterThan(retention, Duration.zero)) {
|
|
19
|
+
return yield* Effect.fail(new JournalRetentionUnset({
|
|
20
|
+
dial: 'journalRetention',
|
|
21
|
+
reason: options.journalRetention === undefined ? 'the flow engine needs journalRetention: how long a finished flow keeps its journal' : `journalRetention ${String(options.journalRetention)} is not a positive duration`
|
|
22
|
+
}));
|
|
23
|
+
}
|
|
24
|
+
const interval = positive(options.purgeInterval);
|
|
25
|
+
return {
|
|
26
|
+
retention,
|
|
27
|
+
interval: Duration.isGreaterThan(interval, Duration.zero) ? interval : JOURNAL_PURGE_INTERVAL,
|
|
28
|
+
batch: options.purgeBatch !== undefined && options.purgeBatch > 0 ? Math.floor(options.purgeBatch) : JOURNAL_PURGE_BATCH
|
|
29
|
+
};
|
|
30
|
+
});
|
|
31
|
+
const TERMINAL = TERMINAL_FLOW_STATES.map((state)=>`'${state}'`).join(', ');
|
|
32
|
+
/**
|
|
33
|
+
* Purges one batch: the flows that ended more than `retention` ago and still
|
|
34
|
+
* hold a journal lose their messages and replies — every one the workflow and
|
|
35
|
+
* its clock entity recorded under the flow's execution id — and their status
|
|
36
|
+
* row keeps its state, step and timestamps but drops its payload columns and
|
|
37
|
+
* is stamped purged. One statement, so a batch is all or nothing; rows locked
|
|
38
|
+
* by a concurrent pass are skipped, never waited on. Answers how many flows it
|
|
39
|
+
* purged.
|
|
40
|
+
*/ export const purgeFinishedJournals = (sql, retention, batch = JOURNAL_PURGE_BATCH)=>sql`
|
|
41
|
+
WITH due AS (
|
|
42
|
+
SELECT flow_id, execution_id FROM entifix_flow_status
|
|
43
|
+
WHERE state IN (${sql.literal(TERMINAL)})
|
|
44
|
+
AND purged_at IS NULL
|
|
45
|
+
AND terminal_at < now() - make_interval(secs => ${Duration.toSeconds(retention)})
|
|
46
|
+
ORDER BY terminal_at
|
|
47
|
+
LIMIT ${batch}
|
|
48
|
+
FOR UPDATE SKIP LOCKED
|
|
49
|
+
),
|
|
50
|
+
replies AS (
|
|
51
|
+
DELETE FROM cluster_replies WHERE request_id IN (
|
|
52
|
+
SELECT id FROM cluster_messages
|
|
53
|
+
WHERE entity_id IN (SELECT execution_id FROM due)
|
|
54
|
+
)
|
|
55
|
+
),
|
|
56
|
+
messages AS (
|
|
57
|
+
DELETE FROM cluster_messages
|
|
58
|
+
WHERE entity_id IN (SELECT execution_id FROM due)
|
|
59
|
+
)
|
|
60
|
+
UPDATE entifix_flow_status
|
|
61
|
+
SET correlation = NULL, accepts = NULL, purged_at = now()
|
|
62
|
+
WHERE flow_id IN (SELECT flow_id FROM due)
|
|
63
|
+
RETURNING flow_id`.pipe(Effect.map((rows)=>rows.length), Effect.mapError((error)=>translateSqlError(error)));
|
|
64
|
+
/** Purges batch after batch until one comes back short. */ const purgeAll = (sql, retention, batch)=>Effect.gen(function*() {
|
|
65
|
+
let total = 0;
|
|
66
|
+
for(;;){
|
|
67
|
+
const purged = yield* purgeFinishedJournals(sql, retention, batch);
|
|
68
|
+
total += purged;
|
|
69
|
+
if (purged < batch) return total;
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
/**
|
|
73
|
+
* The purge as a daemon beside the runner, for as long as the engine's layer
|
|
74
|
+
* lives: one pass every interval, the first an interval after start — by then
|
|
75
|
+
* the engine has created the tables it purges. A failed pass is reported and
|
|
76
|
+
* the next one runs — a purge that stopped would look exactly like one with
|
|
77
|
+
* nothing to do. Fails to build with {@link JournalRetentionUnset} when the
|
|
78
|
+
* retention is not stated.
|
|
79
|
+
*/ export const JournalPurgeLayer = (options)=>Layer.effectDiscard(Effect.gen(function*() {
|
|
80
|
+
var _options_onPurge;
|
|
81
|
+
const { retention, interval, batch } = yield* readRetention(options);
|
|
82
|
+
const sql = yield* SqlClient.SqlClient;
|
|
83
|
+
const report = (_options_onPurge = options.onPurge) != null ? _options_onPurge : ()=>Effect.void;
|
|
84
|
+
const pass = purgeAll(sql, retention, batch).pipe(Effect.matchEffect({
|
|
85
|
+
onSuccess: (flows)=>report({
|
|
86
|
+
_tag: 'purged',
|
|
87
|
+
flows
|
|
88
|
+
}),
|
|
89
|
+
onFailure: (failure)=>report({
|
|
90
|
+
_tag: 'purgeFailed',
|
|
91
|
+
failure
|
|
92
|
+
})
|
|
93
|
+
}));
|
|
94
|
+
yield* Effect.forkScoped(Effect.sleep(interval).pipe(Effect.andThen(pass), Effect.forever));
|
|
95
|
+
}));
|
|
96
|
+
|
|
97
|
+
//# sourceMappingURL=journal-retention.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/postgres/journal-retention.ts"],"sourcesContent":["import { translateSqlError } from '@entifix/sql';\nimport { Data, Duration, Effect, Layer, Option } from 'effect';\nimport { SqlClient } from 'effect/sql';\n\nimport { TERMINAL_FLOW_STATES } from '../status/flow-status-store.js';\n\n/** How often the purge looks for journals past their retention, by default. */\nexport const JOURNAL_PURGE_INTERVAL = Duration.hours(1);\n/** Flows purged per statement, by default. */\nexport const JOURNAL_PURGE_BATCH = 100;\n\n/** What one purge pass did, for the host to log; the package logs nothing. */\nexport type JournalPurgeOutcome =\n | { readonly _tag: 'purged'; readonly flows: number }\n | { readonly _tag: 'purgeFailed'; readonly failure: unknown };\n\n/**\n * How long a finished flow's journal is kept. The journal holds every flow's\n * start input and step inputs, which can carry personal data, so retention is\n * the store owner's — the engine's — and the host must state it: there is no\n * default that silently keeps everything forever.\n */\nexport interface JournalRetention {\n /** How long after a flow ends its journal is purged. Required, and positive. */\n readonly journalRetention: Duration.Input;\n /** How often the purge runs. Defaults to {@link JOURNAL_PURGE_INTERVAL}. */\n readonly purgeInterval?: Duration.Input;\n /** Flows purged per statement. Defaults to {@link JOURNAL_PURGE_BATCH}. */\n readonly purgeBatch?: number;\n /** Told what each pass did. */\n readonly onPurge?: (outcome: JournalPurgeOutcome) => Effect.Effect<void>;\n}\n\n/** The engine was started without a usable retention for its journal. */\nexport class JournalRetentionUnset extends Data.TaggedError(\n 'JournalRetentionUnset',\n)<{ readonly dial: 'journalRetention'; readonly reason: string }> {\n override get message(): string {\n return this.reason;\n }\n}\n\nconst positive = (input: Duration.Input | undefined): Duration.Duration =>\n Option.match(\n input === undefined ? Option.none() : Duration.fromInput(input),\n {\n onNone: () => Duration.zero,\n onSome: duration => duration,\n },\n );\n\n/** The dials, checked; a retention that is missing, unreadable or not positive fails. */\nconst readRetention = (options: JournalRetention) =>\n Effect.gen(function* () {\n const retention = positive(options.journalRetention);\n if (!Duration.isGreaterThan(retention, Duration.zero)) {\n return yield* Effect.fail(\n new JournalRetentionUnset({\n dial: 'journalRetention',\n reason:\n options.journalRetention === undefined\n ? 'the flow engine needs journalRetention: how long a finished flow keeps its journal'\n : `journalRetention ${String(options.journalRetention)} is not a positive duration`,\n }),\n );\n }\n const interval = positive(options.purgeInterval);\n return {\n retention,\n interval: Duration.isGreaterThan(interval, Duration.zero)\n ? interval\n : JOURNAL_PURGE_INTERVAL,\n batch:\n options.purgeBatch !== undefined && options.purgeBatch > 0\n ? Math.floor(options.purgeBatch)\n : JOURNAL_PURGE_BATCH,\n };\n });\n\nconst TERMINAL = TERMINAL_FLOW_STATES.map(state => `'${state}'`).join(', ');\n\n/**\n * Purges one batch: the flows that ended more than `retention` ago and still\n * hold a journal lose their messages and replies — every one the workflow and\n * its clock entity recorded under the flow's execution id — and their status\n * row keeps its state, step and timestamps but drops its payload columns and\n * is stamped purged. One statement, so a batch is all or nothing; rows locked\n * by a concurrent pass are skipped, never waited on. Answers how many flows it\n * purged.\n */\nexport const purgeFinishedJournals = (\n sql: SqlClient.SqlClient,\n retention: Duration.Duration,\n batch: number = JOURNAL_PURGE_BATCH,\n) =>\n sql<{ readonly flow_id: string }>`\n WITH due AS (\n SELECT flow_id, execution_id FROM entifix_flow_status\n WHERE state IN (${sql.literal(TERMINAL)})\n AND purged_at IS NULL\n AND terminal_at < now() - make_interval(secs => ${Duration.toSeconds(retention)})\n ORDER BY terminal_at\n LIMIT ${batch}\n FOR UPDATE SKIP LOCKED\n ),\n replies AS (\n DELETE FROM cluster_replies WHERE request_id IN (\n SELECT id FROM cluster_messages\n WHERE entity_id IN (SELECT execution_id FROM due)\n )\n ),\n messages AS (\n DELETE FROM cluster_messages\n WHERE entity_id IN (SELECT execution_id FROM due)\n )\n UPDATE entifix_flow_status\n SET correlation = NULL, accepts = NULL, purged_at = now()\n WHERE flow_id IN (SELECT flow_id FROM due)\n RETURNING flow_id`.pipe(\n Effect.map(rows => rows.length),\n Effect.mapError(error => translateSqlError(error)),\n );\n\n/** Purges batch after batch until one comes back short. */\nconst purgeAll = (\n sql: SqlClient.SqlClient,\n retention: Duration.Duration,\n batch: number,\n) =>\n Effect.gen(function* () {\n let total = 0;\n for (;;) {\n const purged = yield* purgeFinishedJournals(sql, retention, batch);\n total += purged;\n if (purged < batch) return total;\n }\n });\n\n/**\n * The purge as a daemon beside the runner, for as long as the engine's layer\n * lives: one pass every interval, the first an interval after start — by then\n * the engine has created the tables it purges. A failed pass is reported and\n * the next one runs — a purge that stopped would look exactly like one with\n * nothing to do. Fails to build with {@link JournalRetentionUnset} when the\n * retention is not stated.\n */\nexport const JournalPurgeLayer = (options: JournalRetention) =>\n Layer.effectDiscard(\n Effect.gen(function* () {\n const { retention, interval, batch } = yield* readRetention(options);\n const sql = yield* SqlClient.SqlClient;\n const report = options.onPurge ?? (() => Effect.void);\n const pass = purgeAll(sql, retention, batch).pipe(\n Effect.matchEffect({\n onSuccess: flows => report({ _tag: 'purged', flows }),\n onFailure: failure => report({ _tag: 'purgeFailed', failure }),\n }),\n );\n yield* Effect.forkScoped(\n Effect.sleep(interval).pipe(Effect.andThen(pass), Effect.forever),\n );\n }),\n );\n"],"names":["translateSqlError","Data","Duration","Effect","Layer","Option","SqlClient","TERMINAL_FLOW_STATES","JOURNAL_PURGE_INTERVAL","hours","JOURNAL_PURGE_BATCH","JournalRetentionUnset","TaggedError","message","reason","positive","input","match","undefined","none","fromInput","onNone","zero","onSome","duration","readRetention","options","gen","retention","journalRetention","isGreaterThan","fail","dial","String","interval","purgeInterval","batch","purgeBatch","Math","floor","TERMINAL","map","state","join","purgeFinishedJournals","sql","literal","toSeconds","pipe","rows","length","mapError","error","purgeAll","total","purged","JournalPurgeLayer","effectDiscard","report","onPurge","void","pass","matchEffect","onSuccess","flows","_tag","onFailure","failure","forkScoped","sleep","andThen","forever"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,eAAe;AACjD,SAASC,IAAI,EAAEC,QAAQ,EA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EF,OAAOhE,OAAOiE,UAAU,CACtBjE,OAAOkE,KAAK,CAACnC,UAAUc,IAAI,CAAC7C,OAAOmE,OAAO,CAACT,OAAO1D,OAAOoE,OAAO;IAEpE,IACA"}
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { Layer } from 'effect';
|
|
2
2
|
import type { InterpreterOptions } from '../interpreter/slip-workflow.js';
|
|
3
|
+
import { type JournalRetention } from './journal-retention.js';
|
|
3
4
|
/**
|
|
4
5
|
* The flow engine on one runner in this process, its journal and its status
|
|
5
6
|
* in the host's SQL database — for a deployment of one replica, and for specs.
|
|
6
|
-
*
|
|
7
|
+
* A finished flow's journal is purged after `journalRetention`, which the host
|
|
8
|
+
* must state. Needs the host's `SqlClient` and `Crypto` and a participant
|
|
9
|
+
* client.
|
|
7
10
|
*/
|
|
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>;
|
|
11
|
+
export declare const SingleRunnerFlowEngineLayer: (options: InterpreterOptions & JournalRetention) => Layer.Layer<import("@entifix/transactions").FlowEngineTag, import("@entifix/core").StoreFailure | import("./journal-retention.js").JournalRetentionUnset | 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
12
|
//# sourceMappingURL=single-runner.d.ts.map
|
|
@@ -1 +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;
|
|
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;AAC1E,OAAO,EAEL,KAAK,gBAAgB,EACtB,MAAM,wBAAwB,CAAC;AAGhC;;;;;;GAMG;AACH,eAAO,MAAM,2BAA2B,GACtC,SAAS,kBAAkB,GAAG,gBAAgB,qgBAU7C,CAAC"}
|
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import { Layer } from 'effect';
|
|
2
2
|
import { ClusterWorkflowEngine, SingleRunner } from 'effect/cluster';
|
|
3
3
|
import { FlowEngineLayer } from '../engine/make-flow-engine.js';
|
|
4
|
+
import { JournalPurgeLayer } from './journal-retention.js';
|
|
4
5
|
import { SqlFlowStatusStoreLayer } from './sql-flow-status-store.js';
|
|
5
6
|
/**
|
|
6
7
|
* The flow engine on one runner in this process, its journal and its status
|
|
7
8
|
* in the host's SQL database — for a deployment of one replica, and for specs.
|
|
8
|
-
*
|
|
9
|
-
|
|
9
|
+
* A finished flow's journal is purged after `journalRetention`, which the host
|
|
10
|
+
* must state. Needs the host's `SqlClient` and `Crypto` and a participant
|
|
11
|
+
* client.
|
|
12
|
+
*/ export const SingleRunnerFlowEngineLayer = (options)=>FlowEngineLayer(options).pipe(Layer.merge(JournalPurgeLayer(options)), Layer.provide(SqlFlowStatusStoreLayer), Layer.provide(ClusterWorkflowEngine.layer.pipe(Layer.provide(SingleRunner.layer({
|
|
10
13
|
runnerStorage: 'sql'
|
|
11
14
|
})))));
|
|
12
15
|
|
|
@@ -1 +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
|
|
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 {\n JournalPurgeLayer,\n type JournalRetention,\n} from './journal-retention.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 * A finished flow's journal is purged after `journalRetention`, which the host\n * must state. Needs the host's `SqlClient` and `Crypto` and a participant\n * client.\n */\nexport const SingleRunnerFlowEngineLayer = (\n options: InterpreterOptions & JournalRetention,\n) =>\n FlowEngineLayer(options).pipe(\n Layer.merge(JournalPurgeLayer(options)),\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","JournalPurgeLayer","SqlFlowStatusStoreLayer","SingleRunnerFlowEngineLayer","options","pipe","merge","provide","layer","runnerStorage"],"mappings":"AAAA,SAASA,KAAK,QAAQ,SAAS;AAC/B,SAASC,qBAAqB,EAAEC,YAAY,QAAQ,iBAAiB;AAErE,SAASC,eAAe,QAAQ,gCAAgC;AAEhE,SACEC,iBAAiB,QAEZ,yBAAyB;AAChC,SAASC,uBAAuB,QAAQ,6BAA6B;AAErE;;;;;;CAMC,GACD,OAAO,MAAMC,8BAA8B,CACzCC,UAEAJ,gBAAgBI,SAASC,IAAI,CAC3BR,MAAMS,KAAK,CAACL,kBAAkBG,WAC9BP,MAAMU,OAAO,CAACL,0BACdL,MAAMU,OAAO,CACXT,sBAAsBU,KAAK,CAACH,IAAI,CAC9BR,MAAMU,OAAO,CAACR,aAAaS,KAAK,CAAC;QAAEC,eAAe;IAAM,OAG5D"}
|
|
@@ -1 +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,
|
|
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,EAEnB,MAAM,gCAAgC,CAAC;AAgCxC;;;GAGG;AACH,eAAO,MAAM,qBAAqB,GAAI,KAAK,SAAS,CAAC,SAAS,qEA2B7B,CAAC;AAElC;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,GACjC,KAAK,SAAS,CAAC,SAAS,KACvB,eA8DD,CAAC;AAEH,mEAAmE;AACnE,eAAO,MAAM,uBAAuB,4FAOnC,CAAC"}
|
|
@@ -2,7 +2,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
2
2
|
import { translateSqlError } from '@entifix/sql';
|
|
3
3
|
import { Effect, Layer, Option } from 'effect';
|
|
4
4
|
import { SqlClient } from 'effect/sql';
|
|
5
|
-
import { FlowStatusStoreTag } from '../status/flow-status-store.js';
|
|
5
|
+
import { FlowStatusStoreTag, isTerminalFlowState } from '../status/flow-status-store.js';
|
|
6
6
|
const acceptsOf = (text)=>{
|
|
7
7
|
const parsed = JSON.parse(text);
|
|
8
8
|
return Array.isArray(parsed) ? parsed.map(String) : [];
|
|
@@ -34,10 +34,22 @@ const fault = (error)=>translateSqlError(error);
|
|
|
34
34
|
step text,
|
|
35
35
|
waiting_for text,
|
|
36
36
|
correlation text,
|
|
37
|
-
accepts text
|
|
37
|
+
accepts text,
|
|
38
|
+
terminal_at timestamptz,
|
|
39
|
+
purged_at timestamptz
|
|
38
40
|
)`;
|
|
39
41
|
yield* sql`
|
|
40
42
|
ALTER TABLE entifix_flow_status ADD COLUMN IF NOT EXISTS accepts text`;
|
|
43
|
+
yield* sql`
|
|
44
|
+
ALTER TABLE entifix_flow_status
|
|
45
|
+
ADD COLUMN IF NOT EXISTS terminal_at timestamptz`;
|
|
46
|
+
yield* sql`
|
|
47
|
+
ALTER TABLE entifix_flow_status
|
|
48
|
+
ADD COLUMN IF NOT EXISTS purged_at timestamptz`;
|
|
49
|
+
// What the journal purge walks: ended flows whose journal is still held.
|
|
50
|
+
yield* sql`
|
|
51
|
+
CREATE INDEX IF NOT EXISTS entifix_flow_status_terminal_at
|
|
52
|
+
ON entifix_flow_status (terminal_at) WHERE purged_at IS NULL`;
|
|
41
53
|
}).pipe(Effect.mapError(fault));
|
|
42
54
|
/**
|
|
43
55
|
* The flow status store over SQL, beside the workflow engine's own tables. A
|
|
@@ -55,7 +67,8 @@ const fault = (error)=>translateSqlError(error);
|
|
|
55
67
|
const [existing] = yield* sql`
|
|
56
68
|
SELECT * FROM entifix_flow_status
|
|
57
69
|
WHERE idempotency_key = ${key} OR flow_id = ${record.flowId}`;
|
|
58
|
-
// Gone between the two statements cannot happen: nothing deletes a
|
|
70
|
+
// Gone between the two statements cannot happen: nothing deletes a
|
|
71
|
+
// flow's row — the journal purge empties its payload and keeps it.
|
|
59
72
|
return recordOf(existing);
|
|
60
73
|
}).pipe(Effect.mapError(fault)),
|
|
61
74
|
find: (flowId)=>sql`
|
|
@@ -70,7 +83,11 @@ const fault = (error)=>translateSqlError(error);
|
|
|
70
83
|
SET state = ${patch.state}, step = ${(_patch_step = patch.step) != null ? _patch_step : null},
|
|
71
84
|
waiting_for = ${(_patch_waitingFor = patch.waitingFor) != null ? _patch_waitingFor : null},
|
|
72
85
|
correlation = ${(_patch_correlation = patch.correlation) != null ? _patch_correlation : null},
|
|
73
|
-
accepts = ${patch.accepts === undefined ? null : JSON.stringify(patch.accepts)}
|
|
86
|
+
accepts = ${patch.accepts === undefined ? null : JSON.stringify(patch.accepts)},
|
|
87
|
+
-- When the flow ended, kept from the first terminal write: the
|
|
88
|
+
-- journal purge counts its retention from here.
|
|
89
|
+
terminal_at = CASE WHEN ${isTerminalFlowState(patch.state)}
|
|
90
|
+
THEN COALESCE(terminal_at, now()) END
|
|
74
91
|
WHERE flow_id = ${flowId}`.pipe(Effect.asVoid, Effect.mapError(fault));
|
|
75
92
|
},
|
|
76
93
|
claimWait: (flowId, token)=>sql`
|
|
@@ -1 +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 /** The parked wait's outcomes, as a JSON array. */\n readonly accepts: string | null;\n};\n\nconst acceptsOf = (text: string): readonly string[] => {\n const parsed: unknown = JSON.parse(text);\n return Array.isArray(parsed) ? parsed.map(String) : [];\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 ...(row.accepts === null ? {} : { accepts: acceptsOf(row.accepts) }),\n});\n\nconst fault = (error: unknown) => translateSqlError(error);\n\n/**\n * Creates the flow status table if it is missing, and adds a column a table\n * created by an earlier release lacks. Idempotent.\n */\nexport const ensureFlowStatusTable = (sql: SqlClient.SqlClient) =>\n Effect.gen(function* () {\n yield* 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 accepts text\n )`;\n yield* sql`\n ALTER TABLE entifix_flow_status ADD COLUMN IF NOT EXISTS accepts text`;\n }).pipe(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 accepts = ${\n patch.accepts === undefined ? null : JSON.stringify(patch.accepts)\n }\n WHERE flow_id = ${flowId}`.pipe(Effect.asVoid, Effect.mapError(fault)),\n\n claimWait: (flowId, token) =>\n sql<{ readonly flow_id: string }>`\n UPDATE entifix_flow_status\n SET state = 'running', step = ${token}, waiting_for = NULL,\n accepts = NULL\n WHERE flow_id = ${flowId} AND state = 'waiting' AND waiting_for = ${token}\n RETURNING flow_id`.pipe(\n Effect.map(rows => rows.length > 0),\n Effect.mapError(fault),\n ),\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","acceptsOf","text","parsed","JSON","parse","Array","isArray","map","String","recordOf","row","flowId","flow_id","executionId","execution_id","state","step","waiting_for","waitingFor","correlation","accepts","fault","error","ensureFlowStatusTable","sql","gen","pipe","mapError","makeSqlFlowStatusStore","register","key","record","inserted","undefined","existing","find","none","some","findByCorrelation","update","patch","stringify","asVoid","claimWait","token","rows","length","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,
|
|
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 isTerminalFlowState,\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 /** The parked wait's outcomes, as a JSON array. */\n readonly accepts: string | null;\n};\n\nconst acceptsOf = (text: string): readonly string[] => {\n const parsed: unknown = JSON.parse(text);\n return Array.isArray(parsed) ? parsed.map(String) : [];\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 ...(row.accepts === null ? {} : { accepts: acceptsOf(row.accepts) }),\n});\n\nconst fault = (error: unknown) => translateSqlError(error);\n\n/**\n * Creates the flow status table if it is missing, and adds a column a table\n * created by an earlier release lacks. Idempotent.\n */\nexport const ensureFlowStatusTable = (sql: SqlClient.SqlClient) =>\n Effect.gen(function* () {\n yield* 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 accepts text,\n terminal_at timestamptz,\n purged_at timestamptz\n )`;\n yield* sql`\n ALTER TABLE entifix_flow_status ADD COLUMN IF NOT EXISTS accepts text`;\n yield* sql`\n ALTER TABLE entifix_flow_status\n ADD COLUMN IF NOT EXISTS terminal_at timestamptz`;\n yield* sql`\n ALTER TABLE entifix_flow_status\n ADD COLUMN IF NOT EXISTS purged_at timestamptz`;\n // What the journal purge walks: ended flows whose journal is still held.\n yield* sql`\n CREATE INDEX IF NOT EXISTS entifix_flow_status_terminal_at\n ON entifix_flow_status (terminal_at) WHERE purged_at IS NULL`;\n }).pipe(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\n // flow's row — the journal purge empties its payload and keeps it.\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 accepts = ${\n patch.accepts === undefined ? null : JSON.stringify(patch.accepts)\n },\n -- When the flow ended, kept from the first terminal write: the\n -- journal purge counts its retention from here.\n terminal_at = CASE WHEN ${isTerminalFlowState(patch.state)}\n THEN COALESCE(terminal_at, now()) END\n WHERE flow_id = ${flowId}`.pipe(Effect.asVoid, Effect.mapError(fault)),\n\n claimWait: (flowId, token) =>\n sql<{ readonly flow_id: string }>`\n UPDATE entifix_flow_status\n SET state = 'running', step = ${token}, waiting_for = NULL,\n accepts = NULL\n WHERE flow_id = ${flowId} AND state = 'waiting' AND waiting_for = ${token}\n RETURNING flow_id`.pipe(\n Effect.map(rows => rows.length > 0),\n Effect.mapError(fault),\n ),\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","isTerminalFlowState","acceptsOf","text","parsed","JSON","parse","Array","isArray","map","String","recordOf","row","flowId","flow_id","executionId","execution_id","state","step","waiting_for","waitingFor","correlation","accepts","fault","error","ensureFlowStatusTable","sql","gen","pipe","mapError","makeSqlFlowStatusStore","register","key","record","inserted","undefined","existing","find","none","some","findByCorrelation","update","patch","stringify","asVoid","claimWait","token","rows","length","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,EAClBC,mBAAmB,QACd,iCAAiC;AAexC,MAAMC,YAAY,CAACC;IACjB,MAAMC,SAAkBC,KAAKC,KAAK,CAACH;IACnC,OAAOI,MAAMC,OAAO,CAACJ,UAAUA,OAAOK,GAAG,CAACC,UAAU,EAAE;AACxD;AAEA,MAAMC,WAAW,CAACC,MAAoC;QACpDC,QAAQD,IAAIE,OAAO;QACnBC,aAAaH,IAAII,YAAY;QAC7BC,OAAOL,IAAIK,KAAK;OACZL,IAAIM,IAAI,KAAK,OAAO,CAAC,IAAI;QAAEA,MAAMN,IAAIM,IAAI;IAAC,GAC1CN,IAAIO,WAAW,KAAK,OAAO,CAAC,IAAI;QAAEC,YAAYR,IAAIO,WAAW;IAAC,GAC9DP,IAAIS,WAAW,KAAK,OAAO,CAAC,IAAI;QAAEA,aAAaT,IAAIS,WAAW;IAAC,GAC/DT,IAAIU,OAAO,KAAK,OAAO,CAAC,IAAI;QAAEA,SAASpB,UAAUU,IAAIU,OAAO;IAAE;AAGpE,MAAMC,QAAQ,CAACC,QAAmB7B,kBAAkB6B;AAEpD;;;CAGC,GACD,OAAO,MAAMC,wBAAwB,CAACC,MACpC9B,OAAO+B,GAAG,CA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AQuB,YAAYrC,OAAOwC,IAAI,KAAKxC,OAAOyC,IAAI,CAAC5B,SAASC,QAE3DhB,OAAOiC,QAAQ,CAACN;QAGpBkB,QAAQ,CAAC5B,QAAQ6B;gBAGwBA,aACjBA,mBACAA;mBAJtBhB,GAAG,CAAC;;kBAEU,EAAEgB,MAAMzB,KAAK,CAAC,SAAS,GAAEyB,cAAAA,MAAMxB,IAAI,YAAVwB,cAAc,KAAK;wBACtC,GAAEA,oBAAAA,MAAMtB,UAAU,YAAhBsB,oBAAoB,KAAK;wBAC3B,GAAEA,qBAAAA,MAAMrB,WAAW,YAAjBqB,qBAAqB,KAAK;oBAChC,EACRA,MAAMpB,OAAO,KAAKa,YAAY,OAAO9B,KAAKsC,SAAS,CAACD,MAAMpB,OAAO,EAClE;;;kCAGuB,EAAErB,oBAAoByC,MAAMzB,KAAK,EAAE;;sBAE/C,EAAEJ,OAAO,CAAC,CAACe,IAAI,CAAChC,OAAOgD,MAAM,EAAEhD,OAAOiC,QAAQ,CAACN;;QAEnEsB,WAAW,CAAChC,QAAQiC,QAClBpB,GAAiC,CAAC;;oCAEF,EAAEoB,MAAM;;sBAEtB,EAAEjC,OAAO,yCAAyC,EAAEiC,MAAM;uBACzD,CAAC,CAAClB,IAAI,CACvBhC,OAAOa,GAAG,CAACsC,CAAAA,OAAQA,KAAKC,MAAM,GAAG,IACjCpD,OAAOiC,QAAQ,CAACN;IAEtB,CAAA,EAAG;AAEH,iEAAiE,GACjE,OAAO,MAAM0B,0BAA0BpD,MAAMqD,MAAM,CACjDlD,oBACAJ,OAAO+B,GAAG,CAAC;IACT,MAAMD,MAAM,OAAO3B,UAAUA,SAAS;IACtC,OAAO0B,sBAAsBC;IAC7B,OAAOI,uBAAuBJ;AAChC,IACA"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Layer } from 'effect';
|
|
2
2
|
import { type ShardingConfig } from 'effect/cluster';
|
|
3
3
|
import type { InterpreterOptions } from '../interpreter/slip-workflow.js';
|
|
4
|
+
import { type JournalRetention } from '../postgres/journal-retention.js';
|
|
4
5
|
export interface SocketRunnerOptions {
|
|
5
6
|
/** Where the other runners reach this one, and where it listens. */
|
|
6
7
|
readonly host: string;
|
|
@@ -18,7 +19,8 @@ export interface SocketRunnerOptions {
|
|
|
18
19
|
* ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)):
|
|
19
20
|
* runners register in the shared SQL database, shards are spread between
|
|
20
21
|
* them, and a runner that dies has its flows resumed by another. Every
|
|
21
|
-
* replica runs this with its own port
|
|
22
|
+
* replica runs this with its own port, and each one purges finished flows'
|
|
23
|
+
* journals after `journalRetention` — a pass skips rows another holds.
|
|
22
24
|
*/
|
|
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>;
|
|
25
|
+
export declare const SocketRunnerFlowEngineLayer: (options: InterpreterOptions & JournalRetention, runner: SocketRunnerOptions) => Layer.Layer<import("@entifix/transactions").FlowEngineTag, import("@entifix/core").StoreFailure | import("../postgres/journal-retention.js").JournalRetentionUnset | 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
26
|
//# sourceMappingURL=socket-runner.d.ts.map
|
|
@@ -1 +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;
|
|
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;AAC1E,OAAO,EAEL,KAAK,gBAAgB,EACtB,MAAM,kCAAkC,CAAC;AAG1C,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;;;;;;;GAOG;AACH,eAAO,MAAM,2BAA2B,GACtC,SAAS,kBAAkB,GAAG,gBAAgB,EAC9C,QAAQ,mBAAmB,uiBAoB1B,CAAC"}
|
|
@@ -3,14 +3,16 @@ import { NodeClusterSocket } from '@effect/platform-node';
|
|
|
3
3
|
import { Layer, Option } from 'effect';
|
|
4
4
|
import { ClusterWorkflowEngine, RunnerAddress } from 'effect/cluster';
|
|
5
5
|
import { FlowEngineLayer } from '../engine/make-flow-engine.js';
|
|
6
|
+
import { JournalPurgeLayer } from '../postgres/journal-retention.js';
|
|
6
7
|
import { SqlFlowStatusStoreLayer } from '../postgres/sql-flow-status-store.js';
|
|
7
8
|
/**
|
|
8
9
|
* The flow engine as one runner among several
|
|
9
10
|
* ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)):
|
|
10
11
|
* runners register in the shared SQL database, shards are spread between
|
|
11
12
|
* them, and a runner that dies has its flows resumed by another. Every
|
|
12
|
-
* replica runs this with its own port
|
|
13
|
-
|
|
13
|
+
* replica runs this with its own port, and each one purges finished flows'
|
|
14
|
+
* journals after `journalRetention` — a pass skips rows another holds.
|
|
15
|
+
*/ export const SocketRunnerFlowEngineLayer = (options, runner)=>FlowEngineLayer(options).pipe(Layer.merge(JournalPurgeLayer(options)), Layer.provide(SqlFlowStatusStoreLayer), Layer.provide(ClusterWorkflowEngine.layer.pipe(Layer.provide(NodeClusterSocket.layer({
|
|
14
16
|
storage: 'sql',
|
|
15
17
|
shardingConfig: _extends({}, runner.sharding, {
|
|
16
18
|
runnerAddress: Option.some(RunnerAddress.make(runner.host, runner.port))
|
|
@@ -1 +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
|
|
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 {\n JournalPurgeLayer,\n type JournalRetention,\n} from '../postgres/journal-retention.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, and each one purges finished flows'\n * journals after `journalRetention` — a pass skips rows another holds.\n */\nexport const SocketRunnerFlowEngineLayer = (\n options: InterpreterOptions & JournalRetention,\n runner: SocketRunnerOptions,\n) =>\n FlowEngineLayer(options).pipe(\n Layer.merge(JournalPurgeLayer(options)),\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","JournalPurgeLayer","SqlFlowStatusStoreLayer","SocketRunnerFlowEngineLayer","options","runner","pipe","merge","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,SACEC,iBAAiB,QAEZ,mCAAmC;AAC1C,SAASC,uBAAuB,QAAQ,uCAAuC;AAiB/E;;;;;;;CAOC,GACD,OAAO,MAAMC,8BAA8B,CACzCC,SACAC,SAEAL,gBAAgBI,SAASE,IAAI,CAC3BV,MAAMW,KAAK,CAACN,kBAAkBG,WAC9BR,MAAMY,OAAO,CAACN,0BACdN,MAAMY,OAAO,CACXV,sBAAsBW,KAAK,CAACH,IAAI,CAC9BV,MAAMY,OAAO,CACXb,kBAAkBc,KAAK,CAAC;QACtBC,SAAS;QACTC,gBAAgB,aACXN,OAAOO,QAAQ;YAClBC,eAAehB,OAAOiB,IAAI,CACxBf,cAAcgB,IAAI,CAACV,OAAOW,IAAI,EAAEX,OAAOY,IAAI;;IAGjD,OAIN"}
|
|
@@ -69,5 +69,12 @@ export declare class FlowStatusStoreTag extends FlowStatusStoreTag_base {
|
|
|
69
69
|
* life — specs, and the in-memory workflow engine.
|
|
70
70
|
*/
|
|
71
71
|
export declare const makeInMemoryFlowStatusStore: () => FlowStatusStore;
|
|
72
|
+
/**
|
|
73
|
+
* The states a flow ends in. Nothing resumes a flow from one, so its journal
|
|
74
|
+
* has nothing left to replay.
|
|
75
|
+
*/
|
|
76
|
+
export declare const TERMINAL_FLOW_STATES: readonly ["completed", "compensated", "failed", "interrupted", "stranded"];
|
|
77
|
+
/** Whether a flow in `state` has ended. */
|
|
78
|
+
export declare const isTerminalFlowState: (state: FlowState) => boolean;
|
|
72
79
|
export {};
|
|
73
80
|
//# sourceMappingURL=flow-status-store.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow-status-store.d.ts","sourceRoot":"","sources":["../../src/status/flow-status-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEzD;;;;;;;GAOG;AACH,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,+CAA+C;IAC/C,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC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 @@ export class FlowStatusStoreTag extends Context.Service()('@entifix/workflow/Flo
|
|
|
61
61
|
})
|
|
62
62
|
};
|
|
63
63
|
};
|
|
64
|
+
/**
|
|
65
|
+
* The states a flow ends in. Nothing resumes a flow from one, so its journal
|
|
66
|
+
* has nothing left to replay.
|
|
67
|
+
*/ export const TERMINAL_FLOW_STATES = [
|
|
68
|
+
'completed',
|
|
69
|
+
'compensated',
|
|
70
|
+
'failed',
|
|
71
|
+
'interrupted',
|
|
72
|
+
'stranded'
|
|
73
|
+
];
|
|
74
|
+
/** Whether a flow in `state` has ended. */ export const isTerminalFlowState = (state)=>TERMINAL_FLOW_STATES.includes(state);
|
|
64
75
|
|
|
65
76
|
//# sourceMappingURL=flow-status-store.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/status/flow-status-store.ts"],"sourcesContent":["import type { StoreFailure } from '@entifix/core';\nimport type { FlowState } from '@entifix/transactions';\nimport { Context, Effect, Metric, Option } from 'effect';\n\n/**\n * What the engine knows about one flow beyond its journal: the state a reader\n * is answered with, the step it is at, and the wait it is parked on.\n *\n * Kept beside the journal because the journal answers \"did it finish\" and\n * nothing finer — a flow parked on a signal and one mid-call look the same to\n * it, and a signal must be refused unless the flow is waiting for exactly it.\n */\nexport interface FlowRecord {\n readonly flowId: string;\n /** The workflow execution the flow runs as. */\n readonly executionId: string;\n readonly state: FlowState;\n readonly step?: string;\n /** The step whose signal the flow waits for, while `state` is `waiting`. */\n readonly waitingFor?: string;\n /** What that wait is correlated with — the order a delivery flow follows. */\n readonly correlation?: string;\n /**\n * The outcomes that wait is answered with, when it declares them: a\n * correlated signal naming another is refused rather than taken.\n */\n readonly accepts?: readonly string[];\n}\n\n/** A change to a flow's record: its new state, and where it now stands. */\nexport interface FlowRecordPatch {\n readonly state: FlowState;\n readonly step?: string;\n readonly waitingFor?: string;\n readonly correlation?: string;\n readonly accepts?: readonly string[];\n}\n\nexport interface FlowStatusStore {\n /**\n * Records a flow under its idempotency key, unless the key already names\n * one — then that flow is answered and nothing is written, so a repeated\n * start finds the flow the first one started.\n */\n readonly register: (\n key: string,\n record: FlowRecord,\n ) => Effect.Effect<FlowRecord, StoreFailure>;\n readonly find: (\n flowId: string,\n ) => Effect.Effect<Option.Option<FlowRecord>, StoreFailure>;\n /** The flow parked on a wait correlated with `correlation`, if one is. */\n readonly findByCorrelation: (\n correlation: string,\n ) => Effect.Effect<Option.Option<FlowRecord>, StoreFailure>;\n readonly update: (\n flowId: string,\n patch: FlowRecordPatch,\n ) => Effect.Effect<void, StoreFailure>;\n /**\n * Moves a flow parked on `token` to `running`, and answers whether it was\n * parked on it. The one conditional write a signal makes, and it is made\n * **before** the wait is resumed: written after, it could land behind the\n * resumed flow's own writes and put a finished flow back to `running` for\n * good. Two signals racing one wait claim it once.\n */\n readonly claimWait: (\n flowId: string,\n token: string,\n ) => Effect.Effect<boolean, StoreFailure>;\n}\n\n/**\n * Every state the interpreter journals a flow into, by state and the slice it\n * runs for. Counted inside the Activity that records it, so a replay — which\n * reads the journal rather than executing again — never counts a state twice.\n * `suspended` is the series to alert on: a flow past its commit point that\n * cannot go on, which a person has to look at.\n */\nexport const flowStates = Metric.counter('entifix_flow_states_total', {\n description: 'Flow states the interpreter journaled, by state and source.',\n});\n\nexport class FlowStatusStoreTag extends Context.Service<\n FlowStatusStoreTag,\n FlowStatusStore\n>()('@entifix/workflow/FlowStatusStore') {}\n\n/**\n * A status store in memory, for a single process that keeps no flow past its\n * life — specs, and the in-memory workflow engine.\n */\nexport const makeInMemoryFlowStatusStore = (): FlowStatusStore => {\n const byKey = new Map<string, string>();\n const records = new Map<string, FlowRecord>();\n return {\n register: (key, record) =>\n Effect.sync(() => {\n const known = byKey.get(key);\n if (known !== undefined) return records.get(known) as FlowRecord;\n byKey.set(key, record.flowId);\n records.set(record.flowId, record);\n return record;\n }),\n find: flowId =>\n Effect.sync(() => Option.fromNullishOr(records.get(flowId))),\n findByCorrelation: correlation =>\n Effect.sync(() =>\n Option.fromNullishOr(\n [...records.values()].find(\n record => record.correlation === correlation,\n ),\n ),\n ),\n update: (flowId, patch) =>\n Effect.sync(() => {\n const current = records.get(flowId);\n if (current === undefined) return;\n records.set(flowId, {\n flowId: current.flowId,\n executionId: current.executionId,\n state: patch.state,\n ...(patch.step === undefined ? {} : { step: patch.step }),\n ...(patch.waitingFor === undefined\n ? {}\n : { waitingFor: patch.waitingFor }),\n ...(patch.correlation === undefined\n ? {}\n : { correlation: patch.correlation }),\n ...(patch.accepts === undefined ? {} : { accepts: patch.accepts }),\n });\n }),\n claimWait: (flowId, token) =>\n Effect.sync(() => {\n const current = records.get(flowId);\n if (current?.state !== 'waiting' || current.waitingFor !== token)\n return false;\n records.set(flowId, {\n flowId: current.flowId,\n executionId: current.executionId,\n state: 'running',\n step: token,\n ...(current.correlation === undefined\n ? {}\n : { correlation: current.correlation }),\n });\n return true;\n }),\n };\n};\n"],"names":["Context","Effect","Metric","Option","flowStates","counter","description","FlowStatusStoreTag","Service","makeInMemoryFlowStatusStore","byKey","Map","records","register","key","record","sync","known","get","undefined","set","flowId","find","fromNullishOr","findByCorrelation","correlation","values","update","patch","current","executionId","state","step","waitingFor","accepts","claimWait","token"],"mappings":";AAEA,SAASA,OAAO,EAAEC,MAAM,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAsEzD;;;;;;CAMC,GACD,OAAO,MAAMC,aAAaF,OAAOG,OAAO,CAAC,6BAA6B;IACpEC,aAAa;AACf,GAAG;AAEH,OAAO,MAAMC,2BAA2BP,QAAQQ,OAAO,GAGnD;AAAsC;AAE1C;;;CAGC,GACD,OAAO,MAAMC,8BAA8B;IACzC,MAAMC,QAAQ,IAAIC;IAClB,MAAMC,UAAU,IAAID;IACpB,OAAO;QACLE,UAAU,CAACC,KAAKC,SACdd,OAAOe,IAAI,CAAC;gBACV,MAAMC,QAAQP,MAAMQ,GAAG,CAACJ;gBACxB,IAAIG,UAAUE,WAAW,OAAOP,QAAQM,GAAG,CAACD;gB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,WAAW;oBAChCC,OAAO;oBACPC,MAAMI;mBACFP,QAAQJ,WAAW,KAAKN,YACxB,CAAC,IACD;oBAAEM,aAAaI,QAAQJ,WAAW;gBAAC;gBAEzC,OAAO;YACT;IACJ;AACF,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../src/status/flow-status-store.ts"],"sourcesContent":["import type { StoreFailure } from '@entifix/core';\nimport type { FlowState } from '@entifix/transactions';\nimport { Context, Effect, Metric, Option } from 'effect';\n\n/**\n * What the engine knows about one flow beyond its journal: the state a reader\n * is answered with, the step it is at, and the wait it is parked on.\n *\n * Kept beside the journal because the journal answers \"did it finish\" and\n * nothing finer — a flow parked on a signal and one mid-call look the same to\n * it, and a signal must be refused unless the flow is waiting for exactly it.\n */\nexport interface FlowRecord {\n readonly flowId: string;\n /** The workflow execution the flow runs as. */\n readonly executionId: string;\n readonly state: FlowState;\n readonly step?: string;\n /** The step whose signal the flow waits for, while `state` is `waiting`. */\n readonly waitingFor?: string;\n /** What that wait is correlated with — the order a delivery flow follows. */\n readonly correlation?: string;\n /**\n * The outcomes that wait is answered with, when it declares them: a\n * correlated signal naming another is refused rather than taken.\n */\n readonly accepts?: readonly string[];\n}\n\n/** A change to a flow's record: its new state, and where it now stands. */\nexport interface FlowRecordPatch {\n readonly state: FlowState;\n readonly step?: string;\n readonly waitingFor?: string;\n readonly correlation?: string;\n readonly accepts?: readonly string[];\n}\n\nexport interface FlowStatusStore {\n /**\n * Records a flow under its idempotency key, unless the key already names\n * one — then that flow is answered and nothing is written, so a repeated\n * start finds the flow the first one started.\n */\n readonly register: (\n key: string,\n record: FlowRecord,\n ) => Effect.Effect<FlowRecord, StoreFailure>;\n readonly find: (\n flowId: string,\n ) => Effect.Effect<Option.Option<FlowRecord>, StoreFailure>;\n /** The flow parked on a wait correlated with `correlation`, if one is. */\n readonly findByCorrelation: (\n correlation: string,\n ) => Effect.Effect<Option.Option<FlowRecord>, StoreFailure>;\n readonly update: (\n flowId: string,\n patch: FlowRecordPatch,\n ) => Effect.Effect<void, StoreFailure>;\n /**\n * Moves a flow parked on `token` to `running`, and answers whether it was\n * parked on it. The one conditional write a signal makes, and it is made\n * **before** the wait is resumed: written after, it could land behind the\n * resumed flow's own writes and put a finished flow back to `running` for\n * good. Two signals racing one wait claim it once.\n */\n readonly claimWait: (\n flowId: string,\n token: string,\n ) => Effect.Effect<boolean, StoreFailure>;\n}\n\n/**\n * Every state the interpreter journals a flow into, by state and the slice it\n * runs for. Counted inside the Activity that records it, so a replay — which\n * reads the journal rather than executing again — never counts a state twice.\n * `suspended` is the series to alert on: a flow past its commit point that\n * cannot go on, which a person has to look at.\n */\nexport const flowStates = Metric.counter('entifix_flow_states_total', {\n description: 'Flow states the interpreter journaled, by state and source.',\n});\n\nexport class FlowStatusStoreTag extends Context.Service<\n FlowStatusStoreTag,\n FlowStatusStore\n>()('@entifix/workflow/FlowStatusStore') {}\n\n/**\n * A status store in memory, for a single process that keeps no flow past its\n * life — specs, and the in-memory workflow engine.\n */\nexport const makeInMemoryFlowStatusStore = (): FlowStatusStore => {\n const byKey = new Map<string, string>();\n const records = new Map<string, FlowRecord>();\n return {\n register: (key, record) =>\n Effect.sync(() => {\n const known = byKey.get(key);\n if (known !== undefined) return records.get(known) as FlowRecord;\n byKey.set(key, record.flowId);\n records.set(record.flowId, record);\n return record;\n }),\n find: flowId =>\n Effect.sync(() => Option.fromNullishOr(records.get(flowId))),\n findByCorrelation: correlation =>\n Effect.sync(() =>\n Option.fromNullishOr(\n [...records.values()].find(\n record => record.correlation === correlation,\n ),\n ),\n ),\n update: (flowId, patch) =>\n Effect.sync(() => {\n const current = records.get(flowId);\n if (current === undefined) return;\n records.set(flowId, {\n flowId: current.flowId,\n executionId: current.executionId,\n state: patch.state,\n ...(patch.step === undefined ? {} : { step: patch.step }),\n ...(patch.waitingFor === undefined\n ? {}\n : { waitingFor: patch.waitingFor }),\n ...(patch.correlation === undefined\n ? {}\n : { correlation: patch.correlation }),\n ...(patch.accepts === undefined ? {} : { accepts: patch.accepts }),\n });\n }),\n claimWait: (flowId, token) =>\n Effect.sync(() => {\n const current = records.get(flowId);\n if (current?.state !== 'waiting' || current.waitingFor !== token)\n return false;\n records.set(flowId, {\n flowId: current.flowId,\n executionId: current.executionId,\n state: 'running',\n step: token,\n ...(current.correlation === undefined\n ? {}\n : { correlation: current.correlation }),\n });\n return true;\n }),\n };\n};\n\n/**\n * The states a flow ends in. Nothing resumes a flow from one, so its journal\n * has nothing left to replay.\n */\nexport const TERMINAL_FLOW_STATES = [\n 'completed',\n 'compensated',\n 'failed',\n 'interrupted',\n 'stranded',\n] as const satisfies readonly FlowState[];\n\n/** Whether a flow in `state` has ended. */\nexport const isTerminalFlowState = (state: FlowState): boolean =>\n (TERMINAL_FLOW_STATES as readonly FlowState[]).includes(state);\n"],"names":["Context","Effect","Metric","Option","flowStates","counter","description","FlowStatusStoreTag","Service","makeInMemoryFlowStatusStore","byKey","Map","records","register","key","record","sync","known","get","undefined","set","flowId","find","fromNullishOr","findByCorrelation","correlation","values","update","patch","current","executionId","state","step","waitingFor","accepts","claimWait","token","TERMINAL_FLOW_STATES","isTerminalFlowState","includes"],"mappings":";AAEA,SAASA,OAAO,EAAEC,MAAM,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAsEzD;;;;;;CAMC,GACD,OAAO,MAAMC,aAAaF,OAAOG,OAAO,CAAC,6BAA6B;IACpEC,aAAa;AACf,GAAG;AAEH,OAAO,MAAMC,2BAA2BP,QAAQQ,OAAO,GAGnD;AAAsC;AAE1C;;;CAGC,GACD,OAAO,MAAMC,8BAA8B;IACzC,MAAMC,QAAQ,IAAIC;IAClB,MAAMC,UAAU,IAAID;IACpB,OAAO;QACLE,UAAU,CAACC,KAAKC,SACdd,OAAOe,IAAI,CAAC;gBACV,MAAMC,QAAQP,MAAMQ,GAAG,CAACJ;gBACxB,IAAIG,UAAUE,WAAW,OAAOP,QAAQM,GAAG,CAACD;gBAC5CP,MAAMU,GAAG,CAACN,KAAKC,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I;mBACFP,QAAQJ,WAAW,KAAKN,YACxB,CAAC,IACD;oBAAEM,aAAaI,QAAQJ,WAAW;gBAAC;gBAEzC,OAAO;YACT;IACJ;AACF,EAAE;AAEF;;;CAGC,GACD,OAAO,MAAMY,uBAAuB;IAClC;IACA;IACA;IACA;IACA;CACD,CAAyC;AAE1C,yCAAyC,GACzC,OAAO,MAAMC,sBAAsB,CAACP,QAClC,AAACM,qBAA8CE,QAAQ,CAACR,OAAO"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@entifix/workflow",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.22.1",
|
|
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.
|
|
93
|
-
"@entifix/core": "0.
|
|
94
|
-
"@entifix/sql": "0.
|
|
95
|
-
"@entifix/transactions": "0.
|
|
92
|
+
"@entifix/business": "0.22.1",
|
|
93
|
+
"@entifix/core": "0.22.1",
|
|
94
|
+
"@entifix/sql": "0.22.1",
|
|
95
|
+
"@entifix/transactions": "0.22.1"
|
|
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.
|
|
101
|
+
"@entifix/testing-unit": "0.22.1"
|
|
102
102
|
},
|
|
103
103
|
"peerDependencies": {
|
|
104
104
|
"@effect/platform-node": "^4.0.7",
|