@typeonce/effect-machine 0.47.1 → 0.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +374 -22
- package/CLAUDE.md +374 -22
- package/README.md +56 -7
- package/ai-docs/src/10_modeling/01_create-a-machine.ts +3 -3
- package/ai-docs/src/10_modeling/index.md +64 -17
- package/ai-docs/src/20_root-api/index.md +2 -2
- package/ai-docs/src/35_cluster/index.md +213 -0
- package/ai-docs/src/37_new-host/index.md +90 -0
- package/dist/LocalMachine.d.ts +417 -0
- package/dist/LocalMachine.d.ts.map +1 -0
- package/dist/LocalMachine.js +193 -0
- package/dist/LocalMachine.js.map +1 -0
- package/dist/Machine.d.ts +1120 -812
- package/dist/Machine.d.ts.map +1 -1
- package/dist/Machine.js +195 -186
- package/dist/Machine.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/internal/machine/atom.d.ts +8 -10
- package/dist/internal/machine/atom.d.ts.map +1 -1
- package/dist/internal/machine/atom.js +7 -6
- package/dist/internal/machine/atom.js.map +1 -1
- package/dist/internal/machine/capability.d.ts +101 -0
- package/dist/internal/machine/capability.d.ts.map +1 -0
- package/dist/internal/machine/capability.js +70 -0
- package/dist/internal/machine/capability.js.map +1 -0
- package/dist/internal/machine/{invocationDefinition.d.ts → capturedInvocation.d.ts} +11 -11
- package/dist/internal/machine/capturedInvocation.d.ts.map +1 -0
- package/dist/internal/machine/{invocationDefinition.js → capturedInvocation.js} +2 -2
- package/dist/internal/machine/capturedInvocation.js.map +1 -0
- package/dist/internal/machine/child.d.ts +14 -0
- package/dist/internal/machine/child.d.ts.map +1 -0
- package/dist/internal/machine/child.js +19 -0
- package/dist/internal/machine/child.js.map +1 -0
- package/dist/internal/machine/childRegistry.d.ts +0 -2
- package/dist/internal/machine/childRegistry.d.ts.map +1 -1
- package/dist/internal/machine/childRegistry.js +2 -2
- package/dist/internal/machine/childRegistry.js.map +1 -1
- package/dist/internal/machine/cluster.d.ts +19 -4
- package/dist/internal/machine/cluster.d.ts.map +1 -1
- package/dist/internal/machine/cluster.js +263 -110
- package/dist/internal/machine/cluster.js.map +1 -1
- package/dist/internal/machine/clusterChild.d.ts +66 -0
- package/dist/internal/machine/clusterChild.d.ts.map +1 -0
- package/dist/internal/machine/clusterChild.js +105 -0
- package/dist/internal/machine/clusterChild.js.map +1 -0
- package/dist/internal/machine/clusterFailure.d.ts +14 -0
- package/dist/internal/machine/clusterFailure.d.ts.map +1 -0
- package/dist/internal/machine/clusterFailure.js +44 -0
- package/dist/internal/machine/clusterFailure.js.map +1 -0
- package/dist/internal/machine/clusterInstance.d.ts +194 -0
- package/dist/internal/machine/clusterInstance.d.ts.map +1 -0
- package/dist/internal/machine/clusterInstance.js +1076 -0
- package/dist/internal/machine/clusterInstance.js.map +1 -0
- package/dist/internal/machine/clusterKeepAlive.d.ts +47 -0
- package/dist/internal/machine/clusterKeepAlive.d.ts.map +1 -0
- package/dist/internal/machine/clusterKeepAlive.js +72 -0
- package/dist/internal/machine/clusterKeepAlive.js.map +1 -0
- package/dist/internal/machine/clusterProgress.d.ts +73 -0
- package/dist/internal/machine/clusterProgress.d.ts.map +1 -0
- package/dist/internal/machine/clusterProgress.js +116 -0
- package/dist/internal/machine/clusterProgress.js.map +1 -0
- package/dist/internal/machine/clusterProtocol.d.ts +37 -4
- package/dist/internal/machine/clusterProtocol.d.ts.map +1 -1
- package/dist/internal/machine/clusterProtocol.js +18 -4
- package/dist/internal/machine/clusterProtocol.js.map +1 -1
- package/dist/internal/machine/clusterProxy.d.ts +46 -0
- package/dist/internal/machine/clusterProxy.d.ts.map +1 -0
- package/dist/internal/machine/clusterProxy.js +150 -0
- package/dist/internal/machine/clusterProxy.js.map +1 -0
- package/dist/internal/machine/clusterRead.d.ts +61 -0
- package/dist/internal/machine/clusterRead.d.ts.map +1 -0
- package/dist/internal/machine/clusterRead.js +108 -0
- package/dist/internal/machine/clusterRead.js.map +1 -0
- package/dist/internal/machine/clusterSqlStorage.d.ts +16 -0
- package/dist/internal/machine/clusterSqlStorage.d.ts.map +1 -0
- package/dist/internal/machine/clusterSqlStorage.js +138 -0
- package/dist/internal/machine/clusterSqlStorage.js.map +1 -0
- package/dist/internal/machine/clusterStorageCheck.d.ts +19 -0
- package/dist/internal/machine/clusterStorageCheck.d.ts.map +1 -0
- package/dist/internal/machine/clusterStorageCheck.js +186 -0
- package/dist/internal/machine/clusterStorageCheck.js.map +1 -0
- package/dist/internal/machine/clusterTarget.d.ts +74 -0
- package/dist/internal/machine/clusterTarget.d.ts.map +1 -0
- package/dist/internal/machine/clusterTarget.js +81 -0
- package/dist/internal/machine/clusterTarget.js.map +1 -0
- package/dist/internal/machine/clusterTimer.d.ts +21 -0
- package/dist/internal/machine/clusterTimer.d.ts.map +1 -0
- package/dist/internal/machine/clusterTimer.js +50 -0
- package/dist/internal/machine/clusterTimer.js.map +1 -0
- package/dist/internal/machine/clusterWake.d.ts +61 -0
- package/dist/internal/machine/clusterWake.d.ts.map +1 -0
- package/dist/internal/machine/clusterWake.js +81 -0
- package/dist/internal/machine/clusterWake.js.map +1 -0
- package/dist/internal/machine/clusterWork.d.ts +130 -0
- package/dist/internal/machine/clusterWork.d.ts.map +1 -0
- package/dist/internal/machine/clusterWork.js +191 -0
- package/dist/internal/machine/clusterWork.js.map +1 -0
- package/dist/internal/machine/command.d.ts +4 -4
- package/dist/internal/machine/command.d.ts.map +1 -1
- package/dist/internal/machine/commandRuntime.d.ts +8 -6
- package/dist/internal/machine/commandRuntime.d.ts.map +1 -1
- package/dist/internal/machine/commandRuntime.js +1 -5
- package/dist/internal/machine/commandRuntime.js.map +1 -1
- package/dist/internal/machine/configuration.d.ts +0 -13
- package/dist/internal/machine/configuration.d.ts.map +1 -1
- package/dist/internal/machine/configuration.js +0 -151
- package/dist/internal/machine/configuration.js.map +1 -1
- package/dist/internal/machine/errors.d.ts +11 -2
- package/dist/internal/machine/errors.d.ts.map +1 -1
- package/dist/internal/machine/errors.js +11 -2
- package/dist/internal/machine/errors.js.map +1 -1
- package/dist/internal/machine/executionPlan.d.ts +45 -3
- package/dist/internal/machine/executionPlan.d.ts.map +1 -1
- package/dist/internal/machine/executionPlan.js +328 -191
- package/dist/internal/machine/executionPlan.js.map +1 -1
- package/dist/internal/machine/implementation.d.ts +6 -6
- package/dist/internal/machine/implementation.d.ts.map +1 -1
- package/dist/internal/machine/inspectionRuntime.d.ts +1 -1
- package/dist/internal/machine/inspectionRuntime.d.ts.map +1 -1
- package/dist/internal/machine/invocationChanges.d.ts +60 -0
- package/dist/internal/machine/invocationChanges.d.ts.map +1 -0
- package/dist/internal/machine/invocationChanges.js +54 -0
- package/dist/internal/machine/invocationChanges.js.map +1 -0
- package/dist/internal/machine/{activities.d.ts → invocationDefinitions.d.ts} +8 -8
- package/dist/internal/machine/invocationDefinitions.d.ts.map +1 -0
- package/dist/internal/machine/{activities.js → invocationDefinitions.js} +5 -5
- package/dist/internal/machine/invocationDefinitions.js.map +1 -0
- package/dist/internal/machine/invocationEvent.d.ts +16 -7
- package/dist/internal/machine/invocationEvent.d.ts.map +1 -1
- package/dist/internal/machine/invocationEvent.js +26 -12
- package/dist/internal/machine/invocationEvent.js.map +1 -1
- package/dist/internal/machine/invocationOutcome.d.ts +89 -0
- package/dist/internal/machine/invocationOutcome.d.ts.map +1 -0
- package/dist/internal/machine/invocationOutcome.js +76 -0
- package/dist/internal/machine/invocationOutcome.js.map +1 -0
- package/dist/internal/machine/invocationResolution.d.ts +137 -0
- package/dist/internal/machine/invocationResolution.d.ts.map +1 -0
- package/dist/internal/machine/invocationResolution.js +150 -0
- package/dist/internal/machine/invocationResolution.js.map +1 -0
- package/dist/internal/machine/logicScope.d.ts +24 -0
- package/dist/internal/machine/logicScope.d.ts.map +1 -0
- package/dist/internal/machine/logicScope.js +33 -0
- package/dist/internal/machine/logicScope.js.map +1 -0
- package/dist/internal/machine/machine.d.ts +17 -23
- package/dist/internal/machine/machine.d.ts.map +1 -1
- package/dist/internal/machine/machine.js +24 -40
- package/dist/internal/machine/machine.js.map +1 -1
- package/dist/internal/machine/observation.d.ts +3 -0
- package/dist/internal/machine/observation.d.ts.map +1 -1
- package/dist/internal/machine/observation.js +56 -2
- package/dist/internal/machine/observation.js.map +1 -1
- package/dist/internal/machine/plannedSnapshot.d.ts.map +1 -1
- package/dist/internal/machine/plannedSnapshot.js +11 -20
- package/dist/internal/machine/plannedSnapshot.js.map +1 -1
- package/dist/internal/machine/planner.d.ts +36 -23
- package/dist/internal/machine/planner.d.ts.map +1 -1
- package/dist/internal/machine/planner.js +15 -8
- package/dist/internal/machine/planner.js.map +1 -1
- package/dist/internal/machine/process.d.ts +17 -9
- package/dist/internal/machine/process.d.ts.map +1 -1
- package/dist/internal/machine/process.js +43 -503
- package/dist/internal/machine/process.js.map +1 -1
- package/dist/internal/machine/protocol.d.ts +1 -1
- package/dist/internal/machine/protocol.d.ts.map +1 -1
- package/dist/internal/machine/protocol.js +48 -10
- package/dist/internal/machine/protocol.js.map +1 -1
- package/dist/internal/machine/runtime.d.ts +20 -16
- package/dist/internal/machine/runtime.d.ts.map +1 -1
- package/dist/internal/machine/runtime.js +93 -88
- package/dist/internal/machine/runtime.js.map +1 -1
- package/dist/internal/machine/runtimeCompiled.d.ts.map +1 -1
- package/dist/internal/machine/runtimeCompiled.js +359 -120
- package/dist/internal/machine/runtimeCompiled.js.map +1 -1
- package/dist/internal/machine/runtimeProtocol.d.ts +151 -82
- package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -1
- package/dist/internal/machine/runtimeProtocol.js +236 -219
- package/dist/internal/machine/runtimeProtocol.js.map +1 -1
- package/dist/internal/machine/stateDefinition.d.ts +0 -1
- package/dist/internal/machine/stateDefinition.d.ts.map +1 -1
- package/dist/internal/machine/stateDefinition.js +0 -1
- package/dist/internal/machine/stateDefinition.js.map +1 -1
- package/dist/internal/machine/step.d.ts +486 -0
- package/dist/internal/machine/step.d.ts.map +1 -0
- package/dist/internal/machine/step.js +957 -0
- package/dist/internal/machine/step.js.map +1 -0
- package/dist/internal/machine/stepHost.d.ts +33 -0
- package/dist/internal/machine/stepHost.d.ts.map +1 -0
- package/dist/internal/machine/stepHost.js +501 -0
- package/dist/internal/machine/stepHost.js.map +1 -0
- package/dist/internal/machine/symbols.d.ts +2 -11
- package/dist/internal/machine/symbols.d.ts.map +1 -1
- package/dist/internal/machine/symbols.js +2 -2
- package/dist/internal/machine/symbols.js.map +1 -1
- package/dist/internal/machine/transition.d.ts +7 -7
- package/dist/internal/machine/transition.d.ts.map +1 -1
- package/dist/internal/testing/machine/check.d.ts.map +1 -1
- package/dist/internal/testing/machine/check.js +217 -25
- package/dist/internal/testing/machine/check.js.map +1 -1
- package/dist/internal/testing/machine/exploration.d.ts +19 -2
- package/dist/internal/testing/machine/exploration.d.ts.map +1 -1
- package/dist/internal/testing/machine/exploration.js +14 -3
- package/dist/internal/testing/machine/exploration.js.map +1 -1
- package/dist/internal/testing/machine/format.js.map +1 -1
- package/dist/internal/testing/machine/probe.d.ts.map +1 -1
- package/dist/internal/testing/machine/probe.js +1 -1
- package/dist/internal/testing/machine/probe.js.map +1 -1
- package/dist/internal/testing/machine/runtime.d.ts +2 -2
- package/dist/internal/testing/machine/runtime.d.ts.map +1 -1
- package/dist/internal/testing/machine/runtime.js +10 -3
- package/dist/internal/testing/machine/runtime.js.map +1 -1
- package/dist/internal/testing/machine/trace.d.ts +38 -3
- package/dist/internal/testing/machine/trace.d.ts.map +1 -1
- package/dist/internal/testing/machine/trace.js +180 -33
- package/dist/internal/testing/machine/trace.js.map +1 -1
- package/dist/internal/testing/machine/transitionCoverage.d.ts +1 -1
- package/dist/internal/testing/machine/transitionCoverage.d.ts.map +1 -1
- package/dist/internal/testing/machine/verification.d.ts.map +1 -1
- package/dist/internal/testing/machine/verification.js +9 -1
- package/dist/internal/testing/machine/verification.js.map +1 -1
- package/dist/internal/testing/machine/work.d.ts +47 -0
- package/dist/internal/testing/machine/work.d.ts.map +1 -0
- package/dist/internal/testing/machine/work.js +74 -0
- package/dist/internal/testing/machine/work.js.map +1 -0
- package/dist/testing/MachineTest.d.ts +253 -37
- package/dist/testing/MachineTest.d.ts.map +1 -1
- package/dist/testing/MachineTest.js +81 -9
- package/dist/testing/MachineTest.js.map +1 -1
- package/dist/unstable/cluster/ClusterMachine.d.ts +1071 -41
- package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
- package/dist/unstable/cluster/ClusterMachine.js +441 -12
- package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
- package/dist/unstable/cluster/ClusterMachineProxy.d.ts +257 -0
- package/dist/unstable/cluster/ClusterMachineProxy.d.ts.map +1 -0
- package/dist/unstable/cluster/ClusterMachineProxy.js +73 -0
- package/dist/unstable/cluster/ClusterMachineProxy.js.map +1 -0
- package/dist/unstable/cluster/SqlMachineStorage.d.ts +125 -0
- package/dist/unstable/cluster/SqlMachineStorage.d.ts.map +1 -0
- package/dist/unstable/cluster/SqlMachineStorage.js +62 -0
- package/dist/unstable/cluster/SqlMachineStorage.js.map +1 -0
- package/dist/unstable/cluster/index.d.ts +13 -0
- package/dist/unstable/cluster/index.d.ts.map +1 -1
- package/dist/unstable/cluster/index.js +13 -0
- package/dist/unstable/cluster/index.js.map +1 -1
- package/dist/unstable/reactivity/AtomMachine.d.ts +21 -26
- package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
- package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
- package/package.json +5 -3
- package/src/LocalMachine.ts +611 -0
- package/src/Machine.ts +1379 -1334
- package/src/index.ts +1 -0
- package/src/internal/machine/atom.ts +20 -49
- package/src/internal/machine/capability.ts +123 -0
- package/src/internal/machine/{invocationDefinition.ts → capturedInvocation.ts} +13 -13
- package/src/internal/machine/child.ts +25 -0
- package/src/internal/machine/childRegistry.ts +1 -4
- package/src/internal/machine/cluster.ts +420 -205
- package/src/internal/machine/clusterChild.ts +117 -0
- package/src/internal/machine/clusterFailure.ts +53 -0
- package/src/internal/machine/clusterInstance.ts +1779 -0
- package/src/internal/machine/clusterKeepAlive.ts +93 -0
- package/src/internal/machine/clusterProgress.ts +159 -0
- package/src/internal/machine/clusterProtocol.ts +46 -4
- package/src/internal/machine/clusterProxy.ts +233 -0
- package/src/internal/machine/clusterRead.ts +207 -0
- package/src/internal/machine/clusterSqlStorage.ts +181 -0
- package/src/internal/machine/clusterStorageCheck.ts +274 -0
- package/src/internal/machine/clusterTarget.ts +154 -0
- package/src/internal/machine/clusterTimer.ts +58 -0
- package/src/internal/machine/clusterWake.ts +100 -0
- package/src/internal/machine/clusterWork.ts +269 -0
- package/src/internal/machine/command.ts +4 -4
- package/src/internal/machine/commandRuntime.ts +12 -24
- package/src/internal/machine/configuration.ts +0 -181
- package/src/internal/machine/errors.ts +11 -2
- package/src/internal/machine/executionPlan.ts +493 -263
- package/src/internal/machine/implementation.ts +6 -6
- package/src/internal/machine/inspectionRuntime.ts +1 -1
- package/src/internal/machine/invocationChanges.ts +89 -0
- package/src/internal/machine/{activities.ts → invocationDefinitions.ts} +10 -10
- package/src/internal/machine/invocationEvent.ts +35 -12
- package/src/internal/machine/invocationOutcome.ts +145 -0
- package/src/internal/machine/invocationResolution.ts +307 -0
- package/src/internal/machine/logicScope.ts +47 -0
- package/src/internal/machine/machine.ts +35 -100
- package/src/internal/machine/observation.ts +67 -2
- package/src/internal/machine/plannedSnapshot.ts +17 -20
- package/src/internal/machine/planner.ts +75 -99
- package/src/internal/machine/process.ts +78 -722
- package/src/internal/machine/protocol.ts +70 -26
- package/src/internal/machine/runtime.ts +198 -195
- package/src/internal/machine/runtimeCompiled.ts +496 -171
- package/src/internal/machine/runtimeProtocol.ts +416 -305
- package/src/internal/machine/stateDefinition.ts +0 -5
- package/src/internal/machine/step.ts +1518 -0
- package/src/internal/machine/stepHost.ts +634 -0
- package/src/internal/machine/symbols.ts +3 -14
- package/src/internal/machine/transition.ts +11 -11
- package/src/internal/testing/machine/check.ts +240 -36
- package/src/internal/testing/machine/exploration.ts +42 -3
- package/src/internal/testing/machine/format.ts +1 -1
- package/src/internal/testing/machine/probe.ts +2 -1
- package/src/internal/testing/machine/runtime.ts +15 -5
- package/src/internal/testing/machine/trace.ts +261 -41
- package/src/internal/testing/machine/transitionCoverage.ts +1 -1
- package/src/internal/testing/machine/verification.ts +11 -5
- package/src/internal/testing/machine/work.ts +101 -0
- package/src/testing/MachineTest.ts +268 -44
- package/src/unstable/cluster/ClusterMachine.ts +1183 -59
- package/src/unstable/cluster/ClusterMachineProxy.ts +372 -0
- package/src/unstable/cluster/SqlMachineStorage.ts +136 -0
- package/src/unstable/cluster/index.ts +15 -0
- package/src/unstable/reactivity/AtomMachine.ts +27 -88
- package/dist/internal/machine/activities.d.ts.map +0 -1
- package/dist/internal/machine/activities.js.map +0 -1
- package/dist/internal/machine/invocation.d.ts +0 -33
- package/dist/internal/machine/invocation.d.ts.map +0 -1
- package/dist/internal/machine/invocation.js +0 -220
- package/dist/internal/machine/invocation.js.map +0 -1
- package/dist/internal/machine/invocationDefinition.d.ts.map +0 -1
- package/dist/internal/machine/invocationDefinition.js.map +0 -1
- package/dist/internal/machine/requirements.d.ts +0 -4
- package/dist/internal/machine/requirements.d.ts.map +0 -1
- package/dist/internal/machine/requirements.js +0 -2
- package/dist/internal/machine/requirements.js.map +0 -1
- package/dist/internal/machine/runtimeGeneric.d.ts +0 -3
- package/dist/internal/machine/runtimeGeneric.d.ts.map +0 -1
- package/dist/internal/machine/runtimeGeneric.js +0 -465
- package/dist/internal/machine/runtimeGeneric.js.map +0 -1
- package/src/internal/machine/invocation.ts +0 -376
- package/src/internal/machine/requirements.ts +0 -11
- package/src/internal/machine/runtimeGeneric.ts +0 -797
|
@@ -0,0 +1,1076 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The live instance behind one active Cluster entity.
|
|
3
|
+
*
|
|
4
|
+
* @since 0.48.0
|
|
5
|
+
*/
|
|
6
|
+
import * as Cause from "effect/Cause";
|
|
7
|
+
import * as Clock from "effect/Clock";
|
|
8
|
+
import * as Data from "effect/Data";
|
|
9
|
+
import * as Deferred from "effect/Deferred";
|
|
10
|
+
import * as Effect from "effect/Effect";
|
|
11
|
+
import * as Exit from "effect/Exit";
|
|
12
|
+
import * as Option from "effect/Option";
|
|
13
|
+
import * as Predicate from "effect/Predicate";
|
|
14
|
+
import * as Schedule from "effect/Schedule";
|
|
15
|
+
import * as Semaphore from "effect/Semaphore";
|
|
16
|
+
import * as CapturedInvocation from "./capturedInvocation.js";
|
|
17
|
+
import * as ClusterChild from "./clusterChild.js";
|
|
18
|
+
import { renderFailure } from "./clusterFailure.js";
|
|
19
|
+
import { ClusterKeepAlive, untilDone } from "./clusterKeepAlive.js";
|
|
20
|
+
import * as ClusterProgress from "./clusterProgress.js";
|
|
21
|
+
import { Accepted, Rejected } from "./clusterProtocol.js";
|
|
22
|
+
import * as ClusterTarget from "./clusterTarget.js";
|
|
23
|
+
import * as ClusterTimer from "./clusterTimer.js";
|
|
24
|
+
import * as ClusterWork from "./clusterWork.js";
|
|
25
|
+
import * as Configuration from "./configuration.js";
|
|
26
|
+
import { ProcessLocalError } from "./errors.js";
|
|
27
|
+
import { toImpl } from "./implementation.js";
|
|
28
|
+
import * as internalMachine from "./machine.js";
|
|
29
|
+
import * as Planner from "./planner.js";
|
|
30
|
+
import * as Step from "./step.js";
|
|
31
|
+
/** Ends a step, rolling its transaction back. */
|
|
32
|
+
class Refused extends Data.TaggedError("Refused") {
|
|
33
|
+
}
|
|
34
|
+
/** Ends a step that was based on a state `Storage` no longer holds. */
|
|
35
|
+
class Conflicted extends Data.TaggedError("Conflicted") {
|
|
36
|
+
}
|
|
37
|
+
const reject = (reason, message) => new Rejected({ reason, message });
|
|
38
|
+
const fail = (reason, message) => Effect.fail(reject(reason, message));
|
|
39
|
+
const persistenceFailure = (error) => reject("PersistenceFailure", String(error.cause));
|
|
40
|
+
const messageFromCause = (cause) => {
|
|
41
|
+
const squashed = Cause.squash(cause);
|
|
42
|
+
return squashed instanceof globalThis.Error ? squashed.message : String(squashed);
|
|
43
|
+
};
|
|
44
|
+
const rejectionFromCause = (cause, reason) => {
|
|
45
|
+
const error = Cause.findErrorOption(cause);
|
|
46
|
+
if (Option.isSome(error) && error.value instanceof Rejected) {
|
|
47
|
+
return error.value;
|
|
48
|
+
}
|
|
49
|
+
if (Option.isSome(error) && error.value instanceof internalMachine.ProcessLocalError) {
|
|
50
|
+
return reject("UnsupportedProcessLocal", `${error.value.operation} is process-local and is not supported`);
|
|
51
|
+
}
|
|
52
|
+
return reject(reason, messageFromCause(cause));
|
|
53
|
+
};
|
|
54
|
+
const failureFromCause = (cause) => {
|
|
55
|
+
const error = Cause.findErrorOption(cause);
|
|
56
|
+
return Option.isSome(error) && error.value instanceof Rejected
|
|
57
|
+
? `${error.value.reason}: ${error.value.message}`
|
|
58
|
+
: renderFailure(cause);
|
|
59
|
+
};
|
|
60
|
+
/** Propagates an interruption without the typed failures that accompany it. */
|
|
61
|
+
const propagate = (cause) => Effect.failCause(Cause.fromReasons(cause.reasons.filter((reason) => !Cause.isFailReason(reason))));
|
|
62
|
+
/** Turns every failure of one stage of a step into a refusal. */
|
|
63
|
+
const refuse = (options) => (stage) => Effect.catchCause(stage, (cause) => Cause.hasInterrupts(cause)
|
|
64
|
+
? propagate(cause)
|
|
65
|
+
: Effect.fail(new Refused({
|
|
66
|
+
rejected: rejectionFromCause(cause, "TransitionFailure"),
|
|
67
|
+
memory: options.memory,
|
|
68
|
+
confirm: options.confirm,
|
|
69
|
+
failure: options.stage === "Decision" ? failureFromCause(cause) : undefined
|
|
70
|
+
})));
|
|
71
|
+
/** Reads the status of a checkpoint, whose store may hold anything. */
|
|
72
|
+
export const readStatus = (status) => {
|
|
73
|
+
if (!Predicate.hasProperty(status, "_tag"))
|
|
74
|
+
return undefined;
|
|
75
|
+
if (status._tag === "Failed") {
|
|
76
|
+
return Predicate.hasProperty(status, "failure") && Predicate.isString(status.failure)
|
|
77
|
+
? { _tag: "Failed", failure: status.failure }
|
|
78
|
+
: undefined;
|
|
79
|
+
}
|
|
80
|
+
if (status._tag === "Stopped")
|
|
81
|
+
return { _tag: "Stopped" };
|
|
82
|
+
if (status._tag !== "Active" || !Predicate.hasProperty(status, "invocations"))
|
|
83
|
+
return undefined;
|
|
84
|
+
const progress = ClusterProgress.fromStored(status.invocations);
|
|
85
|
+
return progress && { _tag: "Active", progress };
|
|
86
|
+
};
|
|
87
|
+
const absent = { _tag: "Absent", revision: 0 };
|
|
88
|
+
const progressOf = (memory) => memory._tag === "Active" ? memory.progress : ClusterProgress.empty;
|
|
89
|
+
const accepted = new Accepted({});
|
|
90
|
+
const refuseLocal = (operation) => Effect.die(new ProcessLocalError({ operation }));
|
|
91
|
+
/**
|
|
92
|
+
* A Cluster machine that sends to no Cluster machine has no target of its own.
|
|
93
|
+
* It has no session id, and events sent through it are not durable. Reading
|
|
94
|
+
* either one is a defect of the work that reads it.
|
|
95
|
+
*/
|
|
96
|
+
class HostedTarget {
|
|
97
|
+
id;
|
|
98
|
+
constructor(id) {
|
|
99
|
+
this.id = id;
|
|
100
|
+
}
|
|
101
|
+
get sessionId() {
|
|
102
|
+
throw new ProcessLocalError({ operation: "self.sessionId" });
|
|
103
|
+
}
|
|
104
|
+
send = (_event) => refuseLocal("self.send");
|
|
105
|
+
}
|
|
106
|
+
/** The progress of the work of an active state, as `Machine.toStep` resumes it. */
|
|
107
|
+
const resumeProgress = (progress) => ClusterProgress.entries(progress).map(([{ id, path }, stored]) => ({
|
|
108
|
+
path,
|
|
109
|
+
id,
|
|
110
|
+
// A timer that waits and a child that runs have not ended.
|
|
111
|
+
status: stored._tag === "Settled" ? "Ended" : "Running"
|
|
112
|
+
}));
|
|
113
|
+
/** Fails with why a step could not be taken, or why the machine failed in it. */
|
|
114
|
+
const taken = (exit) => {
|
|
115
|
+
if (Exit.isFailure(exit))
|
|
116
|
+
return Effect.failCause(exit.cause);
|
|
117
|
+
const ended = exit.value.exit;
|
|
118
|
+
return ended !== undefined && Exit.isFailure(ended) ? Effect.failCause(ended.cause) : Effect.succeed(exit.value);
|
|
119
|
+
};
|
|
120
|
+
/** @internal */
|
|
121
|
+
export const make = (options) => Effect.gen(function* () {
|
|
122
|
+
const { address, definitionId, enqueue, machine, messageStorage, onCommit, storage, version } = options;
|
|
123
|
+
const support = ClusterWork.supportOf(toImpl(machine).handlers);
|
|
124
|
+
const hostsWork = support._tag === "Hosted";
|
|
125
|
+
const targets = options.sends;
|
|
126
|
+
const parent = options.children?.parent;
|
|
127
|
+
const clock = yield* Clock.Clock;
|
|
128
|
+
const semaphore = Semaphore.makeUnsafe(1);
|
|
129
|
+
// Owned by the running turn.
|
|
130
|
+
let memory;
|
|
131
|
+
let recovering = false;
|
|
132
|
+
// Work acts on the children that run when it acts, read from memory or,
|
|
133
|
+
// while a turn changes memory, from `Storage`. A child that does not run is
|
|
134
|
+
// ignored, and so is one that work names by an address, which only a local
|
|
135
|
+
// process has.
|
|
136
|
+
const children = {
|
|
137
|
+
spawn: () => refuseLocal("children.spawn"),
|
|
138
|
+
spawnLogic: () => refuseLocal("spawn"),
|
|
139
|
+
sendTo: (child, event) => typeof child === "string" ?
|
|
140
|
+
refuseLocal("sendTo") :
|
|
141
|
+
Effect.flatMap(runningChild(child), (target) => target === undefined ? Effect.void : Effect.flatMap(target.protocol.decodeEvent(event), (decoded) => dispatchToChild(target, "deliver", decoded))),
|
|
142
|
+
stop: (child) => typeof child === "string" ? refuseLocal("stopChild") : Effect.flatMap(runningChild(child), (target) => target === undefined ? Effect.void : dispatchToChild(target, "stop", undefined))
|
|
143
|
+
};
|
|
144
|
+
// Planned with the target of its own entity as `self`.
|
|
145
|
+
const stepper = Step.make(machine, {
|
|
146
|
+
self: targets?.self ?? new HostedTarget(definitionId),
|
|
147
|
+
parent,
|
|
148
|
+
children
|
|
149
|
+
});
|
|
150
|
+
const work = new ClusterWork.ClusterWork({
|
|
151
|
+
definitionId,
|
|
152
|
+
address,
|
|
153
|
+
context: yield* Effect.context(),
|
|
154
|
+
onEnd: (ended, exit) => untilDone(deliver(ended, exit))
|
|
155
|
+
});
|
|
156
|
+
const keepAlive = new ClusterKeepAlive(options.keepAlive);
|
|
157
|
+
// The step state that a step from `base` continues: the one of the running
|
|
158
|
+
// work when it belongs to that revision, so that its results apply, and the
|
|
159
|
+
// resumed state of `base` otherwise, whose work runs nowhere yet.
|
|
160
|
+
const stateOf = (base) => work.current !== undefined && work.current.revision === base.revision ? work.current.state : base.step;
|
|
161
|
+
// The timers whose delayed messages are saved, by key, with their due time.
|
|
162
|
+
// Such a timer does not keep the entity alive: its message brings the entity
|
|
163
|
+
// back when it is due, here or on another runner.
|
|
164
|
+
const wakes = new Map();
|
|
165
|
+
const timerKey = ({ id, path }) => `${path}\u0000${id}`;
|
|
166
|
+
// A timer that never ends needs no message, and one that ends soon stays in
|
|
167
|
+
// memory, as `DurableClock` keeps a short sleep.
|
|
168
|
+
const waitsLong = (dueAt) => dueAt < ClusterProgress.maxDueAt && dueAt - clock.currentTimeMillisUnsafe() > options.wake.threshold;
|
|
169
|
+
// The timers of `after` that wait long for a due time they did not wait for
|
|
170
|
+
// in `before`.
|
|
171
|
+
const longWaits = (before, after) => ClusterProgress.entries(after).flatMap(([key, progress]) => {
|
|
172
|
+
if (progress._tag !== "Waiting" || !waitsLong(progress.dueAt))
|
|
173
|
+
return [];
|
|
174
|
+
const previous = ClusterProgress.get(before, key);
|
|
175
|
+
return previous?._tag === "Waiting" && previous.dueAt === progress.dueAt
|
|
176
|
+
? []
|
|
177
|
+
: [{ path: key.path, id: key.id, dueAt: progress.dueAt }];
|
|
178
|
+
});
|
|
179
|
+
const saveWakes = (timers) => Effect.forEach(timers, options.wake.save, { discard: true });
|
|
180
|
+
const recordWakes = (timers) => {
|
|
181
|
+
for (const timer of timers)
|
|
182
|
+
wakes.set(timerKey(timer), timer.dueAt);
|
|
183
|
+
};
|
|
184
|
+
const waitingFor = (current, key) => {
|
|
185
|
+
if (current?._tag !== "Active")
|
|
186
|
+
return undefined;
|
|
187
|
+
const progress = ClusterProgress.get(current.progress, key);
|
|
188
|
+
return progress?._tag === "Waiting" ? progress.dueAt : undefined;
|
|
189
|
+
};
|
|
190
|
+
// Whether work may run without keeping the entity alive.
|
|
191
|
+
const released = (current, running) => {
|
|
192
|
+
if (running.work._tag !== "Timer")
|
|
193
|
+
return false;
|
|
194
|
+
const dueAt = waitingFor(current, running.work);
|
|
195
|
+
return dueAt !== undefined &&
|
|
196
|
+
(dueAt >= ClusterProgress.maxDueAt || wakes.get(timerKey(running.work)) === dueAt);
|
|
197
|
+
};
|
|
198
|
+
// Callers waiting for memory to change, woken at the end of every turn that
|
|
199
|
+
// changed it.
|
|
200
|
+
const waiters = new Set();
|
|
201
|
+
const annotate = Effect.annotateLogs({ module: "ClusterMachine", definitionId, address });
|
|
202
|
+
const serialized = (run) => Effect.uninterruptibleMask((restore) => Effect.suspend(() => {
|
|
203
|
+
const before = memory;
|
|
204
|
+
return Effect.ensuring(run(restore), Effect.sync(() => {
|
|
205
|
+
if (memory === before || waiters.size === 0)
|
|
206
|
+
return;
|
|
207
|
+
const woken = Array.from(waiters);
|
|
208
|
+
waiters.clear();
|
|
209
|
+
for (const wake of woken)
|
|
210
|
+
wake();
|
|
211
|
+
}));
|
|
212
|
+
})).pipe(Semaphore.withPermit(semaphore));
|
|
213
|
+
// Runs one turn. A turn that leaves something unknown hands it to recovery,
|
|
214
|
+
// whatever ended it.
|
|
215
|
+
const turn = (run) => serialized((restore) => Effect.ensuring(Effect.suspend(() => run(restore)), recoverUnknown));
|
|
216
|
+
const recoverUnknown = Effect.suspend(() => {
|
|
217
|
+
if (!hostsWork || work.closed || recovering || (memory !== undefined && !keepAlive.unknown)) {
|
|
218
|
+
return Effect.void;
|
|
219
|
+
}
|
|
220
|
+
recovering = true;
|
|
221
|
+
return Effect.asVoid(work.fork(untilDone(recover)));
|
|
222
|
+
});
|
|
223
|
+
// One attempt to recover, as a turn that does not ask for recovery itself.
|
|
224
|
+
const recover = Effect.suspend(() => serialized((restore) => Effect.suspend(() => memory === undefined ? reload(restore) : Effect.map(align(restore, undefined), () => memory !== undefined)).pipe(Effect.tap((recovered) => Effect.sync(() => {
|
|
225
|
+
recovering = !recovered;
|
|
226
|
+
})))));
|
|
227
|
+
const loadForRequest = (input) => Effect.suspend(() => storage.loadForRequest(address, input.requestId)).pipe(Effect.mapError(persistenceFailure), Effect.filterOrFail((loaded) => !loaded.processed || Option.isSome(loaded.checkpoint), () => reject("InvalidCheckpoint", "The request was recorded without a checkpoint")));
|
|
228
|
+
const decode = Effect.fnUntraced(function* (checkpoint) {
|
|
229
|
+
if (checkpoint.definitionId !== definitionId) {
|
|
230
|
+
return yield* fail("DefinitionIdMismatch", `Expected machine definition id ${definitionId}, received ${checkpoint.definitionId}`);
|
|
231
|
+
}
|
|
232
|
+
if (checkpoint.version !== version) {
|
|
233
|
+
return yield* fail("VersionMismatch", `Expected version ${version}, received ${checkpoint.version}`);
|
|
234
|
+
}
|
|
235
|
+
if (!Number.isSafeInteger(checkpoint.revision) || checkpoint.revision < 1) {
|
|
236
|
+
return yield* fail("InvalidCheckpoint", `Expected a positive integer revision, received ${checkpoint.revision}`);
|
|
237
|
+
}
|
|
238
|
+
const status = readStatus(checkpoint.status);
|
|
239
|
+
if (status === undefined) {
|
|
240
|
+
return yield* fail("InvalidCheckpoint", "Expected an active or failed status");
|
|
241
|
+
}
|
|
242
|
+
if (status._tag === "Failed") {
|
|
243
|
+
return { _tag: "Failed", revision: checkpoint.revision, failure: status.failure };
|
|
244
|
+
}
|
|
245
|
+
if (status._tag === "Stopped") {
|
|
246
|
+
return { _tag: "Stopped", revision: checkpoint.revision };
|
|
247
|
+
}
|
|
248
|
+
const state = yield* internalMachine.decodeSnapshot(machine, checkpoint.snapshot).pipe(Effect.mapError((error) => reject("InvalidCheckpoint", String(error.cause))));
|
|
249
|
+
const contradiction = contradictionOf(state, status.progress);
|
|
250
|
+
if (contradiction !== undefined) {
|
|
251
|
+
return yield* fail("InvalidCheckpoint", contradiction);
|
|
252
|
+
}
|
|
253
|
+
if (internalMachine.isFinal(machine, state)) {
|
|
254
|
+
return { _tag: "Active", revision: checkpoint.revision, state, progress: status.progress, step: undefined };
|
|
255
|
+
}
|
|
256
|
+
// Work that ended does not run again, and work that runs elsewhere, a timer
|
|
257
|
+
// that waits or a child, is not started twice.
|
|
258
|
+
const resumed = stepper.resume(state, resumeProgress(status.progress));
|
|
259
|
+
if (Exit.isFailure(resumed)) {
|
|
260
|
+
return yield* fail("InvalidCheckpoint", `Expected a state the machine resumes: ${messageFromCause(resumed.cause)}`);
|
|
261
|
+
}
|
|
262
|
+
return {
|
|
263
|
+
_tag: "Active",
|
|
264
|
+
revision: checkpoint.revision,
|
|
265
|
+
state,
|
|
266
|
+
progress: status.progress,
|
|
267
|
+
step: resumed.value.state
|
|
268
|
+
};
|
|
269
|
+
});
|
|
270
|
+
const declaresTimer = ({ id, path }) => CapturedInvocation.list(Configuration.getStateConfigByPath(machine, path)?.invoke).some((definition) => "after" in definition && definition.id === id);
|
|
271
|
+
// What makes progress impossible for a state of this machine.
|
|
272
|
+
const contradictionOf = (state, progress) => {
|
|
273
|
+
if (progress.size === 0)
|
|
274
|
+
return undefined;
|
|
275
|
+
const { active } = Configuration.normalizeConfigurationSync(machine, state);
|
|
276
|
+
const inactive = Array.from(progress.keys()).find((path) => !active.has(path));
|
|
277
|
+
if (inactive !== undefined) {
|
|
278
|
+
return `Expected invocations of active states, received state ${inactive}`;
|
|
279
|
+
}
|
|
280
|
+
const waiting = ClusterProgress.entries(progress).filter(([, { _tag }]) => _tag === "Waiting");
|
|
281
|
+
if (waiting.length > 0 && internalMachine.isFinal(machine, state)) {
|
|
282
|
+
return "Expected no timer to wait in a final state";
|
|
283
|
+
}
|
|
284
|
+
const unknown = waiting.find(([key]) => !declaresTimer(key));
|
|
285
|
+
return unknown && `Expected only timers to wait, received invocation ${unknown[0].id} of state ${unknown[0].path}`;
|
|
286
|
+
};
|
|
287
|
+
const wasFinal = (base) => base._tag === "Active" && base.step === undefined;
|
|
288
|
+
// The target of the child entity that runs `work`, by the progress that
|
|
289
|
+
// stores it.
|
|
290
|
+
const childOf = (progress, work) => {
|
|
291
|
+
if (work._tag !== "Child")
|
|
292
|
+
return undefined;
|
|
293
|
+
const stored = ClusterProgress.get(progress, work);
|
|
294
|
+
const protocol = options.children?.protocols.get(work.child.id);
|
|
295
|
+
return stored?._tag === "Child" && protocol !== undefined
|
|
296
|
+
? new ClusterTarget.Target(protocol, stored.entityId)
|
|
297
|
+
: undefined;
|
|
298
|
+
};
|
|
299
|
+
// The child that runs for a child descriptor in a progress.
|
|
300
|
+
const childTarget = (progress, child) => {
|
|
301
|
+
const protocol = options.children?.protocols.get(child.id);
|
|
302
|
+
const running = ClusterProgress.children(progress).find(([key]) => key.id === child.id);
|
|
303
|
+
return protocol && running && new ClusterTarget.Target(protocol, running[1]);
|
|
304
|
+
};
|
|
305
|
+
const runningChild = (child) => Effect.suspend(() => {
|
|
306
|
+
const known = memory;
|
|
307
|
+
if (known !== undefined) {
|
|
308
|
+
return Effect.succeed(known._tag === "Active" ? childTarget(known.progress, child) : undefined);
|
|
309
|
+
}
|
|
310
|
+
return storage.load(address).pipe(Effect.map((loaded) => {
|
|
311
|
+
const status = Option.isSome(loaded) ? readStatus(loaded.value.status) : undefined;
|
|
312
|
+
return status?._tag === "Active" ? childTarget(status.progress, child) : undefined;
|
|
313
|
+
}),
|
|
314
|
+
// A store that cannot be read now is read again.
|
|
315
|
+
Effect.retry({ schedule: Schedule.spaced("1 second") }), Effect.orDie);
|
|
316
|
+
});
|
|
317
|
+
const dispatchToChild = (target, tag, payload) => options.children === undefined
|
|
318
|
+
? Effect.void
|
|
319
|
+
: options.children.dispatch(target, tag, payload).pipe(
|
|
320
|
+
// A runner that cannot take the request now takes it later.
|
|
321
|
+
Effect.retry({ schedule: Schedule.spaced("1 second") }), Effect.orDie);
|
|
322
|
+
// Stops the child entities that run `works`, which a step stops.
|
|
323
|
+
const stopsOf = (progress, works) => works.flatMap((stopped) => {
|
|
324
|
+
const target = childOf(progress, stopped);
|
|
325
|
+
return target === undefined ? [] : [{ target, tag: "stop", payload: undefined }];
|
|
326
|
+
});
|
|
327
|
+
// A machine that ends stops all of its work, as the step stops it.
|
|
328
|
+
const stopsOfAll = (current) => {
|
|
329
|
+
if (current?._tag !== "Active")
|
|
330
|
+
return [];
|
|
331
|
+
const state = stateOf(current);
|
|
332
|
+
return state === undefined ? [] : stopsOf(current.progress, stepper.stop(state).stop);
|
|
333
|
+
};
|
|
334
|
+
// Tells the parent of a child that it ended, in the step that ends it.
|
|
335
|
+
const endedFor = (ends) => {
|
|
336
|
+
const parent = options.children?.parent;
|
|
337
|
+
return parent === undefined || !ends
|
|
338
|
+
? []
|
|
339
|
+
: [{ target: parent, tag: "ended", payload: { entityId: address.entityId } }];
|
|
340
|
+
};
|
|
341
|
+
// Gives the parent of a child the snapshot of a step that changed it, while
|
|
342
|
+
// the child is active, when the parent takes its snapshots.
|
|
343
|
+
const snapshotFor = (planned, base, snapshot) => {
|
|
344
|
+
const parent = options.children?.parent;
|
|
345
|
+
const last = planned.steps.at(-1);
|
|
346
|
+
if (parent === undefined || options.children?.snapshots !== true || last === undefined)
|
|
347
|
+
return [];
|
|
348
|
+
const moved = base._tag === "Absent" || last.planned;
|
|
349
|
+
return !moved || last.exit !== undefined
|
|
350
|
+
? []
|
|
351
|
+
: [{ target: parent, tag: "snapshot", payload: { entityId: address.entityId, snapshot } }];
|
|
352
|
+
};
|
|
353
|
+
const snapshotForCommit = Effect.fnUntraced(function* (checkpoint, state) {
|
|
354
|
+
if (checkpoint.status._tag === "Failed") {
|
|
355
|
+
return { status: "failed", revision: checkpoint.revision, state, failure: checkpoint.status.failure };
|
|
356
|
+
}
|
|
357
|
+
if (checkpoint.status._tag === "Stopped") {
|
|
358
|
+
return { status: "stopped", revision: checkpoint.revision, state };
|
|
359
|
+
}
|
|
360
|
+
if (!internalMachine.isFinal(machine, state)) {
|
|
361
|
+
return { status: "active", revision: checkpoint.revision, state };
|
|
362
|
+
}
|
|
363
|
+
const output = yield* Planner.getFinalOutputEffect(machine, state, Planner.InitialEvent);
|
|
364
|
+
return { status: "done", revision: checkpoint.revision, state, output };
|
|
365
|
+
});
|
|
366
|
+
const notifyCommit = (checkpoint, state) => onCommit === undefined
|
|
367
|
+
? Effect.void
|
|
368
|
+
: Effect.flatMap(snapshotForCommit(checkpoint, state), (snapshot) => onCommit({ entityId: address.entityId, checkpoint, snapshot }));
|
|
369
|
+
const saveOutgoing = (outgoing) => Effect.forEach(outgoing, ({ payload, tag, target }) => tag === "send" && targets !== undefined
|
|
370
|
+
? targets.save({ target, event: payload })
|
|
371
|
+
: options.children === undefined
|
|
372
|
+
? Effect.die(new Error(`Cannot save ${tag} for ${target.sessionId} without children`))
|
|
373
|
+
: options.children.save(target, tag, payload), { discard: true });
|
|
374
|
+
// Takes the steps of one stored step. A step that the machine fails in is
|
|
375
|
+
// refused, so its previous state still holds.
|
|
376
|
+
const plan = Effect.fnUntraced(function* (base, input) {
|
|
377
|
+
if (base._tag === "Absent") {
|
|
378
|
+
const initial = input._tag === "Request" ? input.initial : undefined;
|
|
379
|
+
if (options.children?.parent !== undefined && initial === undefined) {
|
|
380
|
+
return yield* fail("InvalidEvent", "A child machine takes events once its parent has started it");
|
|
381
|
+
}
|
|
382
|
+
if (machine.input !== undefined && initial === undefined && options.input.length === 0) {
|
|
383
|
+
return yield* fail("InvalidEvent", "A machine with input must be started before it takes events");
|
|
384
|
+
}
|
|
385
|
+
const started = stepper.start(...initial ?? options.input);
|
|
386
|
+
if (Exit.isFailure(started))
|
|
387
|
+
return yield* Effect.failCause(started.cause);
|
|
388
|
+
// The start of a child plans its initial state only.
|
|
389
|
+
if (input._tag !== "Request" || initial !== undefined || started.value.exit !== undefined) {
|
|
390
|
+
return { from: undefined, steps: [started.value] };
|
|
391
|
+
}
|
|
392
|
+
const sent = yield* taken(stepper.send(started.value.state, input.event));
|
|
393
|
+
return { from: undefined, steps: [started.value, sent] };
|
|
394
|
+
}
|
|
395
|
+
const from = stateOf(base);
|
|
396
|
+
// A final machine takes an event without a step.
|
|
397
|
+
if (from === undefined)
|
|
398
|
+
return { from, steps: [] };
|
|
399
|
+
switch (input._tag) {
|
|
400
|
+
case "Request":
|
|
401
|
+
return { from, steps: [yield* taken(stepper.send(from, input.event))] };
|
|
402
|
+
case "Report":
|
|
403
|
+
return { from, steps: [yield* taken(Exit.succeed(stepper.report(from, input.work, input.snapshot)))] };
|
|
404
|
+
case "Outcome":
|
|
405
|
+
return { from: input.from, steps: [yield* taken(Exit.succeed(input.next))] };
|
|
406
|
+
}
|
|
407
|
+
});
|
|
408
|
+
// What the work of a step leaves in `Storage`: its progress, and the
|
|
409
|
+
// requests it saves to child machines, in order.
|
|
410
|
+
const progressAfter = Effect.fnUntraced(function* (before, planned, revision, settled) {
|
|
411
|
+
const last = planned.steps.at(-1);
|
|
412
|
+
if (last === undefined)
|
|
413
|
+
return { progress: before, stops: [], starts: [] };
|
|
414
|
+
const exited = planned.steps.flatMap((step) => step.exited);
|
|
415
|
+
let progress = before;
|
|
416
|
+
// Work that ended keeps its progress while its state stays active, so it
|
|
417
|
+
// does not run again.
|
|
418
|
+
const ended = [
|
|
419
|
+
...(settled === undefined ? [] : [settled]),
|
|
420
|
+
...planned.steps.flatMap((step) => step.commands.flatMap((command) => command._tag === "StopChild" && command.work !== undefined ? [command.work] : []))
|
|
421
|
+
];
|
|
422
|
+
for (const work of ended) {
|
|
423
|
+
if (!exited.includes(work.path))
|
|
424
|
+
progress = ClusterProgress.settle(progress, work);
|
|
425
|
+
}
|
|
426
|
+
progress = ClusterProgress.exit(progress, exited);
|
|
427
|
+
const stops = stopsOf(before, planned.steps.flatMap((step) => [...step.stop, ...step.stopAfter]));
|
|
428
|
+
if (last.exit !== undefined) {
|
|
429
|
+
return { progress: ClusterProgress.stopChildren(ClusterProgress.cancelTimers(progress)), stops, starts: [] };
|
|
430
|
+
}
|
|
431
|
+
progress = ClusterTimer.schedule(progress, last.running, clock.currentTimeMillisUnsafe());
|
|
432
|
+
// Each child gets an entity of its own, named by the revision of the step.
|
|
433
|
+
const starts = [];
|
|
434
|
+
for (const child of last.running) {
|
|
435
|
+
if (child._tag !== "Child" || ClusterProgress.get(progress, child) !== undefined)
|
|
436
|
+
continue;
|
|
437
|
+
const protocol = options.children?.protocols.get(child.child.id);
|
|
438
|
+
if (protocol === undefined)
|
|
439
|
+
continue;
|
|
440
|
+
const input = child.input();
|
|
441
|
+
if (Exit.isFailure(input)) {
|
|
442
|
+
return yield* fail("TransitionFailure", `The input of a child machine cannot be built: ${String(Cause.squash(input.cause))}`);
|
|
443
|
+
}
|
|
444
|
+
const entityId = ClusterChild.entityIdOf(address.entityId, child.child.id, revision);
|
|
445
|
+
progress = ClusterProgress.child(progress, child, entityId);
|
|
446
|
+
starts.push({
|
|
447
|
+
target: new ClusterTarget.Target(protocol, entityId),
|
|
448
|
+
tag: "start",
|
|
449
|
+
payload: { input: input.value[0] }
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
return { progress, stops, starts };
|
|
453
|
+
});
|
|
454
|
+
// The sends and child stops that commands enqueue, in order, decoded by
|
|
455
|
+
// the protocols of their targets. A send or stop for a child that does not
|
|
456
|
+
// run is dropped, as a local runtime drops it.
|
|
457
|
+
const commandsOf = Effect.fnUntraced(function* (planned, before, after) {
|
|
458
|
+
const last = planned.steps.at(-1);
|
|
459
|
+
const outgoing = [];
|
|
460
|
+
for (const command of planned.steps.flatMap((step) => step.commands)) {
|
|
461
|
+
switch (command._tag) {
|
|
462
|
+
case "StopChild": {
|
|
463
|
+
if (typeof command.child === "string") {
|
|
464
|
+
return yield* fail("UnsupportedProcessLocal", "Machine commands on Cluster stop only an invoked child machine");
|
|
465
|
+
}
|
|
466
|
+
const target = command.work === undefined ? undefined : childOf(before, command.work);
|
|
467
|
+
if (target !== undefined)
|
|
468
|
+
outgoing.push({ target, tag: "stop", payload: undefined });
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
case "SendToChild":
|
|
472
|
+
case "Send": {
|
|
473
|
+
if (options.sends === undefined || (command._tag === "SendToChild" && typeof command.child === "string")) {
|
|
474
|
+
return yield* fail("UnsupportedProcessLocal", "Machine commands on Cluster send only to a ClusterMachine target or an invoked child machine");
|
|
475
|
+
}
|
|
476
|
+
let target;
|
|
477
|
+
if (command._tag === "Send") {
|
|
478
|
+
if (!ClusterTarget.isTarget(command.target)) {
|
|
479
|
+
return yield* fail("UnsupportedProcessLocal", "Machine commands on Cluster send only to a ClusterMachine target or an invoked child machine");
|
|
480
|
+
}
|
|
481
|
+
target = command.target;
|
|
482
|
+
}
|
|
483
|
+
else if (command.work !== undefined && last?.running.includes(command.work) === true) {
|
|
484
|
+
// Only a child that still runs once the step is stored takes the
|
|
485
|
+
// send: one whose state the step exits is dropped.
|
|
486
|
+
target = childOf(after, command.work);
|
|
487
|
+
}
|
|
488
|
+
if (target === undefined)
|
|
489
|
+
continue;
|
|
490
|
+
const event = yield* target.protocol.decode(command.event).pipe(Effect.mapError((rejected) => reject("TransitionFailure", `The step sends ${target.sessionId} an event it refuses: ${rejected.message}`)));
|
|
491
|
+
outgoing.push({ target, tag: "send", payload: event });
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
return outgoing;
|
|
496
|
+
});
|
|
497
|
+
// Everything a step decides before it changes `Storage`.
|
|
498
|
+
const prepare = Effect.fnUntraced(function* (base, input) {
|
|
499
|
+
const planned = yield* plan(base, input);
|
|
500
|
+
const last = planned.steps.at(-1);
|
|
501
|
+
const state = last === undefined ? base.state : last.snapshot;
|
|
502
|
+
const snapshot = yield* internalMachine.encodeSnapshot(machine, state).pipe(Effect.mapError((error) => reject("SnapshotEncodeFailure", String(error.cause))));
|
|
503
|
+
const emitted = planned.steps.flatMap((step) => step.emitted);
|
|
504
|
+
if (emitted.length > 0 && enqueue === undefined) {
|
|
505
|
+
return yield* fail("EmissionFailure", "No durable enqueue handler was configured");
|
|
506
|
+
}
|
|
507
|
+
const revision = base.revision + 1;
|
|
508
|
+
const before = progressOf(base);
|
|
509
|
+
// Last, so a step that is refused evaluates no duration and no input.
|
|
510
|
+
const { progress, starts, stops } = yield* progressAfter(before, planned, revision, input._tag === "Outcome" ? input.work : undefined);
|
|
511
|
+
const commanded = yield* commandsOf(planned, before, progress);
|
|
512
|
+
const ends = last?.exit !== undefined;
|
|
513
|
+
const outgoing = [
|
|
514
|
+
...stops,
|
|
515
|
+
...starts,
|
|
516
|
+
...commanded,
|
|
517
|
+
...snapshotFor(planned, base, snapshot),
|
|
518
|
+
...endedFor(ends && !wasFinal(base))
|
|
519
|
+
];
|
|
520
|
+
return {
|
|
521
|
+
planned,
|
|
522
|
+
state,
|
|
523
|
+
emitted,
|
|
524
|
+
outgoing,
|
|
525
|
+
checkpoint: {
|
|
526
|
+
definitionId,
|
|
527
|
+
version,
|
|
528
|
+
revision,
|
|
529
|
+
origin: input._tag === "Outcome"
|
|
530
|
+
? { _tag: "Invocation", path: input.work.path, id: input.work.id }
|
|
531
|
+
: { _tag: "Request", requestId: input.requestId },
|
|
532
|
+
snapshot,
|
|
533
|
+
status: { _tag: "Active", invocations: ClusterProgress.toStored(progress) }
|
|
534
|
+
},
|
|
535
|
+
next: {
|
|
536
|
+
_tag: "Active",
|
|
537
|
+
revision,
|
|
538
|
+
state,
|
|
539
|
+
progress,
|
|
540
|
+
step: last === undefined || ends ? undefined : last.state
|
|
541
|
+
}
|
|
542
|
+
};
|
|
543
|
+
});
|
|
544
|
+
// The transaction body of a step from a known state. Its value holds once the
|
|
545
|
+
// transaction around it has succeeded.
|
|
546
|
+
const step = Effect.fnUntraced(function* (input, base, options) {
|
|
547
|
+
const { checkpoint, emitted, next, outgoing, planned, state } = yield* prepare(base, input).pipe(refuse({ memory: base, confirm: options.confirm, stage: "Decision" }));
|
|
548
|
+
const committed = yield* storage.commit(address, checkpoint).pipe(Effect.mapError(persistenceFailure), refuse({ memory: undefined, confirm: true, stage: "Infrastructure" }));
|
|
549
|
+
switch (committed._tag) {
|
|
550
|
+
case "Duplicate":
|
|
551
|
+
return input._tag !== "Outcome"
|
|
552
|
+
? { memory: base, stored: undefined }
|
|
553
|
+
: yield* Effect.die(new Error("Storage reported a duplicate of a checkpoint without a request id"));
|
|
554
|
+
case "RevisionConflict":
|
|
555
|
+
return yield* new Conflicted();
|
|
556
|
+
case "Committed": {
|
|
557
|
+
if (enqueue !== undefined) {
|
|
558
|
+
// `Committed` proves that no earlier delivery committed this input.
|
|
559
|
+
yield* Effect.forEach(emitted, enqueue, { discard: true }).pipe(Effect.mapError((error) => reject("EmissionFailure", String(error))), refuse({ memory: undefined, confirm: false, stage: "Infrastructure" }));
|
|
560
|
+
}
|
|
561
|
+
// In the transaction of the checkpoint, so a stored wait has its message.
|
|
562
|
+
const woken = longWaits(progressOf(base), progressOf(next));
|
|
563
|
+
yield* saveWakes(woken).pipe(Effect.mapError((error) => reject("PersistenceFailure", String(error))), refuse({ memory: undefined, confirm: false, stage: "Infrastructure" }));
|
|
564
|
+
// In the transaction of the checkpoint, so each request is saved once.
|
|
565
|
+
yield* saveOutgoing(outgoing).pipe(Effect.mapError((error) => reject("PersistenceFailure", String(error))), refuse({ memory: undefined, confirm: false, stage: "Infrastructure" }));
|
|
566
|
+
// In the transaction of the checkpoint, so projections commit or roll back with it.
|
|
567
|
+
yield* notifyCommit(checkpoint, state).pipe(Effect.mapError((error) => reject("PersistenceFailure", String(error))), refuse({ memory: undefined, confirm: false, stage: "Infrastructure" }));
|
|
568
|
+
return {
|
|
569
|
+
memory: next,
|
|
570
|
+
stored: {
|
|
571
|
+
from: planned.from,
|
|
572
|
+
step: planned.steps.at(-1),
|
|
573
|
+
woken,
|
|
574
|
+
sent: outgoing.length > 0
|
|
575
|
+
}
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
});
|
|
580
|
+
// Stores a child as stopped, in the state it has, and stops its own children.
|
|
581
|
+
const stopStep = Effect.fnUntraced(function* (requestId, base) {
|
|
582
|
+
const snapshot = yield* internalMachine.encodeSnapshot(machine, base.state).pipe(Effect.mapError((error) => reject("SnapshotEncodeFailure", String(error.cause))), refuse({ memory: base, confirm: true, stage: "Decision" }));
|
|
583
|
+
const revision = base.revision + 1;
|
|
584
|
+
const checkpoint = {
|
|
585
|
+
definitionId,
|
|
586
|
+
version,
|
|
587
|
+
revision,
|
|
588
|
+
origin: { _tag: "Request", requestId },
|
|
589
|
+
snapshot,
|
|
590
|
+
status: { _tag: "Stopped" }
|
|
591
|
+
};
|
|
592
|
+
const committed = yield* storage.commit(address, checkpoint).pipe(Effect.mapError(persistenceFailure), refuse({ memory: undefined, confirm: true, stage: "Infrastructure" }));
|
|
593
|
+
if (committed._tag === "Duplicate")
|
|
594
|
+
return { memory: base, stored: undefined };
|
|
595
|
+
if (committed._tag === "RevisionConflict")
|
|
596
|
+
return yield* new Conflicted();
|
|
597
|
+
yield* saveOutgoing(stopsOfAll(base)).pipe(Effect.mapError((error) => reject("PersistenceFailure", String(error))), refuse({ memory: undefined, confirm: false, stage: "Infrastructure" }));
|
|
598
|
+
yield* notifyCommit(checkpoint, base.state).pipe(Effect.mapError((error) => reject("PersistenceFailure", String(error))), refuse({ memory: undefined, confirm: false, stage: "Infrastructure" }));
|
|
599
|
+
return { memory: { _tag: "Stopped", revision }, stored: undefined };
|
|
600
|
+
});
|
|
601
|
+
const requestStep = Effect.fnUntraced(function* (input, known) {
|
|
602
|
+
if (support._tag === "Unsupported") {
|
|
603
|
+
return yield* fail("UnsupportedProcessLocal", support.message).pipe(refuse({ memory: known, confirm: true, stage: "Decision" }));
|
|
604
|
+
}
|
|
605
|
+
let base = known;
|
|
606
|
+
if (base === undefined) {
|
|
607
|
+
// A refusal that follows this answer needs no confirmation.
|
|
608
|
+
const refuseLoad = refuse({ memory: undefined, confirm: false, stage: "Infrastructure" });
|
|
609
|
+
const loaded = yield* refuseLoad(loadForRequest(input));
|
|
610
|
+
if (loaded.processed) {
|
|
611
|
+
return { memory: undefined, stored: undefined };
|
|
612
|
+
}
|
|
613
|
+
base = Option.isNone(loaded.checkpoint) ? absent : yield* refuseLoad(decode(loaded.checkpoint.value));
|
|
614
|
+
}
|
|
615
|
+
const confirm = known !== undefined;
|
|
616
|
+
// A start of an active machine, and a stop of one that does not run,
|
|
617
|
+
// change nothing. A start of a failed or stopped machine is rejected below.
|
|
618
|
+
if (input.lifecycle === "Start" && base._tag === "Active")
|
|
619
|
+
return { memory: base, stored: undefined };
|
|
620
|
+
if (input.lifecycle === "Stop") {
|
|
621
|
+
return base._tag === "Active" ? yield* stopStep(input.requestId, base) : { memory: base, stored: undefined };
|
|
622
|
+
}
|
|
623
|
+
if (base._tag === "Failed") {
|
|
624
|
+
return yield* fail("MachineFailed", base.failure).pipe(refuse({ memory: base, confirm, stage: "Decision" }));
|
|
625
|
+
}
|
|
626
|
+
if (base._tag === "Stopped") {
|
|
627
|
+
return yield* fail("MachineFailed", "The child machine was stopped by its parent").pipe(refuse({ memory: base, confirm, stage: "Decision" }));
|
|
628
|
+
}
|
|
629
|
+
if (input.child !== undefined) {
|
|
630
|
+
// The snapshot of a child that no longer runs changes nothing.
|
|
631
|
+
const { entityId } = input.child;
|
|
632
|
+
const running = base._tag === "Active"
|
|
633
|
+
? ClusterProgress.children(base.progress).find(([, id]) => id === entityId)
|
|
634
|
+
: undefined;
|
|
635
|
+
const protocol = running && options.children?.protocols.get(running[0].id);
|
|
636
|
+
const from = base._tag === "Active" ? stateOf(base) : undefined;
|
|
637
|
+
const reported = running &&
|
|
638
|
+
from?.running.find((work) => work._tag === "Child" && work.path === running[0].path && work.id === running[0].id);
|
|
639
|
+
if (reported === undefined || protocol === undefined)
|
|
640
|
+
return { memory: base, stored: undefined };
|
|
641
|
+
const snapshot = yield* internalMachine.decodeSnapshot(protocol.machine, input.child.snapshot).pipe(Effect.mapError((error) => reject("TransitionFailure", `The snapshot of child ${entityId} cannot be decoded: ${String(error)}`)), refuse({ memory: base, confirm, stage: "Decision" }));
|
|
642
|
+
return yield* step({ _tag: "Report", requestId: input.requestId, work: reported, snapshot }, base, { confirm });
|
|
643
|
+
}
|
|
644
|
+
return yield* step({ _tag: "Request", requestId: input.requestId, event: input.event, initial: input.initial }, base, { confirm });
|
|
645
|
+
});
|
|
646
|
+
// Runs after the failed transaction, so the answer excludes its writes. A
|
|
647
|
+
// commit whose transaction failed afterwards may still have taken effect.
|
|
648
|
+
const confirm = (restore, input, refused) => restore(messageStorage.withTransaction(loadForRequest(input))).pipe(Effect.matchCauseEffect({
|
|
649
|
+
onFailure: (cause) => Cause.hasInterrupts(cause)
|
|
650
|
+
? propagate(cause)
|
|
651
|
+
: Effect.succeed(rejectionFromCause(cause, "PersistenceFailure")),
|
|
652
|
+
onSuccess: ({ checkpoint, processed }) => {
|
|
653
|
+
const revision = Option.isNone(checkpoint) ? 0 : checkpoint.value.revision;
|
|
654
|
+
const stale = refused.memory !== undefined && refused.memory.revision !== revision;
|
|
655
|
+
if (stale && !processed) {
|
|
656
|
+
return Effect.fail(new Conflicted());
|
|
657
|
+
}
|
|
658
|
+
return Effect.sync(() => {
|
|
659
|
+
memory = stale ? undefined : refused.memory;
|
|
660
|
+
return processed ? accepted : refused.rejected;
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
}));
|
|
664
|
+
const attempt = (restore, input) => Effect.suspend(() => {
|
|
665
|
+
const known = memory;
|
|
666
|
+
memory = undefined;
|
|
667
|
+
return restore(messageStorage.withTransaction(requestStep(input, known))).pipe(Effect.matchCauseEffect({
|
|
668
|
+
onFailure: (cause) => {
|
|
669
|
+
if (Cause.hasInterrupts(cause)) {
|
|
670
|
+
return propagate(cause);
|
|
671
|
+
}
|
|
672
|
+
const error = Option.getOrUndefined(Cause.findErrorOption(cause));
|
|
673
|
+
if (error instanceof Conflicted) {
|
|
674
|
+
return Effect.fail(error);
|
|
675
|
+
}
|
|
676
|
+
if (!(error instanceof Refused)) {
|
|
677
|
+
return confirm(restore, input, {
|
|
678
|
+
rejected: reject("PersistenceFailure", messageFromCause(cause)),
|
|
679
|
+
memory: undefined
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
// A rollback that failed as well says nothing about `Storage`.
|
|
683
|
+
const refused = Cause.hasDies(cause) ? { rejected: error.rejected, memory: undefined } : error;
|
|
684
|
+
if (error.confirm) {
|
|
685
|
+
return confirm(restore, input, refused);
|
|
686
|
+
}
|
|
687
|
+
return Effect.sync(() => {
|
|
688
|
+
memory = refused.memory;
|
|
689
|
+
return refused.rejected;
|
|
690
|
+
});
|
|
691
|
+
},
|
|
692
|
+
onSuccess: (result) => {
|
|
693
|
+
memory = result.memory;
|
|
694
|
+
return Effect.as(align(restore, result.stored), accepted);
|
|
695
|
+
}
|
|
696
|
+
}));
|
|
697
|
+
});
|
|
698
|
+
// Ends an attempt that leaves memory unknown, and is made again. An
|
|
699
|
+
// interruption is no exception: when it is not this fiber that was
|
|
700
|
+
// interrupted, it is how the infrastructure failed.
|
|
701
|
+
const notDone = (message, cause) => Effect.as(work.closed ? Effect.void : Effect.logWarning(message, cause), false);
|
|
702
|
+
// Loads what `Storage` holds, for an instance that does not know it. The
|
|
703
|
+
// value is whether nothing is left to load.
|
|
704
|
+
const reload = (restore) => restore(messageStorage.withTransaction(Effect.suspend(() => storage.load(address)).pipe(Effect.mapError(persistenceFailure), Effect.flatMap(Option.match({
|
|
705
|
+
onNone: () => Effect.succeedSome(absent),
|
|
706
|
+
onSome: (checkpoint) => decode(checkpoint).pipe(Effect.map(Option.some),
|
|
707
|
+
// A checkpoint this deployment cannot read belongs to another one.
|
|
708
|
+
Effect.catch((unreadable) => Effect.logWarning("Could not read the checkpoint of a Cluster machine", unreadable.message).pipe(Effect.as(Option.none()))))
|
|
709
|
+
}))))).pipe(Effect.matchCauseEffect({
|
|
710
|
+
onFailure: (cause) => notDone("Could not load the checkpoint of a Cluster machine", cause),
|
|
711
|
+
onSuccess: (loaded) => {
|
|
712
|
+
// Its work stops, and its keep-alive request stays for a deployment
|
|
713
|
+
// that can read it.
|
|
714
|
+
if (Option.isNone(loaded))
|
|
715
|
+
return Effect.as(work.stopAll, true);
|
|
716
|
+
memory = loaded.value;
|
|
717
|
+
return Effect.map(align(restore, undefined), () => memory !== undefined);
|
|
718
|
+
}
|
|
719
|
+
}), annotate);
|
|
720
|
+
// Makes the work and the keep-alive match the known memory. `stored` is the
|
|
721
|
+
// step that led to it from the previous state.
|
|
722
|
+
const align = (restore, stored) => Effect.andThen(
|
|
723
|
+
// The runner reads the events the step sent now, rather than at its next poll.
|
|
724
|
+
stored?.sent === true && options.sends !== undefined ? options.sends.poll : Effect.void, alignStored(restore, stored));
|
|
725
|
+
const alignStored = (restore, stored) => Effect.suspend(() => {
|
|
726
|
+
if (!hostsWork || work.closed || memory === undefined)
|
|
727
|
+
return Effect.void;
|
|
728
|
+
if (stored !== undefined)
|
|
729
|
+
recordWakes(stored.woken);
|
|
730
|
+
return Effect.andThen(stored === undefined ? scheduleLoaded(restore, memory) : Effect.void, Effect.suspend(() => {
|
|
731
|
+
if (memory === undefined)
|
|
732
|
+
return Effect.void;
|
|
733
|
+
return Effect.flatMap(alignWork(memory, stored), (failure) => failure === undefined
|
|
734
|
+
? Effect.andThen(stored === undefined ? wakeLoaded(restore) : Effect.void, Effect.suspend(() => {
|
|
735
|
+
const current = memory;
|
|
736
|
+
if (current === undefined)
|
|
737
|
+
return Effect.void;
|
|
738
|
+
forgetWakes(current);
|
|
739
|
+
// A request is answered after this, so a crash in between redelivers it.
|
|
740
|
+
return restore(keepAlive.switchTo(work.pendingExcept((running) => released(current, running))))
|
|
741
|
+
.pipe(annotate);
|
|
742
|
+
}))
|
|
743
|
+
: Effect.asVoid(storeFailure(restore, failure.key, renderFailure(failure.cause))));
|
|
744
|
+
}));
|
|
745
|
+
});
|
|
746
|
+
// Saves the messages that the long waits of a loaded state may lack, as
|
|
747
|
+
// they lack them when a deployment before this one stored the wait. A
|
|
748
|
+
// message that is not saved keeps its timer, and the entity, in memory.
|
|
749
|
+
const wakeLoaded = (restore) => Effect.suspend(() => {
|
|
750
|
+
if (memory === undefined)
|
|
751
|
+
return Effect.void;
|
|
752
|
+
const timers = longWaits(ClusterProgress.empty, progressOf(memory)).filter((timer) => wakes.get(timerKey(timer)) !== timer.dueAt);
|
|
753
|
+
return Effect.forEach(timers, (timer) => restore(options.wake.save(timer)).pipe(Effect.matchCauseEffect({
|
|
754
|
+
onFailure: (cause) => Cause.hasInterrupts(cause)
|
|
755
|
+
? propagate(cause)
|
|
756
|
+
: Effect.logWarning("Could not save the message that wakes a Cluster machine", cause),
|
|
757
|
+
onSuccess: () => Effect.sync(() => recordWakes([timer]))
|
|
758
|
+
})), { discard: true }).pipe(annotate);
|
|
759
|
+
});
|
|
760
|
+
// Keeps only the messages of timers that still wait for their due time.
|
|
761
|
+
const forgetWakes = (current) => {
|
|
762
|
+
for (const [key, dueAt] of wakes) {
|
|
763
|
+
const [path, id] = key.split("\u0000");
|
|
764
|
+
if (waitingFor(current, { path, id }) !== dueAt)
|
|
765
|
+
wakes.delete(key);
|
|
766
|
+
}
|
|
767
|
+
};
|
|
768
|
+
// Stores the due times that the timers of a loaded state lack, as a
|
|
769
|
+
// checkpoint of its own, before any of its work starts. A deployment that
|
|
770
|
+
// did not declare a timer stored none for it. Memory is left unknown when
|
|
771
|
+
// that fails.
|
|
772
|
+
const scheduleLoaded = (restore, loaded) => Effect.suspend(() => {
|
|
773
|
+
if (loaded._tag !== "Active" || loaded.step === undefined || work.current?.revision === loaded.revision) {
|
|
774
|
+
return Effect.void;
|
|
775
|
+
}
|
|
776
|
+
const progress = ClusterTimer.schedule(loaded.progress, loaded.step.running, clock.currentTimeMillisUnsafe());
|
|
777
|
+
if (progress === loaded.progress)
|
|
778
|
+
return Effect.void;
|
|
779
|
+
const woken = longWaits(loaded.progress, progress);
|
|
780
|
+
return amend(restore, {
|
|
781
|
+
origin: { _tag: "Timers" },
|
|
782
|
+
status: { _tag: "Active", invocations: ClusterProgress.toStored(progress) }
|
|
783
|
+
}, woken).pipe(Effect.matchCauseEffect({
|
|
784
|
+
onFailure: (cause) => notDone("Could not store the due times of a Cluster machine", cause),
|
|
785
|
+
onSuccess: (revision) => Effect.sync(() => {
|
|
786
|
+
memory = { ...loaded, revision, progress };
|
|
787
|
+
recordWakes(woken);
|
|
788
|
+
})
|
|
789
|
+
}), annotate, Effect.asVoid);
|
|
790
|
+
});
|
|
791
|
+
// Makes the running work the work of the state in memory. The value is why
|
|
792
|
+
// the machine failed, when work could not start.
|
|
793
|
+
const alignWork = (current, stored) => Effect.suspend(() => {
|
|
794
|
+
if (work.current?.revision === current.revision)
|
|
795
|
+
return Effect.succeed(undefined);
|
|
796
|
+
// A step from the state of the running work stops and starts what it
|
|
797
|
+
// lists, in the step's order (`stop`, then `stopAfter` when terminal).
|
|
798
|
+
const continued = stored?.step !== undefined && stored.from !== undefined &&
|
|
799
|
+
work.current?.state === stored.from
|
|
800
|
+
? stored.step
|
|
801
|
+
: undefined;
|
|
802
|
+
if (current._tag !== "Active" || current.step === undefined) {
|
|
803
|
+
if (continued === undefined)
|
|
804
|
+
return Effect.as(work.stopAll, undefined);
|
|
805
|
+
return work.stop(continued.stop).pipe(Effect.andThen(work.stop(continued.stopAfter)), Effect.andThen(work.stopAll), Effect.as(undefined));
|
|
806
|
+
}
|
|
807
|
+
const state = current.step;
|
|
808
|
+
return (continued === undefined ? work.stopAll : work.stop(continued.stop)).pipe(Effect.andThen(Effect.suspend(() => {
|
|
809
|
+
work.current = { revision: current.revision, state };
|
|
810
|
+
return work.start(continued === undefined ? state.running : continued.start, current.progress);
|
|
811
|
+
})), Effect.flatMap((failure) => {
|
|
812
|
+
if (failure === undefined)
|
|
813
|
+
return Effect.succeed(undefined);
|
|
814
|
+
// Work that could not start fails the machine, which stops all work.
|
|
815
|
+
const failed = stepper.settle(state, failure.work, failure.exit).exit;
|
|
816
|
+
const cause = failed !== undefined && Exit.isFailure(failed) ? failed.cause : Cause.die(new Error(`Work "${failure.work.id}" of state "${failure.work.path}" could not start`));
|
|
817
|
+
return Effect.as(work.stopAll, { key: failure.work, cause });
|
|
818
|
+
}));
|
|
819
|
+
});
|
|
820
|
+
// Replaces the stored checkpoint by one of the same state, whose snapshot is
|
|
821
|
+
// kept as it is. Memory is forgotten first, and the value is the revision that
|
|
822
|
+
// is stored.
|
|
823
|
+
const amend = (restore, amended, woken = [], outgoing = []) => Effect.suspend(() => {
|
|
824
|
+
const revision = memory?.revision;
|
|
825
|
+
memory = undefined;
|
|
826
|
+
return restore(messageStorage.withTransaction(Effect.gen(function* () {
|
|
827
|
+
const loaded = yield* storage.load(address);
|
|
828
|
+
if (Option.isNone(loaded) || loaded.value.revision !== revision) {
|
|
829
|
+
return yield* new Conflicted();
|
|
830
|
+
}
|
|
831
|
+
const checkpoint = { ...loaded.value, ...amended, revision: revision + 1 };
|
|
832
|
+
const committed = yield* storage.commit(address, checkpoint);
|
|
833
|
+
if (committed._tag !== "Committed") {
|
|
834
|
+
return yield* new Conflicted();
|
|
835
|
+
}
|
|
836
|
+
yield* saveWakes(woken);
|
|
837
|
+
yield* saveOutgoing(outgoing);
|
|
838
|
+
if (onCommit !== undefined) {
|
|
839
|
+
const decodedState = yield* internalMachine.decodeSnapshot(machine, checkpoint.snapshot);
|
|
840
|
+
yield* notifyCommit(checkpoint, decodedState);
|
|
841
|
+
}
|
|
842
|
+
return checkpoint.revision;
|
|
843
|
+
})));
|
|
844
|
+
});
|
|
845
|
+
// Stores the machine as failed, in the state it has. The value is whether the
|
|
846
|
+
// failure is stored.
|
|
847
|
+
const storeFailure = (restore, cause, failure) =>
|
|
848
|
+
// A machine that fails stops its children, and a child tells its parent.
|
|
849
|
+
amend(restore, {
|
|
850
|
+
origin: "requestId" in cause
|
|
851
|
+
? { _tag: "Request", requestId: cause.requestId }
|
|
852
|
+
: { _tag: "Invocation", path: cause.path, id: cause.id },
|
|
853
|
+
status: { _tag: "Failed", failure }
|
|
854
|
+
}, [], [...stopsOfAll(memory), ...endedFor(true)]).pipe(Effect.matchCauseEffect({
|
|
855
|
+
onFailure: (cause) => notDone("Could not store the failure of a Cluster machine", cause),
|
|
856
|
+
onSuccess: (revision) => {
|
|
857
|
+
memory = { _tag: "Failed", revision, failure };
|
|
858
|
+
return Effect.logError("A Cluster machine failed", failure).pipe(
|
|
859
|
+
// The runner reads the requests to its children and parent now.
|
|
860
|
+
Effect.andThen(options.sends?.poll ?? Effect.void), Effect.andThen(align(restore, undefined)), Effect.as(true));
|
|
861
|
+
}
|
|
862
|
+
}), annotate);
|
|
863
|
+
// One attempt to apply the end of work. The value is whether nothing is left
|
|
864
|
+
// to do.
|
|
865
|
+
const deliver = (ended, exit) => turn((restore) => Effect.andThen(memory === undefined && !ended.stopped ? reload(restore) : Effect.void, Effect.suspend(() => {
|
|
866
|
+
// Work that this instance stopped reports nothing.
|
|
867
|
+
if (ended.stopped)
|
|
868
|
+
return Effect.succeed(true);
|
|
869
|
+
if (memory === undefined || memory._tag !== "Active")
|
|
870
|
+
return Effect.succeed(false);
|
|
871
|
+
const current = work.current;
|
|
872
|
+
// Work that runs belongs to the revision in memory, or was stopped.
|
|
873
|
+
if (current === undefined || current.revision !== memory.revision)
|
|
874
|
+
return Effect.succeed(true);
|
|
875
|
+
const next = stepper.settle(current.state, ended.work, exit);
|
|
876
|
+
// The step returns the state it was given for a result that no
|
|
877
|
+
// longer applies.
|
|
878
|
+
if (next.state === current.state)
|
|
879
|
+
return Effect.succeed(true);
|
|
880
|
+
return applyOutcome(restore, ended.work, memory, current.state, next, () => work.settle(ended));
|
|
881
|
+
})));
|
|
882
|
+
const applyOutcome = (restore, settled, base, from, next, onApplied) => {
|
|
883
|
+
const key = { path: settled.path, id: settled.id };
|
|
884
|
+
// A machine that fails in the step is stored as failed, in the state it had.
|
|
885
|
+
if (next.exit !== undefined && Exit.isFailure(next.exit)) {
|
|
886
|
+
return storeFailure(restore, key, renderFailure(next.exit.cause));
|
|
887
|
+
}
|
|
888
|
+
memory = undefined;
|
|
889
|
+
return restore(messageStorage.withTransaction(step({ _tag: "Outcome", work: settled, from, next }, base, { confirm: false }))).pipe(Effect.matchCauseEffect({
|
|
890
|
+
onFailure: (cause) => {
|
|
891
|
+
const error = Option.getOrUndefined(Cause.findErrorOption(cause));
|
|
892
|
+
if (error instanceof Refused && error.failure !== undefined && !Cause.hasDies(cause)) {
|
|
893
|
+
memory = error.memory;
|
|
894
|
+
return storeFailure(restore, key, error.failure);
|
|
895
|
+
}
|
|
896
|
+
return notDone("Could not store the outcome of an invocation", cause);
|
|
897
|
+
},
|
|
898
|
+
onSuccess: (result) => {
|
|
899
|
+
memory = result.memory;
|
|
900
|
+
onApplied();
|
|
901
|
+
return Effect.as(align(restore, result.stored), true);
|
|
902
|
+
}
|
|
903
|
+
}), annotate);
|
|
904
|
+
};
|
|
905
|
+
yield* Effect.addFinalizer(() => Effect.andThen(work.close, keepAlive.close));
|
|
906
|
+
if (hostsWork) {
|
|
907
|
+
// After a crash no request may ever come.
|
|
908
|
+
recovering = true;
|
|
909
|
+
yield* work.fork(untilDone(recover));
|
|
910
|
+
}
|
|
911
|
+
else if (support._tag === "Idle") {
|
|
912
|
+
// A deployment whose machine invoked effects may have left a request behind.
|
|
913
|
+
yield* options.keepAlive(false);
|
|
914
|
+
}
|
|
915
|
+
// One look at a timer, as a turn. `undefined` means nothing is left to wait
|
|
916
|
+
// for, and a deferred is completed once memory changes.
|
|
917
|
+
const lookAt = (timer) => serialized((restore) => Effect.andThen(memory === undefined ? reload(restore) : Effect.void, Effect.sync(() => {
|
|
918
|
+
if (memory !== undefined && waitingFor(memory, timer) !== timer.dueAt)
|
|
919
|
+
return undefined;
|
|
920
|
+
const changed = Deferred.makeUnsafe();
|
|
921
|
+
waiters.add(() => Deferred.doneUnsafe(changed, Exit.void));
|
|
922
|
+
return { changed, known: memory !== undefined };
|
|
923
|
+
})));
|
|
924
|
+
const wake = (timer) => Effect.gen(function* () {
|
|
925
|
+
while (true) {
|
|
926
|
+
const waiting = yield* lookAt(timer);
|
|
927
|
+
if (waiting === undefined)
|
|
928
|
+
return;
|
|
929
|
+
// A store that cannot be read is read again later.
|
|
930
|
+
yield* waiting.known
|
|
931
|
+
? Deferred.await(waiting.changed)
|
|
932
|
+
: Effect.raceFirst(Deferred.await(waiting.changed), Effect.sleep("1 second"));
|
|
933
|
+
}
|
|
934
|
+
}).pipe(annotate);
|
|
935
|
+
// How a child ended, read from `Storage`. `undefined` means it has not.
|
|
936
|
+
const readChild = Effect.fnUntraced(function* (target) {
|
|
937
|
+
const children = options.children;
|
|
938
|
+
if (children === undefined)
|
|
939
|
+
return undefined;
|
|
940
|
+
const loaded = yield* storage.load(children.address(target)).pipe(
|
|
941
|
+
// A store that cannot be read now is read again.
|
|
942
|
+
Effect.retry({ schedule: Schedule.spaced("1 second") }));
|
|
943
|
+
if (Option.isNone(loaded))
|
|
944
|
+
return undefined;
|
|
945
|
+
const status = readStatus(loaded.value.status);
|
|
946
|
+
if (status?._tag === "Failed")
|
|
947
|
+
return { _tag: "Failed", failure: status.failure };
|
|
948
|
+
if (status?._tag !== "Active")
|
|
949
|
+
return undefined;
|
|
950
|
+
const child = target.protocol.machine;
|
|
951
|
+
const state = yield* internalMachine.decodeSnapshot(child, loaded.value.snapshot);
|
|
952
|
+
if (!internalMachine.isFinal(child, state))
|
|
953
|
+
return undefined;
|
|
954
|
+
const output = yield* Planner.getFinalOutputEffect(child, state, Planner.InitialEvent);
|
|
955
|
+
return { _tag: "Done", output };
|
|
956
|
+
});
|
|
957
|
+
const childEnded = (entityId) => turn((restore) => Effect.gen(function* () {
|
|
958
|
+
if (memory === undefined)
|
|
959
|
+
yield* reload(restore);
|
|
960
|
+
const current = memory;
|
|
961
|
+
if (current?._tag !== "Active")
|
|
962
|
+
return;
|
|
963
|
+
const running = ClusterProgress.children(current.progress).find(([, id]) => id === entityId);
|
|
964
|
+
const protocol = running && options.children?.protocols.get(running[0].id);
|
|
965
|
+
const from = stateOf(current);
|
|
966
|
+
const ended = running &&
|
|
967
|
+
from?.running.find((work) => work._tag === "Child" && work.path === running[0].path && work.id === running[0].id);
|
|
968
|
+
if (from === undefined || ended === undefined || protocol === undefined)
|
|
969
|
+
return;
|
|
970
|
+
const result = yield* Effect.exit(readChild(new ClusterTarget.Target(protocol, entityId)));
|
|
971
|
+
if (Exit.isFailure(result)) {
|
|
972
|
+
yield* storeFailure(restore, ended, `The end of child ${entityId} cannot be read: ${renderFailure(result.cause)}`);
|
|
973
|
+
return;
|
|
974
|
+
}
|
|
975
|
+
if (result.value === undefined)
|
|
976
|
+
return;
|
|
977
|
+
// A child that fails fails its parent with the failure it stored,
|
|
978
|
+
// whatever the invocation declares.
|
|
979
|
+
if (result.value._tag === "Failed") {
|
|
980
|
+
yield* storeFailure(restore, ended, result.value.failure);
|
|
981
|
+
return;
|
|
982
|
+
}
|
|
983
|
+
const next = stepper.settle(from, ended, Exit.succeed(result.value.output));
|
|
984
|
+
if (next.state === from)
|
|
985
|
+
return;
|
|
986
|
+
yield* applyOutcome(restore, ended, current, from, next, () => { });
|
|
987
|
+
}).pipe(annotate));
|
|
988
|
+
// One attempt to apply an event that another machine sent. Nobody waits for
|
|
989
|
+
// its answer, so an event that cannot be applied fails the machine, as it
|
|
990
|
+
// does locally, and a failure of the infrastructure is retried. The value is
|
|
991
|
+
// whether nothing is left to do.
|
|
992
|
+
const deliverOnce = (input) => turn((restore) => Effect.suspend(() => {
|
|
993
|
+
// Loaded with the request, so a refusal is never one of an earlier
|
|
994
|
+
// delivery that committed.
|
|
995
|
+
memory = undefined;
|
|
996
|
+
return restore(messageStorage.withTransaction(requestStep(input, undefined))).pipe(Effect.matchCauseEffect({
|
|
997
|
+
onFailure: (cause) => {
|
|
998
|
+
if (Cause.hasInterrupts(cause))
|
|
999
|
+
return propagate(cause);
|
|
1000
|
+
const error = Option.getOrUndefined(Cause.findErrorOption(cause));
|
|
1001
|
+
if (!(error instanceof Refused) || error.failure === undefined || Cause.hasDies(cause)) {
|
|
1002
|
+
return notDone("Could not apply an event that another machine sent", cause);
|
|
1003
|
+
}
|
|
1004
|
+
memory = error.memory;
|
|
1005
|
+
// A machine that ended takes no event, as a local one that stopped,
|
|
1006
|
+
// and neither does a child that has not started.
|
|
1007
|
+
if (error.rejected.reason === "MachineFailed" || (memory?._tag === "Absent" && parent !== undefined)) {
|
|
1008
|
+
return Effect.succeed(true);
|
|
1009
|
+
}
|
|
1010
|
+
return memory?._tag === "Absent"
|
|
1011
|
+
? storeInitialFailure(restore, input.requestId, error.failure)
|
|
1012
|
+
: storeFailure(restore, input, error.failure);
|
|
1013
|
+
},
|
|
1014
|
+
onSuccess: (result) => {
|
|
1015
|
+
memory = result.memory;
|
|
1016
|
+
return Effect.as(align(restore, result.stored), true);
|
|
1017
|
+
}
|
|
1018
|
+
}));
|
|
1019
|
+
})).pipe(annotate);
|
|
1020
|
+
// Stores a machine without a checkpoint as failed in its initial state, when
|
|
1021
|
+
// the first event another machine sent it cannot be applied. A machine
|
|
1022
|
+
// whose initial state cannot be planned stores nothing, and drops the event.
|
|
1023
|
+
const storeInitialFailure = (restore, requestId, failure) => Effect.suspend(() => {
|
|
1024
|
+
memory = undefined;
|
|
1025
|
+
return restore(messageStorage.withTransaction(Effect.gen(function* () {
|
|
1026
|
+
const initial = stepper.start(...options.input);
|
|
1027
|
+
if (Exit.isFailure(initial))
|
|
1028
|
+
return false;
|
|
1029
|
+
const state = initial.value.snapshot;
|
|
1030
|
+
const snapshot = yield* internalMachine.encodeSnapshot(machine, state);
|
|
1031
|
+
const checkpoint = {
|
|
1032
|
+
definitionId,
|
|
1033
|
+
version,
|
|
1034
|
+
revision: 1,
|
|
1035
|
+
origin: { _tag: "Request", requestId },
|
|
1036
|
+
snapshot,
|
|
1037
|
+
status: { _tag: "Failed", failure }
|
|
1038
|
+
};
|
|
1039
|
+
const committed = yield* storage.commit(address, checkpoint);
|
|
1040
|
+
if (committed._tag === "RevisionConflict")
|
|
1041
|
+
return yield* new Conflicted();
|
|
1042
|
+
yield* saveOutgoing(endedFor(true));
|
|
1043
|
+
if (committed._tag === "Committed") {
|
|
1044
|
+
yield* notifyCommit(checkpoint, state);
|
|
1045
|
+
}
|
|
1046
|
+
return true;
|
|
1047
|
+
}))).pipe(Effect.matchCauseEffect({
|
|
1048
|
+
onFailure: (cause) => notDone("Could not store the failure of a Cluster machine", cause),
|
|
1049
|
+
onSuccess: (stored) => {
|
|
1050
|
+
memory = stored ? { _tag: "Failed", revision: 1, failure } : undefined;
|
|
1051
|
+
return Effect.logError(stored ? "A Cluster machine failed" : "A Cluster machine cannot plan its initial state", failure).pipe(Effect.as(true));
|
|
1052
|
+
}
|
|
1053
|
+
}), annotate);
|
|
1054
|
+
});
|
|
1055
|
+
const lifecycle = (input) => turn((restore) => attempt(restore, input).pipe(Effect.catchTag("Conflicted", () => attempt(restore, input)), Effect.catchTag("Conflicted", () => Effect.void),
|
|
1056
|
+
// A stop saves the stops of the children of the child.
|
|
1057
|
+
Effect.tap(() => input.lifecycle === "Stop" ? options.sends?.poll ?? Effect.void : Effect.void), Effect.tap(() => align(restore, undefined)), Effect.asVoid));
|
|
1058
|
+
const applyRequest = (input) => turn((restore) => attempt(restore, input).pipe(
|
|
1059
|
+
// A conflict leaves memory unknown, so the retry loads.
|
|
1060
|
+
Effect.catchTag("Conflicted", () => attempt(restore, input)), Effect.catchTag("Conflicted", () => Effect.succeed(reject("RevisionConflict", "Another instance advanced the checkpoint while this request was applied"))), Effect.tap(() => align(restore, undefined))));
|
|
1061
|
+
return {
|
|
1062
|
+
wake,
|
|
1063
|
+
childEnded,
|
|
1064
|
+
deliver: (input) => untilDone(deliverOnce(input)),
|
|
1065
|
+
childSnapshot: ({ entityId, requestId, snapshot }) => untilDone(deliverOnce({ requestId, event: undefined, child: { entityId, snapshot } })),
|
|
1066
|
+
start: ({ input, requestId }) => applyRequest({
|
|
1067
|
+
requestId,
|
|
1068
|
+
event: undefined,
|
|
1069
|
+
lifecycle: "Start",
|
|
1070
|
+
initial: machine.input === undefined ? [] : [input]
|
|
1071
|
+
}),
|
|
1072
|
+
stop: (requestId) => lifecycle({ requestId, event: undefined, lifecycle: "Stop" }),
|
|
1073
|
+
apply: (input) => applyRequest(input)
|
|
1074
|
+
};
|
|
1075
|
+
});
|
|
1076
|
+
//# sourceMappingURL=clusterInstance.js.map
|