@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.
Files changed (334) hide show
  1. package/AGENTS.md +374 -22
  2. package/CLAUDE.md +374 -22
  3. package/README.md +56 -7
  4. package/ai-docs/src/10_modeling/01_create-a-machine.ts +3 -3
  5. package/ai-docs/src/10_modeling/index.md +64 -17
  6. package/ai-docs/src/20_root-api/index.md +2 -2
  7. package/ai-docs/src/35_cluster/index.md +213 -0
  8. package/ai-docs/src/37_new-host/index.md +90 -0
  9. package/dist/LocalMachine.d.ts +417 -0
  10. package/dist/LocalMachine.d.ts.map +1 -0
  11. package/dist/LocalMachine.js +193 -0
  12. package/dist/LocalMachine.js.map +1 -0
  13. package/dist/Machine.d.ts +1120 -812
  14. package/dist/Machine.d.ts.map +1 -1
  15. package/dist/Machine.js +195 -186
  16. package/dist/Machine.js.map +1 -1
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1 -0
  20. package/dist/index.js.map +1 -1
  21. package/dist/internal/machine/atom.d.ts +8 -10
  22. package/dist/internal/machine/atom.d.ts.map +1 -1
  23. package/dist/internal/machine/atom.js +7 -6
  24. package/dist/internal/machine/atom.js.map +1 -1
  25. package/dist/internal/machine/capability.d.ts +101 -0
  26. package/dist/internal/machine/capability.d.ts.map +1 -0
  27. package/dist/internal/machine/capability.js +70 -0
  28. package/dist/internal/machine/capability.js.map +1 -0
  29. package/dist/internal/machine/{invocationDefinition.d.ts → capturedInvocation.d.ts} +11 -11
  30. package/dist/internal/machine/capturedInvocation.d.ts.map +1 -0
  31. package/dist/internal/machine/{invocationDefinition.js → capturedInvocation.js} +2 -2
  32. package/dist/internal/machine/capturedInvocation.js.map +1 -0
  33. package/dist/internal/machine/child.d.ts +14 -0
  34. package/dist/internal/machine/child.d.ts.map +1 -0
  35. package/dist/internal/machine/child.js +19 -0
  36. package/dist/internal/machine/child.js.map +1 -0
  37. package/dist/internal/machine/childRegistry.d.ts +0 -2
  38. package/dist/internal/machine/childRegistry.d.ts.map +1 -1
  39. package/dist/internal/machine/childRegistry.js +2 -2
  40. package/dist/internal/machine/childRegistry.js.map +1 -1
  41. package/dist/internal/machine/cluster.d.ts +19 -4
  42. package/dist/internal/machine/cluster.d.ts.map +1 -1
  43. package/dist/internal/machine/cluster.js +263 -110
  44. package/dist/internal/machine/cluster.js.map +1 -1
  45. package/dist/internal/machine/clusterChild.d.ts +66 -0
  46. package/dist/internal/machine/clusterChild.d.ts.map +1 -0
  47. package/dist/internal/machine/clusterChild.js +105 -0
  48. package/dist/internal/machine/clusterChild.js.map +1 -0
  49. package/dist/internal/machine/clusterFailure.d.ts +14 -0
  50. package/dist/internal/machine/clusterFailure.d.ts.map +1 -0
  51. package/dist/internal/machine/clusterFailure.js +44 -0
  52. package/dist/internal/machine/clusterFailure.js.map +1 -0
  53. package/dist/internal/machine/clusterInstance.d.ts +194 -0
  54. package/dist/internal/machine/clusterInstance.d.ts.map +1 -0
  55. package/dist/internal/machine/clusterInstance.js +1076 -0
  56. package/dist/internal/machine/clusterInstance.js.map +1 -0
  57. package/dist/internal/machine/clusterKeepAlive.d.ts +47 -0
  58. package/dist/internal/machine/clusterKeepAlive.d.ts.map +1 -0
  59. package/dist/internal/machine/clusterKeepAlive.js +72 -0
  60. package/dist/internal/machine/clusterKeepAlive.js.map +1 -0
  61. package/dist/internal/machine/clusterProgress.d.ts +73 -0
  62. package/dist/internal/machine/clusterProgress.d.ts.map +1 -0
  63. package/dist/internal/machine/clusterProgress.js +116 -0
  64. package/dist/internal/machine/clusterProgress.js.map +1 -0
  65. package/dist/internal/machine/clusterProtocol.d.ts +37 -4
  66. package/dist/internal/machine/clusterProtocol.d.ts.map +1 -1
  67. package/dist/internal/machine/clusterProtocol.js +18 -4
  68. package/dist/internal/machine/clusterProtocol.js.map +1 -1
  69. package/dist/internal/machine/clusterProxy.d.ts +46 -0
  70. package/dist/internal/machine/clusterProxy.d.ts.map +1 -0
  71. package/dist/internal/machine/clusterProxy.js +150 -0
  72. package/dist/internal/machine/clusterProxy.js.map +1 -0
  73. package/dist/internal/machine/clusterRead.d.ts +61 -0
  74. package/dist/internal/machine/clusterRead.d.ts.map +1 -0
  75. package/dist/internal/machine/clusterRead.js +108 -0
  76. package/dist/internal/machine/clusterRead.js.map +1 -0
  77. package/dist/internal/machine/clusterSqlStorage.d.ts +16 -0
  78. package/dist/internal/machine/clusterSqlStorage.d.ts.map +1 -0
  79. package/dist/internal/machine/clusterSqlStorage.js +138 -0
  80. package/dist/internal/machine/clusterSqlStorage.js.map +1 -0
  81. package/dist/internal/machine/clusterStorageCheck.d.ts +19 -0
  82. package/dist/internal/machine/clusterStorageCheck.d.ts.map +1 -0
  83. package/dist/internal/machine/clusterStorageCheck.js +186 -0
  84. package/dist/internal/machine/clusterStorageCheck.js.map +1 -0
  85. package/dist/internal/machine/clusterTarget.d.ts +74 -0
  86. package/dist/internal/machine/clusterTarget.d.ts.map +1 -0
  87. package/dist/internal/machine/clusterTarget.js +81 -0
  88. package/dist/internal/machine/clusterTarget.js.map +1 -0
  89. package/dist/internal/machine/clusterTimer.d.ts +21 -0
  90. package/dist/internal/machine/clusterTimer.d.ts.map +1 -0
  91. package/dist/internal/machine/clusterTimer.js +50 -0
  92. package/dist/internal/machine/clusterTimer.js.map +1 -0
  93. package/dist/internal/machine/clusterWake.d.ts +61 -0
  94. package/dist/internal/machine/clusterWake.d.ts.map +1 -0
  95. package/dist/internal/machine/clusterWake.js +81 -0
  96. package/dist/internal/machine/clusterWake.js.map +1 -0
  97. package/dist/internal/machine/clusterWork.d.ts +130 -0
  98. package/dist/internal/machine/clusterWork.d.ts.map +1 -0
  99. package/dist/internal/machine/clusterWork.js +191 -0
  100. package/dist/internal/machine/clusterWork.js.map +1 -0
  101. package/dist/internal/machine/command.d.ts +4 -4
  102. package/dist/internal/machine/command.d.ts.map +1 -1
  103. package/dist/internal/machine/commandRuntime.d.ts +8 -6
  104. package/dist/internal/machine/commandRuntime.d.ts.map +1 -1
  105. package/dist/internal/machine/commandRuntime.js +1 -5
  106. package/dist/internal/machine/commandRuntime.js.map +1 -1
  107. package/dist/internal/machine/configuration.d.ts +0 -13
  108. package/dist/internal/machine/configuration.d.ts.map +1 -1
  109. package/dist/internal/machine/configuration.js +0 -151
  110. package/dist/internal/machine/configuration.js.map +1 -1
  111. package/dist/internal/machine/errors.d.ts +11 -2
  112. package/dist/internal/machine/errors.d.ts.map +1 -1
  113. package/dist/internal/machine/errors.js +11 -2
  114. package/dist/internal/machine/errors.js.map +1 -1
  115. package/dist/internal/machine/executionPlan.d.ts +45 -3
  116. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  117. package/dist/internal/machine/executionPlan.js +328 -191
  118. package/dist/internal/machine/executionPlan.js.map +1 -1
  119. package/dist/internal/machine/implementation.d.ts +6 -6
  120. package/dist/internal/machine/implementation.d.ts.map +1 -1
  121. package/dist/internal/machine/inspectionRuntime.d.ts +1 -1
  122. package/dist/internal/machine/inspectionRuntime.d.ts.map +1 -1
  123. package/dist/internal/machine/invocationChanges.d.ts +60 -0
  124. package/dist/internal/machine/invocationChanges.d.ts.map +1 -0
  125. package/dist/internal/machine/invocationChanges.js +54 -0
  126. package/dist/internal/machine/invocationChanges.js.map +1 -0
  127. package/dist/internal/machine/{activities.d.ts → invocationDefinitions.d.ts} +8 -8
  128. package/dist/internal/machine/invocationDefinitions.d.ts.map +1 -0
  129. package/dist/internal/machine/{activities.js → invocationDefinitions.js} +5 -5
  130. package/dist/internal/machine/invocationDefinitions.js.map +1 -0
  131. package/dist/internal/machine/invocationEvent.d.ts +16 -7
  132. package/dist/internal/machine/invocationEvent.d.ts.map +1 -1
  133. package/dist/internal/machine/invocationEvent.js +26 -12
  134. package/dist/internal/machine/invocationEvent.js.map +1 -1
  135. package/dist/internal/machine/invocationOutcome.d.ts +89 -0
  136. package/dist/internal/machine/invocationOutcome.d.ts.map +1 -0
  137. package/dist/internal/machine/invocationOutcome.js +76 -0
  138. package/dist/internal/machine/invocationOutcome.js.map +1 -0
  139. package/dist/internal/machine/invocationResolution.d.ts +137 -0
  140. package/dist/internal/machine/invocationResolution.d.ts.map +1 -0
  141. package/dist/internal/machine/invocationResolution.js +150 -0
  142. package/dist/internal/machine/invocationResolution.js.map +1 -0
  143. package/dist/internal/machine/logicScope.d.ts +24 -0
  144. package/dist/internal/machine/logicScope.d.ts.map +1 -0
  145. package/dist/internal/machine/logicScope.js +33 -0
  146. package/dist/internal/machine/logicScope.js.map +1 -0
  147. package/dist/internal/machine/machine.d.ts +17 -23
  148. package/dist/internal/machine/machine.d.ts.map +1 -1
  149. package/dist/internal/machine/machine.js +24 -40
  150. package/dist/internal/machine/machine.js.map +1 -1
  151. package/dist/internal/machine/observation.d.ts +3 -0
  152. package/dist/internal/machine/observation.d.ts.map +1 -1
  153. package/dist/internal/machine/observation.js +56 -2
  154. package/dist/internal/machine/observation.js.map +1 -1
  155. package/dist/internal/machine/plannedSnapshot.d.ts.map +1 -1
  156. package/dist/internal/machine/plannedSnapshot.js +11 -20
  157. package/dist/internal/machine/plannedSnapshot.js.map +1 -1
  158. package/dist/internal/machine/planner.d.ts +36 -23
  159. package/dist/internal/machine/planner.d.ts.map +1 -1
  160. package/dist/internal/machine/planner.js +15 -8
  161. package/dist/internal/machine/planner.js.map +1 -1
  162. package/dist/internal/machine/process.d.ts +17 -9
  163. package/dist/internal/machine/process.d.ts.map +1 -1
  164. package/dist/internal/machine/process.js +43 -503
  165. package/dist/internal/machine/process.js.map +1 -1
  166. package/dist/internal/machine/protocol.d.ts +1 -1
  167. package/dist/internal/machine/protocol.d.ts.map +1 -1
  168. package/dist/internal/machine/protocol.js +48 -10
  169. package/dist/internal/machine/protocol.js.map +1 -1
  170. package/dist/internal/machine/runtime.d.ts +20 -16
  171. package/dist/internal/machine/runtime.d.ts.map +1 -1
  172. package/dist/internal/machine/runtime.js +93 -88
  173. package/dist/internal/machine/runtime.js.map +1 -1
  174. package/dist/internal/machine/runtimeCompiled.d.ts.map +1 -1
  175. package/dist/internal/machine/runtimeCompiled.js +359 -120
  176. package/dist/internal/machine/runtimeCompiled.js.map +1 -1
  177. package/dist/internal/machine/runtimeProtocol.d.ts +151 -82
  178. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -1
  179. package/dist/internal/machine/runtimeProtocol.js +236 -219
  180. package/dist/internal/machine/runtimeProtocol.js.map +1 -1
  181. package/dist/internal/machine/stateDefinition.d.ts +0 -1
  182. package/dist/internal/machine/stateDefinition.d.ts.map +1 -1
  183. package/dist/internal/machine/stateDefinition.js +0 -1
  184. package/dist/internal/machine/stateDefinition.js.map +1 -1
  185. package/dist/internal/machine/step.d.ts +486 -0
  186. package/dist/internal/machine/step.d.ts.map +1 -0
  187. package/dist/internal/machine/step.js +957 -0
  188. package/dist/internal/machine/step.js.map +1 -0
  189. package/dist/internal/machine/stepHost.d.ts +33 -0
  190. package/dist/internal/machine/stepHost.d.ts.map +1 -0
  191. package/dist/internal/machine/stepHost.js +501 -0
  192. package/dist/internal/machine/stepHost.js.map +1 -0
  193. package/dist/internal/machine/symbols.d.ts +2 -11
  194. package/dist/internal/machine/symbols.d.ts.map +1 -1
  195. package/dist/internal/machine/symbols.js +2 -2
  196. package/dist/internal/machine/symbols.js.map +1 -1
  197. package/dist/internal/machine/transition.d.ts +7 -7
  198. package/dist/internal/machine/transition.d.ts.map +1 -1
  199. package/dist/internal/testing/machine/check.d.ts.map +1 -1
  200. package/dist/internal/testing/machine/check.js +217 -25
  201. package/dist/internal/testing/machine/check.js.map +1 -1
  202. package/dist/internal/testing/machine/exploration.d.ts +19 -2
  203. package/dist/internal/testing/machine/exploration.d.ts.map +1 -1
  204. package/dist/internal/testing/machine/exploration.js +14 -3
  205. package/dist/internal/testing/machine/exploration.js.map +1 -1
  206. package/dist/internal/testing/machine/format.js.map +1 -1
  207. package/dist/internal/testing/machine/probe.d.ts.map +1 -1
  208. package/dist/internal/testing/machine/probe.js +1 -1
  209. package/dist/internal/testing/machine/probe.js.map +1 -1
  210. package/dist/internal/testing/machine/runtime.d.ts +2 -2
  211. package/dist/internal/testing/machine/runtime.d.ts.map +1 -1
  212. package/dist/internal/testing/machine/runtime.js +10 -3
  213. package/dist/internal/testing/machine/runtime.js.map +1 -1
  214. package/dist/internal/testing/machine/trace.d.ts +38 -3
  215. package/dist/internal/testing/machine/trace.d.ts.map +1 -1
  216. package/dist/internal/testing/machine/trace.js +180 -33
  217. package/dist/internal/testing/machine/trace.js.map +1 -1
  218. package/dist/internal/testing/machine/transitionCoverage.d.ts +1 -1
  219. package/dist/internal/testing/machine/transitionCoverage.d.ts.map +1 -1
  220. package/dist/internal/testing/machine/verification.d.ts.map +1 -1
  221. package/dist/internal/testing/machine/verification.js +9 -1
  222. package/dist/internal/testing/machine/verification.js.map +1 -1
  223. package/dist/internal/testing/machine/work.d.ts +47 -0
  224. package/dist/internal/testing/machine/work.d.ts.map +1 -0
  225. package/dist/internal/testing/machine/work.js +74 -0
  226. package/dist/internal/testing/machine/work.js.map +1 -0
  227. package/dist/testing/MachineTest.d.ts +253 -37
  228. package/dist/testing/MachineTest.d.ts.map +1 -1
  229. package/dist/testing/MachineTest.js +81 -9
  230. package/dist/testing/MachineTest.js.map +1 -1
  231. package/dist/unstable/cluster/ClusterMachine.d.ts +1071 -41
  232. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
  233. package/dist/unstable/cluster/ClusterMachine.js +441 -12
  234. package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
  235. package/dist/unstable/cluster/ClusterMachineProxy.d.ts +257 -0
  236. package/dist/unstable/cluster/ClusterMachineProxy.d.ts.map +1 -0
  237. package/dist/unstable/cluster/ClusterMachineProxy.js +73 -0
  238. package/dist/unstable/cluster/ClusterMachineProxy.js.map +1 -0
  239. package/dist/unstable/cluster/SqlMachineStorage.d.ts +125 -0
  240. package/dist/unstable/cluster/SqlMachineStorage.d.ts.map +1 -0
  241. package/dist/unstable/cluster/SqlMachineStorage.js +62 -0
  242. package/dist/unstable/cluster/SqlMachineStorage.js.map +1 -0
  243. package/dist/unstable/cluster/index.d.ts +13 -0
  244. package/dist/unstable/cluster/index.d.ts.map +1 -1
  245. package/dist/unstable/cluster/index.js +13 -0
  246. package/dist/unstable/cluster/index.js.map +1 -1
  247. package/dist/unstable/reactivity/AtomMachine.d.ts +21 -26
  248. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
  249. package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
  250. package/package.json +5 -3
  251. package/src/LocalMachine.ts +611 -0
  252. package/src/Machine.ts +1379 -1334
  253. package/src/index.ts +1 -0
  254. package/src/internal/machine/atom.ts +20 -49
  255. package/src/internal/machine/capability.ts +123 -0
  256. package/src/internal/machine/{invocationDefinition.ts → capturedInvocation.ts} +13 -13
  257. package/src/internal/machine/child.ts +25 -0
  258. package/src/internal/machine/childRegistry.ts +1 -4
  259. package/src/internal/machine/cluster.ts +420 -205
  260. package/src/internal/machine/clusterChild.ts +117 -0
  261. package/src/internal/machine/clusterFailure.ts +53 -0
  262. package/src/internal/machine/clusterInstance.ts +1779 -0
  263. package/src/internal/machine/clusterKeepAlive.ts +93 -0
  264. package/src/internal/machine/clusterProgress.ts +159 -0
  265. package/src/internal/machine/clusterProtocol.ts +46 -4
  266. package/src/internal/machine/clusterProxy.ts +233 -0
  267. package/src/internal/machine/clusterRead.ts +207 -0
  268. package/src/internal/machine/clusterSqlStorage.ts +181 -0
  269. package/src/internal/machine/clusterStorageCheck.ts +274 -0
  270. package/src/internal/machine/clusterTarget.ts +154 -0
  271. package/src/internal/machine/clusterTimer.ts +58 -0
  272. package/src/internal/machine/clusterWake.ts +100 -0
  273. package/src/internal/machine/clusterWork.ts +269 -0
  274. package/src/internal/machine/command.ts +4 -4
  275. package/src/internal/machine/commandRuntime.ts +12 -24
  276. package/src/internal/machine/configuration.ts +0 -181
  277. package/src/internal/machine/errors.ts +11 -2
  278. package/src/internal/machine/executionPlan.ts +493 -263
  279. package/src/internal/machine/implementation.ts +6 -6
  280. package/src/internal/machine/inspectionRuntime.ts +1 -1
  281. package/src/internal/machine/invocationChanges.ts +89 -0
  282. package/src/internal/machine/{activities.ts → invocationDefinitions.ts} +10 -10
  283. package/src/internal/machine/invocationEvent.ts +35 -12
  284. package/src/internal/machine/invocationOutcome.ts +145 -0
  285. package/src/internal/machine/invocationResolution.ts +307 -0
  286. package/src/internal/machine/logicScope.ts +47 -0
  287. package/src/internal/machine/machine.ts +35 -100
  288. package/src/internal/machine/observation.ts +67 -2
  289. package/src/internal/machine/plannedSnapshot.ts +17 -20
  290. package/src/internal/machine/planner.ts +75 -99
  291. package/src/internal/machine/process.ts +78 -722
  292. package/src/internal/machine/protocol.ts +70 -26
  293. package/src/internal/machine/runtime.ts +198 -195
  294. package/src/internal/machine/runtimeCompiled.ts +496 -171
  295. package/src/internal/machine/runtimeProtocol.ts +416 -305
  296. package/src/internal/machine/stateDefinition.ts +0 -5
  297. package/src/internal/machine/step.ts +1518 -0
  298. package/src/internal/machine/stepHost.ts +634 -0
  299. package/src/internal/machine/symbols.ts +3 -14
  300. package/src/internal/machine/transition.ts +11 -11
  301. package/src/internal/testing/machine/check.ts +240 -36
  302. package/src/internal/testing/machine/exploration.ts +42 -3
  303. package/src/internal/testing/machine/format.ts +1 -1
  304. package/src/internal/testing/machine/probe.ts +2 -1
  305. package/src/internal/testing/machine/runtime.ts +15 -5
  306. package/src/internal/testing/machine/trace.ts +261 -41
  307. package/src/internal/testing/machine/transitionCoverage.ts +1 -1
  308. package/src/internal/testing/machine/verification.ts +11 -5
  309. package/src/internal/testing/machine/work.ts +101 -0
  310. package/src/testing/MachineTest.ts +268 -44
  311. package/src/unstable/cluster/ClusterMachine.ts +1183 -59
  312. package/src/unstable/cluster/ClusterMachineProxy.ts +372 -0
  313. package/src/unstable/cluster/SqlMachineStorage.ts +136 -0
  314. package/src/unstable/cluster/index.ts +15 -0
  315. package/src/unstable/reactivity/AtomMachine.ts +27 -88
  316. package/dist/internal/machine/activities.d.ts.map +0 -1
  317. package/dist/internal/machine/activities.js.map +0 -1
  318. package/dist/internal/machine/invocation.d.ts +0 -33
  319. package/dist/internal/machine/invocation.d.ts.map +0 -1
  320. package/dist/internal/machine/invocation.js +0 -220
  321. package/dist/internal/machine/invocation.js.map +0 -1
  322. package/dist/internal/machine/invocationDefinition.d.ts.map +0 -1
  323. package/dist/internal/machine/invocationDefinition.js.map +0 -1
  324. package/dist/internal/machine/requirements.d.ts +0 -4
  325. package/dist/internal/machine/requirements.d.ts.map +0 -1
  326. package/dist/internal/machine/requirements.js +0 -2
  327. package/dist/internal/machine/requirements.js.map +0 -1
  328. package/dist/internal/machine/runtimeGeneric.d.ts +0 -3
  329. package/dist/internal/machine/runtimeGeneric.d.ts.map +0 -1
  330. package/dist/internal/machine/runtimeGeneric.js +0 -465
  331. package/dist/internal/machine/runtimeGeneric.js.map +0 -1
  332. package/src/internal/machine/invocation.ts +0 -376
  333. package/src/internal/machine/requirements.ts +0 -11
  334. package/src/internal/machine/runtimeGeneric.ts +0 -797
@@ -1,797 +0,0 @@
1
- /** General Effect process worker and supervisor strategy. */
2
- import * as Cause from "effect/Cause"
3
- import * as Channel from "effect/Channel"
4
- import * as Deferred from "effect/Deferred"
5
- import * as Effect from "effect/Effect"
6
- import * as Exit from "effect/Exit"
7
- import * as Fiber from "effect/Fiber"
8
- import * as Option from "effect/Option"
9
- import * as PubSub from "effect/PubSub"
10
- import * as Stream from "effect/Stream"
11
- import * as SynchronizedRef from "effect/SynchronizedRef"
12
- import type * as Take from "effect/Take"
13
- import type { Inspection } from "../../Machine.js"
14
- import { type ChildSelector } from "./childRegistry.js"
15
- import { StoppedError } from "./errors.js"
16
- import * as InspectionRuntime from "./inspectionRuntime.js"
17
- import {
18
- type AcknowledgedDelivery,
19
- AcknowledgedMessageTypeId,
20
- acknowledgedSend,
21
- childlessRuntime,
22
- classifyOutcome,
23
- closeProcessMailbox,
24
- executionIsChildless,
25
- failAcknowledgedMessage,
26
- type InspectedOffer,
27
- inspectionSubject,
28
- isAcknowledgedMessage,
29
- isMachineTarget,
30
- type MachineRef,
31
- makeChildRuntime,
32
- makeEmissionRuntime,
33
- makeInspectedMessage,
34
- makeProcessMailbox,
35
- messageCausation,
36
- messageEvent,
37
- noCausation,
38
- noInspectInitial,
39
- noParentSend,
40
- notifyActiveSnapshot,
41
- offerProcessMailbox,
42
- pollCompactMailbox,
43
- type ProcessAddress,
44
- type ProcessContext,
45
- type ProcessLogic,
46
- type ProcessMessage,
47
- type ProcessScope,
48
- publishInspectedSent,
49
- receiveProcessMailbox,
50
- type RuntimeSnapshot,
51
- sendMachineTarget,
52
- type StartInternalOptions,
53
- type StartProcess,
54
- stopAcknowledgedMessage,
55
- succeedAcknowledgedMessage,
56
- type VersionedSnapshot
57
- } from "./runtimeProtocol.js"
58
-
59
- // `Machine.logic` permits an arbitrary Effect program, including programs that
60
- // suspend or supervise their own fibers. Keep its two-fiber worker/supervisor
61
- // protocol as the general contract rather than weakening it for statecharts.
62
- export const startGenericInternal: StartProcess = Effect.fnUntraced(
63
- function*<State, Event, Error, Requirements, Output, InitialError>(
64
- logic: ProcessLogic<State, Event, Error, Requirements, Output, InitialError>,
65
- options: StartInternalOptions
66
- ) {
67
- const {
68
- detached,
69
- id: requestedId,
70
- onOutcome,
71
- onReady,
72
- onReadySync,
73
- onSnapshot,
74
- onStop,
75
- onStopSync,
76
- parent,
77
- runtime,
78
- sendParent: overrideSendParent
79
- } = options
80
- type ProcessTermination =
81
- | { readonly _tag: "Stopped" }
82
- | { readonly _tag: "Done"; readonly output: Output }
83
- | { readonly _tag: "Failure"; readonly cause: Cause.Cause<Error> }
84
-
85
- const sessionId = options.sessionId ?? (yield* runtime.nextSessionId)
86
- const id = requestedId ?? sessionId
87
- const inspector = runtime.inspection
88
- const subject = inspector === undefined ? undefined : inspectionSubject(logic, id, sessionId)
89
- const activity: Inspection.Activity | undefined = inspector === undefined || options.activity === undefined
90
- ? undefined
91
- : { ...options.activity, sessionId }
92
- let initialEntryPaths: ReadonlyArray<string> | undefined
93
- let initialMicrosteps: ReadonlyArray<unknown> | undefined
94
- const mailbox = makeProcessMailbox<Event>()
95
- const emissions = options.emissions ?? makeEmissionRuntime()
96
- const termination = yield* Deferred.make<ProcessTermination>()
97
- const done = yield* Deferred.make<Output, Error | StoppedError>()
98
- const awaitCompletion = Deferred.await(done).pipe(Effect.exit, Effect.asVoid)
99
- let initializing = true
100
- let inFlightMessage: ProcessMessage<Event> | undefined
101
- const requestStop = Deferred.succeed(termination, { _tag: "Stopped" }).pipe(Effect.asVoid)
102
- const offerDirect = (
103
- message: ProcessMessage<Event>,
104
- onAccepted?: () => void
105
- ): Effect.Effect<void, StoppedError> =>
106
- Effect.suspend(() =>
107
- offerProcessMailbox(mailbox, message, onAccepted) ? Effect.void : Effect.fail(new StoppedError())
108
- )
109
- const offerInspected: InspectedOffer<Event> | undefined = inspector === undefined ? undefined : (
110
- event,
111
- source,
112
- causedBy,
113
- deferred?: Deferred.Deferred<AcknowledgedDelivery<unknown>, unknown>
114
- ) =>
115
- Effect.suspend(() => {
116
- const message: ProcessMessage<Event> = inspector.isActive()
117
- ? makeInspectedMessage(inspector, subject!, event, source, causedBy, deferred)
118
- : deferred === undefined
119
- ? event
120
- : { [AcknowledgedMessageTypeId]: true as const, event, deferred }
121
- return offerDirect(message, () => publishInspectedSent(inspector, subject!, message))
122
- })
123
- const sendAcknowledged:
124
- | ((event: Event) => Effect.Effect<AcknowledgedDelivery<State>, Error | StoppedError>)
125
- | undefined = logic.execution?._tag !== "Compiled"
126
- ? undefined
127
- : (event) =>
128
- Effect.uninterruptibleMask((restore) =>
129
- Deferred.make<AcknowledgedDelivery<unknown>, unknown>().pipe(
130
- Effect.flatMap((deferred) => {
131
- const offered = inspector === undefined
132
- ? offerDirect({ [AcknowledgedMessageTypeId]: true as const, event, deferred })
133
- : offerInspected!(event, undefined, undefined, deferred)
134
- return offered.pipe(Effect.andThen(restore(Deferred.await(deferred))))
135
- }),
136
- Effect.map((delivery) => delivery as AcknowledgedDelivery<State>)
137
- )
138
- ) as Effect.Effect<AcknowledgedDelivery<State>, Error | StoppedError>
139
-
140
- const self: ProcessAddress<Event> = {
141
- id,
142
- sessionId,
143
- // Initialization must finish constructing a state before a stopped
144
- // snapshot can be published. A stop requested there is therefore recorded
145
- // and returns so initialization can finish. Once running, the requesting
146
- // process waits forever and is interrupted by the supervisor after the
147
- // stop request wins, so execution never continues after `self.stop`.
148
- stop: Effect.suspend(() =>
149
- initializing
150
- ? requestStop
151
- : requestStop.pipe(Effect.andThen(Effect.never))
152
- ),
153
- send: inspector === undefined
154
- ? (event) => offerDirect(event)
155
- : (event) => offerInspected!(event, undefined, undefined),
156
- ...(inspector === undefined
157
- ? undefined
158
- : { inspectionSubject: subject!, sendInspected: offerInspected! })
159
- }
160
-
161
- let {
162
- changes: childChanges,
163
- close: closeChildren,
164
- get: getChild,
165
- owned: ownedChildren,
166
- sendTo,
167
- spawn,
168
- stop: stopChild
169
- } = childlessRuntime
170
- if (!executionIsChildless(logic.execution)) {
171
- ;({
172
- changes: childChanges,
173
- close: closeChildren,
174
- get: getChild,
175
- owned: ownedChildren,
176
- sendTo,
177
- spawn,
178
- stop: stopChild
179
- } = yield* makeChildRuntime(
180
- self,
181
- runtime,
182
- undefined,
183
- sendAcknowledged === undefined ? undefined : (event) => sendAcknowledged(event as Event)
184
- ))
185
- }
186
- const cleanupStartupFailure = <A, E>(exit: Exit.Exit<A, E>): Effect.Effect<void> => {
187
- if (Exit.isSuccess(exit)) return Effect.void
188
- if (inspector !== undefined) {
189
- inspector.publishUnsafe(
190
- activity === undefined
191
- ? { _tag: "StartFailed", subject: subject!, cause: exit.cause }
192
- : { _tag: "ActivityStopped", subject: activity.owner, activity, exit }
193
- )
194
- }
195
- return closeChildren(exit).pipe(
196
- Effect.andThen(emissions.close()),
197
- Effect.andThen(options.inspectionRoot === true && inspector !== undefined ? inspector.close : Effect.void)
198
- )
199
- }
200
- const cleanup = onStopSync === undefined ? onStop ?? Effect.void : Effect.sync(() => onStopSync(ref))
201
- const currentCausation = inspector === undefined
202
- ? noCausation
203
- : (): Inspection.Causation | undefined => messageCausation(inFlightMessage, initializing)
204
- const sendParent = overrideSendParent ?? (parent === undefined
205
- ? noParentSend
206
- : inspector === undefined
207
- ? parent.send
208
- : (event) => sendMachineTarget(parent, event, subject, currentCausation()))
209
- const emit = inspector === undefined
210
- ? emissions.emit
211
- : (event: unknown) =>
212
- emissions.emit(event).pipe(
213
- Effect.tap(() =>
214
- Effect.sync(() =>
215
- inspector.publishUnsafe({
216
- _tag: "Emitted",
217
- subject: subject!,
218
- emission: event,
219
- causedBy: currentCausation()
220
- })
221
- )
222
- )
223
- )
224
- const sendToTarget: ProcessScope<Event>["sendTo"] = inspector === undefined
225
- ? ((target: unknown, event: unknown) =>
226
- isMachineTarget(target) ? target.send(event) : sendTo(target as ChildSelector, event))
227
- : ((target: unknown, event: unknown) =>
228
- isMachineTarget(target)
229
- ? sendMachineTarget(target, event, subject, currentCausation())
230
- : sendTo(target as ChildSelector, event, subject, currentCausation()))
231
-
232
- const scope: ProcessScope<Event> = {
233
- self,
234
- parent,
235
- spawn,
236
- sendParent,
237
- emit,
238
- sendTo: sendToTarget,
239
- stopChild,
240
- failCause: (cause) =>
241
- Deferred.succeed(termination, {
242
- _tag: "Failure",
243
- cause: cause as Cause.Cause<Error>
244
- }).pipe(Effect.asVoid),
245
- inspectInitial: inspector === undefined
246
- ? noInspectInitial
247
- : (paths, microsteps = []) => {
248
- initialEntryPaths = paths
249
- initialMicrosteps = microsteps
250
- }
251
- }
252
-
253
- if (inspector !== undefined) {
254
- inspector.publishUnsafe(
255
- activity === undefined
256
- ? {
257
- _tag: "Created",
258
- subject: subject!,
259
- parent: parent?.inspectionSubject,
260
- origin: options.origin ?? { _tag: "Root" },
261
- definition: logic.inspection?.definition
262
- }
263
- : { _tag: "ActivityStarted", subject: activity.owner, activity }
264
- )
265
- }
266
-
267
- const initial = yield* logic.initial(scope).pipe(
268
- Effect.onExit(cleanupStartupFailure),
269
- Effect.ensuring(Effect.sync(() => {
270
- initializing = false
271
- }))
272
- )
273
- const current = yield* SynchronizedRef.make<VersionedSnapshot<State, Error, Output>>({
274
- revision: 0,
275
- terminalizing: false,
276
- changes: undefined,
277
- snapshot: {
278
- status: "active",
279
- state: initial
280
- }
281
- })
282
- if (activity === undefined) {
283
- inspector?.publishUnsafe({
284
- _tag: "Initialized",
285
- subject: subject!,
286
- snapshot: { status: "active", state: initial },
287
- initialEntryPaths: initialEntryPaths ?? [],
288
- microsteps: InspectionRuntime.microsteps({ microsteps: initialMicrosteps ?? [] })
289
- })
290
- }
291
- const publishSnapshot: (
292
- snapshot: VersionedSnapshot<State, Error, Output>
293
- ) => Effect.Effect<VersionedSnapshot<State, Error, Output>> = onSnapshot === undefined
294
- ? (snapshot) =>
295
- snapshot.changes === undefined
296
- ? Effect.succeed(snapshot)
297
- : PubSub.publish(snapshot.changes, [snapshot] as const).pipe(Effect.as(snapshot))
298
- : (snapshot) => {
299
- const publish = snapshot.changes === undefined
300
- ? Effect.succeed(snapshot)
301
- : PubSub.publish(snapshot.changes, [snapshot] as const).pipe(Effect.as(snapshot))
302
- const runtimeSnapshot = snapshot.snapshot
303
- return runtimeSnapshot.status !== "active"
304
- ? publish
305
- : publish.pipe(Effect.tap(() => notifyActiveSnapshot(onSnapshot, runtimeSnapshot)))
306
- }
307
-
308
- const completeChanges = (
309
- snapshot: VersionedSnapshot<State, Error, Output>
310
- ): Effect.Effect<void> =>
311
- snapshot.changes === undefined
312
- ? Effect.void
313
- : PubSub.publish(snapshot.changes, Exit.succeed<void>(undefined)).pipe(Effect.asVoid)
314
-
315
- const completeIfTerminal = (
316
- snapshot: VersionedSnapshot<State, Error, Output>
317
- ): Effect.Effect<VersionedSnapshot<State, Error, Output>> => {
318
- if (snapshot.snapshot.status === "active") {
319
- return Effect.succeed(snapshot)
320
- }
321
- return completeChanges(snapshot).pipe(Effect.as(snapshot))
322
- }
323
-
324
- const publishIfCurrent = (
325
- snapshot: VersionedSnapshot<State, Error, Output>
326
- ): Effect.Effect<VersionedSnapshot<State, Error, Output> | undefined> =>
327
- SynchronizedRef.get(current).pipe(
328
- Effect.flatMap((
329
- currentSnapshot
330
- ): Effect.Effect<VersionedSnapshot<State, Error, Output> | undefined> =>
331
- currentSnapshot.revision === snapshot.revision
332
- ? publishSnapshot(snapshot).pipe(Effect.flatMap(completeIfTerminal))
333
- : Effect.succeed(undefined)
334
- )
335
- )
336
-
337
- type SnapshotModification = readonly [
338
- VersionedSnapshot<State, Error, Output> | undefined,
339
- VersionedSnapshot<State, Error, Output>
340
- ]
341
-
342
- const updateSnapshot = <E2, R2>(
343
- f: (
344
- snapshot: RuntimeSnapshot<State, Error, Output>
345
- ) => Effect.Effect<RuntimeSnapshot<State, Error, Output> | undefined, E2, R2>
346
- ): Effect.Effect<RuntimeSnapshot<State, Error, Output> | undefined, E2, R2> =>
347
- SynchronizedRef.modifyEffect(
348
- current,
349
- (current) =>
350
- current.terminalizing
351
- ? Effect.succeed([undefined, current] as const)
352
- : Effect.map(
353
- f(current.snapshot),
354
- (next) => {
355
- if (next === undefined) {
356
- return [undefined, current] as const
357
- }
358
- const versioned = {
359
- revision: current.revision + 1,
360
- snapshot: next,
361
- terminalizing: false,
362
- changes: current.changes
363
- }
364
- return [versioned, versioned] as const
365
- }
366
- )
367
- ).pipe(
368
- Effect.flatMap((versioned) =>
369
- versioned === undefined ? Effect.succeed(undefined) : publishIfCurrent(versioned)
370
- ),
371
- Effect.map((published) => published?.snapshot)
372
- )
373
-
374
- const reserveTerminalSnapshot = (
375
- f: (
376
- snapshot: Extract<RuntimeSnapshot<State, Error, Output>, { readonly status: "active" }>
377
- ) => RuntimeSnapshot<State, Error, Output>
378
- ): Effect.Effect<RuntimeSnapshot<State, Error, Output> | undefined> =>
379
- SynchronizedRef.modify(
380
- current,
381
- (current): SnapshotModification => {
382
- if (current.terminalizing || current.snapshot.status !== "active") {
383
- return [undefined, current]
384
- }
385
- return [
386
- {
387
- revision: current.revision + 1,
388
- snapshot: f(current.snapshot),
389
- terminalizing: true,
390
- changes: current.changes
391
- },
392
- { ...current, terminalizing: true }
393
- ]
394
- }
395
- ).pipe(Effect.map((versioned) => versioned?.snapshot))
396
-
397
- const setAndPublishSnapshot = (
398
- snapshot: RuntimeSnapshot<State, Error, Output>
399
- ): Effect.Effect<void> =>
400
- SynchronizedRef.updateAndGet(current, (current) => ({
401
- revision: current.revision + 1,
402
- snapshot,
403
- terminalizing: true,
404
- changes: current.changes
405
- })).pipe(
406
- Effect.flatMap(publishSnapshot),
407
- Effect.flatMap(completeIfTerminal),
408
- Effect.asVoid
409
- )
410
-
411
- const setActiveStateDirect = (state: State) =>
412
- updateSnapshot((snapshot) =>
413
- Effect.succeed(
414
- snapshot.status === "active"
415
- ? {
416
- status: "active",
417
- state
418
- }
419
- : undefined
420
- )
421
- ).pipe(Effect.asVoid)
422
-
423
- const setActiveState = inspector === undefined ?
424
- setActiveStateDirect :
425
- (state: State) =>
426
- SynchronizedRef.get(current).pipe(
427
- Effect.flatMap((before) =>
428
- updateSnapshot((snapshot) =>
429
- Effect.succeed(
430
- snapshot.status === "active"
431
- ? {
432
- status: "active",
433
- state
434
- }
435
- : undefined
436
- )
437
- ).pipe(
438
- Effect.tap((after) =>
439
- Effect.sync(() => {
440
- if (logic.inspection?.kind === "Machine" || after === undefined) return
441
- inspector.publishUnsafe({
442
- _tag: "StateChanged",
443
- subject: subject!,
444
- before: before.snapshot.state,
445
- after: state,
446
- causedByDeliveryId: inFlightMessage !== undefined && isAcknowledgedMessage(inFlightMessage)
447
- ? inFlightMessage.inspection?.deliveryId
448
- : undefined
449
- })
450
- })
451
- )
452
- )
453
- ),
454
- Effect.asVoid
455
- )
456
-
457
- const terminalizeWith = (
458
- snapshot: RuntimeSnapshot<State, Error, Output>,
459
- exit: Exit.Exit<unknown, unknown>,
460
- completeDone: Effect.Effect<void>
461
- ): Effect.Effect<void> => {
462
- const notifyOutcome =
463
- onOutcome === undefined || (snapshot.status === "stopped" && options.skipStoppedOutcome === true)
464
- ? Effect.void
465
- : Effect.suspend(() => onOutcome(classifyOutcome(snapshot)!)).pipe(
466
- Effect.exit,
467
- Effect.asVoid
468
- )
469
- const closeEmissionsAndInspect = inspector === undefined
470
- ? emissions.close()
471
- : emissions.close().pipe(
472
- Effect.andThen(Effect.sync(() =>
473
- inspector.publishUnsafe(
474
- activity === undefined
475
- ? { _tag: "Terminated", subject: subject!, snapshot }
476
- : {
477
- _tag: "ActivityStopped",
478
- subject: activity.owner,
479
- activity,
480
- exit: snapshot.status === "stopped" ? Exit.interrupt() : exit
481
- }
482
- )
483
- ))
484
- )
485
- return Effect.uninterruptible(
486
- Effect.sync(() => closeProcessMailbox(mailbox)).pipe(
487
- Effect.andThen(closeChildren(exit)),
488
- Effect.andThen(setAndPublishSnapshot(snapshot)),
489
- Effect.andThen(closeEmissionsAndInspect),
490
- Effect.andThen(Effect.sync(() => {
491
- if (Exit.isFailure(exit)) {
492
- failAcknowledgedMessage(inFlightMessage, exit.cause)
493
- } else {
494
- stopAcknowledgedMessage(inFlightMessage)
495
- }
496
- inFlightMessage = undefined
497
- })),
498
- Effect.andThen(notifyOutcome),
499
- Effect.andThen(cleanup),
500
- Effect.andThen(options.inspectionRoot === true && inspector !== undefined ? inspector.close : Effect.void),
501
- Effect.andThen(completeDone)
502
- )
503
- )
504
- }
505
-
506
- const reserveStoppedSnapshot = reserveTerminalSnapshot((snapshot) => ({
507
- status: "stopped",
508
- state: snapshot.state
509
- }))
510
-
511
- const reserveFailureSnapshot = (cause: Cause.Cause<Error>) =>
512
- reserveTerminalSnapshot((snapshot) => ({
513
- status: "error",
514
- state: snapshot.state,
515
- cause
516
- }))
517
-
518
- const reserveSuccessSnapshot = (output: Output) =>
519
- reserveTerminalSnapshot((snapshot) => ({
520
- status: "done",
521
- state: snapshot.state,
522
- output
523
- }))
524
-
525
- const terminalizeReservedStop = (
526
- snapshot: RuntimeSnapshot<State, Error, Output>
527
- ): Effect.Effect<void> => {
528
- const exit = Exit.void
529
- return terminalizeWith(
530
- snapshot,
531
- exit,
532
- Deferred.fail(done, new StoppedError())
533
- )
534
- }
535
-
536
- const terminalizeReservedFailure = (
537
- snapshot: RuntimeSnapshot<State, Error, Output>,
538
- cause: Cause.Cause<Error>
539
- ): Effect.Effect<void> => {
540
- const exit = Exit.failCause(cause)
541
- return terminalizeWith(snapshot, exit, Deferred.failCause(done, cause))
542
- }
543
-
544
- const terminalizeReservedSuccess = (
545
- snapshot: RuntimeSnapshot<State, Error, Output>,
546
- output: Output
547
- ): Effect.Effect<void> => {
548
- const exit = Exit.succeed(output)
549
- return terminalizeWith(snapshot, exit, Deferred.succeed(done, output))
550
- }
551
-
552
- const stop: Effect.Effect<void> = Effect.uninterruptible(
553
- requestStop.pipe(Effect.andThen(awaitCompletion))
554
- )
555
-
556
- const acknowledgedContext:
557
- | Pick<
558
- ProcessContext<State, Event>,
559
- "receiveMessage" | "pollMessage" | "completeMessage"
560
- >
561
- | undefined = logic.execution?._tag !== "Compiled" ? undefined : {
562
- receiveMessage: receiveProcessMailbox(mailbox).pipe(
563
- Effect.tap((message) =>
564
- Effect.sync(() => {
565
- inFlightMessage = isAcknowledgedMessage(message) ? message : undefined
566
- })
567
- )
568
- ),
569
- pollMessage: Effect.sync(() => pollCompactMailbox(mailbox)).pipe(
570
- Effect.tap((message) =>
571
- Effect.sync(() => {
572
- if (Option.isSome(message)) {
573
- inFlightMessage = isAcknowledgedMessage(message.value) ? message.value : undefined
574
- }
575
- })
576
- )
577
- ),
578
- completeMessage: (delivery) => {
579
- succeedAcknowledgedMessage(inFlightMessage, delivery)
580
- inFlightMessage = undefined
581
- }
582
- }
583
- const receive = inspector === undefined || logic.execution?._tag === "Compiled"
584
- ? receiveProcessMailbox(mailbox).pipe(Effect.map(messageEvent))
585
- : receiveProcessMailbox(mailbox).pipe(
586
- Effect.tap((message) =>
587
- Effect.sync(() => {
588
- inFlightMessage = message
589
- })
590
- ),
591
- Effect.map(messageEvent)
592
- )
593
- const poll = inspector === undefined || logic.execution?._tag === "Compiled"
594
- ? Effect.sync(() => pollCompactMailbox(mailbox)).pipe(Effect.map(Option.map(messageEvent)))
595
- : Effect.sync(() => pollCompactMailbox(mailbox)).pipe(
596
- Effect.tap((message) =>
597
- Effect.sync(() => {
598
- if (Option.isSome(message)) inFlightMessage = message.value
599
- })
600
- ),
601
- Effect.map(Option.map(messageEvent))
602
- )
603
- const updateStateDirect = <E2, R2>(f: (state: State) => Effect.Effect<State, E2, R2>) =>
604
- updateSnapshot((snapshot) =>
605
- snapshot.status === "active"
606
- ? f(snapshot.state).pipe(
607
- Effect.map((state) => ({
608
- status: "active" as const,
609
- state
610
- }))
611
- )
612
- : Effect.succeed(undefined)
613
- ).pipe(Effect.asVoid)
614
- const updateState: ProcessContext<State, Event>["updateState"] = inspector === undefined
615
- ? updateStateDirect
616
- : (f) =>
617
- SynchronizedRef.get(current).pipe(
618
- Effect.flatMap((before) =>
619
- updateSnapshot((snapshot) =>
620
- snapshot.status === "active"
621
- ? f(snapshot.state).pipe(
622
- Effect.map((state) => ({
623
- status: "active" as const,
624
- state
625
- }))
626
- )
627
- : Effect.succeed(undefined)
628
- ).pipe(
629
- Effect.tap((after) =>
630
- Effect.sync(() => {
631
- if (logic.inspection?.kind === "Machine" || after?.status !== "active") return
632
- inspector.publishUnsafe({
633
- _tag: "StateChanged",
634
- subject: subject!,
635
- before: before.snapshot.state,
636
- after: after.state,
637
- causedByDeliveryId: inFlightMessage !== undefined && isAcknowledgedMessage(inFlightMessage)
638
- ? inFlightMessage.inspection?.deliveryId
639
- : undefined
640
- })
641
- })
642
- )
643
- )
644
- ),
645
- Effect.asVoid
646
- )
647
- const context: ProcessContext<State, Event> = {
648
- ...scope,
649
- ...(logic.execution?._tag === "Compiled" && !logic.execution.childless ? { ownedChildren } : undefined),
650
- ...acknowledgedContext,
651
- receive,
652
- poll,
653
- state: SynchronizedRef.get(current).pipe(Effect.map((current) => current.snapshot.state)),
654
- setState: setActiveState,
655
- updateState
656
- }
657
-
658
- const getOrCreateChanges = SynchronizedRef.modifyEffect(
659
- current,
660
- (current) => {
661
- if (current.snapshot.status !== "active") {
662
- return Effect.succeed([undefined, current] as const)
663
- }
664
- if (current.changes !== undefined) {
665
- return Effect.succeed([current.changes, current] as const)
666
- }
667
- return PubSub.unbounded<Take.Take<VersionedSnapshot<State, Error, Output>>>({ replay: 1 }).pipe(
668
- Effect.map((changes) => [changes, { ...current, changes }] as const)
669
- )
670
- }
671
- )
672
-
673
- const changesStream: Stream.Stream<RuntimeSnapshot<State, Error, Output>> = Stream.unwrap(
674
- Effect.gen(function*() {
675
- const changes = yield* getOrCreateChanges
676
- if (changes === undefined) {
677
- return Stream.succeed((yield* SynchronizedRef.get(current)).snapshot)
678
- }
679
- const subscription = yield* PubSub.subscribe(changes)
680
- const captured = yield* SynchronizedRef.get(current)
681
- if (captured.snapshot.status !== "active") {
682
- return Stream.succeed(captured.snapshot)
683
- }
684
- return Stream.succeed(captured.snapshot).pipe(
685
- Stream.concat(
686
- Stream.fromChannel(Channel.fromEffectTake(PubSub.take(subscription))).pipe(
687
- Stream.filter((next) => next.revision > captured.revision),
688
- Stream.map((next) => next.snapshot)
689
- )
690
- )
691
- )
692
- })
693
- )
694
-
695
- const ref: MachineRef<State, Event, Error, Output> = {
696
- id,
697
- sessionId,
698
- ...(inspector === undefined
699
- ? undefined
700
- : { inspectionSubject: subject!, sendInspected: offerInspected! }),
701
- state: SynchronizedRef.get(current).pipe(Effect.map((current) => current.snapshot.state)),
702
- snapshot: SynchronizedRef.get(current).pipe(Effect.map((current) => current.snapshot)),
703
- changes: changesStream,
704
- emissions: emissions.stream as Stream.Stream<never>,
705
- join: Deferred.await(done),
706
- stop,
707
- send: self.send,
708
- ...(sendAcknowledged === undefined ? undefined : { [acknowledgedSend]: sendAcknowledged }),
709
- child: getChild,
710
- childChanges
711
- }
712
-
713
- if (onReadySync !== undefined && !onReadySync(ref)) {
714
- yield* requestStop
715
- } else if (onReady !== undefined) {
716
- yield* onReady(ref, requestStop)
717
- }
718
- if (onSnapshot !== undefined) {
719
- yield* notifyActiveSnapshot(onSnapshot, { status: "active", state: initial })
720
- }
721
-
722
- const reserveTermination = (termination: ProcessTermination) => {
723
- switch (termination._tag) {
724
- case "Stopped":
725
- return reserveStoppedSnapshot
726
- case "Done":
727
- return reserveSuccessSnapshot(termination.output)
728
- case "Failure":
729
- return reserveFailureSnapshot(termination.cause)
730
- }
731
- }
732
-
733
- const completeTermination = (
734
- termination: ProcessTermination,
735
- snapshot: RuntimeSnapshot<State, Error, Output>
736
- ) => {
737
- switch (termination._tag) {
738
- case "Stopped":
739
- return terminalizeReservedStop(snapshot)
740
- case "Done":
741
- return terminalizeReservedSuccess(snapshot, termination.output)
742
- case "Failure":
743
- return terminalizeReservedFailure(snapshot, termination.cause)
744
- }
745
- }
746
-
747
- // The worker starts in the caller's turn and runs until it first suspends,
748
- // so a process started while an event is processed, such as an
749
- // invocation, begins its work before that event's sender continues.
750
- const forkRuntime = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
751
- detached === true
752
- ? Effect.forkDetach(effect, { startImmediately: true })
753
- : Effect.forkChild(effect, { startImmediately: true })
754
-
755
- const pendingTermination = yield* Deferred.poll(termination)
756
- const worker = Option.isNone(pendingTermination)
757
- ? yield* Effect.uninterruptibleMask((restore) =>
758
- restore(Effect.suspend(() => logic.run(context))).pipe(
759
- Effect.exit,
760
- Effect.flatMap((exit) =>
761
- Deferred.succeed(
762
- termination,
763
- Exit.isFailure(exit)
764
- ? { _tag: "Failure", cause: exit.cause }
765
- : { _tag: "Done", output: exit.value }
766
- )
767
- )
768
- )
769
- ).pipe(forkRuntime)
770
- : undefined
771
-
772
- // One Deferred arbitrates all terminal causes. The supervisor reserves the
773
- // terminal snapshot before interrupting the worker, so worker finalizers
774
- // cannot mutate the frozen state. It then waits for those finalizers before
775
- // publishing and completing `join` / `stop`.
776
- const runFiber: Effect.Effect<void, never, Requirements> = Effect.uninterruptibleMask((restore) =>
777
- Effect.gen(function*() {
778
- const requested = Option.isSome(pendingTermination)
779
- ? yield* pendingTermination.value
780
- : yield* restore(Deferred.await(termination))
781
-
782
- const snapshot = yield* reserveTermination(requested)
783
- if (worker !== undefined) {
784
- yield* Fiber.interrupt(worker)
785
- }
786
- if (snapshot === undefined) {
787
- return yield* awaitCompletion
788
- }
789
- return yield* completeTermination(requested, snapshot)
790
- })
791
- )
792
-
793
- yield* forkRuntime(runFiber)
794
-
795
- return ref
796
- }
797
- )