@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
@@ -1,18 +1,26 @@
1
1
  /**
2
2
  * Runs Effect machines as persisted Cluster entities.
3
3
  *
4
+ * Each live entity keeps one machine instance in memory, which applies requests
5
+ * and runs the effects and timers invoked by active states. {@link Storage} holds
6
+ * the truth: every step commits a checkpoint to it, and an entity that comes up
7
+ * anywhere continues from that checkpoint.
8
+ *
4
9
  * @since 0.4.0
5
10
  */
6
- import type { Entity, MessageStorage, Sharding, Snowflake } from "effect/cluster";
11
+ import type { ClusterError, Entity, EntityId, MessageStorage, Sharding, Snowflake } from "effect/cluster";
12
+ import type * as Duration from "effect/Duration";
7
13
  import type * as Effect from "effect/Effect";
8
14
  import type * as Layer from "effect/Layer";
9
15
  import type * as Option from "effect/Option";
10
16
  import type { Rpc } from "effect/rpc";
17
+ import type * as Schedule from "effect/Schedule";
11
18
  import type * as Schema from "effect/Schema";
19
+ import type * as Stream from "effect/Stream";
12
20
  import * as Protocol from "../../internal/machine/clusterProtocol.js";
13
- import { Accepted, Rejected, Storage } from "../../internal/machine/clusterProtocol.js";
21
+ import { Accepted, MachineFailedError, ReadError, Rejected, Storage } from "../../internal/machine/clusterProtocol.js";
22
+ import { StorageCheckFailure } from "../../internal/machine/clusterStorageCheck.js";
14
23
  import type { EnsureExecutable } from "../../internal/machine/readiness.js";
15
- import type { ExcludeCompatibleRuntime } from "../../internal/machine/requirements.js";
16
24
  import type * as Machine from "../../Machine.js";
17
25
  type Snowflake = Snowflake.Snowflake;
18
26
  /**
@@ -20,22 +28,242 @@ type Snowflake = Snowflake.Snowflake;
20
28
  *
21
29
  * **Details**
22
30
  *
23
- * Machine identity and deployment version are stored around the generic
24
- * encoded snapshot. The request id records the request that produced the
25
- * checkpoint.
31
+ * The definition id and deployment version are stored around the generic
32
+ * encoded snapshot. The origin records the input that produced the checkpoint.
33
+ * The revision orders the checkpoints of one entity and decides which
34
+ * checkpoint a commit may replace. The status says whether the machine failed.
35
+ *
36
+ * **Gotchas**
37
+ *
38
+ * Store and return every field unchanged. The bridge assigns them all, and
39
+ * rejects a checkpoint whose revision is not a positive integer, or whose
40
+ * status it does not know or contradicts the snapshot or the machine, as
41
+ * `InvalidCheckpoint`.
26
42
  *
27
43
  * @category models
28
44
  * @since 0.4.0
29
45
  */
30
46
  export interface Checkpoint {
31
- /** Stable identity of the machine definition that produced the snapshot. */
32
- readonly machineId: string;
47
+ /**
48
+ * Stable id of the machine definition that produced the snapshot: `machine.id`
49
+ * when present, otherwise the Cluster entity type.
50
+ */
51
+ readonly definitionId: string;
33
52
  /** Application-controlled deployment or migration version. */
34
53
  readonly version: string;
35
- /** Cluster request whose accepted transition produced this checkpoint. */
36
- readonly requestId: Snowflake;
37
- /** Encoded logical machine state and completed outputs. */
54
+ /**
55
+ * Position in the entity's checkpoint history: `1` for its first checkpoint,
56
+ * then one more than the checkpoint it replaces.
57
+ */
58
+ readonly revision: number;
59
+ /** What produced this checkpoint from the one before it. */
60
+ readonly origin: Checkpoint.Origin;
61
+ /**
62
+ * Encoded logical machine state and completed outputs. For a failed machine,
63
+ * the last state before the failure.
64
+ */
38
65
  readonly snapshot: Machine.Machine.EncodedSnapshot;
66
+ /** Whether the machine can still take steps, or failed. */
67
+ readonly status: Checkpoint.Status;
68
+ }
69
+ /**
70
+ * Types of the parts of a Cluster machine {@link Checkpoint}.
71
+ *
72
+ * @category models
73
+ * @since 0.48.0
74
+ */
75
+ export declare namespace Checkpoint {
76
+ /**
77
+ * What produced a checkpoint.
78
+ *
79
+ * **Details**
80
+ *
81
+ * Only a request has an id to deduplicate. A checkpoint of any other origin is
82
+ * guarded by its revision alone.
83
+ *
84
+ * @category models
85
+ * @since 0.48.0
86
+ */
87
+ type Origin = Origin.Request | Origin.Invocation | Origin.Timers;
88
+ /**
89
+ * Types for what produced a checkpoint.
90
+ *
91
+ * @category models
92
+ * @since 0.48.0
93
+ */
94
+ namespace Origin {
95
+ /**
96
+ * A Cluster request.
97
+ *
98
+ * @category models
99
+ * @since 0.48.0
100
+ */
101
+ interface Request {
102
+ readonly _tag: "Request";
103
+ /** Id that `Storage.commit` deduplicates. */
104
+ readonly requestId: Snowflake;
105
+ }
106
+ /**
107
+ * The end of an invocation, or its failure to start.
108
+ *
109
+ * @category models
110
+ * @since 0.48.0
111
+ */
112
+ interface Invocation extends InvocationKey {
113
+ readonly _tag: "Invocation";
114
+ }
115
+ /**
116
+ * Due times for timers of the state that was stored without one.
117
+ *
118
+ * **Details**
119
+ *
120
+ * No step was taken, and the snapshot is the one before it. This origin
121
+ * occurs when an entity comes up in a state that was stored before the
122
+ * machine declared one of its timers.
123
+ *
124
+ * @category models
125
+ * @since 0.48.0
126
+ */
127
+ interface Timers {
128
+ readonly _tag: "Timers";
129
+ }
130
+ }
131
+ /**
132
+ * Names one invocation of a machine.
133
+ *
134
+ * @category models
135
+ * @since 0.48.0
136
+ */
137
+ interface InvocationKey {
138
+ /** Path of the state that owns the invocation. */
139
+ readonly path: string;
140
+ /** Id of the invocation within its state. */
141
+ readonly id: string;
142
+ }
143
+ /**
144
+ * Progress of the invocations of active states, by the path of the state and
145
+ * then by the id of the invocation within it.
146
+ *
147
+ * **Details**
148
+ *
149
+ * An effect that should run has no entry. A timer has an entry from the step
150
+ * that enters its state, unless its duration cannot be evaluated, which fails
151
+ * the machine. An entry is removed when its state exits, and no entry is
152
+ * `Waiting` once the machine is final.
153
+ *
154
+ * @category models
155
+ * @since 0.48.0
156
+ */
157
+ interface Invocations {
158
+ readonly [path: string]: {
159
+ readonly [id: string]: Progress;
160
+ };
161
+ }
162
+ /**
163
+ * How far one invocation of an active state has come.
164
+ *
165
+ * @category models
166
+ * @since 0.48.0
167
+ */
168
+ type Progress = Progress.Settled | Progress.Waiting | Progress.Child;
169
+ /**
170
+ * Types for the progress of an invocation.
171
+ *
172
+ * @category models
173
+ * @since 0.48.0
174
+ */
175
+ namespace Progress {
176
+ /**
177
+ * The invocation ended while its state stayed active. It does not run again
178
+ * until that state is entered again.
179
+ *
180
+ * @category models
181
+ * @since 0.48.0
182
+ */
183
+ interface Settled {
184
+ readonly _tag: "Settled";
185
+ }
186
+ /**
187
+ * The invocation is a timer that has not completed.
188
+ *
189
+ * @category models
190
+ * @since 0.48.0
191
+ */
192
+ interface Waiting {
193
+ readonly _tag: "Waiting";
194
+ /**
195
+ * When the timer completes, in milliseconds since the Unix epoch. An
196
+ * integer that a date can name, which is the last such instant for a
197
+ * duration that ends later or never.
198
+ */
199
+ readonly dueAt: number;
200
+ }
201
+ /**
202
+ * The invocation is a child machine, which runs as an entity of its own
203
+ * and has not ended.
204
+ *
205
+ * @category models
206
+ * @since 0.48.0
207
+ */
208
+ interface Child {
209
+ readonly _tag: "Child";
210
+ /** Entity id of the child, unique to this activation of its state. */
211
+ readonly entityId: string;
212
+ }
213
+ }
214
+ /**
215
+ * Whether the machine can still take steps, or failed.
216
+ *
217
+ * @category models
218
+ * @since 0.48.0
219
+ */
220
+ type Status = Status.Active | Status.Failed | Status.Stopped;
221
+ /**
222
+ * Types for the status of a checkpoint.
223
+ *
224
+ * @category models
225
+ * @since 0.48.0
226
+ */
227
+ namespace Status {
228
+ /**
229
+ * The machine has not failed. A machine in a final state is active too: its
230
+ * snapshot says that it is final.
231
+ *
232
+ * @category models
233
+ * @since 0.48.0
234
+ */
235
+ interface Active {
236
+ readonly _tag: "Active";
237
+ /**
238
+ * Timers that wait, and invocations that ended while their state stayed
239
+ * active.
240
+ */
241
+ readonly invocations: Invocations;
242
+ }
243
+ /**
244
+ * The machine failed. It is terminal, runs no work, and rejects every later
245
+ * request as `MachineFailed`.
246
+ *
247
+ * @category models
248
+ * @since 0.48.0
249
+ */
250
+ interface Failed {
251
+ readonly _tag: "Failed";
252
+ /** Human-readable rendering of the failure, of bounded length. */
253
+ readonly failure: string;
254
+ }
255
+ /**
256
+ * The machine is a child that its parent stopped, because the state that
257
+ * invoked it exited. It is terminal, runs no work, and rejects every later
258
+ * request as `MachineFailed`.
259
+ *
260
+ * @category models
261
+ * @since 0.48.0
262
+ */
263
+ interface Stopped {
264
+ readonly _tag: "Stopped";
265
+ }
266
+ }
39
267
  }
40
268
  /**
41
269
  * Result of loading a checkpoint for a Cluster machine request.
@@ -44,7 +272,8 @@ export interface Checkpoint {
44
272
  *
45
273
  * `processed` reports whether the exact Cluster request id was already
46
274
  * committed. Storage implementations must retain enough request ids to detect
47
- * redelivery even after later requests have advanced the checkpoint.
275
+ * redelivery even after later requests and invocations have advanced the
276
+ * checkpoint.
48
277
  *
49
278
  * @category models
50
279
  * @since 0.4.0
@@ -56,12 +285,19 @@ export interface LoadResult {
56
285
  readonly processed: boolean;
57
286
  }
58
287
  /**
59
- * Result of atomically committing a Cluster machine request.
288
+ * Result of atomically committing a Cluster machine checkpoint.
289
+ *
290
+ * **Details**
291
+ *
292
+ * The results are ordered. `Duplicate` takes precedence over
293
+ * `RevisionConflict`, so a redelivered request is recognized after later
294
+ * checkpoints have advanced the revision. Only a checkpoint whose origin is a
295
+ * request can be a `Duplicate`.
60
296
  *
61
297
  * @category models
62
298
  * @since 0.4.0
63
299
  */
64
- export type CommitResult = CommitResult.Committed | CommitResult.Duplicate;
300
+ export type CommitResult = CommitResult.Committed | CommitResult.Duplicate | CommitResult.RevisionConflict;
65
301
  /**
66
302
  * Constructors and types for Cluster machine commit results.
67
303
  *
@@ -71,6 +307,7 @@ export type CommitResult = CommitResult.Committed | CommitResult.Duplicate;
71
307
  export declare const CommitResult: {
72
308
  Committed: () => CommitResult.Committed;
73
309
  Duplicate: () => CommitResult.Duplicate;
310
+ RevisionConflict: () => CommitResult.RevisionConflict;
74
311
  };
75
312
  /**
76
313
  * Types for Cluster machine commit results.
@@ -80,7 +317,9 @@ export declare const CommitResult: {
80
317
  */
81
318
  export declare namespace CommitResult {
82
319
  /**
83
- * Indicates that the request id and checkpoint were committed atomically.
320
+ * Indicates that the checkpoint was committed, atomically with the request id
321
+ * of its origin when it has one. The checkpoint directly followed the stored
322
+ * one.
84
323
  *
85
324
  * @category models
86
325
  * @since 0.4.0
@@ -89,7 +328,8 @@ export declare namespace CommitResult {
89
328
  readonly _tag: "Committed";
90
329
  }
91
330
  /**
92
- * Indicates that the request id was already committed.
331
+ * Indicates that the request id was already committed, whatever the revision
332
+ * of the checkpoint. Nothing was written.
93
333
  *
94
334
  * @category models
95
335
  * @since 0.4.0
@@ -97,6 +337,16 @@ export declare namespace CommitResult {
97
337
  interface Duplicate {
98
338
  readonly _tag: "Duplicate";
99
339
  }
340
+ /**
341
+ * Indicates that the origin was not a request committed before, and that the
342
+ * stored checkpoint is not the one this commit replaces. Nothing was written.
343
+ *
344
+ * @category models
345
+ * @since 0.48.0
346
+ */
347
+ interface RevisionConflict {
348
+ readonly _tag: "RevisionConflict";
349
+ }
100
350
  }
101
351
  /**
102
352
  * Checkpoint persistence service used by Cluster machines.
@@ -104,10 +354,48 @@ export declare namespace CommitResult {
104
354
  * **When to use**
105
355
  *
106
356
  * Use to connect `ClusterMachine` to a durable checkpoint store that can
107
- * atomically deduplicate request ids and replace the current checkpoint.
357
+ * atomically deduplicate request ids and compare-and-set the current
358
+ * checkpoint.
359
+ *
360
+ * **Details**
361
+ *
362
+ * `loadForRequest` returns the latest checkpoint of an entity and whether a
363
+ * request id was already committed for it. `load` returns the checkpoint alone,
364
+ * for the inputs that are not requests: an entity that wakes up, and the end of
365
+ * an invocation.
366
+ *
367
+ * `commit` decides and writes atomically, in this order:
368
+ *
369
+ * 1. `Duplicate` when `checkpoint.origin` is a request whose id was already
370
+ * committed, whatever the revision. A checkpoint of any other origin is never
371
+ * a duplicate.
372
+ * 2. `RevisionConflict` when the stored revision is not exactly
373
+ * `checkpoint.revision - 1`. An entity without a checkpoint has revision
374
+ * `0`, so its first checkpoint has revision `1`.
375
+ * 3. `Committed` otherwise. The checkpoint replaces the stored one, and the
376
+ * request id of its origin, when it has one, is recorded with it.
377
+ *
378
+ * Each live entity loads its checkpoint once and keeps the decoded state in
379
+ * memory, so most inputs only call `commit`. Storage remains the truth: memory
380
+ * advances only after the whole transaction succeeded, and is loaded again
381
+ * after any other outcome. Before a request is rejected, `loadForRequest` is
382
+ * called to recognize a redelivery that was already committed.
383
+ *
384
+ * The due time of a timer is part of the checkpoint that enters its state, so
385
+ * storing the checkpoint whole is all that timers require. An entity that loads a
386
+ * state with a timer without a due time, which an earlier deployment can leave
387
+ * behind, commits one more checkpoint before it starts any work. Its origin is
388
+ * `Checkpoint.Origin.Timers`, and `commit` treats it as any origin that is not a
389
+ * request.
108
390
  *
109
391
  * **Gotchas**
110
392
  *
393
+ * The revision check is what stops an entity that lost its shard, and still
394
+ * holds an older state, from overwriting a newer checkpoint. It must be part of
395
+ * the same atomic write, such as an update conditional on the stored revision
396
+ * together with an insert that fails when a checkpoint exists. Comparing in a
397
+ * separate read is not enough.
398
+ *
111
399
  * For checkpoint and emitted-message persistence to commit atomically, this
112
400
  * service must join the transaction opened through the configured
113
401
  * `MessageStorage`. The reply is persisted after that transaction; storing the
@@ -115,6 +403,9 @@ export declare namespace CommitResult {
115
403
  * applying the transition again. A separate transaction or database cannot
116
404
  * provide checkpoint-and-emission atomicity.
117
405
  *
406
+ * A failed operation never fails the machine. An input that is not a request is
407
+ * retried for as long as the entity lives.
408
+ *
118
409
  * @category services
119
410
  * @since 0.4.0
120
411
  */
@@ -131,6 +422,21 @@ export { Accepted };
131
422
  * Schema for reasons a Cluster machine request can be rejected without
132
423
  * advancing its checkpoint.
133
424
  *
425
+ * **Details**
426
+ *
427
+ * `InvalidEvent` reports an event that {@link Client} refused before sending
428
+ * it, because its schema or the protocol of the machine refuses it. The
429
+ * machine never sees such an event.
430
+ *
431
+ * `DefinitionIdMismatch` reports a checkpoint whose `definitionId` is not the id
432
+ * of the machine that loaded it. `PersistenceFailure` reports storage that
433
+ * failed. `RevisionConflict` reports storage that worked and refused the request,
434
+ * because another instance of the entity advanced the checkpoint both times the
435
+ * request was applied.
436
+ * `MachineFailed` reports a machine whose stored status is `Failed`, and its
437
+ * message is the stored failure. A request that was committed before the
438
+ * failure is still answered as accepted.
439
+ *
134
440
  * @category models
135
441
  * @since 0.4.0
136
442
  */
@@ -146,6 +452,11 @@ export type RejectionReason = typeof RejectionReason.Type;
146
452
  * Rejected Cluster machine request. Transaction-participating durable storage
147
453
  * leaves the previous checkpoint in place and suppresses emitted events.
148
454
  *
455
+ * **Details**
456
+ *
457
+ * It is a yieldable error, which {@link Client} reports in its error channel,
458
+ * and the raw `send` RPC of the entity returns as a value of {@link SendResult}.
459
+ *
149
460
  * @category models
150
461
  * @since 0.4.0
151
462
  */
@@ -160,14 +471,71 @@ export declare const SendResult: typeof Protocol.SendResult;
160
471
  type SendRpc<Events extends ReadonlyArray<Machine.Machine.TaggedSchema>> = Rpc.Rpc<"send", Schema.Union<Events>, typeof SendResult>;
161
472
  type MachineEvents<M extends Machine.Machine.Any> = Machine.Machine.InputEvents<M>;
162
473
  type MachineEmits<M extends Machine.Machine.Any> = Machine.Machine.EmittedEvents<M>;
474
+ /**
475
+ * Committed checkpoint passed to {@link LayerOptions.onCommit} inside the same
476
+ * `MessageStorage` transaction as the checkpoint write.
477
+ *
478
+ * @category models
479
+ * @since 0.49.0
480
+ */
481
+ export interface CommitEvent<M extends Machine.Machine.Any> {
482
+ /** Entity id of the machine whose checkpoint was committed. */
483
+ readonly entityId: string;
484
+ /** Stored checkpoint that was just committed. */
485
+ readonly checkpoint: Checkpoint;
486
+ /** Decoded snapshot matching the committed checkpoint. */
487
+ readonly snapshot: Snapshot<M>;
488
+ }
489
+ /**
490
+ * Options for {@link ClusterMachine.toLayer}, combining transactional commit
491
+ * hooks with standard Effect Cluster `Entity.toLayer` tuning options.
492
+ *
493
+ * @category models
494
+ * @since 0.49.0
495
+ */
496
+ export interface LayerOptions<M extends Machine.Machine.Any, RE = never, RC = never> {
497
+ /**
498
+ * Durably enqueues emitted events inside the checkpoint's `MessageStorage`
499
+ * transaction.
500
+ */
501
+ readonly enqueue?: (event: Machine.Machine.EmittedEventOf<MachineEmits<M>>) => Effect.Effect<void, unknown, RE>;
502
+ /**
503
+ * Runs inside the checkpoint's `MessageStorage` transaction right after a
504
+ * checkpoint is committed, for projections, read models, or audit tables that
505
+ * must commit or roll back atomically with the machine state.
506
+ */
507
+ readonly onCommit?: (event: CommitEvent<M>) => Effect.Effect<void, unknown, RC>;
508
+ /** Overrides `ShardingConfig.entityMaxIdleTime` for this entity (and its children). */
509
+ readonly maxIdleTime?: Duration.Input | undefined;
510
+ /** Concurrency forwarded to `Entity.toLayer` for this entity (and its children). */
511
+ readonly concurrency?: number | "unbounded" | undefined;
512
+ /** Overrides `ShardingConfig.entityMailboxCapacity` for this entity (and its children). */
513
+ readonly mailboxCapacity?: number | "unbounded" | undefined;
514
+ /** Enables Cluster mailbox metrics for this entity (and its children). */
515
+ readonly mailboxMetrics?: boolean | undefined;
516
+ /**
517
+ * When `true`, a handler defect fails only its request instead of restarting
518
+ * the entity and replaying its in-flight requests.
519
+ */
520
+ readonly disableFatalDefects?: boolean | undefined;
521
+ /**
522
+ * Schedule for restarting an entity after a defect and for retrying failed
523
+ * handler construction.
524
+ */
525
+ readonly defectRetryPolicy?: Schedule.Schedule<any, unknown> | undefined;
526
+ /** Tracing span attributes attached to entity requests. */
527
+ readonly spanAttributes?: Record<string, string> | undefined;
528
+ }
163
529
  /**
164
530
  * Cluster adapter for one machine definition and entity type.
165
531
  *
166
532
  * **Details**
167
533
  *
168
- * The adapter exposes one persisted `send` RPC. Entity requests are serialized
169
- * by the normal Cluster entity concurrency and every accepted request advances
170
- * the checkpoint at most once.
534
+ * The adapter exposes one persisted `send` RPC, and {@link Client}s that send
535
+ * through it as a local reference sends. Each live entity keeps one
536
+ * machine instance in memory, which applies requests and the outcomes of invoked
537
+ * effects and timers one at a time. Every accepted request advances the
538
+ * checkpoint at most once.
171
539
  *
172
540
  * @category models
173
541
  * @since 0.4.0
@@ -175,26 +543,324 @@ type MachineEmits<M extends Machine.Machine.Any> = Machine.Machine.EmittedEvents
175
543
  export interface ClusterMachine<in out Type extends string, in out M extends Machine.Machine.Any, out Services = MachineServices<M>> {
176
544
  /** Machine definition executed by each entity instance. */
177
545
  readonly machine: M;
178
- /** Cluster entity exposing the persisted, schema-validated `send` RPC. */
546
+ /**
547
+ * Cluster entity exposing the persisted, schema-validated `send` RPC. The
548
+ * entity also answers the delayed messages that wake it for its long timers,
549
+ * which only the machine itself sends, so its type leaves them out.
550
+ */
179
551
  readonly entity: Entity.Entity<Type, SendRpc<MachineEvents<M>>>;
552
+ /**
553
+ * Creates clients for the entities of this machine, one per entity id, like
554
+ * `Entity.client`.
555
+ *
556
+ * **Example** (Sending an event built by a constructor)
557
+ *
558
+ * ```ts import.meta.vitest
559
+ * import { Machine } from "@typeonce/effect-machine"
560
+ * import { ClusterMachine } from "@typeonce/effect-machine/cluster"
561
+ * import { Effect, Schema } from "effect"
562
+ *
563
+ * const Events = Machine.events({ Rename: { name: Schema.NonEmptyString } })
564
+ * const machine = Machine.make({
565
+ * root: Machine.state({ states: { Draft: { fields: { name: Schema.String } } } }),
566
+ * events: Events
567
+ * }).handle({
568
+ * initial: { target: "Draft", data: { name: "untitled" } },
569
+ * states: { Draft: { on: { Rename: { target: "Draft", data: ({ event }) => ({ name: event.name }) } } } }
570
+ * })
571
+ *
572
+ * const adapter = ClusterMachine.make("Document", machine, { version: "1" })
573
+ *
574
+ * // Run with a Cluster runner, which provides `Sharding`.
575
+ * const rename = Effect.gen(function*() {
576
+ * const client = (yield* adapter.client)("document-1")
577
+ * yield* client.send(Events.Rename({ name: "report" })).pipe(
578
+ * Effect.catchTag("Rejected", (rejected) => Effect.logWarning(rejected.reason))
579
+ * )
580
+ * })
581
+ *
582
+ * Effect.isEffect(rename) // => true
583
+ * ```
584
+ *
585
+ * @since 0.48.0
586
+ */
587
+ readonly client: Effect.Effect<(entityId: string) => Client<M>, never, Sharding.Sharding>;
588
+ /**
589
+ * Names the entity of this machine with `entityId`, as a {@link Target} that
590
+ * another Cluster machine sends to with `enqueue.sendTo`.
591
+ *
592
+ * **Example** (Sending to another Cluster machine)
593
+ *
594
+ * ```ts import.meta.vitest
595
+ * import { Machine } from "@typeonce/effect-machine"
596
+ * import { ClusterMachine } from "@typeonce/effect-machine/cluster"
597
+ * import { Schema } from "effect"
598
+ *
599
+ * const Ledger = ClusterMachine.make(
600
+ * "Ledger",
601
+ * Machine.make({
602
+ * root: Machine.state({ states: { Open: { fields: { total: Schema.Number } } } }),
603
+ * events: Machine.events({ Add: { amount: Schema.Number } })
604
+ * }).handle({
605
+ * initial: { target: "Open", data: { total: 0 } },
606
+ * states: {
607
+ * Open: { on: { Add: { update: { Open: ({ event, state }) => ({ total: state.total + event.amount }) } } } }
608
+ * }
609
+ * }),
610
+ * { version: "1" }
611
+ * )
612
+ *
613
+ * const Order = ClusterMachine.make(
614
+ * "Order",
615
+ * Machine.make({
616
+ * root: Machine.state({ states: { Open: { fields: { ledger: Schema.String } }, Paid: {} } }),
617
+ * events: Machine.events({ Pay: { amount: Schema.Number } })
618
+ * }).handle({
619
+ * initial: { target: "Open", data: { ledger: "ledger-1" } },
620
+ * states: {
621
+ * Open: {
622
+ * on: {
623
+ * Pay: {
624
+ * target: "Paid",
625
+ * // Saved with the checkpoint of this step, and applied once.
626
+ * commands: ({ event, state }, enqueue) =>
627
+ * enqueue.sendTo(Ledger.target(state.ledger), { _tag: "Add", amount: event.amount })
628
+ * }
629
+ * }
630
+ * },
631
+ * Paid: {}
632
+ * }
633
+ * }),
634
+ * { version: "1" }
635
+ * )
636
+ *
637
+ * Order.entity.type // => "Order"
638
+ * ```
639
+ *
640
+ * @since 0.48.0
641
+ */
642
+ readonly target: (entityId: string) => Target<Machine.Machine.EventInputOf<MachineEvents<M>>>;
180
643
  /**
181
644
  * Creates the Cluster entity layer for this machine.
182
645
  *
183
646
  * **Gotchas**
184
647
  *
185
- * `enqueue` runs after the checkpoint write in the same `MessageStorage`
186
- * transaction. It must durably enqueue emitted events in that transaction;
648
+ * `enqueue` and `onCommit` run after the checkpoint write in the same
649
+ * `MessageStorage` transaction. Use them only for work that joins that
650
+ * transaction (such as durable outbox writes or SQL read-model projections);
187
651
  * arbitrary external effects are not atomic with the checkpoint. The reply
188
652
  * is persisted after commit and recovered through request-id deduplication if
189
653
  * delivery is interrupted. Machines that never emit may omit `enqueue`.
190
654
  *
655
+ * An `enqueue` failure rejects the request as `EmissionFailure`; an
656
+ * `onCommit` failure rejects it as `PersistenceFailure` and rolls back the
657
+ * transaction. For steps triggered by an invoked effect or timer, both are
658
+ * retried until stored. Entity tuning options (`maxIdleTime`, `concurrency`,
659
+ * `mailboxCapacity`, `mailboxMetrics`, `disableFatalDefects`,
660
+ * `defectRetryPolicy`, `spanAttributes`) are forwarded to `Entity.toLayer`
661
+ * for this entity and its child entities.
662
+ *
191
663
  * @since 0.4.0
192
664
  */
193
- readonly toLayer: <R = never>(options?: {
194
- readonly enqueue?: (event: Machine.Machine.EmittedEventOf<MachineEmits<M>>) => Effect.Effect<void, unknown, R>;
195
- }) => Layer.Layer<never, never, Storage | MessageStorage.MessageStorage | Sharding.Sharding | R | Services>;
665
+ readonly toLayer: <RE = never, RC = never>(options?: LayerOptions<M, RE, RC>) => Layer.Layer<never, never, Storage | MessageStorage.MessageStorage | Sharding.Sharding | RE | RC | Services>;
666
+ }
667
+ /**
668
+ * Failures of Cluster that keep a request from reaching an entity or its reply
669
+ * from reaching the caller.
670
+ *
671
+ * @category errors
672
+ * @since 0.48.0
673
+ */
674
+ export type ClientError = ClusterError.MailboxFull | ClusterError.AlreadyProcessingMessage | ClusterError.PersistenceError | ClusterError.EntityNotAssignedToRunner;
675
+ /**
676
+ * A Cluster machine named by its entity type and id, as Cluster addresses an
677
+ * entity, that a model sends to.
678
+ *
679
+ * **Details**
680
+ *
681
+ * `target` of an adapter makes one, and a Cluster machine is given one for its
682
+ * own entity as `self`. A step that sends to it with `enqueue.sendTo` saves the
683
+ * event as a persisted request to the entity, in the same `MessageStorage`
684
+ * transaction as its checkpoint, so the event is sent if and only if the step
685
+ * is stored. The request has an id of its own, which the target records when it
686
+ * applies the request, so Cluster may deliver it again and it is applied once.
687
+ * Nobody waits for its answer, so the target treats it as a local machine
688
+ * treats an event sent to it: an event it cannot apply, such as one whose
689
+ * transition throws, fails it, and a target that ended drops the event. A
690
+ * failure of storage is retried.
691
+ *
692
+ * `send` sends through the client of the target, from the work of a Cluster
693
+ * machine or from any effect that has `Sharding`, and waits for the target to
694
+ * accept the event. It sends again when a runner cannot take the request, and
695
+ * fails with `StoppedError` once the target failed. Work runs at least once, so
696
+ * an event that work sends may be sent more than once.
697
+ *
698
+ * **Gotchas**
699
+ *
700
+ * The types check the event against the input events of the target, but not
701
+ * that the target was made by this module: a step on Cluster that sends to a
702
+ * local reference is rejected as `UnsupportedProcessLocal`, and so is
703
+ * `enqueue.stop` with a local child address (whereas `enqueue.stop` with the
704
+ * descriptor of an invoked child stops that child). A target made here is not a
705
+ * local reference either, so a local machine cannot send to it.
706
+ *
707
+ * The runner that stores the step reads the request at once. A target owned by
708
+ * another runner reads it at its next poll of `MessageStorage`, after up to
709
+ * `entityMessagePollInterval`.
710
+ *
711
+ * Its `sessionId` is the address of the entity, `Type/entityId`, which stays
712
+ * the same across runners and restarts.
713
+ *
714
+ * @category models
715
+ * @since 0.48.0
716
+ */
717
+ export interface Target<in Event> extends Machine.MachineTarget<Event> {
718
+ readonly "~effect/cluster/ClusterMachine/Target": "~effect/cluster/ClusterMachine/Target";
719
+ /** Entity type of the machine. */
720
+ readonly entityType: string;
721
+ /** Entity id of the machine. */
722
+ readonly entityId: string;
723
+ }
724
+ /**
725
+ * A client for one Cluster machine, addressed by its entity id.
726
+ *
727
+ * **Details**
728
+ *
729
+ * `send` takes what `send` of a local machine reference takes: an event of the
730
+ * machine's input protocol, as a plain value or as built by a constructor of
731
+ * `Machine.events`. It decodes the event as a local reference does, sends it
732
+ * through the persisted `send` RPC of the entity, and succeeds once the request
733
+ * is committed or recognized as a redelivery.
734
+ *
735
+ * An event that its schema refuses is rejected as `InvalidEvent` before it is
736
+ * sent, and the machine never sees it. A request that the machine rejects fails
737
+ * with the same {@link Rejected}, carrying its reason. A transition that throws
738
+ * is such a rejection, because the client waits for the step: by the rule that
739
+ * `Machine.MachineRef` states for `send`, the error goes to the sender, and the
740
+ * machine goes on.
741
+ *
742
+ * `snapshot`, `changes`, and `join` read the machine from {@link Storage}, which
743
+ * is the truth, and never ask the entity. A read works from any process that
744
+ * reaches the store, whichever runner owns the entity and whether it is in
745
+ * memory or not. It does not wake the entity or keep it alive, so a machine that
746
+ * is passivated, moved, or recovered after a restart is read the same way.
747
+ *
748
+ * **Gotchas**
749
+ *
750
+ * Failures of Cluster itself, such as a full mailbox, are {@link ClientError}s.
751
+ * A request that ended in one may still have been delivered, and is delivered at
752
+ * most once when it is sent again.
753
+ *
754
+ * A remote view is narrower than a local `MachineRef`. Reads see committed
755
+ * checkpoints only, and `changes` reads again after each `readInterval`, so it
756
+ * may skip checkpoints committed between two reads and sees a change up to one
757
+ * interval late. A failed machine carries the text of its failure, not a
758
+ * `Cause`. Only a child machine is ever `stopped`, by its parent, and nothing
759
+ * is read before the first event is committed.
760
+ *
761
+ * @category models
762
+ * @since 0.48.0
763
+ */
764
+ export interface Client<M extends Machine.Machine.Any> {
765
+ /** Entity id of the machine this client addresses. */
766
+ readonly entityId: string;
767
+ /**
768
+ * Starts the entity with its initial input, committing its initial state when
769
+ * it has no checkpoint yet. Succeeds as a no-op if the entity is already
770
+ * active, and rejects with `MachineFailed` if it failed or was stopped.
771
+ */
772
+ readonly start: (...input: [...Machine.Machine.InputArgs<Machine.Machine.InputSchema<M>>]) => Effect.Effect<void, Rejected | ClientError>;
773
+ /** Sends one input event and waits until it is committed or rejected. */
774
+ readonly send: (event: Machine.Machine.EventInputOf<MachineEvents<M>>) => Effect.Effect<void, Rejected | ClientError>;
775
+ /**
776
+ * Reads the latest committed checkpoint, or `None` when the machine has not
777
+ * committed one yet.
778
+ */
779
+ readonly snapshot: Effect.Effect<Option.Option<Snapshot<M>>, ReadError | ClusterError.PersistenceError, ReadServices<M>>;
780
+ /**
781
+ * Streams the latest committed checkpoint and the later ones it reads, once
782
+ * each, and ends after a `done` or `failed` one. It waits while the machine
783
+ * has committed none.
784
+ */
785
+ readonly changes: Stream.Stream<Snapshot<M>, ReadError | ClusterError.PersistenceError, ReadServices<M>>;
786
+ /**
787
+ * Waits for the output of the machine, or fails with
788
+ * {@link MachineFailedError} when it failed.
789
+ */
790
+ readonly join: Effect.Effect<Machine.Machine.Output<M>, MachineFailedError | ReadError | ClusterError.PersistenceError, ReadServices<M>>;
196
791
  }
197
- type MachineServices<M extends Machine.Machine.Any> = ExcludeCompatibleRuntime<Machine.ExecutionServices<Machine.Machine.Services<M> | Machine.Machine.InitialServices<M>>, Machine.Machine.Event<M>, Machine.Machine.EmittedEvent<M>> | Machine.Machine.SnapshotDecodingServices<Machine.Machine.States<M>> | Machine.Machine.SnapshotEncodingServices<Machine.Machine.States<M>>;
792
+ /**
793
+ * Services that reading a Cluster machine from outside requires: the
794
+ * {@link Storage} that holds its checkpoints, and what its state schemas need
795
+ * to decode.
796
+ *
797
+ * @category models
798
+ * @since 0.48.0
799
+ */
800
+ export type ReadServices<M extends Machine.Machine.Any> = Storage | Machine.Machine.SnapshotDecodingServices<Machine.Machine.States<M>>;
801
+ /**
802
+ * A committed checkpoint of a Cluster machine, as a {@link Client} reads it.
803
+ *
804
+ * **Details**
805
+ *
806
+ * `revision` orders the checkpoints of one machine. A `done` machine carries
807
+ * its output, as its final state computes it. A `failed` machine carries the
808
+ * text of the failure that ended it, and the last state it committed before.
809
+ * A `stopped` machine is a child machine that its parent stopped.
810
+ *
811
+ * @category models
812
+ * @since 0.48.0
813
+ */
814
+ export type Snapshot<M extends Machine.Machine.Any> = {
815
+ readonly status: "active";
816
+ readonly revision: number;
817
+ readonly state: Machine.Machine.Snapshot<Machine.Machine.States<M>>;
818
+ } | {
819
+ readonly status: "done";
820
+ readonly revision: number;
821
+ readonly state: Machine.Machine.Snapshot<Machine.Machine.States<M>>;
822
+ readonly output: Machine.Machine.Output<M>;
823
+ } | {
824
+ readonly status: "failed";
825
+ readonly revision: number;
826
+ readonly state: Machine.Machine.Snapshot<Machine.Machine.States<M>>;
827
+ readonly failure: string;
828
+ } | {
829
+ readonly status: "stopped";
830
+ readonly revision: number;
831
+ readonly state: Machine.Machine.Snapshot<Machine.Machine.States<M>>;
832
+ };
833
+ /**
834
+ * Why a {@link Client} could not read a checkpoint: it was written by another
835
+ * definition or version, or it is not one that this machine can hold.
836
+ *
837
+ * @category errors
838
+ * @since 0.48.0
839
+ */
840
+ export { ReadError };
841
+ /**
842
+ * Reasons for a {@link ReadError}.
843
+ *
844
+ * @category errors
845
+ * @since 0.48.0
846
+ */
847
+ export declare const ReadFailureReason: typeof Protocol.ReadFailureReason;
848
+ /**
849
+ * Reason for a {@link ReadError}.
850
+ *
851
+ * @category errors
852
+ * @since 0.48.0
853
+ */
854
+ export type ReadFailureReason = typeof ReadFailureReason.Type;
855
+ /**
856
+ * The failure of a Cluster machine that `join` waited for, as the text that
857
+ * the machine stored when it failed.
858
+ *
859
+ * @category errors
860
+ * @since 0.48.0
861
+ */
862
+ export { MachineFailedError };
863
+ type MachineServices<M extends Machine.Machine.Any> = Exclude<Machine.Machine.Services<M>, Machine.InvocationSupport<"Child"> | Machine.ChildMachineRuntime> | Machine.Machine.SnapshotDecodingServices<Machine.Machine.States<M>> | Machine.Machine.SnapshotEncodingServices<Machine.Machine.States<M>>;
198
864
  type IsAny<A> = 0 extends (1 & A) ? true : false;
199
865
  type IsNever<A> = [A] extends [never] ? true : false;
200
866
  type IsUnknown<A> = IsAny<A> extends true ? false : unknown extends A ? true : false;
@@ -206,13 +872,22 @@ type NonJsonOutput<States extends Machine.Machine.StateSchemas> = Machine.Machin
206
872
  type NonJsonInputEvent<Events extends ReadonlyArray<Machine.Machine.TaggedSchema>> = {
207
873
  readonly [Index in keyof Events]: Events[Index] extends infer EventSchema extends Machine.Machine.TaggedSchema ? IsJsonEncoded<EventSchema> extends true ? never : Machine.Machine.TagOf<EventSchema> : never;
208
874
  }[number];
209
- type EnsureJsonEncoded<States extends Machine.Machine.StateSchemas, InputEvents extends ReadonlyArray<Machine.Machine.TaggedSchema>> = [NonJsonState<States> | NonJsonOutput<States> | NonJsonInputEvent<InputEvents>] extends [never] ? unknown : {
210
- readonly "~effect/ClusterMachine/NonJsonEncoded": {
875
+ type NonJsonInput<Input extends Schema.Top> = Input extends typeof Schema.Void ? never : IsJsonEncoded<Input> extends true ? never : Input["Encoded"];
876
+ type EnsureJsonEncoded<States extends Machine.Machine.StateSchemas, InputEvents extends ReadonlyArray<Machine.Machine.TaggedSchema>, Input extends Schema.Top> = [NonJsonState<States> | NonJsonOutput<States> | NonJsonInputEvent<InputEvents> | NonJsonInput<Input>] extends [
877
+ never
878
+ ] ? unknown : {
879
+ readonly "~effect/cluster/ClusterMachine/NonJsonEncoded": {
211
880
  readonly states: NonJsonState<States>;
212
881
  readonly outputs: NonJsonOutput<States>;
213
882
  readonly inputEvents: NonJsonInputEvent<InputEvents>;
883
+ readonly input: NonJsonInput<Input>;
214
884
  };
215
885
  };
886
+ type EnsureSupported<M extends Machine.Machine.Any> = Machine.MachineStep.Supported<M, "Child", Machine.ChildMachineRuntime> extends {
887
+ readonly "~effect/Machine/MachineStep/Unsupported": infer Missing;
888
+ } ? {
889
+ readonly "~effect/cluster/ClusterMachine/UnsupportedProcessLocal": Missing;
890
+ } : unknown;
216
891
  /**
217
892
  * Creates an in-memory Cluster machine checkpoint store.
218
893
  *
@@ -224,7 +899,9 @@ type EnsureJsonEncoded<States extends Machine.Machine.StateSchemas, InputEvents
224
899
  * **Gotchas**
225
900
  *
226
901
  * This store is not durable and does not provide rollback with the in-memory
227
- * `MessageStorage` transaction marker.
902
+ * `MessageStorage` transaction marker. A request rejected as `EmissionFailure`
903
+ * keeps the checkpoint it had already committed. The outcome of an invoked
904
+ * effect or timer whose `enqueue` fails keeps it too, so it is not applied again.
228
905
  *
229
906
  * @category constructors
230
907
  * @since 0.4.0
@@ -237,6 +914,58 @@ export declare const makeMemory: Effect.Effect<Storage["Service"]>;
237
914
  * @since 0.4.0
238
915
  */
239
916
  export declare const layerMemory: Layer.Layer<Storage>;
917
+ /**
918
+ * Checks that a {@link Storage} keeps the contract that Cluster machines rely
919
+ * on, and fails with the first scenario it breaks.
920
+ *
921
+ * **When to use**
922
+ *
923
+ * Use in the tests of a `Storage` of your own, against the database it runs
924
+ * on.
925
+ *
926
+ * **Details**
927
+ *
928
+ * The check commits to new entities of its own entity types, and so runs
929
+ * against a store that holds other machines. It checks that:
930
+ *
931
+ * - every field of a checkpoint is stored unchanged, including a 64-bit request
932
+ * id;
933
+ * - only the revision after the stored one commits;
934
+ * - a committed request is a `Duplicate` whatever the revision, and is
935
+ * reported as processed with the checkpoint it committed;
936
+ * - a rejected commit writes nothing and records no request;
937
+ * - a commit whose origin is not a request is never a `Duplicate`;
938
+ * - entities of other ids and types are kept apart;
939
+ * - of two concurrent commits of one revision, one commits.
940
+ *
941
+ * With `withTransaction`, it also checks that a commit inside a transaction
942
+ * that fails is rolled back. Pass the `withTransaction` of the
943
+ * `MessageStorage` that the store runs beside.
944
+ *
945
+ * **Example** (Checking the in-memory store)
946
+ *
947
+ * ```ts import.meta.vitest
948
+ * import { ClusterMachine } from "@typeonce/effect-machine/cluster"
949
+ * import { Effect } from "effect"
950
+ *
951
+ * const program = Effect.flatMap(ClusterMachine.makeMemory, (storage) => ClusterMachine.checkStorage(storage))
952
+ *
953
+ * await Effect.runPromise(program) // => undefined
954
+ * ```
955
+ *
956
+ * @category testing
957
+ * @since 0.48.0
958
+ */
959
+ export declare const checkStorage: (storage: Storage["Service"], options?: {
960
+ readonly withTransaction?: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
961
+ }) => Effect.Effect<void, StorageCheckFailure | ClusterError.PersistenceError>;
962
+ /**
963
+ * The scenario of {@link checkStorage} that a store breaks, and how.
964
+ *
965
+ * @category errors
966
+ * @since 0.48.0
967
+ */
968
+ export { StorageCheckFailure };
240
969
  /**
241
970
  * Creates a persisted Cluster entity adapter for a machine.
242
971
  *
@@ -247,22 +976,195 @@ export declare const layerMemory: Layer.Layer<Storage>;
247
976
  *
248
977
  * **Details**
249
978
  *
250
- * A missing checkpoint runs initial planning before the first event. Existing
251
- * checkpoints are identity-checked, version-checked, decoded, and resumed
252
- * without rerunning initial entry behavior. Final checkpoints accept later
253
- * requests as no-ops. The stable bridge identity is `machine.id` when present,
979
+ * A missing checkpoint runs initial planning before the first event. An entity
980
+ * may also be started explicitly via `client.start(...input)`. For a machine
981
+ * that declares `input`, you may either omit the default input from
982
+ * `ClusterMachine.make` and pass per-entity input to `client.start(input)`
983
+ * (sending an event before start rejects as `InvalidEvent`), or pass a default
984
+ * input to `ClusterMachine.make` so `client.send` can auto-start while
985
+ * `client.start(input)` still starts an entity with a custom input. Existing
986
+ * checkpoints are checked for their definition id and version, decoded, and
987
+ * resumed without rerunning initial entry behavior. Final checkpoints accept
988
+ * later requests as no-ops. The definition id is `machine.id` when present,
254
989
  * otherwise the Cluster entity type.
255
990
  *
991
+ * A live entity loads its checkpoint when it comes up, or for its first request
992
+ * when the machine invokes nothing, and then keeps the decoded state in memory
993
+ * until the entity is passivated or restarted. Storage remains the truth. A
994
+ * request whose state turns out to be behind storage is applied again to the
995
+ * stored state, and is rejected as `RevisionConflict` when storage has moved
996
+ * again.
997
+ *
998
+ * Effects invoked by active states run in the live entity. Work starts once the
999
+ * step that entered its state is stored, and stops once the step that exited it
1000
+ * is stored. The end of the work is applied as a step of its own, in order with
1001
+ * requests, and only the state it leads to is stored, never the result itself.
1002
+ * While work should run the entity is kept alive, so it is not passivated, and
1003
+ * Cluster brings it up on another runner after a crash. It is kept alive through
1004
+ * `Entity.keepAlive`, so a host that provides an `Entity.KeepAliveHandler` is
1005
+ * told when to keep it, and when to let it go.
1006
+ *
1007
+ * An entity that comes up starts the work of its stored state again. Input
1008
+ * mappers run again against that state, with `Machine.InitialEvent` as their
1009
+ * event, as they do for `LocalMachine.resume`. An invocation that ended while its
1010
+ * state stayed active is not started again until its state is entered again.
1011
+ *
1012
+ * A timer is stored as the time at which it is due, in the same checkpoint as the
1013
+ * step that enters its state. The live entity waits for that time and then
1014
+ * applies the completion as a step of its own. An entity that comes up again,
1015
+ * here or on another runner, waits only for the time that remains, and completes
1016
+ * a timer whose time has passed at once. Leaving the state cancels the timer, and
1017
+ * entering it again stores a new due time. `LocalMachine.resume` differs: it starts the
1018
+ * full duration again.
1019
+ *
1020
+ * The duration of a timer is evaluated after the step that enters its state is
1021
+ * planned and before that step is stored, and not again while its due time is
1022
+ * stored. The local runtime evaluates it once the state is entered, in order with
1023
+ * the other invocations of the state. A duration that cannot be evaluated does
1024
+ * not reject the request. The step is stored, and the machine then fails as it
1025
+ * does locally.
1026
+ *
1027
+ * Work that ends in a way the model does not handle, an outcome that cannot be
1028
+ * applied, and a source that cannot be constructed fail the machine, as they do
1029
+ * locally. The failure is stored with the last state, and every later request is
1030
+ * rejected as `MachineFailed`. There is no retry of failed work: a model that
1031
+ * recovers declares `onFailure`.
1032
+ *
1033
+ * A machine that this host cannot run does not compile: one whose states invoke a
1034
+ * Stream or a `Logic`, or whose invoked work requires `Machine.MachineRuntime`,
1035
+ * as `Machine.spawn` does, and `Machine.sendTo` and `Machine.stopChild` with a
1036
+ * child address. With the descriptor of a child machine, they require only
1037
+ * `Machine.ChildMachineRuntime`, which this host provides: they act on the
1038
+ * child that runs when the work acts, through a persisted request saved outside
1039
+ * the transaction of a step, and ignore a child that does not run. The error
1040
+ * names the property
1041
+ * `~effect/cluster/ClusterMachine/UnsupportedProcessLocal`, and lists there every
1042
+ * invocation kind and capability to replace with an Effect, a timer, or a child
1043
+ * machine. A source that is registered and never invoked is accepted.
1044
+ *
1045
+ * Streams and `Logic` are refused because their progress cannot be stored. A
1046
+ * checkpoint holds the state of a machine, and after a crash, a move to another
1047
+ * runner, or a restart, the machine continues from it and its work runs again
1048
+ * from the start. An Effect or a timer ends with one outcome, so running it
1049
+ * again changes nothing that was applied. A Stream ends after many elements,
1050
+ * and how far it got lives only in memory: run again, it would apply elements
1051
+ * that were applied before, or miss some when it does not produce the same ones.
1052
+ * A `Logic` is a process with a state and a mailbox of its own, and both would
1053
+ * be lost. Model a process, or a source of many events, as a child machine,
1054
+ * whose every step is stored, or as an Effect that ends with one result and a
1055
+ * state that is entered again for the next one.
1056
+ *
256
1057
  * **Gotchas**
257
1058
  *
258
- * Invoked processes, spawned children, action-time `runtime.raise`, timers,
259
- * subscriptions, and other process-local state are not durable and are
260
- * rejected. Planning-time raised events remain part of the current macrostep.
1059
+ * Work runs at least once and must be safe to repeat. It runs again after a
1060
+ * crash, a move to another runner, a restart of the entity, and when another
1061
+ * instance advanced the checkpoint, and it can run twice at the same time while
1062
+ * a shard moves. One result is applied. Results are not stored, so a result that
1063
+ * was not applied before a crash is computed again.
1064
+ *
1065
+ * A storage or `enqueue` failure never fails the machine. An outcome that cannot
1066
+ * be stored is retried for as long as the entity lives.
1067
+ *
1068
+ * Use `effect` 4.1.5 or later. Earlier versions answer the keep-alive request
1069
+ * of an entity after about ten minutes, so a machine whose work runs or whose
1070
+ * timer waits longer would not come up again after a crash.
1071
+ *
1072
+ * A timer that waits no longer than `DurableClock.InMemoryThreshold`, one
1073
+ * minute by default, keeps its entity in memory, as a workflow keeps a short
1074
+ * sleep. The step that stores a longer wait also saves, in the same
1075
+ * transaction of `MessageStorage`, a message to the entity that Cluster
1076
+ * delivers when the timer is due. Such a timer keeps nothing alive, so the
1077
+ * entity may leave memory, and the message brings it back, here or on another
1078
+ * runner. The path, the id, and the due time of the timer name the message, so
1079
+ * the message of a wait that ended is ignored. A timer that never ends saves no
1080
+ * message. A long wait stored before this version gets its message when its
1081
+ * entity next comes up.
1082
+ *
1083
+ * A message is read by the runner every `entityMessagePollInterval`, so a long
1084
+ * timer of an entity that left memory fires up to that much after it is due.
1085
+ *
1086
+ * Due times are read from the wall clock of the runner, so runners whose clocks
1087
+ * differ complete a timer that moves between them that much earlier or later.
1088
+ *
1089
+ * A state that was stored before the machine declared one of its timers has no
1090
+ * due time for it. The entity evaluates the duration when it comes up, with
1091
+ * `Machine.InitialEvent`, and stores the due time before it starts any work. A
1092
+ * state that was stored with a timer the machine no longer declares is rejected
1093
+ * as `InvalidCheckpoint`, so migrate such checkpoints.
1094
+ *
1095
+ * Machines send to each other through a {@link Target}, which names an entity
1096
+ * by its type and id: `target` of an adapter makes one, and `self` is the one of
1097
+ * the machine's own entity. An event that a step sends with `enqueue.sendTo` is
1098
+ * saved with its checkpoint and applied once, and work sends with `send` of a
1099
+ * target.
1100
+ *
1101
+ * A child machine that a state invokes runs as an entity of its own, of type
1102
+ * `Type/childId`, which the layer of the adapter registers too, with the same
1103
+ * version. Each activation of the state starts a new child, whose id is
1104
+ * `entityId/childId/revision`, with the revision of the step that entered the
1105
+ * state, so a child knows nothing of the one before it. The step that enters
1106
+ * the state saves the start of the child, with its input, in the transaction of
1107
+ * its checkpoint, and the step that exits it saves its stop, so a child runs
1108
+ * exactly while its state is stored. `enqueue.sendTo` with the descriptor of a
1109
+ * child sends to the child that runs once the step is stored, and drops the
1110
+ * event when none does. `enqueue.stop` with the descriptor of a child stops the
1111
+ * running child in the same transaction, settles its invocation progress so it
1112
+ * does not restart while the state stays active, and ignores a child that does
1113
+ * not run. Commands are carried out before the work of the states a step enters
1114
+ * starts, as they are locally, so both drop a child that the same step enters.
1115
+ * Work acts on the child of its state with `Machine.sendTo` and
1116
+ * `Machine.stopChild`, and its input mapper with `children.sendTo` and
1117
+ * `children.stop`. The child's `parent` is the target of its parent. A
1118
+ * child that ends tells its parent, which reads its output or its failure from
1119
+ * `Storage` and applies it as the end of the invocation. A failure of a child
1120
+ * fails its parent, also when the parent declares `onFailure`, because the
1121
+ * failure is stored as text and not as the error of the child. A stopped child
1122
+ * is stored as `Stopped`, and a machine that fails or ends stops its children.
1123
+ *
1124
+ * When a state of the parent takes the snapshots of a child with `onSnapshot`,
1125
+ * each step of the child that plans its initial state or takes a transition, and
1126
+ * leaves it active, sends its parent the encoded snapshot in the transaction of
1127
+ * its checkpoint. The parent applies each one once, as Cluster delivers it,
1128
+ * while it runs that child. A transition on a snapshot that cannot
1129
+ * be applied fails the parent. A child whose parent takes none of its snapshots
1130
+ * sends none.
1131
+ *
1132
+ * The compiler reads only the requirements of a machine, so these uses of a local
1133
+ * process compile and fail at run time:
1134
+ *
1135
+ * - A step whose plan sends to a target that is neither a {@link Target} nor
1136
+ * the descriptor of an invoked child, or stops a child address rather than
1137
+ * the descriptor of an invoked child with `enqueue.stop`. It rejects the
1138
+ * request as `UnsupportedProcessLocal`, or fails the machine when the step
1139
+ * applies an outcome. Planning-time raised events remain part of the current
1140
+ * macrostep.
1141
+ * - Work that spawns a child with `children.spawn` from the context of its
1142
+ * input mapper, or that `children.sendTo` and `children.stop` give a child
1143
+ * address. It fails the machine.
1144
+ * - A machine whose requirements are `any`, such as an erased one. When any of its
1145
+ * states declares an unsupported invocation, it rejects every request as
1146
+ * `UnsupportedProcessLocal`. Work of such a machine that uses
1147
+ * `Machine.MachineRuntime`, such as `Machine.spawn`, or `Machine.sendTo` and
1148
+ * `Machine.stopChild` with a child address, fails the machine with
1149
+ * `ProcessLocalError`.
1150
+ *
1151
+ * A deployment that adds an invocation to a state does not wake the entities
1152
+ * that are already in it. Their work starts when they come up.
1153
+ *
1154
+ * A request redelivered to a live entity is planned again before storage
1155
+ * recognizes it. The plan is discarded, but its resolvers have run again, and so
1156
+ * have the input mappers and sources of the timers it enters, so they must not
1157
+ * perform effects.
1158
+ *
1159
+ * A checkpoint changed outside the bridge while an entity is live is noticed
1160
+ * through its revision, so such a change must also advance the revision.
1161
+ *
261
1162
  * Arbitrary action effects may run again after a crash before checkpoint
262
1163
  * commit, so the bridge does not provide exactly-once external effects.
263
1164
  * State values, completion outputs, and public input events must declare
264
- * JSON-compatible encoded representations. Local and internal event protocols
265
- * remain unrestricted because they do not cross the Cluster boundary.
1165
+ * JSON-compatible encoded representations. Local and internal event protocols,
1166
+ * and the inputs, outputs, and errors of invoked work, remain unrestricted
1167
+ * because they do not cross the Cluster boundary.
266
1168
  *
267
1169
  * **Example** (Adapting a machine to an entity)
268
1170
  *
@@ -282,10 +1184,138 @@ export declare const layerMemory: Layer.Layer<Storage>;
282
1184
  * adapter.entity.type // => "IdleMachine"
283
1185
  * ```
284
1186
  *
1187
+ * **Example** (Running an invoked effect in an entity)
1188
+ *
1189
+ * ```ts import.meta.vitest
1190
+ * import { Machine } from "@typeonce/effect-machine"
1191
+ * import { ClusterMachine } from "@typeonce/effect-machine/cluster"
1192
+ * import { Effect, Schema } from "effect"
1193
+ *
1194
+ * const machine = Machine.make({
1195
+ * id: "Invoice",
1196
+ * root: Machine.state({
1197
+ * states: {
1198
+ * Draft: {},
1199
+ * Sending: { fields: { invoiceId: Schema.String } },
1200
+ * Sent: { fields: { receipt: Schema.String } },
1201
+ * Rejected: { fields: { reason: Schema.String } }
1202
+ * }
1203
+ * }),
1204
+ * events: Machine.events({ Send: { invoiceId: Schema.String } }),
1205
+ * effects: {
1206
+ * // Can run more than once, so the invoice id makes it safe to repeat.
1207
+ * send: (invoiceId: string) =>
1208
+ * invoiceId === "" ? Effect.fail({ reason: "No invoice" }) : Effect.succeed(`receipt-${invoiceId}`)
1209
+ * }
1210
+ * }).handle({
1211
+ * initial: { target: "Draft" },
1212
+ * states: {
1213
+ * Draft: { on: { Send: { target: "Sending", data: ({ event }) => ({ invoiceId: event.invoiceId }) } } },
1214
+ * Sending: {
1215
+ * invoke: {
1216
+ * src: "send",
1217
+ * input: ({ state }) => state.invoiceId,
1218
+ * onDone: { target: "Sent", data: ({ output }) => ({ receipt: output }) },
1219
+ * onFailure: { target: "Rejected", data: ({ error }) => ({ reason: error.reason }) }
1220
+ * }
1221
+ * }
1222
+ * }
1223
+ * })
1224
+ *
1225
+ * const adapter = ClusterMachine.make("Invoice", machine, { version: "1" })
1226
+ *
1227
+ * // Provide the layer with a Cluster runner and a durable `ClusterMachine.Storage`.
1228
+ * const layer = adapter.toLayer()
1229
+ *
1230
+ * adapter.entity.type // => "Invoice"
1231
+ * ```
1232
+ *
1233
+ * **Example** (Waiting for a timer that survives its runner)
1234
+ *
1235
+ * ```ts import.meta.vitest
1236
+ * import { Machine } from "@typeonce/effect-machine"
1237
+ * import { ClusterMachine } from "@typeonce/effect-machine/cluster"
1238
+ * import { Schema } from "effect"
1239
+ *
1240
+ * const machine = Machine.make({
1241
+ * id: "Trial",
1242
+ * root: Machine.state({
1243
+ * states: {
1244
+ * Inactive: {},
1245
+ * Running: { fields: { days: Schema.Number } },
1246
+ * Expired: {}
1247
+ * }
1248
+ * }),
1249
+ * events: Machine.events({ Start: { days: Schema.Number }, Cancel: {} }),
1250
+ * timers: { trial: (days: number) => ({ days }) }
1251
+ * }).handle({
1252
+ * initial: { target: "Inactive" },
1253
+ * states: {
1254
+ * Inactive: { on: { Start: { target: "Running", data: ({ event }) => ({ days: event.days }) } } },
1255
+ * Running: {
1256
+ * invoke: { src: "trial", input: ({ state }) => state.days, onDone: { target: "Expired" } },
1257
+ * on: { Cancel: { target: "Inactive" } }
1258
+ * }
1259
+ * }
1260
+ * })
1261
+ *
1262
+ * const adapter = ClusterMachine.make("Trial", machine, { version: "1" })
1263
+ *
1264
+ * adapter.entity.type // => "Trial"
1265
+ * ```
1266
+ *
1267
+ * **Example** (Refusing a machine that Cluster cannot run)
1268
+ *
1269
+ * ```ts import.meta.vitest
1270
+ * import { Machine } from "@typeonce/effect-machine"
1271
+ * import { ClusterMachine } from "@typeonce/effect-machine/cluster"
1272
+ * import { Effect, Stream } from "effect"
1273
+ *
1274
+ * const definition = Machine.make({
1275
+ * id: "Sensor",
1276
+ * root: Machine.state({ states: { Reading: {}, Read: {} } }),
1277
+ * events: Machine.events({}),
1278
+ * effects: { read: Effect.succeed(20) },
1279
+ * streams: { readings: Stream.make(20, 21) }
1280
+ * })
1281
+ *
1282
+ * const streaming = definition.handle({
1283
+ * initial: { target: "Reading" },
1284
+ * states: {
1285
+ * Reading: { invoke: { src: "readings", onElement: { stay: true }, onDone: { target: "Read" } } }
1286
+ * }
1287
+ * })
1288
+ *
1289
+ * // @ts-expect-error Invokes a Stream: { invocations: "Stream"; capabilities: never }
1290
+ * ClusterMachine.make("Sensor", streaming, { version: "1" })
1291
+ *
1292
+ * const reading = definition.handle({
1293
+ * initial: { target: "Reading" },
1294
+ * states: {
1295
+ * Reading: { invoke: { src: "read", onDone: { target: "Read" } } }
1296
+ * }
1297
+ * })
1298
+ *
1299
+ * const adapter = ClusterMachine.make("Sensor", reading, { version: "1" })
1300
+ *
1301
+ * adapter.entity.type // => "Sensor"
1302
+ * ```
1303
+ *
1304
+ * @see {@link Machine.InvocationSupport} for the requirement of each invocation kind.
285
1305
  * @category constructors
286
1306
  * @since 0.4.0
287
1307
  */
288
- export declare const make: <const Type extends string, States extends Machine.Machine.StateSchemas, Events extends ReadonlyArray<Machine.Machine.TaggedSchema>, Input extends Schema.Top, UnhandledStates extends Machine.Machine.StateIdentifier<States>, E, R, InitialE, InitialR, FinalStates extends Machine.Machine.StateIdentifier<States>, Output, Emits extends ReadonlyArray<Machine.Machine.TaggedSchema>, OutputStates extends Machine.Machine.StateIdentifier<States>, InputEvents extends ReadonlyArray<Machine.Machine.TaggedSchema> = Events, ParentEvents extends ReadonlyArray<Machine.Machine.TaggedSchema> = readonly []>(type: Type, machine: Machine.Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits, OutputStates, InputEvents, ParentEvents> & EnsureExecutable<States, UnhandledStates, OutputStates> & Machine.Machine.RootCompatible<ParentEvents> & EnsureJsonEncoded<States, InputEvents>, options: {
1308
+ export declare const make: <const Type extends string, States extends Machine.Machine.StateSchemas, Events extends ReadonlyArray<Machine.Machine.TaggedSchema>, Input extends Schema.Top, UnhandledStates extends Machine.Machine.StateIdentifier<States>, E, R, FinalStates extends Machine.Machine.StateIdentifier<States>, Output, Emits extends ReadonlyArray<Machine.Machine.TaggedSchema>, OutputStates extends Machine.Machine.StateIdentifier<States>, InputEvents extends ReadonlyArray<Machine.Machine.TaggedSchema> = Events, ParentEvents extends ReadonlyArray<Machine.Machine.TaggedSchema> = readonly []>(type: Type, machine: Machine.Machine<States, Events, Input, UnhandledStates, E, R, FinalStates, Output, Emits, OutputStates, InputEvents, ParentEvents> & EnsureExecutable<States, UnhandledStates, OutputStates> & Machine.Machine.RootCompatible<ParentEvents> & EnsureJsonEncoded<States, InputEvents, Input> & EnsureSupported<Machine.Machine<States, Events, Input, UnhandledStates, E, R, FinalStates, Output, Emits, OutputStates, InputEvents, ParentEvents>>, options: {
289
1309
  readonly version: string;
290
- }, ...input: [...Machine.Machine.InputArgs<Input>]) => ClusterMachine<Type, Machine.Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits, OutputStates, InputEvents, ParentEvents>, ExcludeCompatibleRuntime<Machine.ExecutionServices<R | InitialR>, Machine.Machine.EventOf<Events>, Machine.Machine.EmittedEventOf<Emits>> | Machine.Machine.SnapshotDecodingServices<States> | Machine.Machine.SnapshotEncodingServices<States>>;
1310
+ /**
1311
+ * How long `changes` and `join` of a {@link Client} wait between two reads.
1312
+ * Defaults to one second.
1313
+ */
1314
+ readonly readInterval?: Duration.Input | undefined;
1315
+ /**
1316
+ * Selects the Cluster shard group for each entity id (and for any child
1317
+ * entities invoked by that parent). Defaults to Cluster's `"default"` group.
1318
+ */
1319
+ readonly shardGroup?: ((entityId: EntityId.EntityId) => string) | undefined;
1320
+ }, ...input: readonly [] | [...Machine.Machine.InputArgs<Input>]) => ClusterMachine<Type, Machine.Machine<States, Events, Input, UnhandledStates, E, R, FinalStates, Output, Emits, OutputStates, InputEvents, ParentEvents>, Exclude<R, Machine.InvocationSupport<"Child"> | Machine.ChildMachineRuntime> | Machine.Machine.SnapshotDecodingServices<States> | Machine.Machine.SnapshotEncodingServices<States>>;
291
1321
  //# sourceMappingURL=ClusterMachine.d.ts.map