@typeonce/effect-machine 0.47.0 → 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 +1122 -814
  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 +1383 -1336
  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
@@ -0,0 +1,1779 @@
1
+ /**
2
+ * The live instance behind one active Cluster entity.
3
+ *
4
+ * @since 0.48.0
5
+ */
6
+ import * as Cause from "effect/Cause"
7
+ import * as Clock from "effect/Clock"
8
+ import type { EntityAddress, MessageStorage, Snowflake } from "effect/cluster"
9
+ import * as Data from "effect/Data"
10
+ import * as Deferred from "effect/Deferred"
11
+ import * as Effect from "effect/Effect"
12
+ import * as Exit from "effect/Exit"
13
+ import * as Option from "effect/Option"
14
+ import * as Predicate from "effect/Predicate"
15
+ import * as Schedule from "effect/Schedule"
16
+ import type * as Scope from "effect/Scope"
17
+ import * as Semaphore from "effect/Semaphore"
18
+ import type * as Machine from "../../Machine.js"
19
+ import type { Checkpoint, CommitEvent, Snapshot as ClusterSnapshot } from "../../unstable/cluster/ClusterMachine.js"
20
+ import * as CapturedInvocation from "./capturedInvocation.js"
21
+ import * as ClusterChild from "./clusterChild.js"
22
+ import { renderFailure } from "./clusterFailure.js"
23
+ import { ClusterKeepAlive, untilDone } from "./clusterKeepAlive.js"
24
+ import * as ClusterProgress from "./clusterProgress.js"
25
+ import { Accepted, Rejected, type RejectionReason, type Storage } from "./clusterProtocol.js"
26
+ import * as ClusterTarget from "./clusterTarget.js"
27
+ import * as ClusterTimer from "./clusterTimer.js"
28
+ import * as ClusterWork from "./clusterWork.js"
29
+ import * as Configuration from "./configuration.js"
30
+ import { ProcessLocalError } from "./errors.js"
31
+ import { toImpl } from "./implementation.js"
32
+ import * as internalMachine from "./machine.js"
33
+ import * as Planner from "./planner.js"
34
+ import * as Step from "./step.js"
35
+
36
+ type EntityAddress = EntityAddress.EntityAddress
37
+ type Snowflake = Snowflake.Snowflake
38
+ type Snapshot = Machine.Machine.Snapshot<any>
39
+ type SendResult = Accepted | Rejected
40
+ type Restore = <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
41
+
42
+ /** One event to apply, under the id that deduplicates it in `Storage`. */
43
+ export interface Input {
44
+ readonly requestId: Snowflake
45
+ readonly event: unknown
46
+ }
47
+
48
+ /**
49
+ * A request: an event, or the start or stop of a child machine by its parent.
50
+ * A start carries the arguments of the initial plan.
51
+ */
52
+ interface RequestInput extends Input {
53
+ readonly lifecycle?: "Start" | "Stop" | undefined
54
+ readonly initial?: ReadonlyArray<unknown> | undefined
55
+ /** An encoded snapshot of a child, which is the event of the request. */
56
+ readonly child?: { readonly entityId: string; readonly snapshot: unknown } | undefined
57
+ }
58
+
59
+ /**
60
+ * One live instance of a machine, owned by one set of entity handlers.
61
+ *
62
+ * Cluster builds the handlers when an entity becomes active, and again when a
63
+ * defect restarts it, so an instance lives exactly as long as its handlers.
64
+ *
65
+ * It owns the decoded machine state, as a cache of what `Storage` holds:
66
+ *
67
+ * - Memory is either unknown, or the state of one stored revision. An unknown
68
+ * memory is loaded by the next turn.
69
+ * - Requests, outcomes of work, and recovery are turns. Turns run one at a time,
70
+ * whatever the concurrency of their callers, and are the only way to advance
71
+ * the instance.
72
+ * - Memory is forgotten when a step starts, and set again only by an ending
73
+ * that proves what `Storage` holds: the whole transaction succeeded, or the
74
+ * input was refused before a commit was attempted. Every other ending,
75
+ * including a defect or an interruption, leaves it unknown.
76
+ * - Memory may fall behind `Storage` while another instance still runs during a
77
+ * shard handover. Nothing is decided from memory alone: an advance is
78
+ * compared by `Storage.commit`, and a refusal is confirmed with `Storage`.
79
+ *
80
+ * Every input is planned by `Machine.toStep`, which decides which work runs,
81
+ * stops, and starts, and whether an outcome still applies. The instance stores
82
+ * what a step decided and carries it out:
83
+ *
84
+ * - A step continues from the step state of the running work when that work
85
+ * belongs to the stored revision. Otherwise it continues from the stored
86
+ * state, resumed with the progress that `Storage` holds.
87
+ *
88
+ * It owns the work of the stored state, and the keep-alive request of the
89
+ * entity:
90
+ *
91
+ * - Both follow the stored state. They change at the end of a turn, after the
92
+ * state they belong to is known to be stored, never from a planned state.
93
+ * - Running work belongs to one stored revision. A step from the state of that
94
+ * work stops and starts what the step lists. Every other revision stops all
95
+ * work and starts what runs in its resumed state: work that ended does not
96
+ * run again, work of an entry starts with the event that entered it, and work
97
+ * of a resumed state starts with the initial event.
98
+ * - The end of work becomes a turn of its own, which the step settles against
99
+ * the state of that moment, so an outcome whose state exited is ignored.
100
+ * - Work that this instance stops never reports an outcome, whatever stops it.
101
+ * - A timer is work that waits for the due time stored with its state. A step
102
+ * stores the due times of the timers it enters, so work that starts finds
103
+ * them. A loaded state can lack one, when the deployment that stored it did
104
+ * not declare the timer. Its due time is stored as a checkpoint of its own
105
+ * before any work of that state starts.
106
+ * - A duration that cannot be evaluated does not refuse its step. It fails the
107
+ * machine once the step is stored, when the timer would have started.
108
+ * - An outcome the model does not handle, or that cannot be applied, stores the
109
+ * machine as failed. A failure of `Storage`, of its transaction, or of
110
+ * `enqueue` is retried for as long as the instance lives.
111
+ * - Whenever a turn leaves memory or the keep-alive unknown, recovery loads and
112
+ * aligns them again without waiting for another input.
113
+ *
114
+ * Ending the scope of the instance stops its work, its recovery, and every turn
115
+ * that has not started. The keep-alive request stays, so the entity comes up
116
+ * again.
117
+ *
118
+ * @internal
119
+ */
120
+ export interface ClusterInstance<R> {
121
+ /**
122
+ * Applies one input as one step and returns its reply.
123
+ *
124
+ * Only interruption leaves this effect, and it never leaves memory behind
125
+ * that `Storage` does not hold.
126
+ */
127
+ readonly apply: (input: Input) => Effect.Effect<SendResult, never, R>
128
+
129
+ /**
130
+ * Answers the delayed message of a timer once the timer is no longer waiting
131
+ * for that due time, which ignores a message whose activation has ended.
132
+ */
133
+ readonly wake: (timer: Timer) => Effect.Effect<void, never, R>
134
+
135
+ /**
136
+ * Applies an event that another machine sent. An event that cannot be applied
137
+ * fails the machine, and a failure of the infrastructure is retried.
138
+ */
139
+ readonly deliver: (input: Input) => Effect.Effect<void, never, R>
140
+
141
+ /**
142
+ * Starts the machine with its input, committing its initial state if absent.
143
+ * An active machine accepts it as a no-op; a failed or stopped one rejects it.
144
+ */
145
+ readonly start: (
146
+ input: { readonly requestId: Snowflake; readonly input: unknown }
147
+ ) => Effect.Effect<SendResult, never, R>
148
+
149
+ /** Stops a child machine, which then rejects every later request. */
150
+ readonly stop: (requestId: Snowflake) => Effect.Effect<void, never, R>
151
+
152
+ /**
153
+ * Applies the end of the child `entityId`, read from `Storage`, when this
154
+ * machine still runs it.
155
+ */
156
+ readonly childEnded: (entityId: string) => Effect.Effect<void, never, R>
157
+
158
+ /**
159
+ * Applies an encoded snapshot of the child `entityId` as a snapshot of its
160
+ * invocation, when this machine still runs it. A transition that cannot be
161
+ * applied fails the machine.
162
+ */
163
+ readonly childSnapshot: (input: {
164
+ readonly requestId: Snowflake
165
+ readonly entityId: string
166
+ readonly snapshot: unknown
167
+ }) => Effect.Effect<void, never, R>
168
+ }
169
+
170
+ /** @internal */
171
+ export interface Options<R> {
172
+ readonly machine: Machine.Machine.Any
173
+ readonly definitionId: string
174
+ readonly version: string
175
+ /** Arguments for the initial plan of an entity without a checkpoint. */
176
+ readonly input: ReadonlyArray<unknown>
177
+ readonly address: EntityAddress
178
+ readonly storage: Storage["Service"]
179
+ readonly messageStorage: MessageStorage.MessageStorage["Service"]
180
+ readonly enqueue: ((event: any) => Effect.Effect<void, unknown, R>) | undefined
181
+ readonly onCommit?: ((event: CommitEvent<any>) => Effect.Effect<void, unknown, R>) | undefined
182
+ /** `Entity.keepAlive` for the entity of the instance. */
183
+ readonly keepAlive: (enabled: boolean) => Effect.Effect<void>
184
+ /**
185
+ * Saves the delayed message that wakes the entity for a timer that waits
186
+ * longer than `threshold` milliseconds. Inside a transaction of
187
+ * `MessageStorage` it joins that transaction, and saving one that is already
188
+ * saved does nothing.
189
+ */
190
+ readonly wake: {
191
+ readonly threshold: number
192
+ readonly save: (timer: Timer) => Effect.Effect<void, unknown>
193
+ }
194
+ /**
195
+ * How the machine sends to Cluster machines: `self` names its own entity,
196
+ * `save` saves an event a step sends inside the transaction of its
197
+ * checkpoint, and `poll` lets the runner read what was saved. Without it, a
198
+ * step that sends is refused.
199
+ */
200
+ readonly sends?: {
201
+ readonly self: ClusterTarget.Target
202
+ readonly save: (sent: ClusterTarget.Sent) => Effect.Effect<void, unknown>
203
+ readonly poll: Effect.Effect<void>
204
+ } | undefined
205
+ /**
206
+ * The child machines that the states invoke, by their ids, how to save a
207
+ * request to one, and the parent of this machine when it is a child itself.
208
+ */
209
+ readonly children?: {
210
+ readonly protocols: ReadonlyMap<string, ClusterTarget.Protocol>
211
+ readonly save: ClusterTarget.Save
212
+ readonly address: (target: ClusterTarget.Target) => EntityAddress
213
+ readonly parent: ClusterTarget.Target | undefined
214
+ /** Whether this machine sends its parent its snapshots. */
215
+ readonly snapshots: boolean
216
+ /**
217
+ * Saves a request to a child from work, outside the transaction of a step,
218
+ * and lets the runner read it.
219
+ */
220
+ readonly dispatch: (target: ClusterTarget.Target, tag: string, payload: unknown) => Effect.Effect<void, unknown>
221
+ } | undefined
222
+ }
223
+
224
+ /** A timer that waits, as its delayed message names it. */
225
+ export interface Timer extends Checkpoint.InvocationKey {
226
+ readonly dueAt: number
227
+ }
228
+
229
+ /** What `Storage` holds at one stored revision. */
230
+ type Memory =
231
+ /** No checkpoint; the next step plans the initial state. */
232
+ | { readonly _tag: "Absent"; readonly revision: 0 }
233
+ | {
234
+ readonly _tag: "Active"
235
+ readonly revision: number
236
+ readonly state: Snapshot
237
+ readonly progress: ClusterProgress.Progress
238
+ /**
239
+ * The step state of this revision, for an active state. A final state takes
240
+ * no step, and has none.
241
+ */
242
+ readonly step: Step.State | undefined
243
+ }
244
+ | { readonly _tag: "Failed"; readonly revision: number; readonly failure: string }
245
+ /** A child that its parent stopped. */
246
+ | { readonly _tag: "Stopped"; readonly revision: number }
247
+
248
+ /** A memory from which a step can be planned. */
249
+ type Base = Exclude<Memory, { readonly _tag: "Failed" | "Stopped" }>
250
+
251
+ /** What one stored step applies. */
252
+ type StepInput =
253
+ | ({ readonly _tag: "Request" } & Input & {
254
+ /** Arguments of the initial plan, which the start of a child carries. */
255
+ readonly initial?: ReadonlyArray<unknown> | undefined
256
+ })
257
+ /** A request that reports a snapshot of the child machine that `work` runs. */
258
+ | { readonly _tag: "Report"; readonly requestId: Snowflake; readonly work: Step.Work; readonly snapshot: unknown }
259
+ /** The end of `work`, which the step settled from `from` as `next`. */
260
+ | { readonly _tag: "Outcome"; readonly work: Step.Work; readonly from: Step.State; readonly next: Step.Step }
261
+
262
+ /** The steps that one stored step takes. */
263
+ interface PlannedStep {
264
+ /** The step state it continues from, or `undefined` for a machine without one. */
265
+ readonly from: Step.State | undefined
266
+ /**
267
+ * In order: a start of the machine and the event it takes are one stored
268
+ * step. Empty for a final machine, which takes an event without a step.
269
+ */
270
+ readonly steps: ReadonlyArray<Step.Step>
271
+ }
272
+
273
+ /** A request that a step saves, to another machine. */
274
+ interface Outgoing {
275
+ readonly target: ClusterTarget.Target
276
+ readonly tag: string
277
+ readonly payload: unknown
278
+ }
279
+
280
+ /** A stored step. */
281
+ interface StoredStep {
282
+ /** The step state it continued from, and the last step it took. */
283
+ readonly from: Step.State | undefined
284
+ readonly step: Step.Step | undefined
285
+
286
+ /** Timers whose delayed messages the step saved. */
287
+ readonly woken: ReadonlyArray<Timer>
288
+
289
+ /** Whether the step saved a request to another machine. */
290
+ readonly sent: boolean
291
+ }
292
+
293
+ /** What a step leaves behind once the transaction around it has succeeded. */
294
+ interface StepResult {
295
+ readonly memory: Memory | undefined
296
+
297
+ /** The step, when it was stored. */
298
+ readonly stored: StoredStep | undefined
299
+ }
300
+
301
+ /** Ends a step, rolling its transaction back. */
302
+ class Refused extends Data.TaggedError("Refused")<{
303
+ readonly rejected: Rejected
304
+
305
+ /** What memory may hold after the rollback. */
306
+ readonly memory: Memory | undefined
307
+
308
+ /**
309
+ * Whether an earlier delivery may have committed this input. `Storage` must
310
+ * then be asked before the rejection is returned.
311
+ */
312
+ readonly confirm: boolean
313
+
314
+ /**
315
+ * The reason, when applying the same input to the same state would be refused
316
+ * again. Without one, the refusal comes from the infrastructure.
317
+ */
318
+ readonly failure: string | undefined
319
+ }> {}
320
+
321
+ /** Ends a step that was based on a state `Storage` no longer holds. */
322
+ class Conflicted extends Data.TaggedError("Conflicted") {}
323
+
324
+ const reject = (reason: RejectionReason, message: string): Rejected => new Rejected({ reason, message })
325
+
326
+ const fail = (reason: RejectionReason, message: string): Effect.Effect<never, Rejected> =>
327
+ Effect.fail(reject(reason, message))
328
+
329
+ const persistenceFailure = (error: { readonly cause: unknown }): Rejected =>
330
+ reject("PersistenceFailure", String(error.cause))
331
+
332
+ const messageFromCause = (cause: Cause.Cause<unknown>): string => {
333
+ const squashed = Cause.squash(cause)
334
+ return squashed instanceof globalThis.Error ? squashed.message : String(squashed)
335
+ }
336
+
337
+ const rejectionFromCause = (cause: Cause.Cause<unknown>, reason: RejectionReason): Rejected => {
338
+ const error = Cause.findErrorOption(cause)
339
+ if (Option.isSome(error) && error.value instanceof Rejected) {
340
+ return error.value
341
+ }
342
+ if (Option.isSome(error) && error.value instanceof internalMachine.ProcessLocalError) {
343
+ return reject("UnsupportedProcessLocal", `${error.value.operation} is process-local and is not supported`)
344
+ }
345
+ return reject(reason, messageFromCause(cause))
346
+ }
347
+
348
+ const failureFromCause = (cause: Cause.Cause<unknown>): string => {
349
+ const error = Cause.findErrorOption(cause)
350
+ return Option.isSome(error) && error.value instanceof Rejected
351
+ ? `${error.value.reason}: ${error.value.message}`
352
+ : renderFailure(cause)
353
+ }
354
+
355
+ /** Propagates an interruption without the typed failures that accompany it. */
356
+ const propagate = (cause: Cause.Cause<unknown>): Effect.Effect<never> =>
357
+ Effect.failCause(
358
+ Cause.fromReasons(
359
+ cause.reasons.filter((reason): reason is Cause.Die | Cause.Interrupt => !Cause.isFailReason(reason))
360
+ )
361
+ )
362
+
363
+ /** Turns every failure of one stage of a step into a refusal. */
364
+ const refuse = (options: {
365
+ readonly memory: Memory | undefined
366
+ readonly confirm: boolean
367
+ /** `Decision` stages depend only on the state and the input. */
368
+ readonly stage: "Decision" | "Infrastructure"
369
+ }) =>
370
+ <A, E, R>(stage: Effect.Effect<A, E, R>): Effect.Effect<A, Refused, R> =>
371
+ Effect.catchCause(stage, (cause): Effect.Effect<never, Refused> =>
372
+ Cause.hasInterrupts(cause)
373
+ ? propagate(cause)
374
+ : Effect.fail(
375
+ new Refused({
376
+ rejected: rejectionFromCause(cause, "TransitionFailure"),
377
+ memory: options.memory,
378
+ confirm: options.confirm,
379
+ failure: options.stage === "Decision" ? failureFromCause(cause) : undefined
380
+ })
381
+ ))
382
+
383
+ /** The status of a checkpoint, in the form memory holds it. */
384
+ export type ReadStatus =
385
+ | { readonly _tag: "Active"; readonly progress: ClusterProgress.Progress }
386
+ | { readonly _tag: "Failed"; readonly failure: string }
387
+ | { readonly _tag: "Stopped" }
388
+
389
+ /** Reads the status of a checkpoint, whose store may hold anything. */
390
+ export const readStatus = (status: unknown): ReadStatus | undefined => {
391
+ if (!Predicate.hasProperty(status, "_tag")) return undefined
392
+ if (status._tag === "Failed") {
393
+ return Predicate.hasProperty(status, "failure") && Predicate.isString(status.failure)
394
+ ? { _tag: "Failed", failure: status.failure }
395
+ : undefined
396
+ }
397
+ if (status._tag === "Stopped") return { _tag: "Stopped" }
398
+ if (status._tag !== "Active" || !Predicate.hasProperty(status, "invocations")) return undefined
399
+ const progress = ClusterProgress.fromStored(status.invocations)
400
+ return progress && { _tag: "Active", progress }
401
+ }
402
+
403
+ const absent: Memory = { _tag: "Absent", revision: 0 }
404
+
405
+ const progressOf = (memory: Memory): ClusterProgress.Progress =>
406
+ memory._tag === "Active" ? memory.progress : ClusterProgress.empty
407
+
408
+ const accepted = new Accepted({})
409
+
410
+ const refuseLocal = (operation: string): Effect.Effect<never> => Effect.die(new ProcessLocalError({ operation }))
411
+
412
+ /**
413
+ * A Cluster machine that sends to no Cluster machine has no target of its own.
414
+ * It has no session id, and events sent through it are not durable. Reading
415
+ * either one is a defect of the work that reads it.
416
+ */
417
+ class HostedTarget implements Machine.MachineTarget<any> {
418
+ constructor(readonly id: string) {}
419
+
420
+ get sessionId(): string {
421
+ throw new ProcessLocalError({ operation: "self.sessionId" })
422
+ }
423
+
424
+ readonly send = (_event: unknown) => refuseLocal("self.send")
425
+ }
426
+
427
+ /** The progress of the work of an active state, as `Machine.toStep` resumes it. */
428
+ const resumeProgress = (progress: ClusterProgress.Progress): ReadonlyArray<Step.Progress> =>
429
+ ClusterProgress.entries(progress).map(([{ id, path }, stored]) => ({
430
+ path,
431
+ id,
432
+ // A timer that waits and a child that runs have not ended.
433
+ status: stored._tag === "Settled" ? "Ended" : "Running"
434
+ }))
435
+
436
+ /** Fails with why a step could not be taken, or why the machine failed in it. */
437
+ const taken = (exit: Exit.Exit<Step.Step, unknown>): Effect.Effect<Step.Step, unknown> => {
438
+ if (Exit.isFailure(exit)) return Effect.failCause(exit.cause)
439
+ const ended = exit.value.exit
440
+ return ended !== undefined && Exit.isFailure(ended) ? Effect.failCause(ended.cause) : Effect.succeed(exit.value)
441
+ }
442
+
443
+ /** @internal */
444
+ export const make = <R>(options: Options<R>): Effect.Effect<ClusterInstance<R>, never, R | Scope.Scope> =>
445
+ Effect.gen(function*() {
446
+ const { address, definitionId, enqueue, machine, messageStorage, onCommit, storage, version } = options
447
+ const support = ClusterWork.supportOf(toImpl(machine).handlers)
448
+ const hostsWork = support._tag === "Hosted"
449
+ const targets = options.sends
450
+ const parent = options.children?.parent
451
+ const clock = yield* Clock.Clock
452
+ const semaphore = Semaphore.makeUnsafe(1)
453
+
454
+ // Owned by the running turn.
455
+ let memory: Memory | undefined
456
+ let recovering = false
457
+
458
+ // Work acts on the children that run when it acts, read from memory or,
459
+ // while a turn changes memory, from `Storage`. A child that does not run is
460
+ // ignored, and so is one that work names by an address, which only a local
461
+ // process has.
462
+ const children: Step.Children = {
463
+ spawn: () => refuseLocal("children.spawn"),
464
+ spawnLogic: () => refuseLocal("spawn"),
465
+ sendTo: (child, event) =>
466
+ typeof child === "string" ?
467
+ refuseLocal("sendTo") :
468
+ Effect.flatMap(runningChild(child), (target) =>
469
+ target === undefined ? Effect.void : Effect.flatMap(
470
+ target.protocol.decodeEvent(event),
471
+ (decoded) => dispatchToChild(target, "deliver", decoded)
472
+ )),
473
+ stop: (child) =>
474
+ typeof child === "string" ? refuseLocal("stopChild") : Effect.flatMap(
475
+ runningChild(child),
476
+ (target) => target === undefined ? Effect.void : dispatchToChild(target, "stop", undefined)
477
+ )
478
+ }
479
+
480
+ // Planned with the target of its own entity as `self`.
481
+ const stepper = Step.make(machine, {
482
+ self: targets?.self ?? new HostedTarget(definitionId),
483
+ parent,
484
+ children
485
+ })
486
+
487
+ const work = new ClusterWork.ClusterWork<R>({
488
+ definitionId,
489
+ address,
490
+ context: yield* Effect.context<R>(),
491
+ onEnd: (ended, exit) => untilDone(deliver(ended, exit))
492
+ })
493
+ const keepAlive = new ClusterKeepAlive(options.keepAlive)
494
+
495
+ // The step state that a step from `base` continues: the one of the running
496
+ // work when it belongs to that revision, so that its results apply, and the
497
+ // resumed state of `base` otherwise, whose work runs nowhere yet.
498
+ const stateOf = (base: Extract<Memory, { readonly _tag: "Active" }>): Step.State | undefined =>
499
+ work.current !== undefined && work.current.revision === base.revision ? work.current.state : base.step
500
+
501
+ // The timers whose delayed messages are saved, by key, with their due time.
502
+ // Such a timer does not keep the entity alive: its message brings the entity
503
+ // back when it is due, here or on another runner.
504
+ const wakes = new Map<string, number>()
505
+ const timerKey = ({ id, path }: Checkpoint.InvocationKey): string => `${path}\u0000${id}`
506
+
507
+ // A timer that never ends needs no message, and one that ends soon stays in
508
+ // memory, as `DurableClock` keeps a short sleep.
509
+ const waitsLong = (dueAt: number): boolean =>
510
+ dueAt < ClusterProgress.maxDueAt && dueAt - clock.currentTimeMillisUnsafe() > options.wake.threshold
511
+
512
+ // The timers of `after` that wait long for a due time they did not wait for
513
+ // in `before`.
514
+ const longWaits = (before: ClusterProgress.Progress, after: ClusterProgress.Progress): Array<Timer> =>
515
+ ClusterProgress.entries(after).flatMap(([key, progress]): Array<Timer> => {
516
+ if (progress._tag !== "Waiting" || !waitsLong(progress.dueAt)) return []
517
+ const previous = ClusterProgress.get(before, key)
518
+ return previous?._tag === "Waiting" && previous.dueAt === progress.dueAt
519
+ ? []
520
+ : [{ path: key.path, id: key.id, dueAt: progress.dueAt }]
521
+ })
522
+
523
+ const saveWakes = (timers: ReadonlyArray<Timer>): Effect.Effect<void, unknown> =>
524
+ Effect.forEach(timers, options.wake.save, { discard: true })
525
+
526
+ const recordWakes = (timers: ReadonlyArray<Timer>): void => {
527
+ for (const timer of timers) wakes.set(timerKey(timer), timer.dueAt)
528
+ }
529
+
530
+ const waitingFor = (current: Memory | undefined, key: Checkpoint.InvocationKey): number | undefined => {
531
+ if (current?._tag !== "Active") return undefined
532
+ const progress = ClusterProgress.get(current.progress, key)
533
+ return progress?._tag === "Waiting" ? progress.dueAt : undefined
534
+ }
535
+
536
+ // Whether work may run without keeping the entity alive.
537
+ const released = (current: Memory, running: ClusterWork.Running): boolean => {
538
+ if (running.work._tag !== "Timer") return false
539
+ const dueAt = waitingFor(current, running.work)
540
+ return dueAt !== undefined &&
541
+ (dueAt >= ClusterProgress.maxDueAt || wakes.get(timerKey(running.work)) === dueAt)
542
+ }
543
+
544
+ // Callers waiting for memory to change, woken at the end of every turn that
545
+ // changed it.
546
+ const waiters = new Set<() => void>()
547
+
548
+ const annotate = Effect.annotateLogs({ module: "ClusterMachine", definitionId, address })
549
+
550
+ const serialized = <A, E, R1>(run: (restore: Restore) => Effect.Effect<A, E, R1>): Effect.Effect<A, E, R1> =>
551
+ Effect.uninterruptibleMask((restore) =>
552
+ Effect.suspend(() => {
553
+ const before = memory
554
+ return Effect.ensuring(
555
+ run(restore),
556
+ Effect.sync(() => {
557
+ if (memory === before || waiters.size === 0) return
558
+ const woken = Array.from(waiters)
559
+ waiters.clear()
560
+ for (const wake of woken) wake()
561
+ })
562
+ )
563
+ })
564
+ ).pipe(Semaphore.withPermit(semaphore))
565
+
566
+ // Runs one turn. A turn that leaves something unknown hands it to recovery,
567
+ // whatever ended it.
568
+ const turn = <A, E, R1>(run: (restore: Restore) => Effect.Effect<A, E, R1>): Effect.Effect<A, E, R1> =>
569
+ serialized((restore) => Effect.ensuring(Effect.suspend(() => run(restore)), recoverUnknown))
570
+
571
+ const recoverUnknown: Effect.Effect<void> = Effect.suspend(() => {
572
+ if (!hostsWork || work.closed || recovering || (memory !== undefined && !keepAlive.unknown)) {
573
+ return Effect.void
574
+ }
575
+ recovering = true
576
+ return Effect.asVoid(work.fork(untilDone(recover)))
577
+ })
578
+
579
+ // One attempt to recover, as a turn that does not ask for recovery itself.
580
+ const recover: Effect.Effect<boolean, never, R> = Effect.suspend(() =>
581
+ serialized((restore) =>
582
+ Effect.suspend(() =>
583
+ memory === undefined ? reload(restore) : Effect.map(align(restore, undefined), () => memory !== undefined)
584
+ ).pipe(
585
+ Effect.tap((recovered) =>
586
+ Effect.sync(() => {
587
+ recovering = !recovered
588
+ })
589
+ )
590
+ )
591
+ )
592
+ )
593
+
594
+ const loadForRequest = (input: Input) =>
595
+ Effect.suspend(() => storage.loadForRequest(address, input.requestId)).pipe(
596
+ Effect.mapError(persistenceFailure),
597
+ Effect.filterOrFail(
598
+ (loaded) => !loaded.processed || Option.isSome(loaded.checkpoint),
599
+ () => reject("InvalidCheckpoint", "The request was recorded without a checkpoint")
600
+ )
601
+ )
602
+
603
+ const decode = Effect.fnUntraced(function*(
604
+ checkpoint: Checkpoint
605
+ ): Effect.fn.Return<Memory, Rejected, R> {
606
+ if (checkpoint.definitionId !== definitionId) {
607
+ return yield* fail(
608
+ "DefinitionIdMismatch",
609
+ `Expected machine definition id ${definitionId}, received ${checkpoint.definitionId}`
610
+ )
611
+ }
612
+ if (checkpoint.version !== version) {
613
+ return yield* fail(
614
+ "VersionMismatch",
615
+ `Expected version ${version}, received ${checkpoint.version}`
616
+ )
617
+ }
618
+ if (!Number.isSafeInteger(checkpoint.revision) || checkpoint.revision < 1) {
619
+ return yield* fail(
620
+ "InvalidCheckpoint",
621
+ `Expected a positive integer revision, received ${checkpoint.revision}`
622
+ )
623
+ }
624
+ const status = readStatus(checkpoint.status)
625
+ if (status === undefined) {
626
+ return yield* fail("InvalidCheckpoint", "Expected an active or failed status")
627
+ }
628
+ if (status._tag === "Failed") {
629
+ return { _tag: "Failed", revision: checkpoint.revision, failure: status.failure }
630
+ }
631
+ if (status._tag === "Stopped") {
632
+ return { _tag: "Stopped", revision: checkpoint.revision }
633
+ }
634
+ const state: Snapshot = yield* internalMachine.decodeSnapshot(machine, checkpoint.snapshot).pipe(
635
+ Effect.mapError((error) => reject("InvalidCheckpoint", String(error.cause)))
636
+ )
637
+ const contradiction = contradictionOf(state, status.progress)
638
+ if (contradiction !== undefined) {
639
+ return yield* fail("InvalidCheckpoint", contradiction)
640
+ }
641
+ if (internalMachine.isFinal(machine, state)) {
642
+ return { _tag: "Active", revision: checkpoint.revision, state, progress: status.progress, step: undefined }
643
+ }
644
+ // Work that ended does not run again, and work that runs elsewhere, a timer
645
+ // that waits or a child, is not started twice.
646
+ const resumed = stepper.resume(state, resumeProgress(status.progress))
647
+ if (Exit.isFailure(resumed)) {
648
+ return yield* fail(
649
+ "InvalidCheckpoint",
650
+ `Expected a state the machine resumes: ${messageFromCause(resumed.cause)}`
651
+ )
652
+ }
653
+ return {
654
+ _tag: "Active",
655
+ revision: checkpoint.revision,
656
+ state,
657
+ progress: status.progress,
658
+ step: resumed.value.state
659
+ }
660
+ })
661
+
662
+ const declaresTimer = ({ id, path }: Checkpoint.InvocationKey): boolean =>
663
+ CapturedInvocation.list(Configuration.getStateConfigByPath(machine, path)?.invoke).some((definition) =>
664
+ "after" in definition && definition.id === id
665
+ )
666
+
667
+ // What makes progress impossible for a state of this machine.
668
+ const contradictionOf = (state: Snapshot, progress: ClusterProgress.Progress): string | undefined => {
669
+ if (progress.size === 0) return undefined
670
+ const { active } = Configuration.normalizeConfigurationSync(machine, state)
671
+ const inactive = Array.from(progress.keys()).find((path) => !active.has(path))
672
+ if (inactive !== undefined) {
673
+ return `Expected invocations of active states, received state ${inactive}`
674
+ }
675
+ const waiting = ClusterProgress.entries(progress).filter(([, { _tag }]) => _tag === "Waiting")
676
+ if (waiting.length > 0 && internalMachine.isFinal(machine, state)) {
677
+ return "Expected no timer to wait in a final state"
678
+ }
679
+ const unknown = waiting.find(([key]) => !declaresTimer(key))
680
+ return unknown && `Expected only timers to wait, received invocation ${unknown[0].id} of state ${unknown[0].path}`
681
+ }
682
+
683
+ const wasFinal = (base: Base): boolean => base._tag === "Active" && base.step === undefined
684
+
685
+ // The target of the child entity that runs `work`, by the progress that
686
+ // stores it.
687
+ const childOf = (progress: ClusterProgress.Progress, work: Step.Work): ClusterTarget.Target | undefined => {
688
+ if (work._tag !== "Child") return undefined
689
+ const stored = ClusterProgress.get(progress, work)
690
+ const protocol = options.children?.protocols.get(work.child.id)
691
+ return stored?._tag === "Child" && protocol !== undefined
692
+ ? new ClusterTarget.Target(protocol, stored.entityId)
693
+ : undefined
694
+ }
695
+
696
+ // The child that runs for a child descriptor in a progress.
697
+ const childTarget = (
698
+ progress: ClusterProgress.Progress,
699
+ child: Machine.ChildMachine.Any
700
+ ): ClusterTarget.Target | undefined => {
701
+ const protocol = options.children?.protocols.get(child.id)
702
+ const running = ClusterProgress.children(progress).find(([key]) => key.id === child.id)
703
+ return protocol && running && new ClusterTarget.Target(protocol, running[1])
704
+ }
705
+
706
+ const runningChild = (child: Machine.ChildMachine.Any): Effect.Effect<ClusterTarget.Target | undefined> =>
707
+ Effect.suspend(() => {
708
+ const known = memory
709
+ if (known !== undefined) {
710
+ return Effect.succeed(known._tag === "Active" ? childTarget(known.progress, child) : undefined)
711
+ }
712
+ return storage.load(address).pipe(
713
+ Effect.map((loaded) => {
714
+ const status = Option.isSome(loaded) ? readStatus(loaded.value.status) : undefined
715
+ return status?._tag === "Active" ? childTarget(status.progress, child) : undefined
716
+ }),
717
+ // A store that cannot be read now is read again.
718
+ Effect.retry({ schedule: Schedule.spaced("1 second") }),
719
+ Effect.orDie
720
+ )
721
+ })
722
+
723
+ const dispatchToChild = (target: ClusterTarget.Target, tag: string, payload: unknown): Effect.Effect<void> =>
724
+ options.children === undefined
725
+ ? Effect.void
726
+ : options.children.dispatch(target, tag, payload).pipe(
727
+ // A runner that cannot take the request now takes it later.
728
+ Effect.retry({ schedule: Schedule.spaced("1 second") }),
729
+ Effect.orDie
730
+ )
731
+
732
+ // Stops the child entities that run `works`, which a step stops.
733
+ const stopsOf = (progress: ClusterProgress.Progress, works: ReadonlyArray<Step.Work>): Array<Outgoing> =>
734
+ works.flatMap((stopped): Array<Outgoing> => {
735
+ const target = childOf(progress, stopped)
736
+ return target === undefined ? [] : [{ target, tag: "stop", payload: undefined }]
737
+ })
738
+
739
+ // A machine that ends stops all of its work, as the step stops it.
740
+ const stopsOfAll = (current: Memory | undefined): Array<Outgoing> => {
741
+ if (current?._tag !== "Active") return []
742
+ const state = stateOf(current)
743
+ return state === undefined ? [] : stopsOf(current.progress, stepper.stop(state).stop)
744
+ }
745
+
746
+ // Tells the parent of a child that it ended, in the step that ends it.
747
+ const endedFor = (ends: boolean): ReadonlyArray<Outgoing> => {
748
+ const parent = options.children?.parent
749
+ return parent === undefined || !ends
750
+ ? []
751
+ : [{ target: parent, tag: "ended", payload: { entityId: address.entityId } }]
752
+ }
753
+
754
+ // Gives the parent of a child the snapshot of a step that changed it, while
755
+ // the child is active, when the parent takes its snapshots.
756
+ const snapshotFor = (
757
+ planned: PlannedStep,
758
+ base: Base,
759
+ snapshot: Machine.Machine.EncodedSnapshot
760
+ ): ReadonlyArray<Outgoing> => {
761
+ const parent = options.children?.parent
762
+ const last = planned.steps.at(-1)
763
+ if (parent === undefined || options.children?.snapshots !== true || last === undefined) return []
764
+ const moved = base._tag === "Absent" || last.planned
765
+ return !moved || last.exit !== undefined
766
+ ? []
767
+ : [{ target: parent, tag: "snapshot", payload: { entityId: address.entityId, snapshot } }]
768
+ }
769
+
770
+ const snapshotForCommit = Effect.fnUntraced(function*(
771
+ checkpoint: Checkpoint,
772
+ state: Snapshot
773
+ ): Effect.fn.Return<ClusterSnapshot<any>, unknown, R> {
774
+ if (checkpoint.status._tag === "Failed") {
775
+ return { status: "failed", revision: checkpoint.revision, state, failure: checkpoint.status.failure }
776
+ }
777
+ if (checkpoint.status._tag === "Stopped") {
778
+ return { status: "stopped", revision: checkpoint.revision, state }
779
+ }
780
+ if (!internalMachine.isFinal(machine, state)) {
781
+ return { status: "active", revision: checkpoint.revision, state }
782
+ }
783
+ const output = yield* Planner.getFinalOutputEffect(machine, state, Planner.InitialEvent)
784
+ return { status: "done", revision: checkpoint.revision, state, output }
785
+ })
786
+
787
+ const notifyCommit = (checkpoint: Checkpoint, state: Snapshot): Effect.Effect<void, unknown, R> =>
788
+ onCommit === undefined
789
+ ? Effect.void
790
+ : Effect.flatMap(
791
+ snapshotForCommit(checkpoint, state),
792
+ (snapshot) => onCommit({ entityId: address.entityId, checkpoint, snapshot })
793
+ )
794
+
795
+ const saveOutgoing = (outgoing: ReadonlyArray<Outgoing>): Effect.Effect<void, unknown> =>
796
+ Effect.forEach(
797
+ outgoing,
798
+ ({ payload, tag, target }) =>
799
+ tag === "send" && targets !== undefined
800
+ ? targets.save({ target, event: payload })
801
+ : options.children === undefined
802
+ ? Effect.die(new Error(`Cannot save ${tag} for ${target.sessionId} without children`))
803
+ : options.children.save(target, tag, payload),
804
+ { discard: true }
805
+ )
806
+
807
+ // Takes the steps of one stored step. A step that the machine fails in is
808
+ // refused, so its previous state still holds.
809
+ const plan = Effect.fnUntraced(function*(base: Base, input: StepInput): Effect.fn.Return<PlannedStep, unknown> {
810
+ if (base._tag === "Absent") {
811
+ const initial = input._tag === "Request" ? input.initial : undefined
812
+ if (options.children?.parent !== undefined && initial === undefined) {
813
+ return yield* fail("InvalidEvent", "A child machine takes events once its parent has started it")
814
+ }
815
+ if (machine.input !== undefined && initial === undefined && options.input.length === 0) {
816
+ return yield* fail("InvalidEvent", "A machine with input must be started before it takes events")
817
+ }
818
+ const started = stepper.start(...initial ?? options.input)
819
+ if (Exit.isFailure(started)) return yield* Effect.failCause(started.cause)
820
+ // The start of a child plans its initial state only.
821
+ if (input._tag !== "Request" || initial !== undefined || started.value.exit !== undefined) {
822
+ return { from: undefined, steps: [started.value] }
823
+ }
824
+ const sent = yield* taken(stepper.send(started.value.state, input.event))
825
+ return { from: undefined, steps: [started.value, sent] }
826
+ }
827
+ const from = stateOf(base)
828
+ // A final machine takes an event without a step.
829
+ if (from === undefined) return { from, steps: [] }
830
+ switch (input._tag) {
831
+ case "Request":
832
+ return { from, steps: [yield* taken(stepper.send(from, input.event))] }
833
+ case "Report":
834
+ return { from, steps: [yield* taken(Exit.succeed(stepper.report(from, input.work, input.snapshot)))] }
835
+ case "Outcome":
836
+ return { from: input.from, steps: [yield* taken(Exit.succeed(input.next))] }
837
+ }
838
+ })
839
+
840
+ // What the work of a step leaves in `Storage`: its progress, and the
841
+ // requests it saves to child machines, in order.
842
+ const progressAfter = Effect.fnUntraced(function*(
843
+ before: ClusterProgress.Progress,
844
+ planned: PlannedStep,
845
+ revision: number,
846
+ settled: Step.Work | undefined
847
+ ): Effect.fn.Return<
848
+ {
849
+ readonly progress: ClusterProgress.Progress
850
+ readonly stops: ReadonlyArray<Outgoing>
851
+ readonly starts: ReadonlyArray<Outgoing>
852
+ },
853
+ Rejected
854
+ > {
855
+ const last = planned.steps.at(-1)
856
+ if (last === undefined) return { progress: before, stops: [], starts: [] }
857
+ const exited = planned.steps.flatMap((step) => step.exited)
858
+ let progress = before
859
+ // Work that ended keeps its progress while its state stays active, so it
860
+ // does not run again.
861
+ const ended = [
862
+ ...(settled === undefined ? [] : [settled]),
863
+ ...planned.steps.flatMap((step) =>
864
+ step.commands.flatMap((command) =>
865
+ command._tag === "StopChild" && command.work !== undefined ? [command.work] : []
866
+ )
867
+ )
868
+ ]
869
+ for (const work of ended) {
870
+ if (!exited.includes(work.path)) progress = ClusterProgress.settle(progress, work)
871
+ }
872
+ progress = ClusterProgress.exit(progress, exited)
873
+ const stops = stopsOf(before, planned.steps.flatMap((step) => [...step.stop, ...step.stopAfter]))
874
+ if (last.exit !== undefined) {
875
+ return { progress: ClusterProgress.stopChildren(ClusterProgress.cancelTimers(progress)), stops, starts: [] }
876
+ }
877
+ progress = ClusterTimer.schedule(progress, last.running, clock.currentTimeMillisUnsafe())
878
+ // Each child gets an entity of its own, named by the revision of the step.
879
+ const starts: Array<Outgoing> = []
880
+ for (const child of last.running) {
881
+ if (child._tag !== "Child" || ClusterProgress.get(progress, child) !== undefined) continue
882
+ const protocol = options.children?.protocols.get(child.child.id)
883
+ if (protocol === undefined) continue
884
+ const input = child.input()
885
+ if (Exit.isFailure(input)) {
886
+ return yield* fail(
887
+ "TransitionFailure",
888
+ `The input of a child machine cannot be built: ${String(Cause.squash(input.cause))}`
889
+ )
890
+ }
891
+ const entityId = ClusterChild.entityIdOf(address.entityId, child.child.id, revision)
892
+ progress = ClusterProgress.child(progress, child, entityId)
893
+ starts.push({
894
+ target: new ClusterTarget.Target(protocol, entityId),
895
+ tag: "start",
896
+ payload: { input: input.value[0] }
897
+ })
898
+ }
899
+ return { progress, stops, starts }
900
+ })
901
+
902
+ // The sends and child stops that commands enqueue, in order, decoded by
903
+ // the protocols of their targets. A send or stop for a child that does not
904
+ // run is dropped, as a local runtime drops it.
905
+ const commandsOf = Effect.fnUntraced(function*(
906
+ planned: PlannedStep,
907
+ before: ClusterProgress.Progress,
908
+ after: ClusterProgress.Progress
909
+ ): Effect.fn.Return<Array<Outgoing>, Rejected> {
910
+ const last = planned.steps.at(-1)
911
+ const outgoing: Array<Outgoing> = []
912
+ for (const command of planned.steps.flatMap((step) => step.commands)) {
913
+ switch (command._tag) {
914
+ case "StopChild": {
915
+ if (typeof command.child === "string") {
916
+ return yield* fail(
917
+ "UnsupportedProcessLocal",
918
+ "Machine commands on Cluster stop only an invoked child machine"
919
+ )
920
+ }
921
+ const target = command.work === undefined ? undefined : childOf(before, command.work)
922
+ if (target !== undefined) outgoing.push({ target, tag: "stop", payload: undefined })
923
+ continue
924
+ }
925
+ case "SendToChild":
926
+ case "Send": {
927
+ if (options.sends === undefined || (command._tag === "SendToChild" && typeof command.child === "string")) {
928
+ return yield* fail(
929
+ "UnsupportedProcessLocal",
930
+ "Machine commands on Cluster send only to a ClusterMachine target or an invoked child machine"
931
+ )
932
+ }
933
+ let target: ClusterTarget.Target | undefined
934
+ if (command._tag === "Send") {
935
+ if (!ClusterTarget.isTarget(command.target)) {
936
+ return yield* fail(
937
+ "UnsupportedProcessLocal",
938
+ "Machine commands on Cluster send only to a ClusterMachine target or an invoked child machine"
939
+ )
940
+ }
941
+ target = command.target
942
+ } else if (command.work !== undefined && last?.running.includes(command.work) === true) {
943
+ // Only a child that still runs once the step is stored takes the
944
+ // send: one whose state the step exits is dropped.
945
+ target = childOf(after, command.work)
946
+ }
947
+ if (target === undefined) continue
948
+ const event = yield* target.protocol.decode(command.event).pipe(
949
+ Effect.mapError((rejected) =>
950
+ reject(
951
+ "TransitionFailure",
952
+ `The step sends ${target.sessionId} an event it refuses: ${rejected.message}`
953
+ )
954
+ )
955
+ )
956
+ outgoing.push({ target, tag: "send", payload: event })
957
+ }
958
+ }
959
+ }
960
+ return outgoing
961
+ })
962
+
963
+ // Everything a step decides before it changes `Storage`.
964
+ const prepare = Effect.fnUntraced(function*(
965
+ base: Base,
966
+ input: StepInput
967
+ ): Effect.fn.Return<
968
+ {
969
+ readonly planned: PlannedStep
970
+ readonly state: Snapshot
971
+ readonly emitted: ReadonlyArray<unknown>
972
+ readonly checkpoint: Checkpoint
973
+ readonly next: Memory
974
+ readonly outgoing: ReadonlyArray<Outgoing>
975
+ },
976
+ unknown,
977
+ R
978
+ > {
979
+ const planned = yield* plan(base, input)
980
+ const last = planned.steps.at(-1)
981
+ const state: Snapshot = last === undefined ? (base as Extract<Base, { _tag: "Active" }>).state : last.snapshot
982
+ const snapshot = yield* internalMachine.encodeSnapshot(machine, state).pipe(
983
+ Effect.mapError((error) => reject("SnapshotEncodeFailure", String(error.cause)))
984
+ )
985
+ const emitted = planned.steps.flatMap((step) => step.emitted)
986
+ if (emitted.length > 0 && enqueue === undefined) {
987
+ return yield* fail("EmissionFailure", "No durable enqueue handler was configured")
988
+ }
989
+ const revision = base.revision + 1
990
+ const before = progressOf(base)
991
+ // Last, so a step that is refused evaluates no duration and no input.
992
+ const { progress, starts, stops } = yield* progressAfter(
993
+ before,
994
+ planned,
995
+ revision,
996
+ input._tag === "Outcome" ? input.work : undefined
997
+ )
998
+ const commanded = yield* commandsOf(planned, before, progress)
999
+ const ends = last?.exit !== undefined
1000
+ const outgoing = [
1001
+ ...stops,
1002
+ ...starts,
1003
+ ...commanded,
1004
+ ...snapshotFor(planned, base, snapshot),
1005
+ ...endedFor(ends && !wasFinal(base))
1006
+ ]
1007
+ return {
1008
+ planned,
1009
+ state,
1010
+ emitted,
1011
+ outgoing,
1012
+ checkpoint: {
1013
+ definitionId,
1014
+ version,
1015
+ revision,
1016
+ origin: input._tag === "Outcome"
1017
+ ? { _tag: "Invocation", path: input.work.path, id: input.work.id }
1018
+ : { _tag: "Request", requestId: input.requestId },
1019
+ snapshot,
1020
+ status: { _tag: "Active", invocations: ClusterProgress.toStored(progress) }
1021
+ },
1022
+ next: {
1023
+ _tag: "Active",
1024
+ revision,
1025
+ state,
1026
+ progress,
1027
+ step: last === undefined || ends ? undefined : last.state
1028
+ }
1029
+ }
1030
+ })
1031
+
1032
+ // The transaction body of a step from a known state. Its value holds once the
1033
+ // transaction around it has succeeded.
1034
+ const step = Effect.fnUntraced(function*(
1035
+ input: StepInput,
1036
+ base: Base,
1037
+ options: {
1038
+ /** Whether an earlier delivery of a request may have committed it. */
1039
+ readonly confirm: boolean
1040
+ }
1041
+ ): Effect.fn.Return<StepResult, Refused | Conflicted, R> {
1042
+ const { checkpoint, emitted, next, outgoing, planned, state } = yield* prepare(base, input).pipe(
1043
+ refuse({ memory: base, confirm: options.confirm, stage: "Decision" })
1044
+ )
1045
+ const committed = yield* storage.commit(address, checkpoint).pipe(
1046
+ Effect.mapError(persistenceFailure),
1047
+ refuse({ memory: undefined, confirm: true, stage: "Infrastructure" })
1048
+ )
1049
+ switch (committed._tag) {
1050
+ case "Duplicate":
1051
+ return input._tag !== "Outcome"
1052
+ ? { memory: base, stored: undefined }
1053
+ : yield* Effect.die(new Error("Storage reported a duplicate of a checkpoint without a request id"))
1054
+ case "RevisionConflict":
1055
+ return yield* new Conflicted()
1056
+ case "Committed": {
1057
+ if (enqueue !== undefined) {
1058
+ // `Committed` proves that no earlier delivery committed this input.
1059
+ yield* Effect.forEach(emitted, enqueue, { discard: true }).pipe(
1060
+ Effect.mapError((error) => reject("EmissionFailure", String(error))),
1061
+ refuse({ memory: undefined, confirm: false, stage: "Infrastructure" })
1062
+ )
1063
+ }
1064
+ // In the transaction of the checkpoint, so a stored wait has its message.
1065
+ const woken = longWaits(progressOf(base), progressOf(next))
1066
+ yield* saveWakes(woken).pipe(
1067
+ Effect.mapError((error) => reject("PersistenceFailure", String(error))),
1068
+ refuse({ memory: undefined, confirm: false, stage: "Infrastructure" })
1069
+ )
1070
+ // In the transaction of the checkpoint, so each request is saved once.
1071
+ yield* saveOutgoing(outgoing).pipe(
1072
+ Effect.mapError((error) => reject("PersistenceFailure", String(error))),
1073
+ refuse({ memory: undefined, confirm: false, stage: "Infrastructure" })
1074
+ )
1075
+ // In the transaction of the checkpoint, so projections commit or roll back with it.
1076
+ yield* notifyCommit(checkpoint, state).pipe(
1077
+ Effect.mapError((error) => reject("PersistenceFailure", String(error))),
1078
+ refuse({ memory: undefined, confirm: false, stage: "Infrastructure" })
1079
+ )
1080
+ return {
1081
+ memory: next,
1082
+ stored: {
1083
+ from: planned.from,
1084
+ step: planned.steps.at(-1),
1085
+ woken,
1086
+ sent: outgoing.length > 0
1087
+ }
1088
+ }
1089
+ }
1090
+ }
1091
+ })
1092
+
1093
+ // Stores a child as stopped, in the state it has, and stops its own children.
1094
+ const stopStep = Effect.fnUntraced(function*(
1095
+ requestId: Snowflake,
1096
+ base: Extract<Memory, { readonly _tag: "Active" }>
1097
+ ): Effect.fn.Return<StepResult, Refused | Conflicted, R> {
1098
+ const snapshot = yield* internalMachine.encodeSnapshot(machine, base.state).pipe(
1099
+ Effect.mapError((error) => reject("SnapshotEncodeFailure", String(error.cause))),
1100
+ refuse({ memory: base, confirm: true, stage: "Decision" })
1101
+ )
1102
+ const revision = base.revision + 1
1103
+ const checkpoint: Checkpoint = {
1104
+ definitionId,
1105
+ version,
1106
+ revision,
1107
+ origin: { _tag: "Request", requestId },
1108
+ snapshot,
1109
+ status: { _tag: "Stopped" }
1110
+ }
1111
+ const committed = yield* storage.commit(address, checkpoint).pipe(
1112
+ Effect.mapError(persistenceFailure),
1113
+ refuse({ memory: undefined, confirm: true, stage: "Infrastructure" })
1114
+ )
1115
+ if (committed._tag === "Duplicate") return { memory: base, stored: undefined }
1116
+ if (committed._tag === "RevisionConflict") return yield* new Conflicted()
1117
+ yield* saveOutgoing(stopsOfAll(base)).pipe(
1118
+ Effect.mapError((error) => reject("PersistenceFailure", String(error))),
1119
+ refuse({ memory: undefined, confirm: false, stage: "Infrastructure" })
1120
+ )
1121
+ yield* notifyCommit(checkpoint, base.state).pipe(
1122
+ Effect.mapError((error) => reject("PersistenceFailure", String(error))),
1123
+ refuse({ memory: undefined, confirm: false, stage: "Infrastructure" })
1124
+ )
1125
+ return { memory: { _tag: "Stopped", revision }, stored: undefined }
1126
+ })
1127
+
1128
+ const requestStep = Effect.fnUntraced(function*(
1129
+ input: RequestInput,
1130
+ known: Memory | undefined
1131
+ ): Effect.fn.Return<StepResult, Refused | Conflicted, R> {
1132
+ if (support._tag === "Unsupported") {
1133
+ return yield* fail("UnsupportedProcessLocal", support.message).pipe(
1134
+ refuse({ memory: known, confirm: true, stage: "Decision" })
1135
+ )
1136
+ }
1137
+
1138
+ let base = known
1139
+ if (base === undefined) {
1140
+ // A refusal that follows this answer needs no confirmation.
1141
+ const refuseLoad = refuse({ memory: undefined, confirm: false, stage: "Infrastructure" })
1142
+ const loaded = yield* refuseLoad(loadForRequest(input))
1143
+ if (loaded.processed) {
1144
+ return { memory: undefined, stored: undefined }
1145
+ }
1146
+ base = Option.isNone(loaded.checkpoint) ? absent : yield* refuseLoad(decode(loaded.checkpoint.value))
1147
+ }
1148
+
1149
+ const confirm = known !== undefined
1150
+ // A start of an active machine, and a stop of one that does not run,
1151
+ // change nothing. A start of a failed or stopped machine is rejected below.
1152
+ if (input.lifecycle === "Start" && base._tag === "Active") return { memory: base, stored: undefined }
1153
+ if (input.lifecycle === "Stop") {
1154
+ return base._tag === "Active" ? yield* stopStep(input.requestId, base) : { memory: base, stored: undefined }
1155
+ }
1156
+ if (base._tag === "Failed") {
1157
+ return yield* fail("MachineFailed", base.failure).pipe(refuse({ memory: base, confirm, stage: "Decision" }))
1158
+ }
1159
+ if (base._tag === "Stopped") {
1160
+ return yield* fail("MachineFailed", "The child machine was stopped by its parent").pipe(
1161
+ refuse({ memory: base, confirm, stage: "Decision" })
1162
+ )
1163
+ }
1164
+ if (input.child !== undefined) {
1165
+ // The snapshot of a child that no longer runs changes nothing.
1166
+ const { entityId } = input.child
1167
+ const running = base._tag === "Active"
1168
+ ? ClusterProgress.children(base.progress).find(([, id]) => id === entityId)
1169
+ : undefined
1170
+ const protocol = running && options.children?.protocols.get(running[0].id)
1171
+ const from = base._tag === "Active" ? stateOf(base) : undefined
1172
+ const reported = running &&
1173
+ from?.running.find((work) =>
1174
+ work._tag === "Child" && work.path === running[0].path && work.id === running[0].id
1175
+ )
1176
+ if (reported === undefined || protocol === undefined) return { memory: base, stored: undefined }
1177
+ const snapshot = yield* internalMachine.decodeSnapshot(protocol.machine, input.child.snapshot).pipe(
1178
+ Effect.mapError((error) =>
1179
+ reject("TransitionFailure", `The snapshot of child ${entityId} cannot be decoded: ${String(error)}`)
1180
+ ),
1181
+ refuse({ memory: base, confirm, stage: "Decision" })
1182
+ )
1183
+ return yield* step({ _tag: "Report", requestId: input.requestId, work: reported, snapshot }, base, { confirm })
1184
+ }
1185
+ return yield* step(
1186
+ { _tag: "Request", requestId: input.requestId, event: input.event, initial: input.initial },
1187
+ base,
1188
+ { confirm }
1189
+ )
1190
+ })
1191
+
1192
+ // Runs after the failed transaction, so the answer excludes its writes. A
1193
+ // commit whose transaction failed afterwards may still have taken effect.
1194
+ const confirm = (
1195
+ restore: Restore,
1196
+ input: RequestInput,
1197
+ refused: { readonly rejected: Rejected; readonly memory: Memory | undefined }
1198
+ ): Effect.Effect<SendResult, Conflicted> =>
1199
+ restore(messageStorage.withTransaction(loadForRequest(input))).pipe(
1200
+ Effect.matchCauseEffect({
1201
+ onFailure: (cause) =>
1202
+ Cause.hasInterrupts(cause)
1203
+ ? propagate(cause)
1204
+ : Effect.succeed(rejectionFromCause(cause, "PersistenceFailure")),
1205
+ onSuccess: ({ checkpoint, processed }) => {
1206
+ const revision = Option.isNone(checkpoint) ? 0 : checkpoint.value.revision
1207
+ const stale = refused.memory !== undefined && refused.memory.revision !== revision
1208
+ if (stale && !processed) {
1209
+ return Effect.fail(new Conflicted())
1210
+ }
1211
+ return Effect.sync(() => {
1212
+ memory = stale ? undefined : refused.memory
1213
+ return processed ? accepted : refused.rejected
1214
+ })
1215
+ }
1216
+ })
1217
+ )
1218
+
1219
+ const attempt = (restore: Restore, input: RequestInput): Effect.Effect<SendResult, Conflicted, R> =>
1220
+ Effect.suspend(() => {
1221
+ const known = memory
1222
+ memory = undefined
1223
+ return restore(messageStorage.withTransaction(requestStep(input, known))).pipe(
1224
+ Effect.matchCauseEffect({
1225
+ onFailure: (cause): Effect.Effect<SendResult, Conflicted> => {
1226
+ if (Cause.hasInterrupts(cause)) {
1227
+ return propagate(cause)
1228
+ }
1229
+ const error = Option.getOrUndefined(Cause.findErrorOption(cause))
1230
+ if (error instanceof Conflicted) {
1231
+ return Effect.fail(error)
1232
+ }
1233
+ if (!(error instanceof Refused)) {
1234
+ return confirm(restore, input, {
1235
+ rejected: reject("PersistenceFailure", messageFromCause(cause)),
1236
+ memory: undefined
1237
+ })
1238
+ }
1239
+ // A rollback that failed as well says nothing about `Storage`.
1240
+ const refused = Cause.hasDies(cause) ? { rejected: error.rejected, memory: undefined } : error
1241
+ if (error.confirm) {
1242
+ return confirm(restore, input, refused)
1243
+ }
1244
+ return Effect.sync(() => {
1245
+ memory = refused.memory
1246
+ return refused.rejected
1247
+ })
1248
+ },
1249
+ onSuccess: (result) => {
1250
+ memory = result.memory
1251
+ return Effect.as(align(restore, result.stored), accepted)
1252
+ }
1253
+ })
1254
+ )
1255
+ })
1256
+
1257
+ // Ends an attempt that leaves memory unknown, and is made again. An
1258
+ // interruption is no exception: when it is not this fiber that was
1259
+ // interrupted, it is how the infrastructure failed.
1260
+ const notDone = (message: string, cause: Cause.Cause<unknown>): Effect.Effect<false> =>
1261
+ Effect.as(work.closed ? Effect.void : Effect.logWarning(message, cause), false as const)
1262
+
1263
+ // Loads what `Storage` holds, for an instance that does not know it. The
1264
+ // value is whether nothing is left to load.
1265
+ const reload = (restore: Restore): Effect.Effect<boolean, never, R> =>
1266
+ restore(messageStorage.withTransaction(
1267
+ Effect.suspend(() => storage.load(address)).pipe(
1268
+ Effect.mapError(persistenceFailure),
1269
+ Effect.flatMap(Option.match({
1270
+ onNone: () => Effect.succeedSome(absent),
1271
+ onSome: (checkpoint) =>
1272
+ decode(checkpoint).pipe(
1273
+ Effect.map(Option.some),
1274
+ // A checkpoint this deployment cannot read belongs to another one.
1275
+ Effect.catch((unreadable) =>
1276
+ Effect.logWarning("Could not read the checkpoint of a Cluster machine", unreadable.message).pipe(
1277
+ Effect.as(Option.none<Memory>())
1278
+ )
1279
+ )
1280
+ )
1281
+ }))
1282
+ )
1283
+ )).pipe(
1284
+ Effect.matchCauseEffect({
1285
+ onFailure: (cause) => notDone("Could not load the checkpoint of a Cluster machine", cause),
1286
+ onSuccess: (loaded) => {
1287
+ // Its work stops, and its keep-alive request stays for a deployment
1288
+ // that can read it.
1289
+ if (Option.isNone(loaded)) return Effect.as(work.stopAll, true)
1290
+ memory = loaded.value
1291
+ return Effect.map(align(restore, undefined), () => memory !== undefined)
1292
+ }
1293
+ }),
1294
+ annotate
1295
+ )
1296
+
1297
+ // Makes the work and the keep-alive match the known memory. `stored` is the
1298
+ // step that led to it from the previous state.
1299
+ const align = (restore: Restore, stored: StoredStep | undefined): Effect.Effect<void, never, R> =>
1300
+ Effect.andThen(
1301
+ // The runner reads the events the step sent now, rather than at its next poll.
1302
+ stored?.sent === true && options.sends !== undefined ? options.sends.poll : Effect.void,
1303
+ alignStored(restore, stored)
1304
+ )
1305
+
1306
+ const alignStored = (restore: Restore, stored: StoredStep | undefined): Effect.Effect<void, never, R> =>
1307
+ Effect.suspend(() => {
1308
+ if (!hostsWork || work.closed || memory === undefined) return Effect.void
1309
+ if (stored !== undefined) recordWakes(stored.woken)
1310
+ return Effect.andThen(
1311
+ stored === undefined ? scheduleLoaded(restore, memory) : Effect.void,
1312
+ Effect.suspend(() => {
1313
+ if (memory === undefined) return Effect.void
1314
+ return Effect.flatMap(alignWork(memory, stored), (failure) =>
1315
+ failure === undefined
1316
+ ? Effect.andThen(
1317
+ stored === undefined ? wakeLoaded(restore) : Effect.void,
1318
+ Effect.suspend(() => {
1319
+ const current = memory
1320
+ if (current === undefined) return Effect.void
1321
+ forgetWakes(current)
1322
+ // A request is answered after this, so a crash in between redelivers it.
1323
+ return restore(keepAlive.switchTo(work.pendingExcept((running) => released(current, running))))
1324
+ .pipe(annotate)
1325
+ })
1326
+ )
1327
+ : Effect.asVoid(storeFailure(restore, failure.key, renderFailure(failure.cause))))
1328
+ })
1329
+ )
1330
+ })
1331
+
1332
+ // Saves the messages that the long waits of a loaded state may lack, as
1333
+ // they lack them when a deployment before this one stored the wait. A
1334
+ // message that is not saved keeps its timer, and the entity, in memory.
1335
+ const wakeLoaded = (restore: Restore): Effect.Effect<void> =>
1336
+ Effect.suspend(() => {
1337
+ if (memory === undefined) return Effect.void
1338
+ const timers = longWaits(ClusterProgress.empty, progressOf(memory)).filter((timer) =>
1339
+ wakes.get(timerKey(timer)) !== timer.dueAt
1340
+ )
1341
+ return Effect.forEach(timers, (timer) =>
1342
+ restore(options.wake.save(timer)).pipe(
1343
+ Effect.matchCauseEffect({
1344
+ onFailure: (cause) =>
1345
+ Cause.hasInterrupts(cause)
1346
+ ? propagate(cause)
1347
+ : Effect.logWarning("Could not save the message that wakes a Cluster machine", cause),
1348
+ onSuccess: () => Effect.sync(() => recordWakes([timer]))
1349
+ })
1350
+ ), { discard: true }).pipe(annotate)
1351
+ })
1352
+
1353
+ // Keeps only the messages of timers that still wait for their due time.
1354
+ const forgetWakes = (current: Memory): void => {
1355
+ for (const [key, dueAt] of wakes) {
1356
+ const [path, id] = key.split("\u0000") as [string, string]
1357
+ if (waitingFor(current, { path, id }) !== dueAt) wakes.delete(key)
1358
+ }
1359
+ }
1360
+
1361
+ // Stores the due times that the timers of a loaded state lack, as a
1362
+ // checkpoint of its own, before any of its work starts. A deployment that
1363
+ // did not declare a timer stored none for it. Memory is left unknown when
1364
+ // that fails.
1365
+ const scheduleLoaded = (restore: Restore, loaded: Memory): Effect.Effect<void, never, R> =>
1366
+ Effect.suspend(() => {
1367
+ if (loaded._tag !== "Active" || loaded.step === undefined || work.current?.revision === loaded.revision) {
1368
+ return Effect.void
1369
+ }
1370
+ const progress = ClusterTimer.schedule(loaded.progress, loaded.step.running, clock.currentTimeMillisUnsafe())
1371
+ if (progress === loaded.progress) return Effect.void
1372
+ const woken = longWaits(loaded.progress, progress)
1373
+ return amend(restore, {
1374
+ origin: { _tag: "Timers" },
1375
+ status: { _tag: "Active", invocations: ClusterProgress.toStored(progress) }
1376
+ }, woken).pipe(
1377
+ Effect.matchCauseEffect({
1378
+ onFailure: (cause) => notDone("Could not store the due times of a Cluster machine", cause),
1379
+ onSuccess: (revision) =>
1380
+ Effect.sync(() => {
1381
+ memory = { ...loaded, revision, progress }
1382
+ recordWakes(woken)
1383
+ })
1384
+ }),
1385
+ annotate,
1386
+ Effect.asVoid
1387
+ )
1388
+ })
1389
+
1390
+ // Makes the running work the work of the state in memory. The value is why
1391
+ // the machine failed, when work could not start.
1392
+ const alignWork = (
1393
+ current: Memory,
1394
+ stored: StoredStep | undefined
1395
+ ): Effect.Effect<{ readonly key: Checkpoint.InvocationKey; readonly cause: Cause.Cause<unknown> } | undefined> =>
1396
+ Effect.suspend(() => {
1397
+ if (work.current?.revision === current.revision) return Effect.succeed(undefined)
1398
+ // A step from the state of the running work stops and starts what it
1399
+ // lists, in the step's order (`stop`, then `stopAfter` when terminal).
1400
+ const continued = stored?.step !== undefined && stored.from !== undefined &&
1401
+ work.current?.state === stored.from
1402
+ ? stored.step
1403
+ : undefined
1404
+ if (current._tag !== "Active" || current.step === undefined) {
1405
+ if (continued === undefined) return Effect.as(work.stopAll, undefined)
1406
+ return work.stop(continued.stop).pipe(
1407
+ Effect.andThen(work.stop(continued.stopAfter)),
1408
+ Effect.andThen(work.stopAll),
1409
+ Effect.as(undefined)
1410
+ )
1411
+ }
1412
+ const state = current.step
1413
+ return (continued === undefined ? work.stopAll : work.stop(continued.stop)).pipe(
1414
+ Effect.andThen(Effect.suspend(() => {
1415
+ work.current = { revision: current.revision, state }
1416
+ return work.start(continued === undefined ? state.running : continued.start, current.progress)
1417
+ })),
1418
+ Effect.flatMap((failure) => {
1419
+ if (failure === undefined) return Effect.succeed(undefined)
1420
+ // Work that could not start fails the machine, which stops all work.
1421
+ const failed = stepper.settle(state, failure.work, failure.exit).exit
1422
+ const cause = failed !== undefined && Exit.isFailure(failed) ? failed.cause : Cause.die(
1423
+ new Error(`Work "${failure.work.id}" of state "${failure.work.path}" could not start`)
1424
+ )
1425
+ return Effect.as(work.stopAll, { key: failure.work, cause })
1426
+ })
1427
+ )
1428
+ })
1429
+
1430
+ // Replaces the stored checkpoint by one of the same state, whose snapshot is
1431
+ // kept as it is. Memory is forgotten first, and the value is the revision that
1432
+ // is stored.
1433
+ const amend = (
1434
+ restore: Restore,
1435
+ amended: Pick<Checkpoint, "origin" | "status">,
1436
+ woken: ReadonlyArray<Timer> = [],
1437
+ outgoing: ReadonlyArray<Outgoing> = []
1438
+ ): Effect.Effect<number, unknown, R> =>
1439
+ Effect.suspend(() => {
1440
+ const revision = memory?.revision
1441
+ memory = undefined
1442
+ return restore(messageStorage.withTransaction(Effect.gen(function*() {
1443
+ const loaded = yield* storage.load(address)
1444
+ if (Option.isNone(loaded) || loaded.value.revision !== revision) {
1445
+ return yield* new Conflicted()
1446
+ }
1447
+ const checkpoint: Checkpoint = { ...loaded.value, ...amended, revision: revision + 1 }
1448
+ const committed = yield* storage.commit(address, checkpoint)
1449
+ if (committed._tag !== "Committed") {
1450
+ return yield* new Conflicted()
1451
+ }
1452
+ yield* saveWakes(woken)
1453
+ yield* saveOutgoing(outgoing)
1454
+ if (onCommit !== undefined) {
1455
+ const decodedState: Snapshot = yield* internalMachine.decodeSnapshot(machine, checkpoint.snapshot)
1456
+ yield* notifyCommit(checkpoint, decodedState)
1457
+ }
1458
+ return checkpoint.revision
1459
+ })))
1460
+ })
1461
+
1462
+ // Stores the machine as failed, in the state it has. The value is whether the
1463
+ // failure is stored.
1464
+ const storeFailure = (
1465
+ restore: Restore,
1466
+ cause: Checkpoint.InvocationKey | { readonly requestId: Snowflake },
1467
+ failure: string
1468
+ ): Effect.Effect<boolean, never, R> =>
1469
+ // A machine that fails stops its children, and a child tells its parent.
1470
+ amend(
1471
+ restore,
1472
+ {
1473
+ origin: "requestId" in cause
1474
+ ? { _tag: "Request", requestId: cause.requestId }
1475
+ : { _tag: "Invocation", path: cause.path, id: cause.id },
1476
+ status: { _tag: "Failed", failure }
1477
+ },
1478
+ [],
1479
+ [...stopsOfAll(memory), ...endedFor(true)]
1480
+ ).pipe(
1481
+ Effect.matchCauseEffect({
1482
+ onFailure: (cause) => notDone("Could not store the failure of a Cluster machine", cause),
1483
+ onSuccess: (revision) => {
1484
+ memory = { _tag: "Failed", revision, failure }
1485
+ return Effect.logError("A Cluster machine failed", failure).pipe(
1486
+ // The runner reads the requests to its children and parent now.
1487
+ Effect.andThen(options.sends?.poll ?? Effect.void),
1488
+ Effect.andThen(align(restore, undefined)),
1489
+ Effect.as(true)
1490
+ )
1491
+ }
1492
+ }),
1493
+ annotate
1494
+ )
1495
+
1496
+ // One attempt to apply the end of work. The value is whether nothing is left
1497
+ // to do.
1498
+ const deliver = (ended: ClusterWork.Running, exit: Exit.Exit<unknown, unknown>): Effect.Effect<boolean, never, R> =>
1499
+ turn((restore) =>
1500
+ Effect.andThen(
1501
+ memory === undefined && !ended.stopped ? reload(restore) : Effect.void,
1502
+ Effect.suspend((): Effect.Effect<boolean, never, R> => {
1503
+ // Work that this instance stopped reports nothing.
1504
+ if (ended.stopped) return Effect.succeed(true)
1505
+ if (memory === undefined || memory._tag !== "Active") return Effect.succeed(false)
1506
+ const current = work.current
1507
+ // Work that runs belongs to the revision in memory, or was stopped.
1508
+ if (current === undefined || current.revision !== memory.revision) return Effect.succeed(true)
1509
+ const next = stepper.settle(current.state, ended.work, exit)
1510
+ // The step returns the state it was given for a result that no
1511
+ // longer applies.
1512
+ if (next.state === current.state) return Effect.succeed(true)
1513
+ return applyOutcome(restore, ended.work, memory, current.state, next, () => work.settle(ended))
1514
+ })
1515
+ )
1516
+ )
1517
+
1518
+ const applyOutcome = (
1519
+ restore: Restore,
1520
+ settled: Step.Work,
1521
+ base: Base,
1522
+ from: Step.State,
1523
+ next: Step.Step,
1524
+ onApplied: () => void
1525
+ ): Effect.Effect<boolean, never, R> => {
1526
+ const key = { path: settled.path, id: settled.id }
1527
+ // A machine that fails in the step is stored as failed, in the state it had.
1528
+ if (next.exit !== undefined && Exit.isFailure(next.exit)) {
1529
+ return storeFailure(restore, key, renderFailure(next.exit.cause))
1530
+ }
1531
+ memory = undefined
1532
+ return restore(
1533
+ messageStorage.withTransaction(step({ _tag: "Outcome", work: settled, from, next }, base, { confirm: false }))
1534
+ ).pipe(
1535
+ Effect.matchCauseEffect({
1536
+ onFailure: (cause) => {
1537
+ const error = Option.getOrUndefined(Cause.findErrorOption(cause))
1538
+ if (error instanceof Refused && error.failure !== undefined && !Cause.hasDies(cause)) {
1539
+ memory = error.memory
1540
+ return storeFailure(restore, key, error.failure)
1541
+ }
1542
+ return notDone("Could not store the outcome of an invocation", cause)
1543
+ },
1544
+ onSuccess: (result) => {
1545
+ memory = result.memory
1546
+ onApplied()
1547
+ return Effect.as(align(restore, result.stored), true)
1548
+ }
1549
+ }),
1550
+ annotate
1551
+ )
1552
+ }
1553
+
1554
+ yield* Effect.addFinalizer(() => Effect.andThen(work.close, keepAlive.close))
1555
+
1556
+ if (hostsWork) {
1557
+ // After a crash no request may ever come.
1558
+ recovering = true
1559
+ yield* work.fork(untilDone(recover))
1560
+ } else if (support._tag === "Idle") {
1561
+ // A deployment whose machine invoked effects may have left a request behind.
1562
+ yield* options.keepAlive(false)
1563
+ }
1564
+
1565
+ // One look at a timer, as a turn. `undefined` means nothing is left to wait
1566
+ // for, and a deferred is completed once memory changes.
1567
+ const lookAt = (timer: Timer) =>
1568
+ serialized((restore) =>
1569
+ Effect.andThen(
1570
+ memory === undefined ? reload(restore) : Effect.void,
1571
+ Effect.sync(() => {
1572
+ if (memory !== undefined && waitingFor(memory, timer) !== timer.dueAt) return undefined
1573
+ const changed = Deferred.makeUnsafe<void>()
1574
+ waiters.add(() => Deferred.doneUnsafe(changed, Exit.void))
1575
+ return { changed, known: memory !== undefined }
1576
+ })
1577
+ )
1578
+ )
1579
+
1580
+ const wake = (timer: Timer): Effect.Effect<void, never, R> =>
1581
+ Effect.gen(function*() {
1582
+ while (true) {
1583
+ const waiting = yield* lookAt(timer)
1584
+ if (waiting === undefined) return
1585
+ // A store that cannot be read is read again later.
1586
+ yield* waiting.known
1587
+ ? Deferred.await(waiting.changed)
1588
+ : Effect.raceFirst(Deferred.await(waiting.changed), Effect.sleep("1 second"))
1589
+ }
1590
+ }).pipe(annotate)
1591
+
1592
+ // How a child ended, read from `Storage`. `undefined` means it has not.
1593
+ const readChild = Effect.fnUntraced(function*(
1594
+ target: ClusterTarget.Target
1595
+ ): Effect.fn.Return<
1596
+ | { readonly _tag: "Done"; readonly output: unknown }
1597
+ | { readonly _tag: "Failed"; readonly failure: string }
1598
+ | undefined,
1599
+ unknown,
1600
+ R
1601
+ > {
1602
+ const children = options.children
1603
+ if (children === undefined) return undefined
1604
+ const loaded = yield* storage.load(children.address(target)).pipe(
1605
+ // A store that cannot be read now is read again.
1606
+ Effect.retry({ schedule: Schedule.spaced("1 second") })
1607
+ )
1608
+ if (Option.isNone(loaded)) return undefined
1609
+ const status = readStatus(loaded.value.status)
1610
+ if (status?._tag === "Failed") return { _tag: "Failed", failure: status.failure }
1611
+ if (status?._tag !== "Active") return undefined
1612
+ const child = target.protocol.machine
1613
+ const state: Snapshot = yield* internalMachine.decodeSnapshot(child, loaded.value.snapshot)
1614
+ if (!internalMachine.isFinal(child, state)) return undefined
1615
+ const output = yield* Planner.getFinalOutputEffect(child, state, Planner.InitialEvent)
1616
+ return { _tag: "Done", output }
1617
+ })
1618
+
1619
+ const childEnded = (entityId: string): Effect.Effect<void, never, R> =>
1620
+ turn((restore) =>
1621
+ Effect.gen(function*() {
1622
+ if (memory === undefined) yield* reload(restore)
1623
+ const current = memory
1624
+ if (current?._tag !== "Active") return
1625
+ const running = ClusterProgress.children(current.progress).find(([, id]) => id === entityId)
1626
+ const protocol = running && options.children?.protocols.get(running[0].id)
1627
+ const from = stateOf(current)
1628
+ const ended = running &&
1629
+ from?.running.find((work) =>
1630
+ work._tag === "Child" && work.path === running[0].path && work.id === running[0].id
1631
+ )
1632
+ if (from === undefined || ended === undefined || protocol === undefined) return
1633
+ const result = yield* Effect.exit(readChild(new ClusterTarget.Target(protocol, entityId)))
1634
+ if (Exit.isFailure(result)) {
1635
+ yield* storeFailure(
1636
+ restore,
1637
+ ended,
1638
+ `The end of child ${entityId} cannot be read: ${renderFailure(result.cause)}`
1639
+ )
1640
+ return
1641
+ }
1642
+ if (result.value === undefined) return
1643
+ // A child that fails fails its parent with the failure it stored,
1644
+ // whatever the invocation declares.
1645
+ if (result.value._tag === "Failed") {
1646
+ yield* storeFailure(restore, ended, result.value.failure)
1647
+ return
1648
+ }
1649
+ const next = stepper.settle(from, ended, Exit.succeed(result.value.output))
1650
+ if (next.state === from) return
1651
+ yield* applyOutcome(restore, ended, current, from, next, () => {})
1652
+ }).pipe(annotate)
1653
+ )
1654
+
1655
+ // One attempt to apply an event that another machine sent. Nobody waits for
1656
+ // its answer, so an event that cannot be applied fails the machine, as it
1657
+ // does locally, and a failure of the infrastructure is retried. The value is
1658
+ // whether nothing is left to do.
1659
+ const deliverOnce = (input: RequestInput): Effect.Effect<boolean, never, R> =>
1660
+ turn((restore) =>
1661
+ Effect.suspend(() => {
1662
+ // Loaded with the request, so a refusal is never one of an earlier
1663
+ // delivery that committed.
1664
+ memory = undefined
1665
+ return restore(messageStorage.withTransaction(requestStep(input, undefined))).pipe(
1666
+ Effect.matchCauseEffect({
1667
+ onFailure: (cause): Effect.Effect<boolean, never, R> => {
1668
+ if (Cause.hasInterrupts(cause)) return propagate(cause)
1669
+ const error = Option.getOrUndefined(Cause.findErrorOption(cause))
1670
+ if (!(error instanceof Refused) || error.failure === undefined || Cause.hasDies(cause)) {
1671
+ return notDone("Could not apply an event that another machine sent", cause)
1672
+ }
1673
+ memory = error.memory
1674
+ // A machine that ended takes no event, as a local one that stopped,
1675
+ // and neither does a child that has not started.
1676
+ if (error.rejected.reason === "MachineFailed" || (memory?._tag === "Absent" && parent !== undefined)) {
1677
+ return Effect.succeed(true)
1678
+ }
1679
+ return memory?._tag === "Absent"
1680
+ ? storeInitialFailure(restore, input.requestId, error.failure)
1681
+ : storeFailure(restore, input, error.failure)
1682
+ },
1683
+ onSuccess: (result) => {
1684
+ memory = result.memory
1685
+ return Effect.as(align(restore, result.stored), true)
1686
+ }
1687
+ })
1688
+ )
1689
+ })
1690
+ ).pipe(annotate)
1691
+
1692
+ // Stores a machine without a checkpoint as failed in its initial state, when
1693
+ // the first event another machine sent it cannot be applied. A machine
1694
+ // whose initial state cannot be planned stores nothing, and drops the event.
1695
+ const storeInitialFailure = (
1696
+ restore: Restore,
1697
+ requestId: Snowflake,
1698
+ failure: string
1699
+ ): Effect.Effect<boolean, never, R> =>
1700
+ Effect.suspend(() => {
1701
+ memory = undefined
1702
+ return restore(messageStorage.withTransaction(Effect.gen(function*() {
1703
+ const initial = stepper.start(...options.input)
1704
+ if (Exit.isFailure(initial)) return false
1705
+ const state: Snapshot = initial.value.snapshot
1706
+ const snapshot = yield* internalMachine.encodeSnapshot(machine, state)
1707
+ const checkpoint: Checkpoint = {
1708
+ definitionId,
1709
+ version,
1710
+ revision: 1,
1711
+ origin: { _tag: "Request", requestId },
1712
+ snapshot,
1713
+ status: { _tag: "Failed", failure }
1714
+ }
1715
+ const committed = yield* storage.commit(address, checkpoint)
1716
+ if (committed._tag === "RevisionConflict") return yield* new Conflicted()
1717
+ yield* saveOutgoing(endedFor(true))
1718
+ if (committed._tag === "Committed") {
1719
+ yield* notifyCommit(checkpoint, state)
1720
+ }
1721
+ return true
1722
+ }))).pipe(
1723
+ Effect.matchCauseEffect({
1724
+ onFailure: (cause) => notDone("Could not store the failure of a Cluster machine", cause),
1725
+ onSuccess: (stored) => {
1726
+ memory = stored ? { _tag: "Failed", revision: 1, failure } : undefined
1727
+ return Effect.logError(
1728
+ stored ? "A Cluster machine failed" : "A Cluster machine cannot plan its initial state",
1729
+ failure
1730
+ ).pipe(Effect.as(true))
1731
+ }
1732
+ }),
1733
+ annotate
1734
+ )
1735
+ })
1736
+
1737
+ const lifecycle = (input: RequestInput): Effect.Effect<void, never, R> =>
1738
+ turn((restore) =>
1739
+ attempt(restore, input).pipe(
1740
+ Effect.catchTag("Conflicted", () => attempt(restore, input)),
1741
+ Effect.catchTag("Conflicted", () => Effect.void),
1742
+ // A stop saves the stops of the children of the child.
1743
+ Effect.tap(() => input.lifecycle === "Stop" ? options.sends?.poll ?? Effect.void : Effect.void),
1744
+ Effect.tap(() => align(restore, undefined)),
1745
+ Effect.asVoid
1746
+ )
1747
+ )
1748
+
1749
+ const applyRequest = (input: RequestInput): Effect.Effect<SendResult, never, R> =>
1750
+ turn((restore) =>
1751
+ attempt(restore, input).pipe(
1752
+ // A conflict leaves memory unknown, so the retry loads.
1753
+ Effect.catchTag("Conflicted", () => attempt(restore, input)),
1754
+ Effect.catchTag("Conflicted", () =>
1755
+ Effect.succeed(reject(
1756
+ "RevisionConflict",
1757
+ "Another instance advanced the checkpoint while this request was applied"
1758
+ ))),
1759
+ Effect.tap(() => align(restore, undefined))
1760
+ )
1761
+ )
1762
+
1763
+ return {
1764
+ wake,
1765
+ childEnded,
1766
+ deliver: (input) => untilDone(deliverOnce(input)),
1767
+ childSnapshot: ({ entityId, requestId, snapshot }) =>
1768
+ untilDone(deliverOnce({ requestId, event: undefined, child: { entityId, snapshot } })),
1769
+ start: ({ input, requestId }) =>
1770
+ applyRequest({
1771
+ requestId,
1772
+ event: undefined,
1773
+ lifecycle: "Start",
1774
+ initial: machine.input === undefined ? [] : [input]
1775
+ }),
1776
+ stop: (requestId) => lifecycle({ requestId, event: undefined, lifecycle: "Stop" }),
1777
+ apply: (input) => applyRequest(input)
1778
+ }
1779
+ })