@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
@@ -4,69 +4,117 @@
4
4
  * @since 0.4.0
5
5
  */
6
6
  import * as Cause from "effect/Cause"
7
- import { ClusterSchema, Entity, MessageStorage } from "effect/cluster"
8
- import type { EntityAddress, Snowflake } from "effect/cluster"
7
+ import { ClusterSchema, Entity, EntityAddress, EntityId, MessageStorage, Sharding } from "effect/cluster"
8
+ import type { Snowflake } from "effect/cluster"
9
+ import type * as Duration from "effect/Duration"
9
10
  import * as Effect from "effect/Effect"
10
11
  import * as Layer from "effect/Layer"
11
12
  import * as Option from "effect/Option"
12
13
  import { Rpc } from "effect/rpc"
14
+ import type * as Schedule from "effect/Schedule"
13
15
  import * as Schema from "effect/Schema"
14
16
  import type * as Machine from "../../Machine.js"
15
- import type { Checkpoint } from "../../unstable/cluster/ClusterMachine.js"
16
- import type { ClusterMachine } from "../../unstable/cluster/ClusterMachine.js"
17
- import { Accepted, CommitResult, Rejected, type RejectionReason, SendResult, Storage } from "./clusterProtocol.js"
17
+ import type {
18
+ Checkpoint,
19
+ Client,
20
+ ClientError,
21
+ ClusterMachine,
22
+ LayerOptions
23
+ } from "../../unstable/cluster/ClusterMachine.js"
24
+ import * as ClusterChild from "./clusterChild.js"
25
+ import * as ClusterInstance from "./clusterInstance.js"
26
+ import { CommitResult, Rejected, SendResult, Storage } from "./clusterProtocol.js"
27
+ import * as ClusterRead from "./clusterRead.js"
28
+ import * as ClusterTarget from "./clusterTarget.js"
29
+ import * as ClusterWake from "./clusterWake.js"
30
+ import { MachineSchemaDecodeError } from "./errors.js"
18
31
  import { toImpl } from "./implementation.js"
19
- import * as internalMachine from "./machine.js"
20
32
  import * as Protocol from "./protocol.js"
21
33
  import type { EnsureExecutable } from "./readiness.js"
22
- import type { ExcludeCompatibleRuntime } from "./requirements.js"
23
34
 
24
35
  type EntityAddress = EntityAddress.EntityAddress
25
36
  type Snowflake = Snowflake.Snowflake
26
37
 
27
- type SendRpc<Events extends ReadonlyArray<Machine.Machine.TaggedSchema>> = Rpc.Rpc<
28
- "send",
29
- Schema.Union<Events>,
30
- typeof SendResult
31
- >
32
-
33
- type MachineEvents<M extends Machine.Machine.Any> = Machine.Machine.InputEvents<M>
34
-
35
- type MachineEmits<M extends Machine.Machine.Any> = Machine.Machine.EmittedEvents<M>
36
-
37
- const hasInvokes = (machine: Machine.Machine.Any): boolean =>
38
- Reflect.ownKeys(toImpl(machine).handlers).some((key) => toImpl(machine).handlers[key as string]?.invoke !== undefined)
39
-
40
- const reject = (reason: RejectionReason, message: string): Rejected => new Rejected({ reason, message })
38
+ const invalidEvent = (error: MachineSchemaDecodeError): Rejected =>
39
+ new Rejected({
40
+ reason: "InvalidEvent",
41
+ message: error.event === undefined
42
+ ? "The event does not match the protocol of the machine"
43
+ : `The event ${error.event} does not match its schema`
44
+ })
41
45
 
42
- const fail = (reason: RejectionReason, message: string): Effect.Effect<never, Rejected> =>
43
- Effect.fail(reject(reason, message))
46
+ /**
47
+ * Decodes an input event for a waiting caller (`MachineTarget.send` or
48
+ * `sendTo`), failing with `MachineSchemaDecodeError` when refused.
49
+ */
50
+ const decodeInputEventError = (
51
+ machine: Machine.Machine.Any,
52
+ publicTags: ReadonlySet<PropertyKey>,
53
+ event: unknown
54
+ ): Effect.Effect<unknown, MachineSchemaDecodeError> =>
55
+ Protocol.decodeEvent(machine, event).pipe(
56
+ Effect.flatMap((decoded) =>
57
+ publicTags.has(decoded._tag)
58
+ ? Effect.succeed(decoded)
59
+ : Effect.fail(
60
+ new MachineSchemaDecodeError({
61
+ machineId: machine.id,
62
+ boundary: "event",
63
+ event: String(decoded._tag),
64
+ cause: Cause.die(new Error(`The event ${String(decoded._tag)} is not an input event`))
65
+ })
66
+ )
67
+ )
68
+ )
44
69
 
45
- const messageFromCause = (cause: Cause.Cause<unknown>): string => {
46
- const squashed = Cause.squash(cause)
47
- return squashed instanceof globalThis.Error ? squashed.message : String(squashed)
48
- }
70
+ /**
71
+ * Decodes an event as `LocalMachine` does before it sends it, so that a client
72
+ * takes what a local reference takes, and refuses only public input events.
73
+ */
74
+ const decodeInputEvent = (
75
+ machine: Machine.Machine.Any,
76
+ publicTags: ReadonlySet<PropertyKey>,
77
+ event: unknown
78
+ ): Effect.Effect<unknown, Rejected> =>
79
+ Protocol.decodeEvent(machine, event).pipe(
80
+ Effect.mapError(invalidEvent),
81
+ Effect.flatMap((decoded) =>
82
+ publicTags.has(decoded._tag)
83
+ ? Effect.succeed(decoded)
84
+ : Effect.fail(
85
+ new Rejected({
86
+ reason: "InvalidEvent",
87
+ message: `The event ${String(decoded._tag)} is not an input event`
88
+ })
89
+ )
90
+ )
91
+ )
49
92
 
50
- const rejectionFromCause = (cause: Cause.Cause<unknown>): Rejected => {
51
- const error = Cause.findErrorOption(cause)
52
- if (Option.isSome(error) && error.value instanceof Rejected) {
53
- return error.value
54
- }
55
- if (Option.isSome(error) && error.value instanceof internalMachine.ProcessLocalError) {
56
- return reject("UnsupportedProcessLocal", `${error.value.operation} is process-local and is not supported`)
57
- }
58
- return reject("TransitionFailure", messageFromCause(cause))
59
- }
93
+ const decodeMachineInput = (
94
+ machine: Machine.Machine.Any,
95
+ input: unknown
96
+ ): Effect.Effect<unknown, Rejected> =>
97
+ machine.input === undefined
98
+ ? Effect.succeed(undefined)
99
+ : Protocol.decodeBoundary(machine, machine.input, input, { boundary: "input" }).pipe(
100
+ Effect.mapError(() =>
101
+ new Rejected({
102
+ reason: "InvalidEvent",
103
+ message: "The input does not match the schema of the machine"
104
+ })
105
+ )
106
+ )
60
107
 
61
108
  const addressKey = (address: EntityAddress): string => `${address.entityType}\u0000${address.entityId}`
62
109
 
63
110
  export const makeMemory: Effect.Effect<Storage["Service"]> = Effect.sync(() => {
64
111
  const entries = new Map<string, {
65
- checkpoint: Checkpoint
112
+ readonly checkpoint: Checkpoint
66
113
  readonly requests: Set<Snowflake>
67
114
  }>()
68
115
  return Storage.of({
69
- load: (address, requestId) =>
116
+ load: (address) => Effect.sync(() => Option.fromNullishOr(entries.get(addressKey(address))?.checkpoint)),
117
+ loadForRequest: (address, requestId) =>
70
118
  Effect.sync(() => {
71
119
  const entry = entries.get(addressKey(address))
72
120
  return {
@@ -77,19 +125,19 @@ export const makeMemory: Effect.Effect<Storage["Service"]> = Effect.sync(() => {
77
125
  commit: (address, checkpoint) =>
78
126
  Effect.sync(() => {
79
127
  const key = addressKey(address)
80
- const entry = entries.get(key)
81
- if (entry?.requests.has(checkpoint.requestId)) {
128
+ const { origin, revision } = checkpoint
129
+ const stored = entries.get(key)
130
+ if (origin._tag === "Request" && stored?.requests.has(origin.requestId)) {
82
131
  return CommitResult.Duplicate()
83
132
  }
84
- if (entry === undefined) {
85
- entries.set(key, {
86
- checkpoint,
87
- requests: new Set([checkpoint.requestId])
88
- })
89
- } else {
90
- entry.checkpoint = checkpoint
91
- entry.requests.add(checkpoint.requestId)
133
+ if (revision !== (stored?.checkpoint.revision ?? 0) + 1) {
134
+ return CommitResult.RevisionConflict()
135
+ }
136
+ const requests = stored?.requests ?? new Set()
137
+ if (origin._tag === "Request") {
138
+ requests.add(origin.requestId)
92
139
  }
140
+ entries.set(key, { checkpoint, requests })
93
141
  return CommitResult.Committed()
94
142
  })
95
143
  })
@@ -97,6 +145,45 @@ export const makeMemory: Effect.Effect<Storage["Service"]> = Effect.sync(() => {
97
145
 
98
146
  export const layerMemory: Layer.Layer<Storage> = Layer.effect(Storage, makeMemory)
99
147
 
148
+ // `effect` 4.1.3 added the handler, and the published range starts before it.
149
+ const KeepAliveHandler: typeof Entity.KeepAliveHandler | undefined = (Entity as Partial<typeof Entity>).KeepAliveHandler
150
+
151
+ // A `Sharding` runner provides the latch that holds a keep-alive request, and
152
+ // another host can provide an `Entity.KeepAliveHandler` instead, which
153
+ // `Entity.keepAlive` prefers. `Entity.makeTestClient` provides neither, and has
154
+ // no crash to recover from either.
155
+ const makeKeepAlive = Effect.gen(function*() {
156
+ const context = yield* Effect.context<Sharding.Sharding | Entity.CurrentAddress>()
157
+ const supported = (KeepAliveHandler !== undefined && Option.isSome(yield* Effect.serviceOption(KeepAliveHandler))) ||
158
+ Option.isSome(yield* Effect.serviceOption(Entity.KeepAliveLatch))
159
+ return (enabled: boolean): Effect.Effect<void> =>
160
+ enabled && !supported
161
+ ? Effect.logWarning("This Cluster runner cannot keep a machine alive, so its work is not recovered after a crash")
162
+ : Effect.provideContext(Entity.keepAlive(enabled), context)
163
+ })
164
+
165
+ /** Internal metadata captured for a `ClusterMachine` adapter, used by sibling internal bridges. */
166
+ export interface AdapterMeta {
167
+ readonly type: string
168
+ readonly machine: Machine.Machine.Any
169
+ readonly definitionId: string
170
+ readonly version: string
171
+ readonly readInterval: Duration.Input
172
+ readonly decodeEvent: (event: unknown) => Effect.Effect<unknown, Rejected>
173
+ readonly decodeInput: (input: unknown) => Effect.Effect<unknown, Rejected>
174
+ }
175
+
176
+ const adapterMeta = new WeakMap<object, AdapterMeta>()
177
+
178
+ /** Reads the internal metadata of a `ClusterMachine` created by {@link make}. */
179
+ export const getAdapterMeta = (adapter: object): AdapterMeta => {
180
+ const meta = adapterMeta.get(adapter)
181
+ if (meta === undefined) {
182
+ throw new Error("Expected a ClusterMachine created by ClusterMachine.make")
183
+ }
184
+ return meta
185
+ }
186
+
100
187
  export const make = <
101
188
  const Type extends string,
102
189
  States extends Machine.Machine.StateSchemas,
@@ -105,8 +192,6 @@ export const make = <
105
192
  UnhandledStates extends Machine.Machine.StateIdentifier<States>,
106
193
  E,
107
194
  R,
108
- InitialE,
109
- InitialR,
110
195
  FinalStates extends Machine.Machine.StateIdentifier<States>,
111
196
  Output,
112
197
  Emits extends ReadonlyArray<Machine.Machine.TaggedSchema>,
@@ -123,8 +208,6 @@ export const make = <
123
208
  UnhandledStates,
124
209
  E,
125
210
  R,
126
- InitialE,
127
- InitialR,
128
211
  FinalStates,
129
212
  Output,
130
213
  Emits,
@@ -136,8 +219,10 @@ export const make = <
136
219
  & Machine.Machine.RootCompatible<ParentEvents>,
137
220
  options: {
138
221
  readonly version: string
222
+ readonly readInterval?: Duration.Input | undefined
223
+ readonly shardGroup?: ((entityId: EntityId.EntityId) => string) | undefined
139
224
  },
140
- ...input: [...Machine.Machine.InputArgs<Input>]
225
+ ...input: readonly [] | [...Machine.Machine.InputArgs<Input>]
141
226
  ): ClusterMachine<
142
227
  Type,
143
228
  Machine.Machine<
@@ -147,8 +232,6 @@ export const make = <
147
232
  UnhandledStates,
148
233
  E,
149
234
  R,
150
- InitialE,
151
- InitialR,
152
235
  FinalStates,
153
236
  Output,
154
237
  Emits,
@@ -156,173 +239,305 @@ export const make = <
156
239
  InputEvents,
157
240
  ParentEvents
158
241
  >,
159
- | ExcludeCompatibleRuntime<
160
- Machine.ExecutionServices<R | InitialR>,
161
- Machine.Machine.EventOf<Events>,
162
- Machine.Machine.EmittedEventOf<Emits>
163
- >
242
+ | Exclude<R, Machine.InvocationSupport<"Child"> | Machine.ChildMachineRuntime>
164
243
  | Machine.Machine.SnapshotDecodingServices<States>
165
244
  | Machine.Machine.SnapshotEncodingServices<States>
166
245
  > => {
167
- type M = Machine.Machine<
168
- States,
169
- Events,
170
- Input,
171
- UnhandledStates,
172
- E,
173
- R,
174
- InitialE,
175
- InitialR,
176
- FinalStates,
177
- Output,
178
- Emits,
179
- OutputStates,
180
- InputEvents
181
- >
182
- const rootMachine = machine as M & EnsureExecutable<States, UnhandledStates, OutputStates>
183
- const eventSchema = Schema.Union(Protocol.inputEventSchemas(machine) as MachineEvents<M>)
246
+ // The public type of the entity leaves out the RPCs that only machines send.
247
+ return build(type, machine, options, input, undefined) as never
248
+ }
249
+
250
+ /** A request to an entity, as its handlers see it. */
251
+ interface Request {
252
+ readonly requestId: Snowflake
253
+ readonly payload: any
254
+ }
255
+
256
+ /** The parent of a child adapter. */
257
+ interface Parent {
258
+ readonly protocol: ClusterTarget.Protocol
259
+ readonly childId: string
260
+ /** Whether an invocation of the parent takes the snapshots of the child. */
261
+ readonly snapshots: boolean
262
+ }
263
+
264
+ /** Entity layer tuning options forwarded to `Entity.toLayer`. */
265
+ interface EntityLayerOptions {
266
+ readonly maxIdleTime?: Duration.Input | undefined
267
+ readonly concurrency?: number | "unbounded" | undefined
268
+ readonly mailboxCapacity?: number | "unbounded" | undefined
269
+ readonly mailboxMetrics?: boolean | undefined
270
+ readonly disableFatalDefects?: boolean | undefined
271
+ readonly defectRetryPolicy?: Schedule.Schedule<any, unknown> | undefined
272
+ readonly spanAttributes?: Record<string, string> | undefined
273
+ }
274
+
275
+ const pickEntityLayerOptions = (
276
+ options: LayerOptions<any, any, any> | undefined
277
+ ): EntityLayerOptions | undefined => {
278
+ if (options === undefined) return undefined
279
+ const out: {
280
+ maxIdleTime?: Duration.Input
281
+ concurrency?: number | "unbounded"
282
+ mailboxCapacity?: number | "unbounded"
283
+ mailboxMetrics?: boolean
284
+ disableFatalDefects?: boolean
285
+ defectRetryPolicy?: Schedule.Schedule<any, unknown>
286
+ spanAttributes?: Record<string, string>
287
+ } = {}
288
+ let hasAny = false
289
+ if (options.maxIdleTime !== undefined) {
290
+ out.maxIdleTime = options.maxIdleTime
291
+ hasAny = true
292
+ }
293
+ if (options.concurrency !== undefined) {
294
+ out.concurrency = options.concurrency
295
+ hasAny = true
296
+ }
297
+ if (options.mailboxCapacity !== undefined) {
298
+ out.mailboxCapacity = options.mailboxCapacity
299
+ hasAny = true
300
+ }
301
+ if (options.mailboxMetrics !== undefined) {
302
+ out.mailboxMetrics = options.mailboxMetrics
303
+ hasAny = true
304
+ }
305
+ if (options.disableFatalDefects !== undefined) {
306
+ out.disableFatalDefects = options.disableFatalDefects
307
+ hasAny = true
308
+ }
309
+ if (options.defectRetryPolicy !== undefined) {
310
+ out.defectRetryPolicy = options.defectRetryPolicy
311
+ hasAny = true
312
+ }
313
+ if (options.spanAttributes !== undefined) {
314
+ out.spanAttributes = options.spanAttributes
315
+ hasAny = true
316
+ }
317
+ return hasAny ? out : undefined
318
+ }
319
+
320
+ /** An adapter, and the adapters of the child machines that its states invoke. */
321
+ interface Built {
322
+ readonly machine: Machine.Machine.Any
323
+ readonly entity: Entity.Entity<string, any>
324
+ readonly protocol: ClusterTarget.Protocol
325
+ readonly client: Effect.Effect<(entityId: string) => Client<any>, never, Sharding.Sharding>
326
+ readonly target: (entityId: string) => ClusterTarget.Target
327
+ readonly toLayer: (layerOptions?: LayerOptions<any, any, any>) => Layer.Layer<never, never, any>
328
+ }
329
+
330
+ const build = (
331
+ type: string,
332
+ machine: Machine.Machine.Any,
333
+ options: {
334
+ readonly version: string
335
+ readonly readInterval?: Duration.Input | undefined
336
+ readonly shardGroup?: ((entityId: EntityId.EntityId) => string) | undefined
337
+ },
338
+ input: ReadonlyArray<unknown>,
339
+ parent: Parent | undefined
340
+ ): Built => {
341
+ const eventSchema = Schema.Union(Protocol.inputEventSchemas(machine))
184
342
  const rpc = Rpc.make("send", {
185
343
  payload: eventSchema,
186
344
  success: SendResult
187
345
  })
188
- .annotate(ClusterSchema.Persisted, true) as SendRpc<MachineEvents<M>>
189
- const entity = Entity.make(type, [rpc])
190
- const machineId = machine.id ?? type
346
+ .annotate(ClusterSchema.Persisted, true)
347
+ // An event that another machine sends, which nobody waits for.
348
+ const deliver = Rpc.make("deliver", { payload: eventSchema }).annotate(ClusterSchema.Persisted, true)
349
+ // `deliver` carries an event another machine sends, `wake` is the delayed
350
+ // message of a long timer, `start` and `stop` come from the parent of a
351
+ // child, and `ended` and `snapshot` from a child. Only machines send them.
352
+ const rawEntity = Entity.make(type, [
353
+ rpc,
354
+ deliver,
355
+ ClusterWake.WakeRpc,
356
+ ClusterChild.makeStartRpc(machine.input),
357
+ ClusterChild.StopRpc,
358
+ ClusterChild.EndedRpc,
359
+ ClusterChild.SnapshotRpc
360
+ ])
361
+ const entity = options.shardGroup === undefined
362
+ ? rawEntity
363
+ : rawEntity.annotate(ClusterSchema.ShardGroup, options.shardGroup)
364
+ const definitionId = machine.id ?? type
365
+ const publicTags: ReadonlySet<PropertyKey> = new Set(Reflect.ownKeys(machine.events))
191
366
 
192
- const toLayer: ClusterMachine<
193
- Type,
194
- M,
195
- | ExcludeCompatibleRuntime<
196
- Machine.ExecutionServices<R | InitialR>,
197
- Machine.Machine.EventOf<Events>,
198
- Machine.Machine.EmittedEventOf<Emits>
199
- >
200
- | Machine.Machine.SnapshotDecodingServices<States>
201
- | Machine.Machine.SnapshotEncodingServices<States>
202
- >["toLayer"] = (layerOptions) =>
203
- entity.toLayer(
204
- Effect.gen(function*() {
205
- const storage = yield* Storage
206
- const messageStorage = yield* MessageStorage.MessageStorage
367
+ type EntityClient = ReturnType<Effect.Success<typeof entity.client>>
207
368
 
208
- const handle = Effect.fnUntraced(function*(request: Entity.Request<SendRpc<MachineEvents<M>>>) {
209
- if (hasInvokes(machine)) {
210
- return yield* fail(
211
- "UnsupportedProcessLocal",
212
- "Machine invoke configurations are process-local and cannot be restored"
213
- )
214
- }
369
+ const sendDecodedThroughClient = (
370
+ rpc: EntityClient,
371
+ decoded: unknown
372
+ ): Effect.Effect<void, Rejected | ClientError> =>
373
+ // The cast drops the encoding services of the event schemas, as the
374
+ // layer drops their decoding services.
375
+ (rpc.send(decoded as never) as Effect.Effect<typeof SendResult.Type, ClientError>).pipe(
376
+ Effect.flatMap((result) => result._tag === "Accepted" ? Effect.void : Effect.fail(result))
377
+ )
215
378
 
216
- const loaded = yield* storage.load(request.address, request.requestId).pipe(
217
- Effect.mapError((error) => reject("PersistenceFailure", String(error.cause)))
218
- )
219
- let current: Machine.Machine.Snapshot<States> | undefined
220
- const emitted: Array<Machine.Machine.EmittedEventOf<MachineEmits<M>>> = []
379
+ const sendThroughClient = (rpc: EntityClient, event: unknown): Effect.Effect<void, Rejected | ClientError> =>
380
+ decodeInputEvent(machine, publicTags, event).pipe(
381
+ Effect.flatMap((decoded) => sendDecodedThroughClient(rpc, decoded))
382
+ )
221
383
 
222
- if (Option.isSome(loaded.checkpoint)) {
223
- const checkpoint = loaded.checkpoint.value
224
- if (loaded.processed) {
225
- return new Accepted({})
226
- }
227
- if (checkpoint.machineId !== machineId) {
228
- return yield* fail(
229
- "MachineIdMismatch",
230
- `Expected machine id ${machineId}, received ${checkpoint.machineId}`
231
- )
232
- }
233
- if (checkpoint.version !== options.version) {
234
- return yield* fail(
235
- "VersionMismatch",
236
- `Expected version ${options.version}, received ${checkpoint.version}`
237
- )
238
- }
239
- current = yield* internalMachine.decodeSnapshot(rootMachine, checkpoint.snapshot).pipe(
240
- Effect.mapError((error) => reject("InvalidCheckpoint", String(error.cause)))
241
- )
242
- } else if (loaded.processed) {
243
- return yield* fail("InvalidCheckpoint", "The request was recorded without a checkpoint")
244
- }
245
-
246
- if (current === undefined) {
247
- const initial = yield* internalMachine.planInitial(rootMachine, ...input)
248
- if (initial.commands.length > 0) {
249
- return yield* fail(
250
- "UnsupportedProcessLocal",
251
- "Machine commands require a managed local process"
252
- )
253
- }
254
- current = initial.state
255
- emitted.push(...initial.emittedEvents)
256
- }
384
+ const startThroughClient = (
385
+ rpc: EntityClient,
386
+ args: ReadonlyArray<unknown>
387
+ ): Effect.Effect<void, Rejected | ClientError> =>
388
+ decodeMachineInput(machine, args[0]).pipe(
389
+ Effect.flatMap((decoded) =>
390
+ rpc.start(
391
+ (machine.input === undefined ? {} : { input: decoded }) as never
392
+ ) as Effect.Effect<typeof SendResult.Type, ClientError>
393
+ ),
394
+ Effect.flatMap((result) => result._tag === "Accepted" ? Effect.void : Effect.fail(result))
395
+ )
257
396
 
258
- if (!internalMachine.isFinal(rootMachine, current)) {
259
- const planned = yield* internalMachine.plan(rootMachine, current, request.payload)
260
- if (planned.commands.length > 0) {
261
- return yield* fail(
262
- "UnsupportedProcessLocal",
263
- "Machine commands require a managed local process"
264
- )
265
- }
266
- current = planned.next
267
- emitted.push(...planned.emittedEvents)
268
- }
397
+ const protocol: ClusterTarget.Protocol = {
398
+ entity,
399
+ machine,
400
+ definitionId,
401
+ version: options.version,
402
+ decode: (event) => decodeInputEvent(machine, publicTags, event),
403
+ decodeEvent: (event) => decodeInputEventError(machine, publicTags, event),
404
+ send: (entityId, event) =>
405
+ Effect.flatMap(entity.client, (makeEntityClient) => sendDecodedThroughClient(makeEntityClient(entityId), event))
406
+ }
407
+ const target = (entityId: string): ClusterTarget.Target => new ClusterTarget.Target(protocol, entityId)
269
408
 
270
- const encoded = yield* internalMachine.encodeSnapshot(rootMachine, current).pipe(
271
- Effect.mapError((error) => reject("SnapshotEncodeFailure", String(error.cause)))
272
- )
273
- if (emitted.length > 0 && layerOptions?.enqueue === undefined) {
274
- return yield* fail("EmissionFailure", "No durable enqueue handler was configured")
275
- }
276
- const committed = yield* storage.commit(request.address, {
277
- machineId,
278
- version: options.version,
279
- requestId: request.requestId,
280
- snapshot: encoded
281
- }).pipe(
282
- Effect.mapError((error) => reject("PersistenceFailure", String(error.cause)))
283
- )
284
- if (committed._tag === "Duplicate") {
285
- return new Accepted({})
409
+ // Each child runs as an entity of its own, with the version and shard group of its parent.
410
+ const snapshots = ClusterChild.snapshotsOf(toImpl(machine).handlers)
411
+ const children = Array.from(
412
+ ClusterChild.childrenOf(toImpl(machine).handlers),
413
+ ([childId, child]) => {
414
+ const childShardGroup = options.shardGroup === undefined
415
+ ? undefined
416
+ : (childEntityId: EntityId.EntityId) => {
417
+ const parentId = ClusterChild.parentEntityIdOf(childEntityId, childId)
418
+ return options.shardGroup!(parentId === undefined ? childEntityId : EntityId.make(parentId))
419
+ }
420
+ return [
421
+ childId,
422
+ build(
423
+ ClusterChild.entityTypeOf(type, childId),
424
+ child.machine,
425
+ { version: options.version, shardGroup: childShardGroup },
426
+ [],
427
+ {
428
+ protocol,
429
+ childId,
430
+ snapshots: snapshots.has(childId)
286
431
  }
432
+ )
433
+ ] as const
434
+ }
435
+ )
436
+ const childProtocols: ReadonlyMap<string, ClusterTarget.Protocol> = new Map(
437
+ children.map(([childId, child]) => [childId, child.protocol])
438
+ )
287
439
 
288
- if (layerOptions?.enqueue !== undefined) {
289
- yield* Effect.forEach(emitted, layerOptions.enqueue, { discard: true }).pipe(
290
- Effect.mapError((error) => reject("EmissionFailure", String(error)))
291
- )
440
+ const toLayer: Built["toLayer"] = (layerOptions) => {
441
+ const entityLayerOptions = pickEntityLayerOptions(layerOptions)
442
+ // Each live entity builds its own handlers, and so owns its own instance.
443
+ const layer = entity.toLayer(
444
+ Effect.gen(function*() {
445
+ const address = yield* Entity.CurrentAddress
446
+ const messageStorage = yield* MessageStorage.MessageStorage
447
+ const sharding = yield* Sharding.Sharding
448
+ const save = ClusterTarget.makeSave({ messageStorage, sharding })
449
+ const parentEntityId = parent && ClusterChild.parentEntityIdOf(address.entityId, parent.childId)
450
+ const instance = yield* ClusterInstance.make<any>({
451
+ machine,
452
+ definitionId,
453
+ version: options.version,
454
+ input,
455
+ address,
456
+ storage: yield* Storage,
457
+ messageStorage,
458
+ // A child has no observers, so what it emits reaches nobody.
459
+ enqueue: parent === undefined ? layerOptions?.enqueue : () => Effect.void,
460
+ onCommit: parent === undefined ? layerOptions?.onCommit : undefined,
461
+ keepAlive: yield* makeKeepAlive,
462
+ wake: {
463
+ threshold: yield* ClusterWake.threshold,
464
+ save: ClusterWake.makeSave({ address, messageStorage, sharding })
465
+ },
466
+ sends: {
467
+ self: target(address.entityId),
468
+ save: (sent) => save(sent.target, "deliver", sent.event),
469
+ poll: sharding.pollStorage
470
+ },
471
+ children: {
472
+ protocols: childProtocols,
473
+ save,
474
+ address: (target) => ClusterTarget.addressOf(sharding, target),
475
+ snapshots: parent?.snapshots ?? false,
476
+ // Saved as a step saves it, so the child takes it after its start.
477
+ dispatch: (target, tag, payload) => Effect.andThen(save(target, tag, payload), sharding.pollStorage),
478
+ parent: parent === undefined || parentEntityId === undefined
479
+ ? undefined
480
+ : new ClusterTarget.Target(parent.protocol, parentEntityId)
292
481
  }
293
- return new Accepted({})
294
482
  })
483
+ const handlers: Record<string, (request: Request) => Effect.Effect<unknown, never, any>> = {
484
+ send: (request) => instance.apply({ requestId: request.requestId, event: request.payload }),
485
+ deliver: (request) => instance.deliver({ requestId: request.requestId, event: request.payload }),
486
+ wake: (request) => instance.wake(request.payload),
487
+ start: (request) => instance.start({ requestId: request.requestId, input: request.payload.input }),
488
+ stop: (request) => instance.stop(request.requestId),
489
+ ended: (request) => instance.childEnded(request.payload.entityId),
490
+ snapshot: (request) =>
491
+ instance.childSnapshot({
492
+ requestId: request.requestId,
493
+ entityId: request.payload.entityId,
494
+ snapshot: request.payload.snapshot
495
+ })
496
+ }
497
+ return entity.of(handlers as never)
498
+ }),
499
+ entityLayerOptions
500
+ )
501
+ return children.length === 0
502
+ ? layer
503
+ : Layer.mergeAll(layer, ...children.map(([, child]) => child.toLayer(entityLayerOptions)))
504
+ }
295
505
 
296
- return entity.of({
297
- send: (request) =>
298
- messageStorage.withTransaction(
299
- handle(request).pipe(
300
- Effect.catchCause((cause) =>
301
- Cause.hasInterrupts(cause)
302
- ? Effect.failCause(cause)
303
- : Effect.fail(rejectionFromCause(cause))
304
- )
305
- )
306
- ).pipe(
307
- Effect.catchCause((cause) => {
308
- if (Cause.hasInterrupts(cause)) {
309
- return Effect.failCause(cause)
310
- }
311
- const error = Cause.findErrorOption(cause)
312
- return Effect.succeed(
313
- Option.isSome(error) && error.value instanceof Rejected
314
- ? error.value
315
- : reject("PersistenceFailure", messageFromCause(cause))
316
- )
317
- })
318
- ) as any
319
- })
320
- }) as any
321
- ) as any
506
+ const client = Effect.gen(function*() {
507
+ const makeEntityClient = yield* entity.client
508
+ const sharding = yield* Sharding.Sharding
509
+ return (entityId: string): Client<any> => {
510
+ const rpc = makeEntityClient(entityId)
511
+ const id = EntityId.make(entityId)
512
+ const reader = ClusterRead.make({
513
+ machine,
514
+ definitionId,
515
+ version: options.version,
516
+ address: EntityAddress.make({
517
+ shardId: sharding.getShardId(id, entity.getShardGroup(id)),
518
+ entityType: entity.type,
519
+ entityId: id
520
+ }),
521
+ interval: options.readInterval ?? "1 second"
522
+ })
523
+ return {
524
+ entityId,
525
+ ...reader,
526
+ start: (...args: ReadonlyArray<unknown>) => startThroughClient(rpc, args),
527
+ send: (event) => sendThroughClient(rpc, event)
528
+ }
529
+ }
530
+ })
322
531
 
323
- return {
532
+ const built: Built = { machine, entity, protocol, client, target, toLayer }
533
+ adapterMeta.set(built, {
534
+ type,
324
535
  machine,
325
- entity,
326
- toLayer
327
- }
536
+ definitionId,
537
+ version: options.version,
538
+ readInterval: options.readInterval ?? "1 second",
539
+ decodeEvent: (event) => decodeInputEvent(machine, publicTags, event),
540
+ decodeInput: (value) => decodeMachineInput(machine, value)
541
+ })
542
+ return built
328
543
  }