@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,1518 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pure form of a machine: what its next state is, and which work a host
|
|
3
|
+
* starts and stops, shared by every host that runs a machine.
|
|
4
|
+
*
|
|
5
|
+
* Every function is synchronous and returns a value. The host state holds the
|
|
6
|
+
* execution state of the plan, the work that runs, and how many entries of
|
|
7
|
+
* invoking states have begun. Whether work is current is read from
|
|
8
|
+
* the state that a caller passes back, and never from a handle shared with the
|
|
9
|
+
* caller: work is current when that state lists the very object the caller
|
|
10
|
+
* reports, so work of an earlier entry, of a step that was not kept, or of a
|
|
11
|
+
* machine before it resumed, is never taken for the work that runs.
|
|
12
|
+
*
|
|
13
|
+
* A step plans with the execution plan passed to its kernel — normally
|
|
14
|
+
* `compileExecutionPlan` (an indexed kernel for the machines and events it
|
|
15
|
+
* covers, and the reference planner for anything else), or
|
|
16
|
+
* `referenceExecutionPlan` when a caller forces the reference planner.
|
|
17
|
+
*
|
|
18
|
+
* A step function has an {@link Ownership}. A `"Persistent"` step, which
|
|
19
|
+
* `Machine.toStep` returns, takes and returns immutable state values. An
|
|
20
|
+
* `"Owned"` step, for a host that keeps only its latest state, takes each state
|
|
21
|
+
* over and may update its storage in place. See `build` for the full list of
|
|
22
|
+
* differences between the two ownerships.
|
|
23
|
+
*
|
|
24
|
+
* A host applies a step in one order, as the local host in `stepHost.ts`
|
|
25
|
+
* does: commands, `stop` (the work of exited states, or all work when the
|
|
26
|
+
* machine fails or is stopped), the new state, emitted events, `start` (the
|
|
27
|
+
* work of entered states), and `stopAfter` (remaining work of states that
|
|
28
|
+
* stayed active when the machine reached a final state). A step calls no user
|
|
29
|
+
* code for the work it lists: each piece of work evaluates its source and its
|
|
30
|
+
* input mapper when its host starts it, at most once, inside its own startup
|
|
31
|
+
* failure boundary.
|
|
32
|
+
*
|
|
33
|
+
* @since 0.48.0
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import * as Context from "effect/Context"
|
|
37
|
+
import type * as Duration from "effect/Duration"
|
|
38
|
+
import * as Effect from "effect/Effect"
|
|
39
|
+
import * as Equal from "effect/Equal"
|
|
40
|
+
import * as Exit from "effect/Exit"
|
|
41
|
+
import * as Hash from "effect/Hash"
|
|
42
|
+
import * as Stream from "effect/Stream"
|
|
43
|
+
import type { ChildMachine, ChildOwner, Logic, Machine, MachineTarget } from "../../Machine.js"
|
|
44
|
+
import { ChildMachineRuntime, MachineRuntime } from "./capability.js"
|
|
45
|
+
import * as CapturedInvocation from "./capturedInvocation.js"
|
|
46
|
+
import { isChildMachine } from "./child.js"
|
|
47
|
+
import type { RuntimeCommand } from "./command.js"
|
|
48
|
+
import * as Configuration from "./configuration.js"
|
|
49
|
+
import {
|
|
50
|
+
isPlanningError,
|
|
51
|
+
MachineSchemaDecodeError,
|
|
52
|
+
ProcessLocalError,
|
|
53
|
+
StoppedError,
|
|
54
|
+
toStartupFailure
|
|
55
|
+
} from "./errors.js"
|
|
56
|
+
import * as ExecutionPlan from "./executionPlan.js"
|
|
57
|
+
import * as InvocationChanges from "./invocationChanges.js"
|
|
58
|
+
import * as InvocationEvent from "./invocationEvent.js"
|
|
59
|
+
import * as InvocationOutcome from "./invocationOutcome.js"
|
|
60
|
+
import * as InvocationResolution from "./invocationResolution.js"
|
|
61
|
+
import * as LogicScope from "./logicScope.js"
|
|
62
|
+
import * as Planner from "./planner.js"
|
|
63
|
+
import * as Protocol from "./protocol.js"
|
|
64
|
+
import * as Serialization from "./serialization.js"
|
|
65
|
+
|
|
66
|
+
/** @internal */
|
|
67
|
+
export const StateTypeId: unique symbol = Symbol.for("effect/Machine/MachineStep/State")
|
|
68
|
+
|
|
69
|
+
/** @internal */
|
|
70
|
+
export const WorkTypeId: unique symbol = Symbol.for("effect/Machine/MachineStep/Work")
|
|
71
|
+
|
|
72
|
+
/** @internal */
|
|
73
|
+
export const OwnershipTypeId: unique symbol = Symbol.for("effect/Machine/MachineStep/Ownership")
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Who owns the states that a step function takes.
|
|
77
|
+
*
|
|
78
|
+
* - `"Persistent"`: a state is an immutable value. A caller may keep it, step
|
|
79
|
+
* from it again, and read any step it returned at any time. Equal arguments
|
|
80
|
+
* give equal results. `Machine.toStep` returns these step functions.
|
|
81
|
+
* - `"Owned"`: a caller hands each state over to the step function it passes
|
|
82
|
+
* it to, and never uses it again: neither that state nor any step that
|
|
83
|
+
* returned it. The step may update the storage of the state in place and
|
|
84
|
+
* reuse it for the state it returns. Passing a state that was handed over
|
|
85
|
+
* already throws, unless the step returned that very state. A host that keeps
|
|
86
|
+
* only its latest state, such as the local runtime, uses these.
|
|
87
|
+
*
|
|
88
|
+
* Both give equal results for the same inputs, as long as an owned step's
|
|
89
|
+
* results are read before its state is handed over.
|
|
90
|
+
*
|
|
91
|
+
* @internal
|
|
92
|
+
*/
|
|
93
|
+
export type Ownership = ExecutionPlan.ExecutionOwnership
|
|
94
|
+
|
|
95
|
+
type AnyLogic = Logic<unknown, unknown, unknown, unknown, unknown, unknown>
|
|
96
|
+
|
|
97
|
+
/** Selects a child of the running machine: a typed address, or a child machine descriptor. */
|
|
98
|
+
type ChildSelector = string | ChildMachine.Any
|
|
99
|
+
|
|
100
|
+
interface WorkBase {
|
|
101
|
+
readonly [WorkTypeId]: InvocationResolution.ResolvedInvocation
|
|
102
|
+
readonly path: string
|
|
103
|
+
readonly id: string
|
|
104
|
+
readonly source: string | undefined
|
|
105
|
+
readonly run: number
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* One piece of work. Each accessor evaluates user code at most once, and
|
|
110
|
+
* returns its failure instead of throwing.
|
|
111
|
+
*
|
|
112
|
+
* @internal
|
|
113
|
+
*/
|
|
114
|
+
export type Work =
|
|
115
|
+
| WorkBase & {
|
|
116
|
+
readonly _tag: "Effect"
|
|
117
|
+
readonly effect: () => Exit.Exit<Effect.Effect<unknown, unknown, unknown>>
|
|
118
|
+
}
|
|
119
|
+
| WorkBase & {
|
|
120
|
+
readonly _tag: "Timer"
|
|
121
|
+
readonly duration: () => Exit.Exit<Duration.Duration>
|
|
122
|
+
readonly effect: () => Exit.Exit<Effect.Effect<void>>
|
|
123
|
+
}
|
|
124
|
+
| WorkBase & {
|
|
125
|
+
readonly _tag: "Stream"
|
|
126
|
+
readonly stream: () => Exit.Exit<Stream.Stream<unknown, unknown, unknown>>
|
|
127
|
+
}
|
|
128
|
+
| WorkBase & {
|
|
129
|
+
readonly _tag: "Logic"
|
|
130
|
+
readonly address: string
|
|
131
|
+
readonly logic: () => Exit.Exit<AnyLogic>
|
|
132
|
+
}
|
|
133
|
+
| WorkBase & {
|
|
134
|
+
readonly _tag: "Child"
|
|
135
|
+
readonly child: ChildMachine.Any
|
|
136
|
+
readonly input: () => Exit.Exit<ReadonlyArray<unknown>>
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* What a transition asked of the host, in order.
|
|
141
|
+
*
|
|
142
|
+
* @internal
|
|
143
|
+
*/
|
|
144
|
+
export type Command =
|
|
145
|
+
| { readonly _tag: "Send"; readonly target: MachineTarget<unknown>; readonly event: unknown }
|
|
146
|
+
| {
|
|
147
|
+
readonly _tag: "SendToChild"
|
|
148
|
+
readonly child: ChildSelector
|
|
149
|
+
readonly work: Work | undefined
|
|
150
|
+
readonly event: unknown
|
|
151
|
+
}
|
|
152
|
+
| { readonly _tag: "StopChild"; readonly child: ChildSelector; readonly work: Work | undefined }
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Operations on the children of the running machine, which its host owns.
|
|
156
|
+
*
|
|
157
|
+
* @internal
|
|
158
|
+
*/
|
|
159
|
+
export interface Children {
|
|
160
|
+
readonly spawn: (
|
|
161
|
+
child: ChildMachine.Any,
|
|
162
|
+
options: { readonly input: unknown } | undefined
|
|
163
|
+
) => Effect.Effect<unknown, unknown, unknown>
|
|
164
|
+
readonly spawnLogic: (
|
|
165
|
+
logic: AnyLogic,
|
|
166
|
+
options: { readonly id?: string | undefined } | undefined
|
|
167
|
+
) => Effect.Effect<unknown, unknown, unknown>
|
|
168
|
+
readonly sendTo: (
|
|
169
|
+
child: ChildSelector,
|
|
170
|
+
event: unknown
|
|
171
|
+
) => Effect.Effect<void, StoppedError | MachineSchemaDecodeError>
|
|
172
|
+
readonly stop: (child: ChildSelector) => Effect.Effect<void>
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** @internal */
|
|
176
|
+
export interface Options {
|
|
177
|
+
readonly self: MachineTarget<any>
|
|
178
|
+
readonly parent?: MachineTarget<any> | undefined
|
|
179
|
+
readonly children?: Children | undefined
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** @internal */
|
|
183
|
+
export interface Progress {
|
|
184
|
+
readonly path: string
|
|
185
|
+
readonly id: string
|
|
186
|
+
readonly status: "Ended" | "Running"
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* A microstep of a plan. Its state is an execution state of the plan, or a
|
|
191
|
+
* snapshot already for the initial plan.
|
|
192
|
+
*/
|
|
193
|
+
type PlannedMicrostep = ExecutionPlan.ExecutionMicrostep
|
|
194
|
+
|
|
195
|
+
/** A microstep as a step publishes it. */
|
|
196
|
+
interface PublishedMicrostep {
|
|
197
|
+
readonly next: Machine.Snapshot<any>
|
|
198
|
+
readonly event: unknown
|
|
199
|
+
readonly transitions: ReadonlyArray<Machine.RetainedTransition>
|
|
200
|
+
readonly commands: ReadonlyArray<RuntimeCommand>
|
|
201
|
+
readonly raisedEvents: ReadonlyArray<unknown>
|
|
202
|
+
readonly emittedEvents: ReadonlyArray<unknown>
|
|
203
|
+
readonly exitPaths: ReadonlyArray<string>
|
|
204
|
+
readonly entryPaths: ReadonlyArray<string>
|
|
205
|
+
readonly changed: boolean
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Shared planning host base: holds only the machine and execution plan, so
|
|
210
|
+
* subclasses such as the local host can expose their scope's targets and
|
|
211
|
+
* children from the prototype without duplicating own slots.
|
|
212
|
+
*
|
|
213
|
+
* @internal
|
|
214
|
+
*/
|
|
215
|
+
export abstract class PlanningBase implements Configuration.PlanningMachineReferences {
|
|
216
|
+
constructor(
|
|
217
|
+
readonly machine: Machine.Any,
|
|
218
|
+
readonly plan: ExecutionPlan.CompiledExecutionPlan
|
|
219
|
+
) {}
|
|
220
|
+
|
|
221
|
+
abstract readonly self: MachineTarget<any>
|
|
222
|
+
abstract readonly parent: MachineTarget<any> | undefined
|
|
223
|
+
abstract readonly children: Children
|
|
224
|
+
abstract readonly ambient: boolean
|
|
225
|
+
abstract readonly services: Context.Context<MachineRuntime | ChildMachineRuntime>;
|
|
226
|
+
|
|
227
|
+
// A host is compared by identity: hashing a state, as a failure that holds one
|
|
228
|
+
// may be hashed, never reads the targets of the host.
|
|
229
|
+
[Hash.symbol](): number {
|
|
230
|
+
return Hash.random(this)
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
[Equal.symbol](that: unknown): boolean {
|
|
234
|
+
return this === that
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** What the source and input mapper of work receive, built for each entry that resolves work. */
|
|
238
|
+
get capabilities(): InvocationResolution.InvocationCapabilities {
|
|
239
|
+
return { self: this.self, parent: this.parent, children: childOwnerOf(this.children) }
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* The machine of a step function, the plan it steps with, and the host it runs
|
|
245
|
+
* on: what its transitions address, and the children its work acts on. A host
|
|
246
|
+
* builds one for each machine it runs, and every state of that machine carries
|
|
247
|
+
* it. What work needs of it is built when work first needs it, so a machine
|
|
248
|
+
* that invokes nothing holds only these fields.
|
|
249
|
+
*
|
|
250
|
+
* @internal
|
|
251
|
+
*/
|
|
252
|
+
export class Planning extends PlanningBase {
|
|
253
|
+
#services: Context.Context<MachineRuntime | ChildMachineRuntime> | undefined
|
|
254
|
+
readonly children: Children
|
|
255
|
+
|
|
256
|
+
constructor(
|
|
257
|
+
machine: Machine.Any,
|
|
258
|
+
plan: ExecutionPlan.CompiledExecutionPlan,
|
|
259
|
+
readonly self: MachineTarget<any>,
|
|
260
|
+
readonly parent: MachineTarget<any> | undefined,
|
|
261
|
+
/** The children of the machine, or `undefined` when the host supplies none. */
|
|
262
|
+
children: Children = refusedChildren,
|
|
263
|
+
/**
|
|
264
|
+
* Whether the host runs work inside the services of this machine already,
|
|
265
|
+
* as the local runtime runs work in processes of the machine, so work is
|
|
266
|
+
* not provided them again.
|
|
267
|
+
*/
|
|
268
|
+
readonly ambient = false
|
|
269
|
+
) {
|
|
270
|
+
super(machine, plan)
|
|
271
|
+
this.children = children
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** The services through which work acts on the children of this machine. */
|
|
275
|
+
get services(): Context.Context<MachineRuntime | ChildMachineRuntime> {
|
|
276
|
+
return this.#services ??= servicesOf(this.children)
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const empty: ReadonlyArray<never> = []
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* The host state. `execution` is the execution state of the plan, which
|
|
284
|
+
* carries no machine references: they are attached for each plan, as the local
|
|
285
|
+
* runtime attaches them. The configuration and the public snapshot are built
|
|
286
|
+
* from it on first read.
|
|
287
|
+
*
|
|
288
|
+
* A state that rests holds only its snapshot, its work and its runs: its
|
|
289
|
+
* execution state is built again from the snapshot when a step needs it, as a
|
|
290
|
+
* host that keeps a machine idle does not hold it.
|
|
291
|
+
*
|
|
292
|
+
* A `"Persistent"` state never changes after it is built. The `execution` of
|
|
293
|
+
* an `"Owned"` state is written in place by the step that it is handed over to,
|
|
294
|
+
* and so is everything read from it that was not read before.
|
|
295
|
+
*
|
|
296
|
+
* @internal
|
|
297
|
+
*/
|
|
298
|
+
export class State<O extends Ownership = "Persistent"> {
|
|
299
|
+
declare readonly [StateTypeId]: typeof StateTypeId
|
|
300
|
+
declare readonly [OwnershipTypeId]: O
|
|
301
|
+
#execution: unknown
|
|
302
|
+
#configuration: Configuration.ActiveConfiguration | undefined
|
|
303
|
+
#snapshot: Machine.Snapshot<any> | undefined
|
|
304
|
+
/** Whether an owned state was handed over to a step, which may have written it. */
|
|
305
|
+
#handedOver = false
|
|
306
|
+
|
|
307
|
+
constructor(
|
|
308
|
+
readonly planning: PlanningBase,
|
|
309
|
+
/** The execution state of the plan, or `undefined` for a state that rests. */
|
|
310
|
+
execution: unknown,
|
|
311
|
+
configuration: Configuration.ActiveConfiguration | undefined,
|
|
312
|
+
snapshot: Machine.Snapshot<any> | undefined,
|
|
313
|
+
/** The work that runs, in start order. */
|
|
314
|
+
readonly running: ReadonlyArray<Work>,
|
|
315
|
+
/** How many entries of invoking states have begun: the run of the next one. */
|
|
316
|
+
readonly runs: number,
|
|
317
|
+
readonly exit: Exit.Exit<unknown, unknown> | undefined
|
|
318
|
+
) {
|
|
319
|
+
this.#execution = execution
|
|
320
|
+
this.#configuration = configuration
|
|
321
|
+
this.#snapshot = snapshot
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
get machine(): Machine.Any {
|
|
325
|
+
return this.planning.machine
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** The execution state of the plan. Building it again from the snapshot may throw. */
|
|
329
|
+
get execution(): unknown {
|
|
330
|
+
const execution = this.#execution
|
|
331
|
+
return execution !== undefined
|
|
332
|
+
? execution
|
|
333
|
+
: (this.#execution = this.planning.plan.fromConfiguration(this.configuration))
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
get configuration(): Configuration.ActiveConfiguration {
|
|
337
|
+
const configuration = this.#configuration
|
|
338
|
+
if (configuration !== undefined) return configuration
|
|
339
|
+
return this.#configuration = this.#execution === undefined
|
|
340
|
+
? Configuration.normalizeConfigurationSync(this.planning.machine, this.#snapshot!)
|
|
341
|
+
: this.planning.plan.toConfiguration(this.#execution)
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
get snapshot(): Machine.Snapshot<any> {
|
|
345
|
+
const snapshot = this.#snapshot
|
|
346
|
+
return snapshot !== undefined ? snapshot : (this.#snapshot = this.planning.plan.snapshot(this.#execution))
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** This state with other running work, keeping what was read of it. */
|
|
350
|
+
withRunning(running: ReadonlyArray<Work>): State<O> {
|
|
351
|
+
return new State(this.planning, this.#execution, this.#configuration, this.#snapshot, running, this.runs, this.exit)
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** This state as it rests: its snapshot, its work and its runs. */
|
|
355
|
+
resting(): State<O> {
|
|
356
|
+
return new State(this.planning, undefined, undefined, this.snapshot, this.running, this.runs, this.exit)
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Updates an owned state in place to rest without allocating a new wrapper. */
|
|
360
|
+
restInPlace(): this {
|
|
361
|
+
if (this.#handedOver) {
|
|
362
|
+
throw new Error(
|
|
363
|
+
"An owned MachineStep state was reused after it was handed over to a step: never reuse an owned state after passing it"
|
|
364
|
+
)
|
|
365
|
+
}
|
|
366
|
+
this.#snapshot ??= this.planning.plan.snapshot(this.#execution)
|
|
367
|
+
this.#execution = undefined
|
|
368
|
+
this.#configuration = undefined
|
|
369
|
+
return this
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** Updates an owned state's execution and snapshot in place when a move needs no new state wrapper. */
|
|
373
|
+
replaceExecution(execution: unknown, snapshot: Machine.Snapshot<any>): void {
|
|
374
|
+
this.#execution = execution
|
|
375
|
+
this.#configuration = undefined
|
|
376
|
+
this.#snapshot = snapshot
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** What was built of this state, without building anything. */
|
|
380
|
+
get built(): { readonly execution: unknown; readonly configuration: Configuration.ActiveConfiguration | undefined } {
|
|
381
|
+
return { execution: this.#execution, configuration: this.#configuration }
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** Checks that an owned state has not been handed over, without marking it handed over. */
|
|
385
|
+
assertNotHandedOver(): void {
|
|
386
|
+
if (this.#handedOver) {
|
|
387
|
+
throw new Error(
|
|
388
|
+
"An owned MachineStep state was reused after it was handed over to a step: never reuse an owned state after passing it"
|
|
389
|
+
)
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Hands an owned state over to one step. From this call on, the caller
|
|
395
|
+
* promises never to reuse this state, nor any step that returned it: the step
|
|
396
|
+
* may write it in place. Handing over a state twice throws.
|
|
397
|
+
*/
|
|
398
|
+
handOverNeverReuse(): this {
|
|
399
|
+
this.assertNotHandedOver()
|
|
400
|
+
this.#handedOver = true
|
|
401
|
+
return this
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Gives an owned state back to its caller, only when the step returned this
|
|
406
|
+
* very state unchanged, or refused the event: the caller may pass it again.
|
|
407
|
+
*/
|
|
408
|
+
giveBackUnchanged(): void {
|
|
409
|
+
this.#handedOver = false
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** The paths that a step exited and entered. */
|
|
414
|
+
interface Paths {
|
|
415
|
+
readonly exited: ReadonlyArray<string>
|
|
416
|
+
readonly entered: ReadonlyArray<string>
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const noPaths: Paths = { exited: empty, entered: empty }
|
|
420
|
+
|
|
421
|
+
/** The paths of an initial step, sorted when first read. */
|
|
422
|
+
class InitialPaths implements Paths {
|
|
423
|
+
#entered: ReadonlyArray<string> | undefined
|
|
424
|
+
readonly exited: ReadonlyArray<string> = empty
|
|
425
|
+
constructor(
|
|
426
|
+
private readonly machine: Machine.Any,
|
|
427
|
+
private readonly paths: ReadonlyArray<string> | (() => ReadonlyArray<string>)
|
|
428
|
+
) {}
|
|
429
|
+
get entered(): ReadonlyArray<string> {
|
|
430
|
+
return this.#entered ??= Planner.sortEntryPaths(
|
|
431
|
+
this.machine,
|
|
432
|
+
typeof this.paths === "function" ? this.paths() : this.paths
|
|
433
|
+
)
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
const pathsOf = (microsteps: ReadonlyArray<InvocationChanges.Microstep>): Paths => {
|
|
438
|
+
const changes = InvocationChanges.fromMicrosteps(microsteps)
|
|
439
|
+
return changes === undefined
|
|
440
|
+
? noPaths
|
|
441
|
+
: { exited: Array.from(new Set(changes.exited)), entered: Array.from(changes.entered.keys()) }
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* What one step did. Its microsteps are made public on first read.
|
|
446
|
+
*
|
|
447
|
+
* @internal
|
|
448
|
+
*/
|
|
449
|
+
export class Step<O extends Ownership = "Persistent"> {
|
|
450
|
+
#microsteps: ReadonlyArray<PlannedMicrostep> | undefined
|
|
451
|
+
#published: ReadonlyArray<PublishedMicrostep> | undefined
|
|
452
|
+
#paths: Paths | undefined
|
|
453
|
+
|
|
454
|
+
constructor(
|
|
455
|
+
readonly state: State<O>,
|
|
456
|
+
readonly event: unknown,
|
|
457
|
+
microsteps: ReadonlyArray<PlannedMicrostep>,
|
|
458
|
+
readonly emitted: ReadonlyArray<unknown>,
|
|
459
|
+
readonly commands: ReadonlyArray<Command>,
|
|
460
|
+
readonly stop: ReadonlyArray<Work>,
|
|
461
|
+
readonly start: ReadonlyArray<Work>,
|
|
462
|
+
readonly stopAfter: ReadonlyArray<Work> = empty,
|
|
463
|
+
/** The paths of an initial step, which its microsteps do not list. Read from the microsteps otherwise. */
|
|
464
|
+
paths?: Paths
|
|
465
|
+
) {
|
|
466
|
+
this.#microsteps = microsteps
|
|
467
|
+
this.#paths = paths
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** Paths of the states the step exited, in exit order, each once. */
|
|
471
|
+
get exited(): ReadonlyArray<string> {
|
|
472
|
+
return (this.#paths ??= pathsOf(this.#microsteps ?? this.#published!)).exited
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** Paths of the states the step entered, in entry order, each once. */
|
|
476
|
+
get entered(): ReadonlyArray<string> {
|
|
477
|
+
return (this.#paths ??= pathsOf(this.#microsteps ?? this.#published!)).entered
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
get snapshot(): Machine.Snapshot<any> {
|
|
481
|
+
return this.state.snapshot
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** Whether the step planned a microstep, so its state is a new one to publish. */
|
|
485
|
+
get planned(): boolean {
|
|
486
|
+
return (this.#microsteps ?? this.#published!).length > 0
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
get running(): ReadonlyArray<Work> {
|
|
490
|
+
return this.state.running
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
get exit(): Exit.Exit<unknown, unknown> | undefined {
|
|
494
|
+
return this.state.exit
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
get microsteps(): ReadonlyArray<PublishedMicrostep> {
|
|
498
|
+
if (this.#published === undefined) {
|
|
499
|
+
const plan = this.state.planning.plan
|
|
500
|
+
const planned = this.#microsteps!
|
|
501
|
+
this.#microsteps = undefined
|
|
502
|
+
// Initial planning has published its microsteps already.
|
|
503
|
+
this.#published = planned.length === 0 || this.event === Planner.InitialEvent
|
|
504
|
+
? planned as ReadonlyArray<PublishedMicrostep>
|
|
505
|
+
: planned.map((microstep): PublishedMicrostep => ({
|
|
506
|
+
next: plan.snapshot(microstep.next),
|
|
507
|
+
event: microstep.event,
|
|
508
|
+
transitions: microstep.transitions!,
|
|
509
|
+
commands: microstep.commands,
|
|
510
|
+
raisedEvents: microstep.raisedEvents,
|
|
511
|
+
emittedEvents: microstep.emittedEvents,
|
|
512
|
+
exitPaths: microstep.exitPaths,
|
|
513
|
+
entryPaths: microstep.entryPaths,
|
|
514
|
+
changed: microstep.changed
|
|
515
|
+
}))
|
|
516
|
+
}
|
|
517
|
+
return this.#published
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* The step functions of a machine. Each one takes a state of its own
|
|
523
|
+
* {@link Ownership}.
|
|
524
|
+
*
|
|
525
|
+
* @internal
|
|
526
|
+
*/
|
|
527
|
+
export interface MachineStep<O extends Ownership = "Persistent"> {
|
|
528
|
+
readonly start: (...input: ReadonlyArray<unknown>) => Exit.Exit<Step<O>, unknown>
|
|
529
|
+
readonly send: (state: State<O>, event: unknown) => Exit.Exit<Step<O>, unknown>
|
|
530
|
+
/**
|
|
531
|
+
* Plans an event that its host decoded already, as `send` does after it
|
|
532
|
+
* decodes. A machine that has ended takes no event: its host stops sending.
|
|
533
|
+
*/
|
|
534
|
+
readonly sendDecoded: (state: State<O>, event: Machine.EventOf<any>) => Step<O>
|
|
535
|
+
readonly settle: (state: State<O>, work: Work, exit: Exit.Exit<unknown, unknown>) => Step<O>
|
|
536
|
+
readonly element: (state: State<O>, work: Work, element: unknown) => Step<O>
|
|
537
|
+
readonly report: (state: State<O>, work: Work, snapshot: unknown) => Step<O>
|
|
538
|
+
readonly stop: (state: State<O>) => Step<O>
|
|
539
|
+
readonly resume: (
|
|
540
|
+
snapshot: Machine.Snapshot<any>,
|
|
541
|
+
progress?: ReadonlyArray<Progress>
|
|
542
|
+
) => Exit.Exit<Step<O>, unknown>
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* Step functions that take each state over, for a host that keeps only its
|
|
547
|
+
* latest state. See {@link Ownership}.
|
|
548
|
+
*
|
|
549
|
+
* @internal
|
|
550
|
+
*/
|
|
551
|
+
export type OwnedMachineStep = MachineStep<"Owned">
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* The step functions of a machine, built once for each `(ownership, plan)`
|
|
555
|
+
* pair, for every host that runs it. A state carries the {@link PlanningBase}
|
|
556
|
+
* of its host, so only `start`, `resume`, and `fromSnapshot`, which take no
|
|
557
|
+
* state, are passed one.
|
|
558
|
+
*
|
|
559
|
+
* Host-level optimizations on this kernel:
|
|
560
|
+
* - `retain`: passing `retain: false` to `start`, `sendDecoded`, `settle`,
|
|
561
|
+
* `element`, or `report` tells the step that its host reads no microstep
|
|
562
|
+
* (only `snapshot`, `exited`, `entered`, `commands`, `emitted`, work, and
|
|
563
|
+
* `exit`). An `"Owned"` plan may write in place without retaining
|
|
564
|
+
* transitions, and `start` takes `plan.initial` when available.
|
|
565
|
+
* - `ambient`: on {@link PlanningBase}, `ambient: true` tells work accessors
|
|
566
|
+
* that the host runs work inside the machine's own services already, so work
|
|
567
|
+
* does not wrap effects/streams/logic with `planning.services` again.
|
|
568
|
+
* - `move`: unretained fast path for a host that commits snapshots directly.
|
|
569
|
+
* - `rest` and `fromSnapshot`: let an idle host drop execution storage and
|
|
570
|
+
* rebuild it from the published snapshot when the next message arrives.
|
|
571
|
+
*
|
|
572
|
+
* @internal
|
|
573
|
+
*/
|
|
574
|
+
export interface Kernel<O extends Ownership>
|
|
575
|
+
extends Omit<MachineStep<O>, "start" | "resume" | "sendDecoded" | "settle" | "element" | "report">
|
|
576
|
+
{
|
|
577
|
+
readonly plan: ExecutionPlan.CompiledExecutionPlan
|
|
578
|
+
/**
|
|
579
|
+
* As in {@link MachineStep}. A host that reads no microstep of the step it
|
|
580
|
+
* gets passes `retain: false`, so an owned plan writes in place and keeps no
|
|
581
|
+
* transition; the step still lists the paths it exited and entered.
|
|
582
|
+
*/
|
|
583
|
+
readonly sendDecoded: (state: State<O>, event: Machine.EventOf<any>, retain?: boolean) => Step<O>
|
|
584
|
+
/**
|
|
585
|
+
* Plans a decoded event whose microsteps no one reads, as `sendDecoded` with
|
|
586
|
+
* `retain: false` does, for a host that commits snapshots directly.
|
|
587
|
+
*
|
|
588
|
+
* - Returns `undefined` when the event changed nothing or the machine has
|
|
589
|
+
* already ended (an `"Owned"` state remains live).
|
|
590
|
+
* - When a childless machine only moves to a new state (no commands,
|
|
591
|
+
* emissions, or end): an `"Owned"` kernel updates `state` in place and
|
|
592
|
+
* returns the new snapshot with no `State` or `Step` allocation (keeping
|
|
593
|
+
* `state` live); a `"Persistent"` kernel leaves `state` untouched and
|
|
594
|
+
* returns a `Step` holding the new state.
|
|
595
|
+
* - Otherwise (invoking machine, commands, emissions, completion, or throw)
|
|
596
|
+
* returns a `Step`, handing an `"Owned"` `state` over unless the step
|
|
597
|
+
* returned `state` unchanged.
|
|
598
|
+
*/
|
|
599
|
+
readonly move: (
|
|
600
|
+
state: State<O>,
|
|
601
|
+
event: Machine.EventOf<any>
|
|
602
|
+
) => Machine.Snapshot<any> | Step<O> | undefined
|
|
603
|
+
readonly settle: (state: State<O>, work: Work, exit: Exit.Exit<unknown, unknown>, retain?: boolean) => Step<O>
|
|
604
|
+
readonly element: (state: State<O>, work: Work, element: unknown, retain?: boolean) => Step<O>
|
|
605
|
+
readonly report: (state: State<O>, work: Work, snapshot: unknown, retain?: boolean) => Step<O>
|
|
606
|
+
/** Whether `work` observes active snapshots (so a host subscribes to them). */
|
|
607
|
+
readonly observesSnapshots: (work: Work) => boolean
|
|
608
|
+
/**
|
|
609
|
+
* The invocation event that `settle` will plan for `exit`, for a host that
|
|
610
|
+
* attaches inspection causation to its mailbox message, or `undefined` when
|
|
611
|
+
* `settle` fails the machine directly or ignores the result.
|
|
612
|
+
*/
|
|
613
|
+
readonly settleEvent: (work: Work, exit: Exit.Exit<unknown, unknown>) => unknown
|
|
614
|
+
/**
|
|
615
|
+
* The invocation event that `element` will plan for `value`, for inspection
|
|
616
|
+
* causation, or `undefined` when ignored.
|
|
617
|
+
*/
|
|
618
|
+
readonly elementEvent: (work: Work, value: unknown) => unknown
|
|
619
|
+
/**
|
|
620
|
+
* The invocation event that `report` will plan for `snapshot`, for inspection
|
|
621
|
+
* causation, or `undefined` when ignored.
|
|
622
|
+
*/
|
|
623
|
+
readonly snapshotEvent: (work: Work, snapshot: unknown) => unknown
|
|
624
|
+
/**
|
|
625
|
+
* Starts the machine with `input`. With `retain: false`, a machine that
|
|
626
|
+
* `plan.initial` covers starts directly on the plan and its step lists no
|
|
627
|
+
* microsteps; `exited`, `entered`, `snapshot`, work, and `exit` stay equal.
|
|
628
|
+
*/
|
|
629
|
+
readonly start: (
|
|
630
|
+
planning: PlanningBase,
|
|
631
|
+
input: ReadonlyArray<unknown>,
|
|
632
|
+
retain?: boolean
|
|
633
|
+
) => Exit.Exit<Step<O>, unknown>
|
|
634
|
+
/**
|
|
635
|
+
* Starts a childless machine directly from `plan.initial`, returning its
|
|
636
|
+
* initial snapshot and completion without allocating a `Step` or `State`.
|
|
637
|
+
* Throws the same startup failure that `start` fails with. Present only when
|
|
638
|
+
* the machine invokes no work and `plan.initial` covers it.
|
|
639
|
+
*/
|
|
640
|
+
readonly startSnapshot:
|
|
641
|
+
| ((
|
|
642
|
+
references: Configuration.PlanningMachineReferences,
|
|
643
|
+
input: ReadonlyArray<unknown>
|
|
644
|
+
) =>
|
|
645
|
+
| { readonly state: Machine.Snapshot<any>; readonly done: false; readonly output: undefined }
|
|
646
|
+
| { readonly state: Machine.Snapshot<any>; readonly done: true; readonly output: unknown })
|
|
647
|
+
| undefined
|
|
648
|
+
readonly resume: (
|
|
649
|
+
planning: PlanningBase,
|
|
650
|
+
snapshot: Machine.Snapshot<any>,
|
|
651
|
+
progress?: ReadonlyArray<Progress>
|
|
652
|
+
) => Exit.Exit<Step<O>, unknown>
|
|
653
|
+
/**
|
|
654
|
+
* The state of an active machine that invokes no work, from a snapshot that
|
|
655
|
+
* its host published: a host that keeps only that snapshot while the machine
|
|
656
|
+
* is idle builds its state again with it. It throws for a machine that
|
|
657
|
+
* invokes work, whose work a snapshot does not hold, and for a snapshot that
|
|
658
|
+
* does not normalize.
|
|
659
|
+
*/
|
|
660
|
+
readonly fromSnapshot: (planning: PlanningBase, snapshot: Machine.Snapshot<any>) => State<O>
|
|
661
|
+
/**
|
|
662
|
+
* The state as it rests, for a host that keeps a machine idle: its snapshot,
|
|
663
|
+
* its work and its runs. A later step builds its execution state again from
|
|
664
|
+
* the snapshot. `"Persistent"` returns a new resting state; `"Owned"` clears
|
|
665
|
+
* execution and configuration storage in place and returns the same state.
|
|
666
|
+
*/
|
|
667
|
+
readonly rest: (state: State<O>) => State<O>
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
/** @internal */
|
|
671
|
+
export const isState = (value: unknown): value is State<Ownership> => value instanceof State
|
|
672
|
+
|
|
673
|
+
/**
|
|
674
|
+
* One piece of work, as a step lists it. What it describes is read from its
|
|
675
|
+
* invocation, and each accessor evaluates user code once and keeps its result,
|
|
676
|
+
* so a piece of work holds no closure of its own. Work is compared by identity.
|
|
677
|
+
*/
|
|
678
|
+
class WorkOf {
|
|
679
|
+
#evaluated: Exit.Exit<unknown> | undefined
|
|
680
|
+
readonly [WorkTypeId]: InvocationResolution.ResolvedInvocation
|
|
681
|
+
|
|
682
|
+
constructor(
|
|
683
|
+
invocation: InvocationResolution.ResolvedInvocation,
|
|
684
|
+
readonly run: number,
|
|
685
|
+
private readonly planning: PlanningBase | undefined
|
|
686
|
+
) {
|
|
687
|
+
this[WorkTypeId] = invocation
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
[Hash.symbol](): number {
|
|
691
|
+
return Hash.random(this)
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
[Equal.symbol](that: unknown): boolean {
|
|
695
|
+
return this === that
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
get _tag(): Work["_tag"] {
|
|
699
|
+
return this[WorkTypeId]._tag
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
get path(): string {
|
|
703
|
+
return this[WorkTypeId].path
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
get id(): string {
|
|
707
|
+
return this[WorkTypeId].id
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
get source(): string | undefined {
|
|
711
|
+
const invocation = this[WorkTypeId]
|
|
712
|
+
return invocation._tag === "Child" ? undefined : invocation.sourceName
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
get address(): string | undefined {
|
|
716
|
+
const invocation = this[WorkTypeId]
|
|
717
|
+
return invocation._tag === "Logic" ? invocation.address : undefined
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
get child(): ChildMachine.Any | undefined {
|
|
721
|
+
const invocation = this[WorkTypeId]
|
|
722
|
+
return invocation._tag === "Child" ? invocation.child : undefined
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
/** Evaluates user code once, and keeps its result or its throw. */
|
|
726
|
+
private evaluate<A>(evaluate: (invocation: any) => A): Exit.Exit<A> {
|
|
727
|
+
if (this.#evaluated === undefined) {
|
|
728
|
+
try {
|
|
729
|
+
this.#evaluated = Exit.succeed(evaluate(this[WorkTypeId]))
|
|
730
|
+
} catch (error) {
|
|
731
|
+
this.#evaluated = Exit.die(error)
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
return this.#evaluated as Exit.Exit<A>
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/** Work acts on the children of its machine through the services of its host. */
|
|
738
|
+
private provide<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, unknown> {
|
|
739
|
+
const planning = this.planning
|
|
740
|
+
return planning === undefined || planning.ambient
|
|
741
|
+
? effect
|
|
742
|
+
: Effect.updateContext(effect, (context: Context.Context<unknown>) => Context.merge(context, planning.services))
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
effect(): Exit.Exit<Effect.Effect<unknown, unknown, unknown>> {
|
|
746
|
+
if (this[WorkTypeId]._tag === "Timer") return Exit.map(this.duration(), Effect.sleep)
|
|
747
|
+
// Each run owns a scope, closed with its exit, as on the local runtime.
|
|
748
|
+
return this.evaluate((invocation: InvocationResolution.EffectInvocation) =>
|
|
749
|
+
this.provide(Effect.scoped(invocation.effect()))
|
|
750
|
+
)
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
duration(): Exit.Exit<Duration.Duration> {
|
|
754
|
+
return this.evaluate((invocation: InvocationResolution.TimerInvocation) => invocation.duration())
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
stream(): Exit.Exit<Stream.Stream<unknown, unknown, unknown>> {
|
|
758
|
+
// A run of a Stream owns a scope too, closed with its end or its stop.
|
|
759
|
+
return this.evaluate((invocation: InvocationResolution.StreamInvocation) => {
|
|
760
|
+
const planning = this.planning
|
|
761
|
+
const stream = Stream.scoped(invocation.stream())
|
|
762
|
+
return planning === undefined || planning.ambient
|
|
763
|
+
? stream
|
|
764
|
+
: Stream.updateContext(stream, (context: Context.Context<unknown>) => Context.merge(context, planning.services))
|
|
765
|
+
})
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
logic(): Exit.Exit<AnyLogic> {
|
|
769
|
+
return this.evaluate((invocation: InvocationResolution.LogicInvocation) => {
|
|
770
|
+
const scoped = LogicScope.scoped(invocation.logic())
|
|
771
|
+
if (this.planning === undefined || this.planning.ambient) return scoped
|
|
772
|
+
return {
|
|
773
|
+
initial: (context) => this.provide(scoped.initial(context)),
|
|
774
|
+
run: (context) => this.provide(scoped.run(context))
|
|
775
|
+
}
|
|
776
|
+
})
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
input(): Exit.Exit<ReadonlyArray<unknown>> {
|
|
780
|
+
return this.evaluate((invocation: Extract<InvocationResolution.ResolvedInvocation, { readonly _tag: "Child" }>) =>
|
|
781
|
+
invocation.input === undefined ? empty : [invocation.input()]
|
|
782
|
+
)
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
const unchanged = <O extends Ownership>(state: State<O>): Step<O> =>
|
|
787
|
+
new Step(state, undefined, empty, empty, empty, empty, empty)
|
|
788
|
+
|
|
789
|
+
/** Builds the step of a childless machine for a planned macrostep. */
|
|
790
|
+
const childlessStep = <O extends Ownership>(
|
|
791
|
+
state: State<O>,
|
|
792
|
+
planned: ExecutionPlan.ExecutionMacrostep,
|
|
793
|
+
commands: ReadonlyArray<Command>
|
|
794
|
+
): Step<O> =>
|
|
795
|
+
new Step(
|
|
796
|
+
new State<O>(
|
|
797
|
+
state.planning,
|
|
798
|
+
planned.next,
|
|
799
|
+
undefined,
|
|
800
|
+
undefined,
|
|
801
|
+
empty,
|
|
802
|
+
state.runs,
|
|
803
|
+
planned.done ? Exit.succeed(planned.output) : undefined
|
|
804
|
+
),
|
|
805
|
+
planned.event,
|
|
806
|
+
planned.microsteps,
|
|
807
|
+
planned.emittedEvents,
|
|
808
|
+
commands,
|
|
809
|
+
empty,
|
|
810
|
+
empty
|
|
811
|
+
)
|
|
812
|
+
|
|
813
|
+
/** A planning throw: typed for the planner's own errors, a defect otherwise. */
|
|
814
|
+
const exitOfThrow = (error: unknown): Exit.Exit<never, unknown> =>
|
|
815
|
+
isPlanningError(error) ? Exit.fail(error) : Exit.die(error)
|
|
816
|
+
|
|
817
|
+
/** The work that runs in a state, latest first, as a host stops it when its machine ends. */
|
|
818
|
+
const latestFirst = (running: ReadonlyArray<Work>): ReadonlyArray<Work> =>
|
|
819
|
+
running.length < 2 ? running : running.slice().reverse()
|
|
820
|
+
|
|
821
|
+
/** Whether a running piece of work is the child that a command selects, as the local registry matches it. */
|
|
822
|
+
const selects = (work: Work, child: ChildSelector): boolean =>
|
|
823
|
+
typeof child === "string"
|
|
824
|
+
? (work._tag === "Logic" && work.address === child) || (work._tag === "Child" && work.child.id === child)
|
|
825
|
+
: work._tag === "Child" && work.child.id === child.id && work.child.machine === child.machine
|
|
826
|
+
|
|
827
|
+
const refuse = (operation: string): Effect.Effect<never> => Effect.die(new ProcessLocalError({ operation }))
|
|
828
|
+
|
|
829
|
+
// A host that supplies no children owns none, as on Cluster.
|
|
830
|
+
const refusedChildren: Children = {
|
|
831
|
+
spawn: () => refuse("children.spawn"),
|
|
832
|
+
spawnLogic: () => refuse("spawn"),
|
|
833
|
+
sendTo: () => refuse("sendTo"),
|
|
834
|
+
stop: () => refuse("stopChild")
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
const childOwnerOf = (children: Children): ChildOwner<any> => ({
|
|
838
|
+
spawn:
|
|
839
|
+
((child: ChildMachine.Any, ...options: ReadonlyArray<{ readonly input: unknown }>) =>
|
|
840
|
+
children.spawn(child, options[0])) as ChildOwner<any>["spawn"],
|
|
841
|
+
sendTo: (child, event) => children.sendTo(child, event),
|
|
842
|
+
stop: (child) => children.stop(child)
|
|
843
|
+
})
|
|
844
|
+
|
|
845
|
+
const servicesOf = (children: Children): Context.Context<MachineRuntime | ChildMachineRuntime> =>
|
|
846
|
+
Context.make(
|
|
847
|
+
MachineRuntime,
|
|
848
|
+
MachineRuntime.of({
|
|
849
|
+
spawn: ((logic: AnyLogic, options?: { readonly id?: string }) =>
|
|
850
|
+
children.spawnLogic(logic, options)) as MachineRuntime["Service"]["spawn"],
|
|
851
|
+
sendTo: (child, event) =>
|
|
852
|
+
children.sendTo(child as ChildSelector, event),
|
|
853
|
+
stopChild: (child) => children.stop(child as ChildSelector)
|
|
854
|
+
})
|
|
855
|
+
).pipe(
|
|
856
|
+
Context.add(
|
|
857
|
+
ChildMachineRuntime,
|
|
858
|
+
ChildMachineRuntime.of({
|
|
859
|
+
sendTo: (child, event) => children.sendTo(child, event),
|
|
860
|
+
stopChild: (child) => children.stop(child)
|
|
861
|
+
})
|
|
862
|
+
)
|
|
863
|
+
)
|
|
864
|
+
|
|
865
|
+
/** The paths whose states invoke work. */
|
|
866
|
+
const invokingPathsCache = new WeakMap<Machine.Any, ReadonlySet<string>>()
|
|
867
|
+
|
|
868
|
+
const invokingPaths = (machine: Machine.Any): ReadonlySet<string> => {
|
|
869
|
+
let paths = invokingPathsCache.get(machine)
|
|
870
|
+
if (paths === undefined) {
|
|
871
|
+
const invoking = new Set<string>()
|
|
872
|
+
for (const path of machine.stateNodes.byPath.keys()) {
|
|
873
|
+
if (CapturedInvocation.list(Configuration.getStateConfigByPath(machine, path)?.invoke).length > 0) {
|
|
874
|
+
invoking.add(path)
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
paths = invoking
|
|
878
|
+
invokingPathsCache.set(machine, paths)
|
|
879
|
+
}
|
|
880
|
+
return paths
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
const observesSnapshots = (work: Work): boolean => work[WorkTypeId].channels.snapshot
|
|
884
|
+
|
|
885
|
+
const settleEvent = (work: Work, exit: Exit.Exit<unknown, unknown>): unknown => {
|
|
886
|
+
const decision = InvocationOutcome.decide(work[WorkTypeId], { current: true }, InvocationOutcome.fromExit(exit))
|
|
887
|
+
return decision._tag === "Deliver" ? decision.event : undefined
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
const elementEvent = (work: Work, value: unknown): unknown => {
|
|
891
|
+
const invocation = work[WorkTypeId]
|
|
892
|
+
if (invocation._tag !== "Stream") return undefined
|
|
893
|
+
const decision = InvocationOutcome.decideElement(invocation, { current: true }, value)
|
|
894
|
+
return decision._tag === "Deliver" ? decision.event : undefined
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
const snapshotEvent = (work: Work, snapshot: unknown): unknown => {
|
|
898
|
+
const invocation = work[WorkTypeId]
|
|
899
|
+
if (invocation._tag !== "Logic" && invocation._tag !== "Child") return undefined
|
|
900
|
+
const decision = InvocationOutcome.decideSnapshot(invocation, { current: true }, {
|
|
901
|
+
status: "active",
|
|
902
|
+
state: snapshot
|
|
903
|
+
})
|
|
904
|
+
return decision._tag === "Deliver" ? decision.event : undefined
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
/**
|
|
908
|
+
* The step functions of `machine`, which plan with `plan` and take states of
|
|
909
|
+
* `ownership`. Every difference between `"Owned"` and `"Persistent"` lives here:
|
|
910
|
+
*
|
|
911
|
+
* 1. **Execution-state writes**: `ownership` is passed to `plan.planDecoded`
|
|
912
|
+
* (a `"Persistent"` plan copies what it writes; an `"Owned"` flat indexed
|
|
913
|
+
* plan writes active values in place, restoring them on throw).
|
|
914
|
+
* 2. **Handover enforcement**: `"Owned"` marks a passed state handed over so
|
|
915
|
+
* reusing it throws, giving it back only when a step returns that exact
|
|
916
|
+
* state unchanged or refuses the event.
|
|
917
|
+
* 3. **Retained configuration in `enter`**: `"Owned"` drops the resolved
|
|
918
|
+
* `ActiveConfiguration` after resolving invocations so idle or subsequent
|
|
919
|
+
* steps do not retain it; `"Persistent"` keeps it on the state.
|
|
920
|
+
* 4. **Resting (`rest`)**: `"Owned"` clears execution and configuration storage
|
|
921
|
+
* in place on the state (`restInPlace`); `"Persistent"` allocates a new
|
|
922
|
+
* resting `State`.
|
|
923
|
+
* 5. **Unretained childless moves (`move`)**: when a childless machine only
|
|
924
|
+
* moves to a new state (no commands, emissions, or end), `"Owned"` updates
|
|
925
|
+
* `state` in place and returns its new `Snapshot` directly; `"Persistent"`
|
|
926
|
+
* returns a `Step` with a fresh `State`.
|
|
927
|
+
*/
|
|
928
|
+
const build = <O extends Ownership>(
|
|
929
|
+
machine: Machine.Any,
|
|
930
|
+
ownership: O,
|
|
931
|
+
plan: ExecutionPlan.CompiledExecutionPlan
|
|
932
|
+
): Kernel<O> => {
|
|
933
|
+
// A machine that invokes no work runs none, so its steps track none.
|
|
934
|
+
const invoking = invokingPaths(machine)
|
|
935
|
+
const decodeEvent = Protocol.makeEventDecoderSync(machine)
|
|
936
|
+
|
|
937
|
+
/** Describes one invocation, without calling any of its user code. */
|
|
938
|
+
const describe = (
|
|
939
|
+
planning: PlanningBase,
|
|
940
|
+
invocation: InvocationResolution.ResolvedInvocation,
|
|
941
|
+
run: number
|
|
942
|
+
): Work => new WorkOf(invocation, run, planning.ambient ? undefined : planning) as unknown as Work
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
* Commands of a transition, as data, in order. A command that selects a
|
|
946
|
+
* child names the running work it selects, which a stop ends.
|
|
947
|
+
*/
|
|
948
|
+
const commandsOf = (
|
|
949
|
+
commands: ReadonlyArray<RuntimeCommand>,
|
|
950
|
+
running: ReadonlyArray<Work>
|
|
951
|
+
): { readonly commands: ReadonlyArray<Command>; readonly running: ReadonlyArray<Work> } => {
|
|
952
|
+
if (commands.length === 0) return { commands: empty, running }
|
|
953
|
+
const out: Array<Command> = []
|
|
954
|
+
let current = running
|
|
955
|
+
for (const command of commands) {
|
|
956
|
+
if (command._tag === "Stop") {
|
|
957
|
+
const child = command.child as ChildSelector
|
|
958
|
+
const work = current.find((work) => selects(work, child))
|
|
959
|
+
if (work !== undefined) current = current.filter((other) => other !== work)
|
|
960
|
+
out.push({ _tag: "StopChild", child, work })
|
|
961
|
+
continue
|
|
962
|
+
}
|
|
963
|
+
const target = command.target
|
|
964
|
+
if (typeof target === "string" || isChildMachine(target)) {
|
|
965
|
+
const child = target as ChildSelector
|
|
966
|
+
out.push({
|
|
967
|
+
_tag: "SendToChild",
|
|
968
|
+
child,
|
|
969
|
+
work: current.find((work) => selects(work, child)),
|
|
970
|
+
event: command.event
|
|
971
|
+
})
|
|
972
|
+
} else {
|
|
973
|
+
out.push({ _tag: "Send", target, event: command.event })
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
return { commands: out, running: current }
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
interface Published {
|
|
980
|
+
readonly event: unknown
|
|
981
|
+
readonly microsteps: ReadonlyArray<PlannedMicrostep>
|
|
982
|
+
readonly emitted: ReadonlyArray<unknown>
|
|
983
|
+
readonly commands: ReadonlyArray<Command>
|
|
984
|
+
/** The paths of an initial step, which its microsteps do not list. */
|
|
985
|
+
readonly paths?: Paths
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
const nothing: Published = { event: undefined, microsteps: empty, emitted: empty, commands: empty }
|
|
989
|
+
|
|
990
|
+
/** The logical state that a step reached, and what was built of it already. */
|
|
991
|
+
interface Reached {
|
|
992
|
+
readonly planning: PlanningBase
|
|
993
|
+
readonly execution: unknown
|
|
994
|
+
readonly configuration: Configuration.ActiveConfiguration | undefined
|
|
995
|
+
readonly snapshot: Machine.Snapshot<any> | undefined
|
|
996
|
+
readonly runs: number
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
const reached = (
|
|
1000
|
+
planning: PlanningBase,
|
|
1001
|
+
execution: unknown,
|
|
1002
|
+
configuration: Configuration.ActiveConfiguration | undefined,
|
|
1003
|
+
snapshot: Machine.Snapshot<any> | undefined,
|
|
1004
|
+
runs: number
|
|
1005
|
+
): Reached => ({ planning, execution, configuration, snapshot, runs })
|
|
1006
|
+
|
|
1007
|
+
/**
|
|
1008
|
+
* A machine that ends in a step stops all of its work: `stop` before
|
|
1009
|
+
* publishing the final state, and `stopAfter` after publishing and delivering
|
|
1010
|
+
* emitted events. `next` is the state the step reached, or the state before
|
|
1011
|
+
* it when the step could not be applied.
|
|
1012
|
+
*/
|
|
1013
|
+
const ended = (
|
|
1014
|
+
next: Reached,
|
|
1015
|
+
stop: ReadonlyArray<Work>,
|
|
1016
|
+
exit: Exit.Exit<unknown, unknown>,
|
|
1017
|
+
published: Published = nothing,
|
|
1018
|
+
stopAfter: ReadonlyArray<Work> = empty
|
|
1019
|
+
): Step<O> =>
|
|
1020
|
+
new Step(
|
|
1021
|
+
new State<O>(next.planning, next.execution, next.configuration, next.snapshot, empty, next.runs, exit),
|
|
1022
|
+
published.event,
|
|
1023
|
+
published.microsteps,
|
|
1024
|
+
published.emitted,
|
|
1025
|
+
published.commands,
|
|
1026
|
+
stop,
|
|
1027
|
+
empty,
|
|
1028
|
+
stopAfter,
|
|
1029
|
+
published.paths
|
|
1030
|
+
)
|
|
1031
|
+
|
|
1032
|
+
// A plan that throws leaves the state it received as it was, so the state
|
|
1033
|
+
// before a failed step is still the state that was passed in.
|
|
1034
|
+
const endedFrom = (state: State<O>): Reached => {
|
|
1035
|
+
const built = state.built
|
|
1036
|
+
return reached(state.planning, built.execution, built.configuration, state.snapshot, state.runs)
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
/**
|
|
1040
|
+
* Lists the work of the entered paths, one run per entry. Work that `progress`
|
|
1041
|
+
* names is not started: work that ended is left out, and work that still runs
|
|
1042
|
+
* is kept without being listed in `start`. Only a configuration that enters
|
|
1043
|
+
* an invoking state is built to resolve its work.
|
|
1044
|
+
*/
|
|
1045
|
+
const enter = (
|
|
1046
|
+
next: Reached,
|
|
1047
|
+
entered: ReadonlyArray<readonly [ReadonlyArray<string>, Machine.LifecycleEvent<any>]>,
|
|
1048
|
+
kept: ReadonlyArray<Work>,
|
|
1049
|
+
stop: ReadonlyArray<Work>,
|
|
1050
|
+
published: Published,
|
|
1051
|
+
progress?: ReadonlyArray<Progress>
|
|
1052
|
+
): Step<O> => {
|
|
1053
|
+
let configuration = next.configuration
|
|
1054
|
+
let runs = next.runs
|
|
1055
|
+
let start: Array<Work> | undefined
|
|
1056
|
+
// Every piece of work that runs after the entry, in start order: what
|
|
1057
|
+
// `progress` says still runs takes its place among the work that starts.
|
|
1058
|
+
let added: Array<Work> | undefined
|
|
1059
|
+
if (entered.some(([paths]) => paths.some((path) => invoking.has(path)))) {
|
|
1060
|
+
configuration ??= plan.toConfiguration(next.execution)
|
|
1061
|
+
for (
|
|
1062
|
+
const group of InvocationResolution.resolveEntries(
|
|
1063
|
+
machine,
|
|
1064
|
+
configuration,
|
|
1065
|
+
entered,
|
|
1066
|
+
() => next.planning.capabilities
|
|
1067
|
+
)
|
|
1068
|
+
) {
|
|
1069
|
+
const run = runs++
|
|
1070
|
+
for (const invocation of group.invocations) {
|
|
1071
|
+
const status = progress?.find((entry) => entry.path === invocation.path && entry.id === invocation.id)
|
|
1072
|
+
?.status
|
|
1073
|
+
if (status === "Ended") continue
|
|
1074
|
+
const work = describe(next.planning, invocation, run)
|
|
1075
|
+
// A literal holds one entry where a push onto an empty array
|
|
1076
|
+
// reserves seventeen, and the running work outlives this step.
|
|
1077
|
+
if (added === undefined) added = [work]
|
|
1078
|
+
else added.push(work)
|
|
1079
|
+
if (status !== "Running") (start ??= []).push(work)
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
const running = added === undefined ? kept : kept.length === 0 ? added : [...kept, ...added]
|
|
1084
|
+
return new Step(
|
|
1085
|
+
// An owned state keeps only what its host reads again: the configuration
|
|
1086
|
+
// is built again when a later step needs it.
|
|
1087
|
+
new State<O>(
|
|
1088
|
+
next.planning,
|
|
1089
|
+
next.execution,
|
|
1090
|
+
ownership === "Owned" ? undefined : configuration,
|
|
1091
|
+
next.snapshot,
|
|
1092
|
+
running,
|
|
1093
|
+
runs,
|
|
1094
|
+
undefined
|
|
1095
|
+
),
|
|
1096
|
+
published.event,
|
|
1097
|
+
published.microsteps,
|
|
1098
|
+
published.emitted,
|
|
1099
|
+
published.commands,
|
|
1100
|
+
stop,
|
|
1101
|
+
start ?? empty,
|
|
1102
|
+
empty,
|
|
1103
|
+
published.paths
|
|
1104
|
+
)
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
/**
|
|
1108
|
+
* Plans one event on a state that runs `running`: a public event that `send`
|
|
1109
|
+
* decoded, or the invocation event of a result.
|
|
1110
|
+
*/
|
|
1111
|
+
const advance = (
|
|
1112
|
+
state: State<O>,
|
|
1113
|
+
running: ReadonlyArray<Work>,
|
|
1114
|
+
event: Machine.EventOf<any> | InvocationEvent.InvocationEvent,
|
|
1115
|
+
retain: boolean
|
|
1116
|
+
): Step<O> => {
|
|
1117
|
+
let planned: ExecutionPlan.ExecutionMacrostep
|
|
1118
|
+
try {
|
|
1119
|
+
// A step publishes its microsteps, so a plan retains them unless its host reads none.
|
|
1120
|
+
planned = plan.planDecoded(state.execution, event, ownership, retain, state.planning)
|
|
1121
|
+
} catch (error) {
|
|
1122
|
+
// The step planned the event, as transitions receive it, and its planning failed.
|
|
1123
|
+
const planning = InvocationEvent.isInvocationEvent(event) ? InvocationEvent.toLifecycleEvent(event) : event
|
|
1124
|
+
return ended(endedFrom(state), latestFirst(running), exitOfThrow(error), { ...nothing, event: planning })
|
|
1125
|
+
}
|
|
1126
|
+
if (planned.microsteps.length === 0) {
|
|
1127
|
+
return new Step(
|
|
1128
|
+
running === state.running ? state : state.withRunning(running),
|
|
1129
|
+
planned.event,
|
|
1130
|
+
empty,
|
|
1131
|
+
empty,
|
|
1132
|
+
empty,
|
|
1133
|
+
empty,
|
|
1134
|
+
empty
|
|
1135
|
+
)
|
|
1136
|
+
}
|
|
1137
|
+
const commanded = planned.commands.length === 0 ? undefined : commandsOf(planned.commands, running)
|
|
1138
|
+
const commands = commanded === undefined ? empty : commanded.commands
|
|
1139
|
+
if (invoking.size === 0) return childlessStep(state, planned, commands)
|
|
1140
|
+
const changes = InvocationChanges.fromMicrosteps(planned.microsteps)
|
|
1141
|
+
const published: Published = {
|
|
1142
|
+
event: planned.event,
|
|
1143
|
+
microsteps: planned.microsteps,
|
|
1144
|
+
emitted: planned.emittedEvents,
|
|
1145
|
+
commands
|
|
1146
|
+
}
|
|
1147
|
+
const next = reached(state.planning, planned.next, undefined, undefined, state.runs)
|
|
1148
|
+
const { kept, stop } = InvocationChanges.partition(commanded === undefined ? running : commanded.running, changes)
|
|
1149
|
+
if (planned.done) {
|
|
1150
|
+
return ended(next, stop, Exit.succeed(planned.output), published, latestFirst(kept))
|
|
1151
|
+
}
|
|
1152
|
+
return enter(next, InvocationChanges.entries(changes), kept, stop, published)
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
/**
|
|
1156
|
+
* `work`, when `state` runs it and its result still applies. Work is compared
|
|
1157
|
+
* by identity: `path`, `id` and `run` repeat after a resume and across steps
|
|
1158
|
+
* taken from one kept state, and the object a step listed does not.
|
|
1159
|
+
*/
|
|
1160
|
+
const current = (state: State<O>, work: Work): Work | undefined =>
|
|
1161
|
+
state.exit === undefined && state.running.includes(work) ? work : undefined
|
|
1162
|
+
|
|
1163
|
+
// The planner reads currency from a generation handle. The state value has
|
|
1164
|
+
// decided it already, so each delivered event gets a fresh one.
|
|
1165
|
+
const generation = (): InvocationEvent.Generation => ({ current: true })
|
|
1166
|
+
|
|
1167
|
+
/** The state a step starts in, from a configuration that the reference planner built. */
|
|
1168
|
+
const initial = (
|
|
1169
|
+
planning: PlanningBase,
|
|
1170
|
+
configuration: Configuration.ActiveConfiguration,
|
|
1171
|
+
snapshot: Machine.Snapshot<any>
|
|
1172
|
+
): Reached => reached(planning, plan.fromConfiguration(configuration), configuration, snapshot, 0)
|
|
1173
|
+
|
|
1174
|
+
// Starting and resuming plan with the reference planner: they happen once per
|
|
1175
|
+
// machine, and their result enters the plan through `fromConfiguration`.
|
|
1176
|
+
const start: Kernel<O>["start"] = (planning, input, retain = true) => {
|
|
1177
|
+
// The execution plan starts a machine that it covers without publishing
|
|
1178
|
+
// microsteps: a host that reads none takes that start.
|
|
1179
|
+
if (!retain && plan.initial !== undefined) return startUnretained(planning, plan.initial, input)
|
|
1180
|
+
let planned: ReturnType<typeof Planner.planInitialSync>
|
|
1181
|
+
let configuration: Configuration.ActiveConfiguration
|
|
1182
|
+
try {
|
|
1183
|
+
planned = Planner.planInitialSync(Planner.withMachineReferences(machine, planning), ...input)
|
|
1184
|
+
configuration = Configuration.normalizeConfigurationSync(machine, planned.state)
|
|
1185
|
+
} catch (error) {
|
|
1186
|
+
return Exit.fail(toStartupFailure(error))
|
|
1187
|
+
}
|
|
1188
|
+
const published: Published = {
|
|
1189
|
+
event: Planner.InitialEvent,
|
|
1190
|
+
microsteps: planned.microsteps,
|
|
1191
|
+
emitted: planned.emittedEvents,
|
|
1192
|
+
commands: commandsOf(planned.commands, empty).commands,
|
|
1193
|
+
paths: new InitialPaths(machine, () => Configuration.getInitialEntryPaths(machine, configuration))
|
|
1194
|
+
}
|
|
1195
|
+
const next = initial(planning, configuration, planned.state)
|
|
1196
|
+
if (planned.done) {
|
|
1197
|
+
return Exit.succeed(ended(next, empty, Exit.succeed(planned.output), published))
|
|
1198
|
+
}
|
|
1199
|
+
return Exit.succeed(
|
|
1200
|
+
enter(
|
|
1201
|
+
next,
|
|
1202
|
+
invoking.size === 0 ? empty : InvocationResolution.initialEntries(machine, configuration),
|
|
1203
|
+
empty,
|
|
1204
|
+
empty,
|
|
1205
|
+
published
|
|
1206
|
+
)
|
|
1207
|
+
)
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
const startUnretained = (
|
|
1211
|
+
planning: PlanningBase,
|
|
1212
|
+
initialOf: NonNullable<ExecutionPlan.CompiledExecutionPlan["initial"]>,
|
|
1213
|
+
input: ReadonlyArray<unknown>
|
|
1214
|
+
): Exit.Exit<Step<O>, unknown> => {
|
|
1215
|
+
let planned: ReturnType<typeof initialOf>
|
|
1216
|
+
try {
|
|
1217
|
+
planned = initialOf(input, planning)
|
|
1218
|
+
} catch (error) {
|
|
1219
|
+
return Exit.fail(toStartupFailure(error))
|
|
1220
|
+
}
|
|
1221
|
+
const configuration = planned.activeConfiguration
|
|
1222
|
+
const published: Published = {
|
|
1223
|
+
event: Planner.InitialEvent,
|
|
1224
|
+
microsteps: empty,
|
|
1225
|
+
emitted: empty,
|
|
1226
|
+
commands: empty,
|
|
1227
|
+
paths: new InitialPaths(machine, planned.initialEntryPaths)
|
|
1228
|
+
}
|
|
1229
|
+
const next = reached(planning, planned.configuration, configuration, planned.state, 0)
|
|
1230
|
+
if (planned.done) {
|
|
1231
|
+
return Exit.succeed(ended(next, empty, Exit.succeed(planned.output), published))
|
|
1232
|
+
}
|
|
1233
|
+
return Exit.succeed(
|
|
1234
|
+
enter(
|
|
1235
|
+
next,
|
|
1236
|
+
invoking.size === 0 ? empty : [[planned.initialEntryPaths, Planner.InitialEvent]],
|
|
1237
|
+
empty,
|
|
1238
|
+
empty,
|
|
1239
|
+
published
|
|
1240
|
+
)
|
|
1241
|
+
)
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
const startSnapshot: Kernel<O>["startSnapshot"] = invoking.size === 0 && plan.initial !== undefined
|
|
1245
|
+
? (references, input) => {
|
|
1246
|
+
let planned: ReturnType<NonNullable<typeof plan.initial>>
|
|
1247
|
+
try {
|
|
1248
|
+
planned = plan.initial!(input, references)
|
|
1249
|
+
} catch (error) {
|
|
1250
|
+
throw toStartupFailure(error)
|
|
1251
|
+
}
|
|
1252
|
+
return planned.done
|
|
1253
|
+
? { state: planned.state, done: true, output: planned.output }
|
|
1254
|
+
: { state: planned.state, done: false, output: undefined }
|
|
1255
|
+
}
|
|
1256
|
+
: undefined
|
|
1257
|
+
|
|
1258
|
+
const fromSnapshot: Kernel<O>["fromSnapshot"] = (planning, snapshot) => {
|
|
1259
|
+
if (invoking.size > 0) throw new Error("A machine that invokes work runs its work in its state")
|
|
1260
|
+
return new State<O>(planning, undefined, undefined, snapshot, empty, 0, undefined)
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
const send = (state: State<O>, event: unknown): Exit.Exit<Step<O>, unknown> => {
|
|
1264
|
+
if (state.exit !== undefined) return Exit.fail(new StoppedError())
|
|
1265
|
+
let decoded: Machine.EventOf<any>
|
|
1266
|
+
try {
|
|
1267
|
+
decoded = decodeEvent(event)
|
|
1268
|
+
} catch (error) {
|
|
1269
|
+
// Only an event that its schema refuses is rejected. Any other throw is
|
|
1270
|
+
// a defect of the machine, as it is when the planner decodes the event.
|
|
1271
|
+
return error instanceof MachineSchemaDecodeError
|
|
1272
|
+
? Exit.fail(error)
|
|
1273
|
+
: Exit.succeed(ended(endedFrom(state), latestFirst(state.running), Exit.die(error)))
|
|
1274
|
+
}
|
|
1275
|
+
return Exit.succeed(advance(state, state.running, decoded, true))
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
const sendDecoded = (state: State<O>, event: Machine.EventOf<any>, retain = true): Step<O> =>
|
|
1279
|
+
state.exit === undefined ? advance(state, state.running, event, retain) : unchanged(state)
|
|
1280
|
+
|
|
1281
|
+
const moveChildlessOwned = (
|
|
1282
|
+
state: State<O>,
|
|
1283
|
+
event: Machine.EventOf<any>
|
|
1284
|
+
): Machine.Snapshot<any> | Step<O> | undefined => {
|
|
1285
|
+
state.assertNotHandedOver()
|
|
1286
|
+
if (state.exit !== undefined) return undefined
|
|
1287
|
+
let planned: ExecutionPlan.ExecutionMacrostep
|
|
1288
|
+
try {
|
|
1289
|
+
planned = plan.planDecoded(state.execution, event, "Owned", false, state.planning)
|
|
1290
|
+
} catch (error) {
|
|
1291
|
+
state.handOverNeverReuse()
|
|
1292
|
+
return ended(endedFrom(state), empty, exitOfThrow(error), { ...nothing, event })
|
|
1293
|
+
}
|
|
1294
|
+
if (planned.microsteps.length === 0) return undefined
|
|
1295
|
+
if (!planned.done && planned.commands.length === 0 && planned.emittedEvents.length === 0) {
|
|
1296
|
+
const snapshot = plan.snapshot(planned.next)
|
|
1297
|
+
state.replaceExecution(planned.next, snapshot)
|
|
1298
|
+
return snapshot
|
|
1299
|
+
}
|
|
1300
|
+
state.handOverNeverReuse()
|
|
1301
|
+
const commands = planned.commands.length === 0 ? empty : commandsOf(planned.commands, empty).commands
|
|
1302
|
+
return childlessStep(state, planned, commands)
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
const move = (
|
|
1306
|
+
state: State<O>,
|
|
1307
|
+
event: Machine.EventOf<any>
|
|
1308
|
+
): Machine.Snapshot<any> | Step<O> | undefined => {
|
|
1309
|
+
if (state.exit !== undefined) return undefined
|
|
1310
|
+
const step = advance(state, state.running, event, false)
|
|
1311
|
+
return step.state === state && !step.planned && step.exit === undefined ? undefined : step
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
const settle = (state: State<O>, work: Work, exit: Exit.Exit<unknown, unknown>, retain = true): Step<O> => {
|
|
1315
|
+
const settled = current(state, work)
|
|
1316
|
+
if (settled === undefined) return unchanged(state)
|
|
1317
|
+
const running = state.running.filter((other) => other !== settled)
|
|
1318
|
+
const decision = InvocationOutcome.decide(settled[WorkTypeId], generation(), InvocationOutcome.fromExit(exit))
|
|
1319
|
+
switch (decision._tag) {
|
|
1320
|
+
case "Deliver":
|
|
1321
|
+
return advance(state, running, decision.event, retain)
|
|
1322
|
+
case "Fail":
|
|
1323
|
+
return ended(endedFrom(state), latestFirst(running), Exit.failCause(decision.cause))
|
|
1324
|
+
case "Ignore":
|
|
1325
|
+
return unchanged(state.withRunning(running))
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
const element = (state: State<O>, work: Work, value: unknown, retain = true): Step<O> => {
|
|
1330
|
+
const streaming = current(state, work)
|
|
1331
|
+
if (streaming === undefined) return unchanged(state)
|
|
1332
|
+
const invocation = streaming[WorkTypeId]
|
|
1333
|
+
if (invocation._tag !== "Stream") return unchanged(state)
|
|
1334
|
+
const decision = InvocationOutcome.decideElement(invocation, generation(), value)
|
|
1335
|
+
return decision._tag === "Ignore" ? unchanged(state) : advance(state, state.running, decision.event, retain)
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
const report = (state: State<O>, work: Work, snapshot: unknown, retain = true): Step<O> => {
|
|
1339
|
+
const reporting = current(state, work)
|
|
1340
|
+
if (reporting === undefined) return unchanged(state)
|
|
1341
|
+
const invocation = reporting[WorkTypeId]
|
|
1342
|
+
if (invocation._tag !== "Logic" && invocation._tag !== "Child") return unchanged(state)
|
|
1343
|
+
// Owners read the state of an active process, as the local runtime reports it.
|
|
1344
|
+
const decision = InvocationOutcome.decideSnapshot(invocation, generation(), { status: "active", state: snapshot })
|
|
1345
|
+
return decision._tag === "Ignore" ? unchanged(state) : advance(state, state.running, decision.event, retain)
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
const stop = (state: State<O>): Step<O> =>
|
|
1349
|
+
state.exit === undefined
|
|
1350
|
+
? ended(endedFrom(state), latestFirst(state.running), Exit.fail(new StoppedError()))
|
|
1351
|
+
: unchanged(state)
|
|
1352
|
+
|
|
1353
|
+
const resume: Kernel<O>["resume"] = (planning, snapshot, progress) => {
|
|
1354
|
+
const normalized = Effect.runSyncExit(Serialization.normalizeSnapshotEffect(machine, snapshot))
|
|
1355
|
+
if (Exit.isFailure(normalized)) return Exit.failCause(normalized.cause)
|
|
1356
|
+
const state = normalized.value
|
|
1357
|
+
let configuration: Configuration.ActiveConfiguration
|
|
1358
|
+
try {
|
|
1359
|
+
configuration = Configuration.normalizeConfigurationSync(machine, state)
|
|
1360
|
+
} catch (error) {
|
|
1361
|
+
return exitOfThrow(error)
|
|
1362
|
+
}
|
|
1363
|
+
const published: Published = { ...nothing, event: Planner.InitialEvent }
|
|
1364
|
+
const next = initial(planning, configuration, state)
|
|
1365
|
+
if (!Planner.isFinalState(machine, state)) {
|
|
1366
|
+
return Exit.succeed(
|
|
1367
|
+
enter(next, InvocationResolution.initialEntries(machine, configuration), empty, empty, published, progress)
|
|
1368
|
+
)
|
|
1369
|
+
}
|
|
1370
|
+
const output = Effect.runSyncExit(Planner.getFinalOutputEffect(machine, state, Planner.InitialEvent))
|
|
1371
|
+
return Exit.isFailure(output)
|
|
1372
|
+
? Exit.failCause(output.cause)
|
|
1373
|
+
: Exit.succeed(ended(next, empty, Exit.succeed(output.value), published))
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
if (ownership === "Persistent") {
|
|
1377
|
+
return {
|
|
1378
|
+
plan,
|
|
1379
|
+
start,
|
|
1380
|
+
startSnapshot,
|
|
1381
|
+
fromSnapshot,
|
|
1382
|
+
rest: (state) => state.resting(),
|
|
1383
|
+
send,
|
|
1384
|
+
sendDecoded,
|
|
1385
|
+
move,
|
|
1386
|
+
settle,
|
|
1387
|
+
element,
|
|
1388
|
+
report,
|
|
1389
|
+
observesSnapshots,
|
|
1390
|
+
settleEvent,
|
|
1391
|
+
elementEvent,
|
|
1392
|
+
snapshotEvent,
|
|
1393
|
+
stop,
|
|
1394
|
+
resume
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
// An owned state is taken over by the step it is passed to, and handed back
|
|
1398
|
+
// when the step returns that very state, or refuses the event.
|
|
1399
|
+
return {
|
|
1400
|
+
plan,
|
|
1401
|
+
start,
|
|
1402
|
+
startSnapshot,
|
|
1403
|
+
fromSnapshot,
|
|
1404
|
+
rest: (state) => state.restInPlace(),
|
|
1405
|
+
send: (state, event) => {
|
|
1406
|
+
const exit = send(state.handOverNeverReuse(), event)
|
|
1407
|
+
if (Exit.isFailure(exit) || exit.value.state === state) state.giveBackUnchanged()
|
|
1408
|
+
return exit
|
|
1409
|
+
},
|
|
1410
|
+
sendDecoded: (state, event, retain) =>
|
|
1411
|
+
givenBackIfUnchanged(state, sendDecoded(state.handOverNeverReuse(), event, retain)),
|
|
1412
|
+
move: invoking.size === 0
|
|
1413
|
+
? moveChildlessOwned
|
|
1414
|
+
: (state, event) => {
|
|
1415
|
+
const moved = move(state.handOverNeverReuse(), event)
|
|
1416
|
+
if (!(moved instanceof Step) || moved.state === state) state.giveBackUnchanged()
|
|
1417
|
+
return moved
|
|
1418
|
+
},
|
|
1419
|
+
settle: (state, work, exit, retain) =>
|
|
1420
|
+
givenBackIfUnchanged(state, settle(state.handOverNeverReuse(), work, exit, retain)),
|
|
1421
|
+
element: (state, work, value, retain) =>
|
|
1422
|
+
givenBackIfUnchanged(state, element(state.handOverNeverReuse(), work, value, retain)),
|
|
1423
|
+
report: (state, work, snapshot, retain) =>
|
|
1424
|
+
givenBackIfUnchanged(state, report(state.handOverNeverReuse(), work, snapshot, retain)),
|
|
1425
|
+
observesSnapshots,
|
|
1426
|
+
settleEvent,
|
|
1427
|
+
elementEvent,
|
|
1428
|
+
snapshotEvent,
|
|
1429
|
+
stop: (state) => givenBackIfUnchanged(state, stop(state.handOverNeverReuse())),
|
|
1430
|
+
resume
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
Object.defineProperty(State.prototype, StateTypeId, { value: StateTypeId })
|
|
1435
|
+
|
|
1436
|
+
/** Gives an owned state back to the caller of a step that returned it unchanged. */
|
|
1437
|
+
const givenBackIfUnchanged = <O extends Ownership>(state: State<O>, step: Step<O>): Step<O> => {
|
|
1438
|
+
if (step.state === state) state.giveBackUnchanged()
|
|
1439
|
+
return step
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
const kernels: Record<Ownership, WeakMap<ExecutionPlan.CompiledExecutionPlan, Kernel<any>>> = {
|
|
1443
|
+
Persistent: new WeakMap(),
|
|
1444
|
+
Owned: new WeakMap()
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
/**
|
|
1448
|
+
* The step functions of `machine` that take states of `ownership` and plan
|
|
1449
|
+
* with `plan`. Cached per `(ownership, plan)`, since execution plans are
|
|
1450
|
+
* cached per machine.
|
|
1451
|
+
*
|
|
1452
|
+
* @internal
|
|
1453
|
+
*/
|
|
1454
|
+
export const kernel = <O extends Ownership>(
|
|
1455
|
+
machine: Machine.Any,
|
|
1456
|
+
ownership: O,
|
|
1457
|
+
plan: ExecutionPlan.CompiledExecutionPlan
|
|
1458
|
+
): Kernel<O> => {
|
|
1459
|
+
const cache = kernels[ownership] as WeakMap<ExecutionPlan.CompiledExecutionPlan, Kernel<O>>
|
|
1460
|
+
let built = cache.get(plan)
|
|
1461
|
+
if (built === undefined) {
|
|
1462
|
+
built = build(machine, ownership, plan)
|
|
1463
|
+
cache.set(plan, built)
|
|
1464
|
+
}
|
|
1465
|
+
return built
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
/** The step functions of `kernel`, bound to one host. */
|
|
1469
|
+
const bind = <O extends Ownership>(machine: Machine.Any, kernel: Kernel<O>, options: Options): MachineStep<O> => {
|
|
1470
|
+
const planning = new Planning(
|
|
1471
|
+
machine,
|
|
1472
|
+
kernel.plan,
|
|
1473
|
+
options.self,
|
|
1474
|
+
options.parent,
|
|
1475
|
+
options.children ?? refusedChildren
|
|
1476
|
+
)
|
|
1477
|
+
return {
|
|
1478
|
+
start: (...input) => kernel.start(planning, input),
|
|
1479
|
+
send: kernel.send,
|
|
1480
|
+
sendDecoded: kernel.sendDecoded,
|
|
1481
|
+
settle: kernel.settle,
|
|
1482
|
+
element: kernel.element,
|
|
1483
|
+
report: kernel.report,
|
|
1484
|
+
stop: kernel.stop,
|
|
1485
|
+
resume: (snapshot, progress) => kernel.resume(planning, snapshot, progress)
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
/**
|
|
1490
|
+
* The step functions of `Machine.toStep`, which take immutable state values.
|
|
1491
|
+
*
|
|
1492
|
+
* @internal
|
|
1493
|
+
*/
|
|
1494
|
+
export const make = (machine: Machine.Any, options: Options): MachineStep<"Persistent"> =>
|
|
1495
|
+
bind(machine, kernel(machine, "Persistent", ExecutionPlan.compileExecutionPlan(machine)), options)
|
|
1496
|
+
|
|
1497
|
+
/**
|
|
1498
|
+
* Step functions that take each state over and may update it in place, for a
|
|
1499
|
+
* host that keeps only its latest state. The caller never uses a state again
|
|
1500
|
+
* after it passes it to one of them, nor any step that returned it. See
|
|
1501
|
+
* {@link Ownership}.
|
|
1502
|
+
*
|
|
1503
|
+
* @internal
|
|
1504
|
+
*/
|
|
1505
|
+
export const makeOwned = (machine: Machine.Any, options: Options): OwnedMachineStep =>
|
|
1506
|
+
bind(machine, kernel(machine, "Owned", ExecutionPlan.compileExecutionPlan(machine)), options)
|
|
1507
|
+
|
|
1508
|
+
/**
|
|
1509
|
+
* Step functions of either ownership that plan with `plan`.
|
|
1510
|
+
*
|
|
1511
|
+
* @internal
|
|
1512
|
+
*/
|
|
1513
|
+
export const makeForTesting = <O extends Ownership>(
|
|
1514
|
+
machine: Machine.Any,
|
|
1515
|
+
options: Options,
|
|
1516
|
+
ownership: O,
|
|
1517
|
+
plan: ExecutionPlan.CompiledExecutionPlan
|
|
1518
|
+
): MachineStep<O> => bind(machine, kernel(machine, ownership, plan), options)
|