rivetkit 0.0.0-active-actors-fix-active-count.253e406 → 0.0.0-bisect-sync-sqlite-1.910d1c7

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 (303) hide show
  1. package/dist/browser/client.d.ts +1286 -89
  2. package/dist/browser/client.js +1699 -704
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.d.ts +252 -129
  5. package/dist/browser/inspector/client.js +2083 -236
  6. package/dist/browser/inspector/client.js.map +1 -1
  7. package/dist/tsup/actor/errors.cjs +8 -2
  8. package/dist/tsup/actor/errors.cjs.map +1 -1
  9. package/dist/tsup/actor/errors.d.cts +1 -1
  10. package/dist/tsup/actor/errors.d.ts +1 -1
  11. package/dist/tsup/actor/errors.js +7 -1
  12. package/dist/tsup/agent-os/index.cjs +3 -2289
  13. package/dist/tsup/agent-os/index.cjs.map +1 -1
  14. package/dist/tsup/agent-os/index.d.cts +1 -1813
  15. package/dist/tsup/agent-os/index.d.ts +1 -1813
  16. package/dist/tsup/agent-os/index.js +3 -2289
  17. package/dist/tsup/agent-os/index.js.map +1 -1
  18. package/dist/tsup/chunk-2JJU7IQ7.cjs +14 -0
  19. package/dist/tsup/chunk-2JJU7IQ7.cjs.map +1 -0
  20. package/dist/tsup/{chunk-DZJZLZ4R.js → chunk-2MXBZGUP.js} +2 -2
  21. package/dist/tsup/{chunk-L4FVS7GY.js → chunk-47IS5ZFI.js} +6 -6
  22. package/dist/tsup/chunk-47IS5ZFI.js.map +1 -0
  23. package/dist/tsup/{chunk-DXWOGCZY.js → chunk-5XWY5CBA.js} +70 -8
  24. package/dist/tsup/chunk-5XWY5CBA.js.map +1 -0
  25. package/dist/tsup/{chunk-OQEEZDIK.cjs → chunk-6XVNZKKP.cjs} +506 -31
  26. package/dist/tsup/chunk-6XVNZKKP.cjs.map +1 -0
  27. package/dist/tsup/{chunk-3YY5S6TV.js → chunk-A2CF6PFH.js} +20 -12
  28. package/dist/tsup/chunk-A2CF6PFH.js.map +1 -0
  29. package/dist/tsup/{chunk-WQ4HNA4W.cjs → chunk-AQJFKHBK.cjs} +276 -27
  30. package/dist/tsup/chunk-AQJFKHBK.cjs.map +1 -0
  31. package/dist/tsup/chunk-DPWLASMC.cjs +244 -0
  32. package/dist/tsup/chunk-DPWLASMC.cjs.map +1 -0
  33. package/dist/tsup/{chunk-VUF2YEF4.cjs → chunk-DYJOU3MF.cjs} +10 -10
  34. package/dist/tsup/chunk-DYJOU3MF.cjs.map +1 -0
  35. package/dist/tsup/{chunk-7WXCRV25.cjs → chunk-ELZ6MT3V.cjs} +18 -11
  36. package/dist/tsup/chunk-ELZ6MT3V.cjs.map +1 -0
  37. package/dist/tsup/chunk-HYIVSH5X.js +244 -0
  38. package/dist/tsup/chunk-HYIVSH5X.js.map +1 -0
  39. package/dist/tsup/{chunk-T6YVRM4K.js → chunk-IHEO5OT3.js} +275 -26
  40. package/dist/tsup/chunk-IHEO5OT3.js.map +1 -0
  41. package/dist/tsup/chunk-IWACVNN5.js +14 -0
  42. package/dist/tsup/chunk-IWACVNN5.js.map +1 -0
  43. package/dist/tsup/{chunk-PCBNKI2J.js → chunk-JTHHCZCZ.js} +24 -1
  44. package/dist/tsup/chunk-JTHHCZCZ.js.map +1 -0
  45. package/dist/tsup/{chunk-V4JUWAT6.js → chunk-K3AJOPSF.js} +498 -23
  46. package/dist/tsup/chunk-K3AJOPSF.js.map +1 -0
  47. package/dist/tsup/{chunk-2NDZ7JCR.cjs → chunk-KVFIONKQ.cjs} +25 -2
  48. package/dist/tsup/chunk-KVFIONKQ.cjs.map +1 -0
  49. package/dist/tsup/{chunk-QAZLM4WT.cjs → chunk-MGI2VVF6.cjs} +45 -9
  50. package/dist/tsup/chunk-MGI2VVF6.cjs.map +1 -0
  51. package/dist/tsup/{chunk-QNLGOTQP.js → chunk-NPHTIUUJ.js} +1291 -420
  52. package/dist/tsup/chunk-NPHTIUUJ.js.map +1 -0
  53. package/dist/tsup/{chunk-7GKQJFSB.cjs → chunk-POCSZXPQ.cjs} +72 -10
  54. package/dist/tsup/chunk-POCSZXPQ.cjs.map +1 -0
  55. package/dist/tsup/{chunk-LD5YASJU.cjs → chunk-RTWH3AX3.cjs} +19 -11
  56. package/dist/tsup/chunk-RTWH3AX3.cjs.map +1 -0
  57. package/dist/tsup/{chunk-ARRBQTAR.cjs → chunk-X76BM5JS.cjs} +1420 -549
  58. package/dist/tsup/chunk-X76BM5JS.cjs.map +1 -0
  59. package/dist/tsup/{chunk-AGBP757I.js → chunk-X7SYKFPM.js} +16 -9
  60. package/dist/tsup/chunk-X7SYKFPM.js.map +1 -0
  61. package/dist/tsup/{chunk-GKAMEBTZ.cjs → chunk-XLDJSZ3B.cjs} +3 -3
  62. package/dist/tsup/{chunk-GKAMEBTZ.cjs.map → chunk-XLDJSZ3B.cjs.map} +1 -1
  63. package/dist/tsup/{chunk-KIWH5H3K.js → chunk-ZOVJDAOW.js} +44 -8
  64. package/dist/tsup/chunk-ZOVJDAOW.js.map +1 -0
  65. package/dist/tsup/client/mod.cjs +8 -9
  66. package/dist/tsup/client/mod.cjs.map +1 -1
  67. package/dist/tsup/client/mod.d.cts +33 -7
  68. package/dist/tsup/client/mod.d.ts +33 -7
  69. package/dist/tsup/client/mod.js +7 -8
  70. package/dist/tsup/common/log.cjs +5 -3
  71. package/dist/tsup/common/log.cjs.map +1 -1
  72. package/dist/tsup/common/log.d.cts +5 -1
  73. package/dist/tsup/common/log.d.ts +5 -1
  74. package/dist/tsup/common/log.js +6 -4
  75. package/dist/tsup/common/websocket.cjs +4 -4
  76. package/dist/tsup/common/websocket.js +3 -3
  77. package/dist/tsup/{config-nlTlOKaE.d.cts → config-BMGUEKMZ.d.cts} +1252 -75
  78. package/dist/tsup/config-CBTr4IhE.d.cts +224 -0
  79. package/dist/tsup/config-CBTr4IhE.d.ts +224 -0
  80. package/dist/tsup/{config-D7ykAntK.d.ts → config-iBpXyITj.d.ts} +1252 -75
  81. package/dist/tsup/context-hyVakgnU.d.ts +136 -0
  82. package/dist/tsup/context-qfvLuF0P.d.cts +136 -0
  83. package/dist/tsup/db/drizzle.cjs +127 -67
  84. package/dist/tsup/db/drizzle.cjs.map +1 -1
  85. package/dist/tsup/db/drizzle.d.cts +8 -4
  86. package/dist/tsup/db/drizzle.d.ts +8 -4
  87. package/dist/tsup/db/drizzle.js +127 -67
  88. package/dist/tsup/db/drizzle.js.map +1 -1
  89. package/dist/tsup/db/mod.cjs +6 -124
  90. package/dist/tsup/db/mod.cjs.map +1 -1
  91. package/dist/tsup/db/mod.d.cts +12 -4
  92. package/dist/tsup/db/mod.d.ts +12 -4
  93. package/dist/tsup/db/mod.js +5 -123
  94. package/dist/tsup/db/mod.js.map +1 -1
  95. package/dist/tsup/dynamic/mod.cjs +24 -0
  96. package/dist/tsup/dynamic/mod.cjs.map +1 -0
  97. package/dist/tsup/dynamic/mod.d.cts +39 -0
  98. package/dist/tsup/dynamic/mod.d.ts +39 -0
  99. package/dist/tsup/dynamic/mod.js +24 -0
  100. package/dist/tsup/dynamic/mod.js.map +1 -0
  101. package/dist/tsup/inspector/mod.cjs +47 -12
  102. package/dist/tsup/inspector/mod.cjs.map +1 -1
  103. package/dist/tsup/inspector/mod.d.cts +26 -136
  104. package/dist/tsup/inspector/mod.d.ts +26 -136
  105. package/dist/tsup/inspector/mod.js +46 -11
  106. package/dist/tsup/inspector/mod.js.map +1 -1
  107. package/dist/tsup/inspector/workflow.cjs +21 -0
  108. package/dist/tsup/inspector/workflow.cjs.map +1 -0
  109. package/dist/tsup/inspector/workflow.d.cts +144 -0
  110. package/dist/tsup/inspector/workflow.d.ts +144 -0
  111. package/dist/tsup/inspector/workflow.js +21 -0
  112. package/dist/tsup/inspector/workflow.js.map +1 -0
  113. package/dist/tsup/inspector-tab/mod.cjs +162 -0
  114. package/dist/tsup/inspector-tab/mod.cjs.map +1 -0
  115. package/dist/tsup/inspector-tab/mod.d.cts +242 -0
  116. package/dist/tsup/inspector-tab/mod.d.ts +242 -0
  117. package/dist/tsup/inspector-tab/mod.js +162 -0
  118. package/dist/tsup/inspector-tab/mod.js.map +1 -0
  119. package/dist/tsup/mod.cjs +3527 -753
  120. package/dist/tsup/mod.cjs.map +1 -1
  121. package/dist/tsup/mod.d.cts +11 -7
  122. package/dist/tsup/mod.d.ts +11 -7
  123. package/dist/tsup/mod.js +3468 -694
  124. package/dist/tsup/mod.js.map +1 -1
  125. package/dist/tsup/test/mod.cjs +26 -21
  126. package/dist/tsup/test/mod.cjs.map +1 -1
  127. package/dist/tsup/test/mod.d.cts +7 -5
  128. package/dist/tsup/test/mod.d.ts +7 -5
  129. package/dist/tsup/test/mod.js +25 -20
  130. package/dist/tsup/test/mod.js.map +1 -1
  131. package/dist/tsup/unstable/migrations.cjs +101 -0
  132. package/dist/tsup/unstable/migrations.cjs.map +1 -0
  133. package/dist/tsup/unstable/migrations.d.cts +29 -0
  134. package/dist/tsup/unstable/migrations.d.ts +29 -0
  135. package/dist/tsup/unstable/migrations.js +101 -0
  136. package/dist/tsup/unstable/migrations.js.map +1 -0
  137. package/dist/tsup/{utils-DVekpm4I.d.ts → utils-3rsE0JvI.d.cts} +26 -2
  138. package/dist/tsup/{utils-DVekpm4I.d.cts → utils-3rsE0JvI.d.ts} +26 -2
  139. package/dist/tsup/utils-C1O-SklO.d.ts +162 -0
  140. package/dist/tsup/utils-C6b0aYUM.d.cts +162 -0
  141. package/dist/tsup/utils.cjs +7 -3
  142. package/dist/tsup/utils.cjs.map +1 -1
  143. package/dist/tsup/utils.d.cts +4 -147
  144. package/dist/tsup/utils.d.ts +4 -147
  145. package/dist/tsup/utils.js +6 -2
  146. package/dist/tsup/workflow/mod.cjs +557 -410
  147. package/dist/tsup/workflow/mod.cjs.map +1 -1
  148. package/dist/tsup/workflow/mod.d.cts +11 -9
  149. package/dist/tsup/workflow/mod.d.ts +11 -9
  150. package/dist/tsup/workflow/mod.js +551 -404
  151. package/dist/tsup/workflow/mod.js.map +1 -1
  152. package/package.json +67 -18
  153. package/src/actor/actions.ts +155 -0
  154. package/src/actor/config.ts +679 -101
  155. package/src/actor/contexts/index.ts +9 -2
  156. package/src/actor/definition.ts +75 -26
  157. package/src/actor/errors.ts +107 -8
  158. package/src/actor/keys.ts +87 -1
  159. package/src/actor/mod.ts +36 -20
  160. package/src/actor/schema.ts +6 -2
  161. package/src/actor/tracing.ts +28 -0
  162. package/src/agent-os/index.ts +5 -64
  163. package/src/client/actor-common.ts +84 -54
  164. package/src/client/actor-conn.ts +231 -68
  165. package/src/client/actor-handle.ts +283 -89
  166. package/src/client/actor-query.ts +13 -6
  167. package/src/client/auth.ts +37 -0
  168. package/src/client/client.ts +182 -21
  169. package/src/client/config.ts +28 -3
  170. package/src/client/errors.ts +15 -2
  171. package/src/client/lifecycle-errors.ts +63 -5
  172. package/src/client/mod.ts +10 -0
  173. package/src/client/outbound-telemetry.ts +66 -0
  174. package/src/client/query.ts +3 -1
  175. package/src/client/queue.ts +13 -3
  176. package/src/client/raw-utils.ts +59 -14
  177. package/src/client/resolve-gateway-target.ts +3 -1
  178. package/src/client/retry-budget.ts +81 -0
  179. package/src/client/token-provider.ts +93 -0
  180. package/src/client/utils.ts +22 -9
  181. package/src/common/actor-router-consts.ts +6 -0
  182. package/src/common/actor-telemetry-context.ts +19 -0
  183. package/src/common/actor-websocket.ts +3 -1
  184. package/src/common/bare/actor-persist/v1.ts +205 -163
  185. package/src/common/bare/actor-persist/v2.ts +265 -213
  186. package/src/common/bare/actor-persist/v3.ts +176 -172
  187. package/src/common/bare/actor-persist/v4.ts +254 -253
  188. package/src/common/bare/generated/inspector/v5.ts +1016 -0
  189. package/src/common/bare/generated/inspector/v6.ts +1367 -0
  190. package/src/common/bare/transport/v1.ts +694 -542
  191. package/src/common/client-protocol-versioned.ts +66 -64
  192. package/src/common/database/config.ts +175 -9
  193. package/src/common/database/mod.ts +262 -77
  194. package/src/common/database/native-database.ts +442 -20
  195. package/src/common/database/shared.ts +25 -0
  196. package/src/common/encoding.ts +278 -34
  197. package/src/common/engine.ts +28 -1
  198. package/src/common/eventsource.ts +1 -1
  199. package/src/common/fetch-like.ts +63 -0
  200. package/src/common/inline-websocket-adapter.ts +14 -13
  201. package/src/common/inspector-transport.ts +12 -2
  202. package/src/common/log.ts +15 -8
  203. package/src/common/otel-context.ts +99 -0
  204. package/src/common/router.ts +14 -18
  205. package/src/common/utils.ts +8 -169
  206. package/src/common/websocket-interface.ts +1 -1
  207. package/src/db/drizzle.ts +182 -80
  208. package/src/db/mod.ts +5 -1
  209. package/src/devtools-loader/index.ts +4 -7
  210. package/src/devtools-loader/serve-devtools.ts +26 -0
  211. package/src/dynamic/instance.ts +32 -0
  212. package/src/dynamic/internal.ts +50 -0
  213. package/src/dynamic/isolate-runtime.ts +64 -0
  214. package/src/dynamic/mod.ts +32 -0
  215. package/src/engine-api/actors.ts +15 -3
  216. package/src/engine-client/actor-http-client.ts +37 -22
  217. package/src/engine-client/actor-websocket-client.ts +37 -9
  218. package/src/engine-client/api-endpoints.ts +128 -5
  219. package/src/engine-client/api-utils.ts +2 -2
  220. package/src/engine-client/driver.ts +21 -16
  221. package/src/engine-client/mod.ts +280 -111
  222. package/src/engine-client/ws-proxy.ts +9 -4
  223. package/src/inspector/client.browser.ts +127 -15
  224. package/src/inspector/mod.ts +2 -4
  225. package/src/inspector/workflow.ts +61 -0
  226. package/src/inspector-tab/mod.ts +301 -0
  227. package/src/registry/config/envoy.ts +3 -20
  228. package/src/registry/config/index.ts +91 -74
  229. package/src/registry/index.ts +702 -80
  230. package/src/registry/napi-runtime.ts +643 -42
  231. package/src/registry/native-http.ts +225 -0
  232. package/src/registry/native-validation.ts +10 -12
  233. package/src/registry/native.ts +1881 -582
  234. package/src/registry/run-handler-coordinator.ts +219 -0
  235. package/src/registry/runtime.ts +441 -7
  236. package/src/registry/wasm-runtime.ts +516 -23
  237. package/src/registry/write-through-proxy.ts +141 -0
  238. package/src/serde.ts +2 -2
  239. package/src/serverless/configure.ts +18 -7
  240. package/src/test/mod.ts +2 -17
  241. package/src/test/ready.ts +22 -0
  242. package/src/unstable/migrations.ts +141 -0
  243. package/src/utils/endpoint-parser.ts +1 -1
  244. package/src/utils/env-vars.ts +50 -2
  245. package/src/utils/node.ts +44 -28
  246. package/src/utils/router.ts +1 -1
  247. package/src/utils.ts +4 -2
  248. package/src/workflow/context.ts +703 -242
  249. package/src/workflow/driver.ts +284 -125
  250. package/src/workflow/inspector.ts +24 -24
  251. package/src/workflow/mod.ts +76 -84
  252. package/dist/tsup/chunk-2NDZ7JCR.cjs.map +0 -1
  253. package/dist/tsup/chunk-3YY5S6TV.js.map +0 -1
  254. package/dist/tsup/chunk-6NT2LIFN.cjs +0 -268
  255. package/dist/tsup/chunk-6NT2LIFN.cjs.map +0 -1
  256. package/dist/tsup/chunk-7GKQJFSB.cjs.map +0 -1
  257. package/dist/tsup/chunk-7WXCRV25.cjs.map +0 -1
  258. package/dist/tsup/chunk-AGBP757I.js.map +0 -1
  259. package/dist/tsup/chunk-ARRBQTAR.cjs.map +0 -1
  260. package/dist/tsup/chunk-DXWOGCZY.js.map +0 -1
  261. package/dist/tsup/chunk-JGIPV3QU.js +0 -268
  262. package/dist/tsup/chunk-JGIPV3QU.js.map +0 -1
  263. package/dist/tsup/chunk-KIWH5H3K.js.map +0 -1
  264. package/dist/tsup/chunk-L4FVS7GY.js.map +0 -1
  265. package/dist/tsup/chunk-LD5YASJU.cjs.map +0 -1
  266. package/dist/tsup/chunk-OQEEZDIK.cjs.map +0 -1
  267. package/dist/tsup/chunk-PCBNKI2J.js.map +0 -1
  268. package/dist/tsup/chunk-QAZLM4WT.cjs.map +0 -1
  269. package/dist/tsup/chunk-QNLGOTQP.js.map +0 -1
  270. package/dist/tsup/chunk-T6YVRM4K.js.map +0 -1
  271. package/dist/tsup/chunk-V4JUWAT6.js.map +0 -1
  272. package/dist/tsup/chunk-VUF2YEF4.cjs.map +0 -1
  273. package/dist/tsup/chunk-WQ4HNA4W.cjs.map +0 -1
  274. package/dist/tsup/config-CxjGYf4K.d.cts +0 -121
  275. package/dist/tsup/config-CxjGYf4K.d.ts +0 -121
  276. package/dist/tsup/context-88opQsfZ.d.cts +0 -92
  277. package/dist/tsup/context-CVEG5zfg.d.ts +0 -92
  278. package/src/actor/driver.ts +0 -141
  279. package/src/actor/instance/mod.ts +0 -2492
  280. package/src/actor/keys.test.ts +0 -275
  281. package/src/actor/utils.test.ts +0 -48
  282. package/src/agent-os/actor/cron.ts +0 -84
  283. package/src/agent-os/actor/db.ts +0 -54
  284. package/src/agent-os/actor/filesystem.ts +0 -131
  285. package/src/agent-os/actor/index.ts +0 -265
  286. package/src/agent-os/actor/network.ts +0 -58
  287. package/src/agent-os/actor/preview.ts +0 -191
  288. package/src/agent-os/actor/process.ts +0 -177
  289. package/src/agent-os/actor/session.ts +0 -518
  290. package/src/agent-os/actor/shell.ts +0 -60
  291. package/src/agent-os/config.ts +0 -79
  292. package/src/agent-os/fs/database-vfs.ts +0 -624
  293. package/src/agent-os/types.ts +0 -148
  294. package/src/client/test.ts +0 -44
  295. package/src/common/database/mod.test.ts +0 -137
  296. package/src/common/database/native-database.test.ts +0 -211
  297. package/src/common/inline-websocket-adapter.test.ts +0 -51
  298. package/src/drivers/engine/actor-driver.ts +0 -2460
  299. package/src/registry/runtime.test.ts +0 -50
  300. package/src/utils/endpoint-parser.test.ts +0 -206
  301. package/src/utils/serve.ts +0 -217
  302. package/src/utils.test.ts +0 -34
  303. /package/dist/tsup/{chunk-DZJZLZ4R.js.map → chunk-2MXBZGUP.js.map} +0 -0
@@ -1,17 +1,38 @@
1
1
  import { VirtualWebSocket } from "@rivetkit/virtual-websocket";
2
+ import {
3
+ flattenActionHandlers,
4
+ flattenActionInputSchemas,
5
+ flattenActionTraceSamplers,
6
+ } from "@/actor/actions";
2
7
  import {
3
8
  ACTOR_CONTEXT_INTERNAL_SYMBOL,
9
+ type ActorCron,
10
+ type ActorCronEveryOptions,
11
+ type ActorCronSetOptions,
12
+ type ActorForkLink,
13
+ type ActorLogger,
14
+ type ActorRun,
15
+ type ActorSchedule,
4
16
  CONN_STATE_MANAGER_SYMBOL,
17
+ type CronFire,
18
+ type CronJobInfo,
19
+ disposeRunInspector,
5
20
  getRunFunction,
6
21
  getRunInspectorConfig,
22
+ getRunInspectorKind,
23
+ hasRunInspectorConfig,
24
+ RAW_STATE_SYMBOL,
25
+ type ScheduledEventInfo,
7
26
  type WorkflowInspectorConfig,
8
27
  } from "@/actor/config";
9
28
  import type { AnyActorDefinition } from "@/actor/definition";
10
29
  import {
30
+ actorStopping,
11
31
  decodeBridgeRivetError,
12
32
  encodeBridgeRivetError,
13
33
  forbiddenError,
14
34
  INTERNAL_ERROR_CODE,
35
+ isActorAbortedError,
15
36
  isRivetErrorLike,
16
37
  RivetError,
17
38
  type RivetErrorLike,
@@ -23,6 +44,7 @@ import {
23
44
  getQueueCanPublish,
24
45
  hasSchemaConfigKey,
25
46
  } from "@/actor/schema";
47
+ import type { ActionSampleRates } from "@/actor/tracing";
26
48
  import {
27
49
  type AnyClient,
28
50
  type Client,
@@ -30,9 +52,27 @@ import {
30
52
  } from "@/client/client";
31
53
  import { convertRegistryConfigToClientConfig } from "@/client/config";
32
54
  import { HEADER_CONN_PARAMS } from "@/common/actor-router-consts";
33
- import type { AnyDatabaseProvider } from "@/common/database/config";
34
- import { wrapJsNativeDatabase } from "@/common/database/native-database";
35
- import { decodeWorkflowHistoryTransport } from "@/common/inspector-transport";
55
+ import type { ActorInvocationTraceContext } from "@/common/actor-telemetry-context";
56
+ import type {
57
+ AnyDatabaseProvider,
58
+ SqliteProfilingOptions,
59
+ } from "@/common/database/config";
60
+ import {
61
+ bindNativeStateTransactionContext,
62
+ db as defaultDb,
63
+ registerNativeStateTransactionOpener,
64
+ } from "@/common/database/mod";
65
+ import {
66
+ type JsNativeDatabaseLike,
67
+ type JsNativeSynchronousTransactionLike,
68
+ wrapJsNativeDatabase,
69
+ } from "@/common/database/native-database";
70
+ import { assertJsonCompatValue, type JsonCompatValue } from "@/common/encoding";
71
+ import { isResponseLike } from "@/common/fetch-like";
72
+ import {
73
+ decodeWorkflowHistoryTransport,
74
+ type WorkflowHistoryBytes,
75
+ } from "@/common/inspector-transport";
36
76
  import { deconstructError, stringifyError } from "@/common/utils";
37
77
  import type {
38
78
  RivetCloseEvent,
@@ -47,14 +87,22 @@ import type {
47
87
  RuntimeKind,
48
88
  SqliteBackend,
49
89
  } from "@/registry/config";
90
+ import { decodeCborCompat, encodeCborCompat } from "@/serde";
91
+ import { getEnvUniversal, toUint8Array, VERSION } from "@/utils";
50
92
  import {
51
- decodeCborCompat,
52
- decodeCborJsonCompat,
53
- encodeCborCompat,
54
- } from "@/serde";
55
- import { getEnvUniversal, VERSION } from "@/utils";
93
+ getNodeFsSync,
94
+ getNodePath,
95
+ importNodeDependencies,
96
+ } from "@/utils/node";
56
97
  import { logger } from "./log";
57
98
  import { loadNapiRuntime } from "./napi-runtime";
99
+ import {
100
+ buildNativeHttpRequest,
101
+ cancelNativeHttpRequestBody,
102
+ convertNativeHttpResponse,
103
+ type NativeHttpRequestBodyStream,
104
+ type NativeHttpResponseBodyStream,
105
+ } from "./native-http";
58
106
  import {
59
107
  type NativeValidationConfig,
60
108
  validateActionArgs,
@@ -63,6 +111,7 @@ import {
63
111
  validateQueueBody,
64
112
  validateQueueComplete,
65
113
  } from "./native-validation";
114
+ import { RunHandlerCoordinator } from "./run-handler-coordinator";
66
115
  import type {
67
116
  ActorContextHandle,
68
117
  ActorFactoryHandle,
@@ -71,17 +120,30 @@ import type {
71
120
  CoreRuntime,
72
121
  RegistryHandle,
73
122
  RuntimeActorConfig,
123
+ RuntimeActorKeySegment,
124
+ RuntimeActorTracingConfig,
74
125
  RuntimeBytes,
75
- RuntimeHttpResponse,
126
+ RuntimeCronFire,
127
+ RuntimeCronJobInfo,
128
+ RuntimeInspectorTabEntry,
76
129
  RuntimeQueueMessage,
130
+ RuntimeScheduledEventInfo,
131
+ RuntimeScheduledFireInfo,
77
132
  RuntimeServeConfig,
78
133
  RuntimeStateDeltaPayload,
134
+ SqliteTransactionHandle,
79
135
  WebSocketHandle,
80
136
  } from "./runtime";
137
+ import { servicesBinaryUnavailable } from "./runtime";
81
138
  import { loadWasmRuntime } from "./wasm-runtime";
139
+ import {
140
+ createWriteThroughProxy,
141
+ unwrapWriteThroughProxy,
142
+ } from "./write-through-proxy";
82
143
 
83
144
  const textEncoder = new TextEncoder();
84
145
  const textDecoder = new TextDecoder();
146
+
85
147
  type ResolvedRuntimeKind = Exclude<RuntimeKind, "auto">;
86
148
  type RuntimeHostKind = "node-like" | "edge-like";
87
149
  export type RuntimeLoaders = {
@@ -91,6 +153,7 @@ export type RuntimeLoaders = {
91
153
  ) => ReturnType<typeof loadWasmRuntime>;
92
154
  detectHost: () => RuntimeHostKind;
93
155
  };
156
+
94
157
  type SerializeStateReason = "save" | "inspector";
95
158
  type NativeOnStateChangeHandler = (
96
159
  ctx: ActorContextHandleAdapter,
@@ -100,6 +163,14 @@ type NativePersistConnState = {
100
163
  state: unknown;
101
164
  };
102
165
 
166
+ type NativeStateTransactionScope = {
167
+ actorContext: ActorContextHandleAdapter;
168
+ actorStateBaseline: unknown;
169
+ connectionStateBaselines: Map<string, Uint8Array>;
170
+ committed: boolean;
171
+ release: () => void;
172
+ };
173
+
103
174
  const defaultRuntimeLoaders: RuntimeLoaders = {
104
175
  loadNative: loadNapiRuntime,
105
176
  loadWasm: loadWasmRuntime,
@@ -168,10 +239,36 @@ export async function loadAutoRuntime(
168
239
  return (await loaders.loadWasm(config.wasm)).runtime;
169
240
  }
170
241
 
242
+ let nativeError: unknown;
171
243
  try {
172
244
  return (await loaders.loadNative()).runtime;
173
- } catch {
245
+ } catch (error) {
246
+ nativeError = error;
247
+ // Native is the expected runtime on a node-like host, so this is the
248
+ // actionable error even when the wasm fallback goes on to succeed.
249
+ // Discarding it hides causes such as a platform binding that npm
250
+ // silently skipped, which then resurfaces as an unrelated wasm error.
251
+ logger().warn({
252
+ msg: "native runtime failed to load; falling back to wasm",
253
+ error: stringifyError(error),
254
+ });
255
+ }
256
+
257
+ try {
174
258
  return (await loaders.loadWasm(config.wasm)).runtime;
259
+ } catch (wasmError) {
260
+ // Report both, native first. The wasm failure on a node-like host is
261
+ // usually just its loader fetching over `file://`, which says nothing
262
+ // about why native was unavailable.
263
+ throw new RivetError(
264
+ "config",
265
+ "runtime_unavailable",
266
+ `RivetKit could not load a core runtime. Native runtime: ${stringifyError(nativeError)} Wasm runtime: ${stringifyError(wasmError)}`,
267
+ {
268
+ public: true,
269
+ statusCode: 500,
270
+ },
271
+ );
175
272
  }
176
273
  }
177
274
 
@@ -243,6 +340,14 @@ type NativePersistActorState = {
243
340
  state: unknown;
244
341
  isInOnStateChange: boolean;
245
342
  connStates: Map<string, NativePersistConnState>;
343
+ // Set when a coalesced save and onStateChange flush is pending for the
344
+ // current event loop tick.
345
+ saveScheduled?: boolean;
346
+ pendingSaveHandle?: ReturnType<typeof setImmediate>;
347
+ activeStateTransactionOwner?: symbol;
348
+ pendingStateTransactionOwners?: Set<symbol>;
349
+ stateTransactionTail?: Promise<void>;
350
+ stateTransactionSaveDeferred?: boolean;
246
351
  };
247
352
  type NativeDestroyGate = {
248
353
  destroyCompletion?: Promise<void>;
@@ -251,6 +356,11 @@ type NativeDestroyGate = {
251
356
  type NativeDatabaseClientState = {
252
357
  client: unknown;
253
358
  };
359
+ type NativeActorAbort = {
360
+ signal: AbortSignal;
361
+ listeners: Set<() => void>;
362
+ };
363
+
254
364
  type NativeActorRuntimeState = {
255
365
  sql?: ReturnType<typeof wrapJsNativeDatabase>;
256
366
  databaseClient?: NativeDatabaseClientState;
@@ -258,6 +368,17 @@ type NativeActorRuntimeState = {
258
368
  vars?: unknown;
259
369
  destroyGate?: NativeDestroyGate;
260
370
  persistState?: NativePersistActorState;
371
+ // One native actor abort signal shared by every context of the actor. Each
372
+ // native signal parks a task and a callback handle until the actor stops,
373
+ // so creating one per request or action leaks both. Per-context listeners
374
+ // live in `listeners` so the shared signal never collects one listener per
375
+ // in-flight request.
376
+ actorAbort?: NativeActorAbort;
377
+ // Set once shutdown cleanup has cleared this generation's caches. Work that
378
+ // outlives the generation, such as an untracked timer or a late WebSocket
379
+ // message handler, then fails with `actor.stopping` instead of reading an
380
+ // empty bag as if `vars` or the database were never initialized.
381
+ cleared?: true;
261
382
  };
262
383
 
263
384
  // Keep JS-only actor caches on the NAPI ActorContext runtime-state bag instead
@@ -267,9 +388,10 @@ function getNativeRuntimeState(
267
388
  runtime: CoreRuntime,
268
389
  ctx: ActorContextHandle,
269
390
  ): NativeActorRuntimeState {
270
- const runtimeState = callNativeSync(() =>
271
- runtime.actorRuntimeState(ctx),
272
- ) as NativeActorRuntimeState;
391
+ const runtimeState = readNativeRuntimeStateBag(runtime, ctx);
392
+ if (runtimeState.cleared) {
393
+ throw actorStopping(callNativeSync(() => runtime.actorId(ctx)));
394
+ }
273
395
  if (!runtimeState.destroyGate) {
274
396
  runtimeState.destroyGate = {};
275
397
  }
@@ -283,6 +405,22 @@ function getNativeRuntimeState(
283
405
  return runtimeState;
284
406
  }
285
407
 
408
+ function readNativeRuntimeStateBag(
409
+ runtime: CoreRuntime,
410
+ ctx: ActorContextHandle,
411
+ ): NativeActorRuntimeState {
412
+ return callNativeSync(() =>
413
+ runtime.actorRuntimeState(ctx),
414
+ ) as NativeActorRuntimeState;
415
+ }
416
+
417
+ function isNativeRuntimeStateCleared(
418
+ runtime: CoreRuntime,
419
+ ctx: ActorContextHandle,
420
+ ): boolean {
421
+ return readNativeRuntimeStateBag(runtime, ctx).cleared === true;
422
+ }
423
+
286
424
  function getNativePersistState(
287
425
  runtime: CoreRuntime,
288
426
  ctx: ActorContextHandle,
@@ -328,6 +466,15 @@ function stateMutationReentrantError(): RivetError {
328
466
  );
329
467
  }
330
468
 
469
+ function stateTransactionConflictError(): RivetError {
470
+ return new RivetError(
471
+ "actor",
472
+ "state_transaction_conflict",
473
+ "State cannot be mutated by another action while an experimental state-aware database transaction is active.",
474
+ { public: true, statusCode: 409 },
475
+ );
476
+ }
477
+
331
478
  function databaseNotConfiguredError(): RivetError {
332
479
  return new RivetError(
333
480
  "actor",
@@ -337,6 +484,23 @@ function databaseNotConfiguredError(): RivetError {
337
484
  );
338
485
  }
339
486
 
487
+ function databaseClientNotReadyError(): RivetError {
488
+ return new RivetError(
489
+ "actor",
490
+ "database_client_not_ready",
491
+ "actor database client was not initialized before user code ran. this is an internal lifecycle error; the migration callback should have pre-warmed the client. file an issue if you can reproduce.",
492
+ { public: true },
493
+ );
494
+ }
495
+ function runHandlerNotConfiguredError(): RivetError {
496
+ return new RivetError(
497
+ "actor",
498
+ "run_handler_unavailable",
499
+ "Cannot schedule a run wake because this actor does not define a run handler.",
500
+ { public: true, statusCode: 409 },
501
+ );
502
+ }
503
+
340
504
  function stateNotEnabledError(): RivetError {
341
505
  return new RivetError(
342
506
  "actor",
@@ -399,19 +563,69 @@ function clearNativeRuntimeState(
399
563
  runtime: CoreRuntime,
400
564
  ctx: ActorContextHandle,
401
565
  ) {
566
+ // A coalesced save armed before the clear would otherwise fire against the
567
+ // cleared bag and throw outside any caller.
568
+ const pendingSaveHandle = readNativeRuntimeStateBag(runtime, ctx)
569
+ .persistState?.pendingSaveHandle;
570
+ if (pendingSaveHandle !== undefined) {
571
+ clearImmediate(pendingSaveHandle);
572
+ }
402
573
  callNativeSync(() => runtime.actorClearRuntimeState(ctx));
574
+ // The runtime hands out a fresh bag after a clear. Each generation has its
575
+ // own bag, so marking it makes later access from this generation fail typed
576
+ // without touching any newer generation of the same actor.
577
+ readNativeRuntimeStateBag(runtime, ctx).cleared = true;
403
578
  }
404
579
 
405
580
  async function cleanupNativeSleepRuntimeState(
406
581
  runtime: CoreRuntime,
407
582
  ctx: ActorContextHandle,
583
+ afterTrackedWorkDrained?: () => Promise<void>,
408
584
  ): Promise<void> {
409
- await runtime.actorWaitForTrackedShutdownWork(ctx);
410
- await closeNativeDatabaseClient(runtime, ctx);
411
- await closeNativeSqlDatabase(runtime, ctx);
585
+ // The bounded wait gives shutdown work one grace-period chance to finish.
586
+ // Drained means all tracked shutdown work completed before the deadline, so
587
+ // we can save final state and clear runtime state immediately. If it did not
588
+ // drain, close database handles now, then defer the final save and clear until
589
+ // the tracked work finishes without a deadline.
590
+ const drained = await runtime.actorWaitForTrackedShutdownWork(ctx);
591
+ if (!drained) {
592
+ await detachNativeDatabaseForShutdown(runtime, ctx);
593
+ void runtime
594
+ .actorWaitForTrackedShutdownWorkUnbounded(ctx)
595
+ .then(async () => {
596
+ await afterTrackedWorkDrained?.();
597
+ clearNativeRuntimeState(runtime, ctx);
598
+ })
599
+ .catch((error) => {
600
+ logger().warn({
601
+ msg: "deferred native sleep cleanup failed",
602
+ error: stringifyError(error),
603
+ });
604
+ });
605
+ return;
606
+ }
607
+
608
+ await afterTrackedWorkDrained?.();
609
+ await detachNativeDatabaseForShutdown(runtime, ctx);
412
610
  clearNativeRuntimeState(runtime, ctx);
413
611
  }
414
612
 
613
+ async function detachNativeDatabaseForShutdown(
614
+ runtime: CoreRuntime,
615
+ ctx: ActorContextHandle,
616
+ ): Promise<void> {
617
+ const runtimeState = getNativeRuntimeState(runtime, ctx);
618
+ // Stop JS access without closing the runtime-owned SQLite backend. Rust still
619
+ // needs it to reconcile scheduled alarms and performs the physical close after
620
+ // this lifecycle callback returns.
621
+ await runtimeState.sql?.detachForShutdown();
622
+ try {
623
+ await closeNativeDatabaseClient(runtime, ctx);
624
+ } finally {
625
+ runtimeState.sql = undefined;
626
+ }
627
+ }
628
+
415
629
  function closeNativeSqlDatabase(
416
630
  runtime: CoreRuntime,
417
631
  ctx: ActorContextHandle,
@@ -448,6 +662,26 @@ async function closeNativeDatabaseClient(
448
662
  }
449
663
  }
450
664
 
665
+ function createNativeSqlTransaction(
666
+ runtime: CoreRuntime,
667
+ transaction: SqliteTransactionHandle,
668
+ ): JsNativeSynchronousTransactionLike {
669
+ return {
670
+ exec: (sql) => runtime.actorSqlTransactionExec(transaction, sql),
671
+ execSync: (sql) =>
672
+ runtime.actorSqlTransactionExecSync(transaction, sql),
673
+ execute: (sql, params) =>
674
+ runtime.actorSqlTransactionExecute(transaction, sql, params),
675
+ executeSync: (sql, params) =>
676
+ runtime.actorSqlTransactionExecuteSync(transaction, sql, params),
677
+ commit: () => runtime.actorSqlTransactionCommit(transaction),
678
+ commitSync: () => runtime.actorSqlTransactionCommitSync(transaction),
679
+ rollback: () => runtime.actorSqlTransactionRollback(transaction),
680
+ rollbackSync: () =>
681
+ runtime.actorSqlTransactionRollbackSync(transaction),
682
+ };
683
+ }
684
+
451
685
  function getOrCreateNativeSqlDatabase(
452
686
  runtime: CoreRuntime,
453
687
  ctx: ActorContextHandle,
@@ -458,15 +692,77 @@ function getOrCreateNativeSqlDatabase(
458
692
  return cachedDatabase;
459
693
  }
460
694
 
461
- const database = wrapJsNativeDatabase({
695
+ const bindings: JsNativeDatabaseLike = {
462
696
  exec: (sql) => runtime.actorSqlExec(ctx, sql),
697
+ execSync: (sql) => runtime.actorSqlExecSync(ctx, sql),
463
698
  execute: (sql, params) => runtime.actorSqlExecute(ctx, sql, params),
699
+ executeSync: (sql, params) =>
700
+ runtime.actorSqlExecuteSync(ctx, sql, params),
701
+ executeBatch: (statements) =>
702
+ runtime.actorSqlExecuteBatch(ctx, statements),
703
+ beginTransaction: async (timeoutMs, name) => {
704
+ const transaction = await runtime.actorSqlBeginTransaction(
705
+ ctx,
706
+ timeoutMs,
707
+ name,
708
+ );
709
+ return createNativeSqlTransaction(runtime, transaction);
710
+ },
711
+ beginTransactionSync: (timeoutMs, name) => {
712
+ const transaction = runtime.actorSqlBeginTransactionSync(
713
+ ctx,
714
+ timeoutMs,
715
+ name,
716
+ );
717
+ return createNativeSqlTransaction(runtime, transaction);
718
+ },
719
+ beginStateTransaction: async (timeoutMs, context, name) => {
720
+ const scope = context as NativeStateTransactionScope | undefined;
721
+ if (!scope) {
722
+ throw new Error(
723
+ "actor state transaction context is not configured",
724
+ );
725
+ }
726
+ const transaction = await runtime.actorBeginStateTransaction(
727
+ ctx,
728
+ timeoutMs,
729
+ name,
730
+ );
731
+ return {
732
+ exec: async () => {
733
+ throw new Error(
734
+ "actor state transactions only support single-statement execute calls",
735
+ );
736
+ },
737
+ execute: (sql, params) =>
738
+ runtime.actorStateTransactionExecute(
739
+ transaction,
740
+ sql,
741
+ params,
742
+ ),
743
+ commit: async () => {
744
+ await runtime.actorStateTransactionCommit(
745
+ transaction,
746
+ scope.actorContext.serializeForTick("save"),
747
+ );
748
+ scope.committed = true;
749
+ },
750
+ rollback: () =>
751
+ runtime.actorStateTransactionRollback(transaction),
752
+ };
753
+ },
464
754
  query: (sql, params) => runtime.actorSqlQuery(ctx, sql, params),
465
755
  run: (sql, params) => runtime.actorSqlRun(ctx, sql, params),
466
756
  metrics: () => runtime.actorSqlMetrics(ctx),
467
757
  takeLastKvError: () => runtime.actorSqlTakeLastKvError(ctx),
758
+ open: () => runtime.actorSqlOpen(ctx),
759
+ commitTicket: () => runtime.actorSqlCommitTicket(ctx),
760
+ whenDurable: (ticket) => runtime.actorSqlWhenDurable(ctx, ticket),
761
+ abortGeneration: (reason) =>
762
+ runtime.actorSqlAbortGeneration(ctx, reason),
468
763
  close: () => runtime.actorSqlClose(ctx),
469
- });
764
+ };
765
+ const database = wrapJsNativeDatabase(bindings);
470
766
  runtimeState.sql = database;
471
767
  return database;
472
768
  }
@@ -571,19 +867,48 @@ function decodeNativeKvValue<T extends NativeKvValueType = "text">(
571
867
  }
572
868
 
573
869
  async function loadEngineCli(): Promise<typeof import("@rivetkit/engine-cli")> {
870
+ // LOAD-BEARING: the specifier is computed (`.join("/")`) on purpose. Do NOT
871
+ // "simplify" it to a literal `import("@rivetkit/engine-cli")`. Edge adapters
872
+ // pre-bundle this module for Deno; a literal
873
+ // dynamic import is statically resolvable, so Deno's eszip bundler would
874
+ // snapshot the ~117 MB engine-cli binary into the deploy and 413. The
875
+ // computed specifier keeps it opaque to static analysis so it is never
876
+ // bundled. Enforced by scripts/ci/check-edge-native-closure.mjs.
574
877
  return import(["@rivetkit", "engine-cli"].join("/"));
575
878
  }
576
879
 
880
+ async function loadServices(): Promise<{ getServicesPath: () => string }> {
881
+ // Keep the native binary opaque to edge bundlers for the same reason as
882
+ // engine-cli above.
883
+ return import(["@rivet-dev", "services"].join("/"));
884
+ }
885
+
577
886
  function decodeValue<T>(value?: RuntimeBytes | null): T {
578
887
  if (!value || value.length === 0) {
579
888
  return undefined as T;
580
889
  }
581
890
 
582
- return decodeCborJsonCompat(value);
891
+ return decodeCborCompat(value);
892
+ }
893
+
894
+ // Rejects `WorkflowHistoryBytes`: the compat layer rewrites an ArrayBuffer as
895
+ // `["$ArrayBuffer", "<base64>"]`, and the inspector wire field carries raw BARE.
896
+ // The conditional distributes, so it catches the branded type on its own but
897
+ // only strips it from a union that also has other members. A non-distributive
898
+ // `[T] extends [...]` resolves to `never` for the `any` arguments this takes
899
+ // elsewhere, so the union case stays uncovered.
900
+ function encodeValue<T>(
901
+ value: T extends WorkflowHistoryBytes ? never : T,
902
+ ): RuntimeBytes {
903
+ return encodeCborCompat(value as JsonCompatValue);
583
904
  }
584
905
 
585
- function encodeValue(value: unknown): RuntimeBytes {
586
- return encodeCborCompat(value);
906
+ function normalizeArgs(value: unknown): unknown[] {
907
+ return Array.isArray(value)
908
+ ? value
909
+ : value === undefined || value === null
910
+ ? []
911
+ : [value];
587
912
  }
588
913
 
589
914
  function unwrapTsfnPayload<T>(error: unknown, payload: T): T {
@@ -640,13 +965,26 @@ function encodeNativeCallbackError(error: unknown): Error {
640
965
  ? error
641
966
  : deconstructError(error, true);
642
967
 
643
- const bridgeError = new Error(encodeBridgeRivetError(structuredError), {
968
+ const { encoded, droppedMetadataCause } =
969
+ encodeBridgeRivetError(structuredError);
970
+ if (droppedMetadataCause !== undefined) {
971
+ logger().warn(
972
+ {
973
+ group: structuredError.group,
974
+ code: structuredError.code,
975
+ error: String(droppedMetadataCause),
976
+ },
977
+ "dropped error metadata that JSON cannot encode",
978
+ );
979
+ }
980
+ const bridgeError = new Error(encoded, {
644
981
  cause: error instanceof Error ? error : undefined,
645
982
  });
646
983
  return Object.assign(bridgeError, {
647
984
  group: structuredError.group,
648
985
  code: structuredError.code,
649
986
  metadata: structuredError.metadata,
987
+ rayId: structuredError.rayId,
650
988
  });
651
989
  }
652
990
 
@@ -666,16 +1004,10 @@ function callNativeSync<T>(invoke: () => T): T {
666
1004
  }
667
1005
  }
668
1006
 
669
- function actorAbortedError(): Error & { group: string; code: string } {
670
- return Object.assign(new Error("Actor aborted"), {
671
- group: "actor",
672
- code: "aborted",
673
- });
674
- }
675
-
676
- type NativeWorkflowInspectorConfig = WorkflowInspectorConfig<ArrayBuffer> & {
677
- getState?: () => Promise<unknown> | unknown;
678
- };
1007
+ type NativeWorkflowInspectorConfig =
1008
+ WorkflowInspectorConfig<WorkflowHistoryBytes> & {
1009
+ getState?: () => Promise<unknown> | unknown;
1010
+ };
679
1011
 
680
1012
  function isClosedTaskRegistrationError(error: unknown): boolean {
681
1013
  const metadata = error instanceof RivetError ? error.metadata : undefined;
@@ -848,6 +1180,10 @@ function serializeWorkflowEntryKind(
848
1180
  | {
849
1181
  tag: "WorkflowRemovedEntry";
850
1182
  val: { originalType: string; originalName: string | null };
1183
+ }
1184
+ | {
1185
+ tag: "WorkflowVersionCheckEntry";
1186
+ val: { resolved: number; latest: number };
851
1187
  } {
852
1188
  switch (kind.tag) {
853
1189
  case "WorkflowStepEntry":
@@ -913,9 +1249,18 @@ function serializeWorkflowEntryKind(
913
1249
  originalName: kind.val.originalName,
914
1250
  },
915
1251
  };
1252
+ case "WorkflowVersionCheckEntry":
1253
+ return {
1254
+ tag: kind.tag,
1255
+ val: {
1256
+ resolved: kind.val.resolved,
1257
+ latest: kind.val.latest,
1258
+ },
1259
+ };
916
1260
  }
917
1261
  }
918
1262
 
1263
+ // TODO: Switch inspector routes to CBOR encoding
919
1264
  function serializeWorkflowHistoryForJson(data: ArrayBuffer | null): {
920
1265
  nameRegistry: string[];
921
1266
  entries: Array<{
@@ -949,7 +1294,7 @@ function serializeWorkflowHistoryForJson(data: ArrayBuffer | null): {
949
1294
 
950
1295
  const history = decodeWorkflowHistoryTransport(data);
951
1296
 
952
- return {
1297
+ return jsonSafe({
953
1298
  nameRegistry: [...history.nameRegistry],
954
1299
  entries: history.entries.map((entry) => ({
955
1300
  id: entry.id,
@@ -979,7 +1324,7 @@ function serializeWorkflowHistoryForJson(data: ArrayBuffer | null): {
979
1324
  ],
980
1325
  ),
981
1326
  ),
982
- };
1327
+ });
983
1328
  }
984
1329
 
985
1330
  function toHttpJsonCompatible<T>(value: T): T {
@@ -1051,92 +1396,7 @@ function wrapNativeCallback<Args extends Array<unknown>, Result>(
1051
1396
 
1052
1397
  function decodeArgs(value?: RuntimeBytes | null): unknown[] {
1053
1398
  const decoded = decodeValue<unknown>(value);
1054
- return Array.isArray(decoded)
1055
- ? decoded
1056
- : decoded === undefined
1057
- ? []
1058
- : [decoded];
1059
- }
1060
-
1061
- function createWriteThroughProxy<T>(
1062
- value: T,
1063
- commit: (next: T) => void,
1064
- beforeChange?: () => void,
1065
- ): T {
1066
- if (!value || typeof value !== "object") {
1067
- return value;
1068
- }
1069
-
1070
- const proxies = new WeakMap<object, object>();
1071
- const wrap = (target: object): object => {
1072
- const cached = proxies.get(target);
1073
- if (cached) {
1074
- return cached;
1075
- }
1076
-
1077
- const proxy = new Proxy(target, {
1078
- get(innerTarget, property, receiver) {
1079
- const result = Reflect.get(innerTarget, property, receiver);
1080
- return result && typeof result === "object"
1081
- ? wrap(result as object)
1082
- : result;
1083
- },
1084
- set(innerTarget, property, nextValue, receiver) {
1085
- beforeChange?.();
1086
- const updated = Reflect.set(
1087
- innerTarget,
1088
- property,
1089
- nextValue,
1090
- receiver,
1091
- );
1092
- commit(value);
1093
- return updated;
1094
- },
1095
- deleteProperty(innerTarget, property) {
1096
- beforeChange?.();
1097
- const updated = Reflect.deleteProperty(innerTarget, property);
1098
- commit(value);
1099
- return updated;
1100
- },
1101
- });
1102
-
1103
- proxies.set(target, proxy);
1104
- return proxy;
1105
- };
1106
-
1107
- return wrap(value as object) as T;
1108
- }
1109
-
1110
- function buildRequest(init: {
1111
- method: string;
1112
- uri: string;
1113
- headers?: Record<string, string>;
1114
- body?: RuntimeBytes;
1115
- }): Request {
1116
- const url = init.uri.startsWith("http")
1117
- ? init.uri
1118
- : new URL(init.uri, "http://127.0.0.1").toString();
1119
- const body =
1120
- init.body && init.body.length > 0
1121
- ? runtimeBytesToArrayBuffer(init.body)
1122
- : undefined;
1123
- return new Request(url, {
1124
- method: init.method,
1125
- headers: init.headers,
1126
- body,
1127
- });
1128
- }
1129
-
1130
- async function toRuntimeHttpResponse(
1131
- response: Response,
1132
- ): Promise<RuntimeHttpResponse> {
1133
- const headers = Object.fromEntries(response.headers.entries());
1134
- const body = new Uint8Array(await response.arrayBuffer());
1135
- return {
1136
- status: response.status,
1137
- headers,
1138
- body,
1139
- };
1399
+ return normalizeArgs(decoded);
1140
1400
  }
1141
1401
 
1142
1402
  function toActorKey(
@@ -1159,6 +1419,9 @@ class NativeConnAdapter {
1159
1419
  #schemas: NativeValidationConfig;
1160
1420
  #ctx?: ActorContextHandle;
1161
1421
  #queueHibernationRemoval?: (connId: string) => void;
1422
+ #assertCanMutateState?: () => void;
1423
+ #stateProxy?: unknown;
1424
+ #stateProxyTarget?: unknown;
1162
1425
 
1163
1426
  constructor(
1164
1427
  runtime: CoreRuntime,
@@ -1166,12 +1429,14 @@ class NativeConnAdapter {
1166
1429
  schemas: NativeValidationConfig = {},
1167
1430
  ctx?: ActorContextHandle,
1168
1431
  queueHibernationRemoval?: (connId: string) => void,
1432
+ assertCanMutateState?: () => void,
1169
1433
  ) {
1170
1434
  this.#runtime = runtime;
1171
1435
  this.#conn = conn;
1172
1436
  this.#schemas = schemas;
1173
1437
  this.#ctx = ctx;
1174
1438
  this.#queueHibernationRemoval = queueHibernationRemoval;
1439
+ this.#assertCanMutateState = assertCanMutateState;
1175
1440
  (
1176
1441
  this as NativeConnAdapter & {
1177
1442
  [CONN_STATE_MANAGER_SYMBOL]?: unknown;
@@ -1196,19 +1461,61 @@ class NativeConnAdapter {
1196
1461
  );
1197
1462
  }
1198
1463
 
1464
+ [RAW_STATE_SYMBOL](): unknown {
1465
+ return this.#readState();
1466
+ }
1467
+
1199
1468
  get state(): unknown {
1200
1469
  const nextState = this.#readState();
1201
- return createWriteThroughProxy(nextState, (nextValue) => {
1202
- this.#writeState(nextValue, { writeNative: true });
1203
- });
1470
+ if (!this.#ctx) {
1471
+ return this.#createStateProxy(nextState);
1472
+ }
1473
+
1474
+ // Reading `conn.state` rebuilds the deep write-through proxy, which
1475
+ // allocates fresh on-change caches and rewraps the whole tree. Memoize
1476
+ // the proxy keyed on the underlying state object so repeated reads and
1477
+ // deep read cascades reuse a single proxy.
1478
+ if (
1479
+ this.#stateProxy === undefined ||
1480
+ this.#stateProxyTarget !== nextState
1481
+ ) {
1482
+ this.#stateProxyTarget = nextState;
1483
+ this.#stateProxy = this.#createStateProxy(nextState);
1484
+ }
1485
+ return this.#stateProxy;
1486
+ }
1487
+
1488
+ #createStateProxy(state: unknown): unknown {
1489
+ const assertCurrentState = () => {
1490
+ this.#assertCanMutateState?.();
1491
+ if (this.#ctx && this.#readState() !== state) {
1492
+ throw stateTransactionConflictError();
1493
+ }
1494
+ };
1495
+ return createWriteThroughProxy(
1496
+ state,
1497
+ (nextValue) => {
1498
+ assertCurrentState();
1499
+ this.#writeState(nextValue, { writeNative: true });
1500
+ },
1501
+ (newValue) => {
1502
+ assertCurrentState();
1503
+ assertJsonCompatValue(newValue);
1504
+ },
1505
+ );
1204
1506
  }
1205
1507
 
1206
1508
  set state(value: unknown) {
1207
- this.#writeState(value, { writeNative: true });
1509
+ this.#assertCanMutateState?.();
1510
+ const nextValue = unwrapWriteThroughProxy(value);
1511
+ assertJsonCompatValue(nextValue);
1512
+ this.#writeState(nextValue, { writeNative: true });
1208
1513
  }
1209
1514
 
1210
1515
  initializeState(value: unknown): void {
1211
- this.#writeState(value, { writeNative: false });
1516
+ this.#writeState(unwrapWriteThroughProxy(value), {
1517
+ writeNative: false,
1518
+ });
1212
1519
  }
1213
1520
 
1214
1521
  get isHibernatable(): boolean {
@@ -1282,7 +1589,7 @@ class NativeConnAdapter {
1282
1589
  }
1283
1590
  }
1284
1591
 
1285
- class NativeScheduleAdapter {
1592
+ class NativeScheduleAdapter implements ActorSchedule {
1286
1593
  #runtime: CoreRuntime;
1287
1594
  #ctx: ActorContextHandle;
1288
1595
 
@@ -1295,14 +1602,12 @@ class NativeScheduleAdapter {
1295
1602
  duration: number,
1296
1603
  action: string,
1297
1604
  ...args: unknown[]
1298
- ): Promise<void> {
1299
- callNativeSync(() =>
1300
- this.#runtime.actorScheduleAfter(
1301
- this.#ctx,
1302
- duration,
1303
- action,
1304
- encodeValue(args),
1305
- ),
1605
+ ): Promise<string> {
1606
+ return await this.#runtime.actorScheduleAfter(
1607
+ this.#ctx,
1608
+ duration,
1609
+ action,
1610
+ encodeValue(args),
1306
1611
  );
1307
1612
  }
1308
1613
 
@@ -1310,16 +1615,129 @@ class NativeScheduleAdapter {
1310
1615
  timestamp: number,
1311
1616
  action: string,
1312
1617
  ...args: unknown[]
1313
- ): Promise<void> {
1314
- callNativeSync(() =>
1315
- this.#runtime.actorScheduleAt(
1316
- this.#ctx,
1317
- timestamp,
1318
- action,
1319
- encodeValue(args),
1320
- ),
1618
+ ): Promise<string> {
1619
+ return await this.#runtime.actorScheduleAt(
1620
+ this.#ctx,
1621
+ timestamp,
1622
+ action,
1623
+ encodeValue(args),
1624
+ );
1625
+ }
1626
+
1627
+ async cancel(id: string): Promise<boolean> {
1628
+ return await this.#runtime.actorScheduleCancel(this.#ctx, id);
1629
+ }
1630
+
1631
+ async get(id: string): Promise<ScheduledEventInfo | undefined> {
1632
+ const event = await this.#runtime.actorScheduleGet(this.#ctx, id);
1633
+ return event ? decodeScheduledEventInfo(event) : undefined;
1634
+ }
1635
+
1636
+ async list(): Promise<ScheduledEventInfo[]> {
1637
+ return (await this.#runtime.actorScheduleList(this.#ctx)).map(
1638
+ decodeScheduledEventInfo,
1639
+ );
1640
+ }
1641
+ }
1642
+
1643
+ class NativeCronAdapter implements ActorCron {
1644
+ #runtime: CoreRuntime;
1645
+ #ctx: ActorContextHandle;
1646
+
1647
+ constructor(runtime: CoreRuntime, ctx: ActorContextHandle) {
1648
+ this.#runtime = runtime;
1649
+ this.#ctx = ctx;
1650
+ }
1651
+
1652
+ async set(options: ActorCronSetOptions): Promise<void> {
1653
+ await this.#runtime.actorCronSet(
1654
+ this.#ctx,
1655
+ options.name,
1656
+ options.expression,
1657
+ options.timezone,
1658
+ options.action,
1659
+ encodeValue(options.args ?? []),
1660
+ options.maxHistory,
1661
+ );
1662
+ }
1663
+
1664
+ async every(options: ActorCronEveryOptions): Promise<void> {
1665
+ await this.#runtime.actorCronEvery(
1666
+ this.#ctx,
1667
+ options.name,
1668
+ options.interval,
1669
+ options.action,
1670
+ encodeValue(options.args ?? []),
1671
+ options.maxHistory,
1672
+ );
1673
+ }
1674
+
1675
+ async get(name: string): Promise<CronJobInfo | undefined> {
1676
+ const job = await this.#runtime.actorCronGet(this.#ctx, name);
1677
+ return job ? decodeCronJobInfo(job) : undefined;
1678
+ }
1679
+
1680
+ async list(): Promise<CronJobInfo[]> {
1681
+ return (await this.#runtime.actorCronList(this.#ctx)).map(
1682
+ decodeCronJobInfo,
1321
1683
  );
1322
1684
  }
1685
+
1686
+ async delete(name: string): Promise<boolean> {
1687
+ return await this.#runtime.actorCronDelete(this.#ctx, name);
1688
+ }
1689
+
1690
+ async history(
1691
+ name: string,
1692
+ options?: { limit?: number },
1693
+ ): Promise<CronFire[]> {
1694
+ return (
1695
+ await this.#runtime.actorCronHistory(
1696
+ this.#ctx,
1697
+ name,
1698
+ options?.limit,
1699
+ )
1700
+ ).map(decodeCronFire);
1701
+ }
1702
+ }
1703
+
1704
+ function decodeScheduledEventInfo(
1705
+ event: RuntimeScheduledEventInfo,
1706
+ ): ScheduledEventInfo {
1707
+ return {
1708
+ id: event.id,
1709
+ action: event.action,
1710
+ args: decodeArgs(event.args),
1711
+ runAt: event.runAt,
1712
+ };
1713
+ }
1714
+
1715
+ function decodeCronJobInfo(job: RuntimeCronJobInfo): CronJobInfo {
1716
+ const base = {
1717
+ name: job.name,
1718
+ action: job.action,
1719
+ args: decodeArgs(job.args),
1720
+ nextRunAt: job.nextRunAt,
1721
+ lastRunAt: job.lastRunAt,
1722
+ maxHistory: job.maxHistory,
1723
+ };
1724
+ if (job.kind === "cron") {
1725
+ return {
1726
+ ...base,
1727
+ kind: "cron",
1728
+ expression: job.expression as string,
1729
+ timezone: job.timezone as string,
1730
+ };
1731
+ }
1732
+ return {
1733
+ ...base,
1734
+ kind: "every",
1735
+ interval: job.intervalMs as number,
1736
+ };
1737
+ }
1738
+
1739
+ function decodeCronFire(fire: RuntimeCronFire): CronFire {
1740
+ return { ...fire };
1323
1741
  }
1324
1742
 
1325
1743
  class NativeKvAdapter {
@@ -1510,8 +1928,9 @@ function wrapQueueMessage(
1510
1928
  schemas: NativeValidationConfig["queues"],
1511
1929
  ) {
1512
1930
  const name = callNativeSync(() => message.name());
1931
+ const id = callNativeSync(() => message.id());
1513
1932
  return {
1514
- id: Number(callNativeSync(() => message.id())),
1933
+ id: id <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(id) : id,
1515
1934
  name,
1516
1935
  body: validateQueueBody(
1517
1936
  schemas,
@@ -1675,7 +2094,12 @@ class NativeQueueAdapter {
1675
2094
  signal?: AbortSignal;
1676
2095
  },
1677
2096
  ) {
1678
- if (!options?.signal) {
2097
+ const { token, cleanup } = await createCancellationTokenHandle(
2098
+ this.#runtime,
2099
+ options?.signal,
2100
+ );
2101
+
2102
+ try {
1679
2103
  await callNative(() =>
1680
2104
  this.#runtime.actorQueueWaitForNamesAvailable(
1681
2105
  this.#ctx,
@@ -1683,59 +2107,39 @@ class NativeQueueAdapter {
1683
2107
  {
1684
2108
  timeoutMs: options?.timeout,
1685
2109
  },
2110
+ token,
1686
2111
  ),
1687
2112
  );
1688
- return;
2113
+ } finally {
2114
+ cleanup?.();
1689
2115
  }
2116
+ }
2117
+ async waitForAvailable(
2118
+ names?: readonly string[],
2119
+ options?: { timeout?: number; signal?: AbortSignal },
2120
+ ): Promise<void> {
2121
+ await this.waitForNamesAvailable(names ?? [], options);
2122
+ }
1690
2123
 
1691
- const deadline =
1692
- options.timeout === undefined
1693
- ? undefined
1694
- : Date.now() + options.timeout;
1695
-
1696
- for (;;) {
1697
- if (options.signal.aborted) {
1698
- throw actorAbortedError();
1699
- }
1700
-
1701
- const remainingTimeout =
1702
- deadline === undefined
1703
- ? undefined
1704
- : Math.max(0, deadline - Date.now());
1705
- const sliceTimeout =
1706
- remainingTimeout === undefined
1707
- ? 100
1708
- : Math.min(remainingTimeout, 100);
1709
-
1710
- try {
1711
- await callNative(() =>
1712
- this.#runtime.actorQueueWaitForNamesAvailable(
1713
- this.#ctx,
1714
- [...names],
1715
- {
1716
- timeoutMs: sliceTimeout,
1717
- },
1718
- ),
1719
- );
1720
- return;
1721
- } catch (error) {
1722
- if (
1723
- (error as { group?: string; code?: string }).group ===
1724
- "queue" &&
1725
- (error as { group?: string; code?: string }).code ===
1726
- "timed_out"
1727
- ) {
1728
- if (
1729
- remainingTimeout === undefined ||
1730
- remainingTimeout > 100
1731
- ) {
1732
- continue;
1733
- }
1734
- }
1735
- throw error;
1736
- }
1737
- }
1738
- }
2124
+ async complete(
2125
+ message: { id: number | bigint; name: string },
2126
+ response?: unknown,
2127
+ ): Promise<void> {
2128
+ const validatedResponse = validateQueueComplete(
2129
+ this.#schemas,
2130
+ message.name,
2131
+ response,
2132
+ );
2133
+ await callNative(() =>
2134
+ this.#runtime.actorQueueCompletePersisted(
2135
+ this.#ctx,
2136
+ BigInt(message.id),
2137
+ message.name,
2138
+ encodeValue(validatedResponse),
2139
+ ),
2140
+ );
2141
+ this.#pendingCompletableMessageIds.delete(message.id.toString());
2142
+ }
1739
2143
 
1740
2144
  async enqueueAndWait(
1741
2145
  name: string,
@@ -1836,11 +2240,7 @@ class NativeQueueAdapter {
1836
2240
  }
1837
2241
  yield message;
1838
2242
  } catch (error) {
1839
- if (
1840
- isRivetErrorLike(error) &&
1841
- error.group === "actor" &&
1842
- error.code === "aborted"
1843
- ) {
2243
+ if (isActorAbortedError(error)) {
1844
2244
  return;
1845
2245
  }
1846
2246
  throw error;
@@ -2315,6 +2715,111 @@ class TrackedWebSocketHandleAdapter implements UniversalWebSocket {
2315
2715
  }
2316
2716
  }
2317
2717
 
2718
+ class NativeConnectionMap implements ReadonlyMap<string, NativeConnAdapter> {
2719
+ #runtime: CoreRuntime;
2720
+ #ctx: ActorContextHandle;
2721
+ #schemas: NativeValidationConfig;
2722
+ #assertCanMutateState: () => void;
2723
+
2724
+ constructor(
2725
+ runtime: CoreRuntime,
2726
+ ctx: ActorContextHandle,
2727
+ schemas: NativeValidationConfig,
2728
+ assertCanMutateState: () => void,
2729
+ ) {
2730
+ this.#runtime = runtime;
2731
+ this.#ctx = ctx;
2732
+ this.#schemas = schemas;
2733
+ this.#assertCanMutateState = assertCanMutateState;
2734
+ }
2735
+
2736
+ #connToAdapter(conn: ConnHandle): NativeConnAdapter {
2737
+ return new NativeConnAdapter(
2738
+ this.#runtime,
2739
+ conn,
2740
+ this.#schemas,
2741
+ this.#ctx,
2742
+ (connId) =>
2743
+ callNativeSync(() =>
2744
+ this.#runtime.actorQueueHibernationRemoval(
2745
+ this.#ctx,
2746
+ connId,
2747
+ ),
2748
+ ),
2749
+ this.#assertCanMutateState,
2750
+ );
2751
+ }
2752
+
2753
+ get size(): number {
2754
+ return callNativeSync(() => this.#runtime.actorConns(this.#ctx)).length;
2755
+ }
2756
+
2757
+ get(key: string): NativeConnAdapter | undefined {
2758
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
2759
+ const conn = conns.find((c) => this.#runtime.connId(c) === key);
2760
+ if (!conn) return undefined;
2761
+ return this.#connToAdapter(conn);
2762
+ }
2763
+
2764
+ has(key: string): boolean {
2765
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
2766
+ return conns.some((c) => this.#runtime.connId(c) === key);
2767
+ }
2768
+
2769
+ keys(): MapIterator<string> {
2770
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
2771
+ return conns
2772
+ .map((c) => this.#runtime.connId(c))
2773
+ [Symbol.iterator]() satisfies MapIterator<string>;
2774
+ }
2775
+
2776
+ values(): MapIterator<NativeConnAdapter> {
2777
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
2778
+ return conns
2779
+ .map((c) => this.#connToAdapter(c))
2780
+ [Symbol.iterator]() satisfies MapIterator<NativeConnAdapter>;
2781
+ }
2782
+
2783
+ entries(): MapIterator<[string, NativeConnAdapter]> {
2784
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
2785
+ return conns
2786
+ .map(
2787
+ (c) =>
2788
+ [this.#runtime.connId(c), this.#connToAdapter(c)] as [
2789
+ string,
2790
+ NativeConnAdapter,
2791
+ ],
2792
+ )
2793
+ [Symbol.iterator]() satisfies MapIterator<
2794
+ [string, NativeConnAdapter]
2795
+ >;
2796
+ }
2797
+
2798
+ forEach(
2799
+ callback: (
2800
+ value: NativeConnAdapter,
2801
+ key: string,
2802
+ map: ReadonlyMap<string, NativeConnAdapter>,
2803
+ ) => void,
2804
+ thisArg?: unknown,
2805
+ ): void {
2806
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
2807
+ for (const conn of conns) {
2808
+ const id = this.#runtime.connId(conn);
2809
+ callback.call(thisArg, this.#connToAdapter(conn), id, this);
2810
+ }
2811
+ }
2812
+
2813
+ [Symbol.iterator](): MapIterator<[string, NativeConnAdapter]> {
2814
+ return this.entries();
2815
+ }
2816
+
2817
+ readonly [Symbol.toStringTag] = "NativeConnectionMap";
2818
+ }
2819
+
2820
+ /** Logger cache key for code that runs outside any invocation. */
2821
+ const NO_INVOCATION_SCOPE = {};
2822
+
2318
2823
  export class ActorContextHandleAdapter {
2319
2824
  #runtime: CoreRuntime;
2320
2825
  #ctx: ActorContextHandle;
@@ -2323,18 +2828,23 @@ export class ActorContextHandleAdapter {
2323
2828
  #abortSignalCleanup?: () => void;
2324
2829
  #client?: AnyClient;
2325
2830
  #clientFactory?: () => AnyClient;
2831
+ #connMap?: NativeConnectionMap;
2832
+ #cron?: NativeCronAdapter;
2326
2833
  #databaseProvider?: Exclude<AnyDatabaseProvider, undefined>;
2327
2834
  #db?: unknown;
2328
- #dbProxy?: unknown;
2329
2835
  #dispatchCancelToken?: CancellationTokenHandle;
2330
2836
  #kv?: NativeKvAdapter;
2837
+ #logByInvocationScope = new WeakMap<object, ActorLogger>();
2331
2838
  #queue?: NativeQueueAdapter;
2332
2839
  #request?: Request;
2333
2840
  #schedule?: NativeScheduleAdapter;
2334
- #sql?: ReturnType<typeof wrapJsNativeDatabase>;
2335
- #runHandlerActiveProvider?: () => boolean;
2841
+ #run?: ActorRun;
2842
+ #runHandlerConfigured: boolean;
2336
2843
  #onStateChange?: NativeOnStateChangeHandler;
2337
2844
  #stateEnabled: boolean;
2845
+ #stateProxy?: unknown;
2846
+ #stateProxyTarget?: unknown;
2847
+ readonly #stateTransactionOwner = Symbol("actor-state-transaction-owner");
2338
2848
 
2339
2849
  constructor(
2340
2850
  runtime: CoreRuntime,
@@ -2344,16 +2854,16 @@ export class ActorContextHandleAdapter {
2344
2854
  databaseProvider?: AnyDatabaseProvider,
2345
2855
  request?: Request,
2346
2856
  stateEnabled = true,
2347
- runHandlerActiveProvider?: () => boolean,
2348
2857
  onStateChange?: NativeOnStateChangeHandler,
2349
2858
  dispatchCancelToken?: CancellationTokenHandle,
2859
+ runHandlerConfigured = false,
2350
2860
  ) {
2351
2861
  this.#runtime = runtime;
2352
2862
  this.#ctx = ctx;
2353
2863
  this.#clientFactory = clientFactory;
2354
2864
  this.#schemas = schemas;
2355
2865
  this.#dispatchCancelToken = dispatchCancelToken;
2356
- this.#runHandlerActiveProvider = runHandlerActiveProvider;
2866
+ this.#runHandlerConfigured = runHandlerConfigured;
2357
2867
  this.#onStateChange = onStateChange;
2358
2868
  this.#stateEnabled = stateEnabled;
2359
2869
  if (databaseProvider) {
@@ -2366,6 +2876,11 @@ export class ActorContextHandleAdapter {
2366
2876
  }
2367
2877
  )[ACTOR_CONTEXT_INTERNAL_SYMBOL] = new NativeWorkflowRuntimeAdapter(
2368
2878
  this,
2879
+ () =>
2880
+ this.#logByInvocationScope.delete(
2881
+ this.#runtime.currentInvocationScope() ??
2882
+ NO_INVOCATION_SCOPE,
2883
+ ),
2369
2884
  );
2370
2885
  }
2371
2886
 
@@ -2376,44 +2891,30 @@ export class ActorContextHandleAdapter {
2376
2891
  return this.#kv;
2377
2892
  }
2378
2893
 
2379
- get sql() {
2380
- if (!this.#sql) {
2381
- this.#sql = getOrCreateNativeSqlDatabase(this.#runtime, this.#ctx);
2382
- }
2383
- return this.#sql;
2384
- }
2385
-
2386
2894
  get db() {
2387
2895
  if (!this.#databaseProvider) {
2388
2896
  throw databaseNotConfiguredError();
2389
2897
  }
2390
2898
 
2391
- if (!this.#dbProxy) {
2392
- this.#dbProxy = new Proxy(
2393
- {},
2394
- {
2395
- get: (_target, property) => {
2396
- if (property === "then") {
2397
- return undefined;
2398
- }
2899
+ if (this.#db) {
2900
+ return this.#db;
2901
+ }
2399
2902
 
2400
- return async (...args: Array<unknown>) => {
2401
- const client = await this.ensureDatabaseClient();
2402
- const value = Reflect.get(
2403
- client as object,
2404
- property,
2405
- );
2406
- if (typeof value !== "function") {
2407
- return value;
2408
- }
2409
- return await value.apply(client, args);
2410
- };
2411
- },
2412
- },
2413
- );
2903
+ const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
2904
+ const cachedClient = runtimeState.databaseClient;
2905
+ if (cachedClient) {
2906
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
2907
+ return this.#db;
2414
2908
  }
2415
2909
 
2416
- return this.#dbProxy;
2910
+ throw databaseClientNotReadyError();
2911
+ }
2912
+
2913
+ [RAW_STATE_SYMBOL](): unknown {
2914
+ if (!this.#stateEnabled) {
2915
+ throw stateNotEnabledError();
2916
+ }
2917
+ return this.#readState();
2417
2918
  }
2418
2919
 
2419
2920
  get state(): unknown {
@@ -2421,15 +2922,34 @@ export class ActorContextHandleAdapter {
2421
2922
  throw stateNotEnabledError();
2422
2923
  }
2423
2924
  const nextState = this.#readState();
2424
- return createWriteThroughProxy(
2425
- nextState,
2426
- (nextValue) => {
2427
- this.#writeState(nextValue, { scheduleSave: true });
2428
- },
2429
- () => {
2925
+ // Reading `c.state` rebuilds the deep write-through proxy, which
2926
+ // allocates fresh on-change caches and rewraps the whole tree. Memoize
2927
+ // the proxy keyed on the underlying state object so repeated reads and
2928
+ // deep read cascades reuse a single proxy.
2929
+ if (
2930
+ this.#stateProxy === undefined ||
2931
+ this.#stateProxyTarget !== nextState
2932
+ ) {
2933
+ const assertCurrentState = () => {
2430
2934
  this.#assertCanMutateState();
2431
- },
2432
- );
2935
+ if (this.#readState() !== nextState) {
2936
+ throw stateTransactionConflictError();
2937
+ }
2938
+ };
2939
+ this.#stateProxyTarget = nextState;
2940
+ this.#stateProxy = createWriteThroughProxy(
2941
+ nextState,
2942
+ (nextValue) => {
2943
+ assertCurrentState();
2944
+ this.#writeState(nextValue, { scheduleSave: true });
2945
+ },
2946
+ (newValue) => {
2947
+ assertCurrentState();
2948
+ assertJsonCompatValue(newValue);
2949
+ },
2950
+ );
2951
+ }
2952
+ return this.#stateProxy;
2433
2953
  }
2434
2954
 
2435
2955
  set state(value: unknown) {
@@ -2437,14 +2957,18 @@ export class ActorContextHandleAdapter {
2437
2957
  throw stateNotEnabledError();
2438
2958
  }
2439
2959
  this.#assertCanMutateState();
2440
- this.#writeState(value, { scheduleSave: true });
2960
+ const nextValue = unwrapWriteThroughProxy(value);
2961
+ assertJsonCompatValue(nextValue);
2962
+ this.#writeState(nextValue, { scheduleSave: true });
2441
2963
  }
2442
2964
 
2443
2965
  initializeState(value: unknown): void {
2444
2966
  if (!this.#stateEnabled) {
2445
2967
  return;
2446
2968
  }
2447
- this.#writeState(value, { scheduleSave: false });
2969
+ this.#writeState(unwrapWriteThroughProxy(value), {
2970
+ scheduleSave: false,
2971
+ });
2448
2972
  }
2449
2973
 
2450
2974
  get vars(): unknown {
@@ -2475,6 +2999,36 @@ export class ActorContextHandleAdapter {
2475
2999
  return this.#queue;
2476
3000
  }
2477
3001
 
3002
+ get run() {
3003
+ if (!this.#run) {
3004
+ this.#run = {
3005
+ setWakeAt: async (timestamp: number | null) => {
3006
+ if (timestamp !== null && !this.#runHandlerConfigured) {
3007
+ throw runHandlerNotConfiguredError();
3008
+ }
3009
+ if (
3010
+ timestamp !== null &&
3011
+ (!Number.isSafeInteger(timestamp) || timestamp < 0)
3012
+ ) {
3013
+ throw new TypeError(
3014
+ "Run wake timestamp must be a non-negative safe integer or null",
3015
+ );
3016
+ }
3017
+ await callNative(() =>
3018
+ this.#runtime.actorSetRunWakeAt(this.#ctx, timestamp),
3019
+ );
3020
+ },
3021
+ startWorkflowSpan: () =>
3022
+ callNative(() =>
3023
+ this.#runtime.startWorkflowSpan(this.#ctx),
3024
+ ),
3025
+ runOutsideWorkflowSpan: (body) =>
3026
+ this.#runtime.runOutsideActorInvocationContext(body),
3027
+ };
3028
+ }
3029
+ return this.#run;
3030
+ }
3031
+
2478
3032
  get schedule(): NativeScheduleAdapter {
2479
3033
  if (!this.#schedule) {
2480
3034
  this.#schedule = new NativeScheduleAdapter(
@@ -2485,6 +3039,13 @@ export class ActorContextHandleAdapter {
2485
3039
  return this.#schedule;
2486
3040
  }
2487
3041
 
3042
+ get cron(): NativeCronAdapter {
3043
+ if (!this.#cron) {
3044
+ this.#cron = new NativeCronAdapter(this.#runtime, this.#ctx);
3045
+ }
3046
+ return this.#cron;
3047
+ }
3048
+
2488
3049
  get actorId(): string {
2489
3050
  return callNativeSync(() => this.#runtime.actorId(this.#ctx));
2490
3051
  }
@@ -2499,55 +3060,91 @@ export class ActorContextHandleAdapter {
2499
3060
  );
2500
3061
  }
2501
3062
 
3063
+ get forkChain(): ActorForkLink[] {
3064
+ return callNativeSync(() =>
3065
+ this.#runtime.actorForkChain(this.#ctx),
3066
+ ).map((link) => ({
3067
+ actorId: link.actorId,
3068
+ key: toActorKey(link.key),
3069
+ forkedAt: link.forkedAt,
3070
+ }));
3071
+ }
3072
+
2502
3073
  get region(): string {
2503
3074
  return callNativeSync(() => this.#runtime.actorRegion(this.#ctx));
2504
3075
  }
2505
3076
 
2506
- get conns(): Map<string, NativeConnAdapter> {
2507
- return new Map(
2508
- callNativeSync(() => this.#runtime.actorConns(this.#ctx)).map(
2509
- (conn) => [
2510
- this.#runtime.connId(conn),
2511
- new NativeConnAdapter(
2512
- this.#runtime,
2513
- conn,
2514
- this.#schemas,
2515
- this.#ctx,
2516
- (connId) =>
2517
- callNativeSync(() =>
2518
- this.#runtime.actorQueueHibernationRemoval(
2519
- this.#ctx,
2520
- connId,
2521
- ),
2522
- ),
2523
- ),
2524
- ],
2525
- ),
3077
+ get namespace(): string {
3078
+ return callNativeSync(() => this.#runtime.actorNamespace(this.#ctx));
3079
+ }
3080
+
3081
+ get conns(): ReadonlyMap<string, NativeConnAdapter> {
3082
+ if (!this.#connMap) {
3083
+ this.#connMap = new NativeConnectionMap(
3084
+ this.#runtime,
3085
+ this.#ctx,
3086
+ this.#schemas,
3087
+ () => this.#assertCanMutateState(),
3088
+ );
3089
+ }
3090
+ return this.#connMap;
3091
+ }
3092
+
3093
+ #invocationTraceContext(): ActorInvocationTraceContext | undefined {
3094
+ return callNativeSync(() =>
3095
+ this.#runtime.actorInvocationTraceContext(this.#ctx),
2526
3096
  );
2527
3097
  }
2528
3098
 
3099
+ /**
3100
+ * Cached per invocation, because the `run` context outlives workflow runs and steps.
3101
+ * A workflow queue receive clears the entry, because the run's ray becomes the message's ray.
3102
+ */
2529
3103
  get log() {
2530
- return logger();
3104
+ const scope =
3105
+ this.#runtime.currentInvocationScope() ?? NO_INVOCATION_SCOPE;
3106
+ const cached = this.#logByInvocationScope.get(scope);
3107
+ if (cached) return cached;
3108
+
3109
+ const invocation = this.#invocationTraceContext();
3110
+ const log = logger().child({
3111
+ actorId: this.actorId,
3112
+ actorName: this.name,
3113
+ actorKey: this.key,
3114
+ ...(invocation?.rayId && { rayId: invocation.rayId }),
3115
+ ...(invocation?.span && {
3116
+ traceId: invocation.span.traceId,
3117
+ spanId: invocation.span.spanId,
3118
+ }),
3119
+ });
3120
+ this.#logByInvocationScope.set(scope, log);
3121
+ return log;
2531
3122
  }
2532
3123
 
2533
3124
  get abortSignal(): AbortSignal {
2534
3125
  if (!this.#abortSignal) {
2535
- const actorSignal = this.#createActorAbortSignal();
3126
+ const actorAbort = this.#actorAbort();
3127
+ const actorSignal = actorAbort.signal;
2536
3128
  if (this.#dispatchCancelToken === undefined) {
2537
3129
  this.#abortSignal = actorSignal;
2538
3130
  } else {
2539
3131
  const controller = new AbortController();
2540
3132
  let cleanedUp = false;
3133
+ let releaseDispatchListener: (() => void) | undefined;
2541
3134
  const onActorAbort = () => {
2542
3135
  cleanup();
2543
3136
  controller.abort();
2544
3137
  };
3138
+ // Releasing the native listener on dispose frees it even when the
3139
+ // dispatch token is never cancelled.
2545
3140
  const cleanup = () => {
2546
3141
  if (cleanedUp) {
2547
3142
  return;
2548
3143
  }
2549
3144
  cleanedUp = true;
2550
- actorSignal.removeEventListener("abort", onActorAbort);
3145
+ actorAbort.listeners.delete(onActorAbort);
3146
+ releaseDispatchListener?.();
3147
+ releaseDispatchListener = undefined;
2551
3148
  this.#abortSignalCleanup = undefined;
2552
3149
  };
2553
3150
 
@@ -2561,10 +3158,8 @@ export class ActorContextHandleAdapter {
2561
3158
  } else {
2562
3159
  const dispatchCancelToken = this.#dispatchCancelToken;
2563
3160
  this.#abortSignalCleanup = cleanup;
2564
- actorSignal.addEventListener("abort", onActorAbort, {
2565
- once: true,
2566
- });
2567
- callNativeSync(() =>
3161
+ actorAbort.listeners.add(onActorAbort);
3162
+ releaseDispatchListener = callNativeSync(() =>
2568
3163
  this.#runtime.onCancellationTokenCancelled(
2569
3164
  dispatchCancelToken,
2570
3165
  () => {
@@ -2601,12 +3196,12 @@ export class ActorContextHandleAdapter {
2601
3196
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
2602
3197
  const cachedClient = runtimeState.databaseClient;
2603
3198
  if (cachedClient) {
2604
- this.#db = cachedClient.client;
3199
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
2605
3200
  return this.#db;
2606
3201
  }
2607
3202
 
2608
3203
  const actorId = this.actorId;
2609
- const client = await this.#databaseProvider.createClient({
3204
+ const createdClient = await this.#databaseProvider.createClient({
2610
3205
  actorId,
2611
3206
  kv: {
2612
3207
  batchPut: async (entries) => {
@@ -2627,21 +3222,153 @@ export class ActorContextHandleAdapter {
2627
3222
  log: {
2628
3223
  debug: (obj) => logger().debug(obj),
2629
3224
  },
2630
- nativeDatabaseProvider: {
2631
- open: async (requestedActorId) => {
2632
- void requestedActorId;
2633
- return getOrCreateNativeSqlDatabase(
3225
+ nativeDatabaseProvider: registerNativeStateTransactionOpener(
3226
+ {
3227
+ open: async (requestedActorId) => {
3228
+ void requestedActorId;
3229
+ const database = getOrCreateNativeSqlDatabase(
3230
+ this.#runtime,
3231
+ this.#ctx,
3232
+ );
3233
+ // Synchronous calls need an open database. Other actors keep opening
3234
+ // it on first use.
3235
+ if (usesSqliteDeferredCommits(this.#databaseProvider)) {
3236
+ await database.open();
3237
+ }
3238
+ return database;
3239
+ },
3240
+ },
3241
+ async (timeoutMs, context, name) =>
3242
+ await getOrCreateNativeSqlDatabase(
2634
3243
  this.#runtime,
2635
3244
  this.#ctx,
2636
- );
2637
- },
2638
- },
3245
+ ).beginStateTransaction(timeoutMs, context, name),
3246
+ ),
2639
3247
  });
2640
3248
  runtimeState.databaseClient = {
2641
- client,
3249
+ client: createdClient,
2642
3250
  };
2643
- this.#db = client;
2644
- return client;
3251
+ this.#db = this.#bindDatabaseClient(createdClient);
3252
+ return this.#db;
3253
+ }
3254
+
3255
+ #bindDatabaseClient(client: unknown): unknown {
3256
+ return bindNativeStateTransactionContext(client, {
3257
+ enter: async () => await this.#enterStateTransaction(),
3258
+ exit: (scope) =>
3259
+ this.#exitStateTransaction(
3260
+ scope as NativeStateTransactionScope,
3261
+ ),
3262
+ });
3263
+ }
3264
+
3265
+ async #enterStateTransaction(): Promise<NativeStateTransactionScope> {
3266
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
3267
+ let pendingOwners = actorState.pendingStateTransactionOwners;
3268
+ if (!pendingOwners) {
3269
+ pendingOwners = new Set();
3270
+ actorState.pendingStateTransactionOwners = pendingOwners;
3271
+ }
3272
+ if (
3273
+ actorState.activeStateTransactionOwner ===
3274
+ this.#stateTransactionOwner ||
3275
+ pendingOwners.has(this.#stateTransactionOwner)
3276
+ ) {
3277
+ throw stateTransactionConflictError();
3278
+ }
3279
+ pendingOwners.add(this.#stateTransactionOwner);
3280
+ const predecessor =
3281
+ actorState.stateTransactionTail ?? Promise.resolve();
3282
+ let release!: () => void;
3283
+ const hold = new Promise<void>((resolve) => {
3284
+ release = resolve;
3285
+ });
3286
+ actorState.stateTransactionTail = predecessor.then(
3287
+ async () => await hold,
3288
+ );
3289
+ try {
3290
+ await predecessor;
3291
+ pendingOwners.delete(this.#stateTransactionOwner);
3292
+ actorState.activeStateTransactionOwner =
3293
+ this.#stateTransactionOwner;
3294
+ return {
3295
+ actorContext: this,
3296
+ actorStateBaseline: this.#stateEnabled
3297
+ ? structuredClone(this.#readState())
3298
+ : undefined,
3299
+ connectionStateBaselines: new Map(
3300
+ callNativeSync(() =>
3301
+ this.#runtime.actorConns(this.#ctx),
3302
+ ).map((conn) => [
3303
+ callNativeSync(() => this.#runtime.connId(conn)),
3304
+ new Uint8Array(
3305
+ callNativeSync(() => this.#runtime.connState(conn)),
3306
+ ),
3307
+ ]),
3308
+ ),
3309
+ committed: false,
3310
+ release,
3311
+ };
3312
+ } catch (error) {
3313
+ pendingOwners.delete(this.#stateTransactionOwner);
3314
+ if (
3315
+ actorState.activeStateTransactionOwner ===
3316
+ this.#stateTransactionOwner
3317
+ ) {
3318
+ actorState.activeStateTransactionOwner = undefined;
3319
+ }
3320
+ release();
3321
+ throw error;
3322
+ }
3323
+ }
3324
+
3325
+ #exitStateTransaction(scope: NativeStateTransactionScope): void {
3326
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
3327
+ try {
3328
+ if (!scope.committed) {
3329
+ this.#restoreStateTransactionBaseline(scope);
3330
+ }
3331
+ } finally {
3332
+ if (
3333
+ actorState.activeStateTransactionOwner ===
3334
+ this.#stateTransactionOwner
3335
+ ) {
3336
+ actorState.activeStateTransactionOwner = undefined;
3337
+ }
3338
+ if (actorState.stateTransactionSaveDeferred) {
3339
+ actorState.stateTransactionSaveDeferred = false;
3340
+ this.#scheduleSave();
3341
+ }
3342
+ scope.release();
3343
+ }
3344
+ }
3345
+
3346
+ #restoreStateTransactionBaseline(scope: NativeStateTransactionScope): void {
3347
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
3348
+ if (actorState.pendingSaveHandle !== undefined) {
3349
+ clearImmediate(actorState.pendingSaveHandle);
3350
+ }
3351
+ actorState.pendingSaveHandle = undefined;
3352
+ actorState.saveScheduled = false;
3353
+
3354
+ if (this.#stateEnabled) {
3355
+ actorState.state = structuredClone(scope.actorStateBaseline);
3356
+ }
3357
+ for (const conn of callNativeSync(() =>
3358
+ this.#runtime.actorConns(this.#ctx),
3359
+ )) {
3360
+ const connId = callNativeSync(() => this.#runtime.connId(conn));
3361
+ const baseline = scope.connectionStateBaselines.get(connId);
3362
+ if (baseline === undefined) {
3363
+ continue;
3364
+ }
3365
+ callNativeSync(() => this.#runtime.connSetState(conn, baseline));
3366
+ const cached = actorState.connStates.get(connId);
3367
+ if (cached) {
3368
+ cached.state = decodeValue(baseline);
3369
+ }
3370
+ }
3371
+ this.#scheduleSave();
2645
3372
  }
2646
3373
 
2647
3374
  async prepare(): Promise<void> {
@@ -2664,7 +3391,6 @@ export class ActorContextHandleAdapter {
2664
3391
 
2665
3392
  async closeDatabase(): Promise<void> {
2666
3393
  this.#db = undefined;
2667
- this.#sql = undefined;
2668
3394
  await closeNativeDatabaseClient(this.#runtime, this.#ctx);
2669
3395
  await closeNativeSqlDatabase(this.#runtime, this.#ctx);
2670
3396
  }
@@ -2689,6 +3415,7 @@ export class ActorContextHandleAdapter {
2689
3415
  maxWait?: number;
2690
3416
  }): Promise<void> {
2691
3417
  if (opts?.immediate) {
3418
+ this.#assertCanAwaitStateSave();
2692
3419
  await callNative(() =>
2693
3420
  this.#runtime.actorRequestSaveAndWait(this.#ctx, {
2694
3421
  immediate: true,
@@ -2711,6 +3438,25 @@ export class ActorContextHandleAdapter {
2711
3438
  );
2712
3439
  }
2713
3440
 
3441
+ async saveStateAndWorkflowBatch(
3442
+ writes: Array<{ key: Uint8Array; value: Uint8Array }>,
3443
+ ): Promise<void> {
3444
+ this.#assertCanAwaitStateSave();
3445
+ await callNative(() =>
3446
+ this.#runtime.actorSaveStateAndWorkflowBatch(this.#ctx, writes),
3447
+ );
3448
+ }
3449
+
3450
+ #assertCanAwaitStateSave(): void {
3451
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
3452
+ if (
3453
+ actorState.activeStateTransactionOwner ===
3454
+ this.#stateTransactionOwner
3455
+ ) {
3456
+ throw stateTransactionConflictError();
3457
+ }
3458
+ }
3459
+
2714
3460
  serializeForTick(reason: SerializeStateReason): RuntimeStateDeltaPayload {
2715
3461
  void reason;
2716
3462
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -2774,13 +3520,17 @@ export class ActorContextHandleAdapter {
2774
3520
  return promise;
2775
3521
  }
2776
3522
 
2777
- runHandlerActive(): boolean {
2778
- return this.#runHandlerActiveProvider?.() ?? false;
2779
- }
2780
-
2781
3523
  internalKeepAwake<T>(run: Promise<T> | (() => Promise<T>)): Promise<T> {
2782
3524
  const promise = typeof run === "function" ? run() : run;
2783
- const trackedPromise = promise.then(() => null);
3525
+ // Track only completion, swallowing the outcome. The real result/error
3526
+ // is delivered through the returned `promise`; without a rejection
3527
+ // handler here every workflow yield (which rejects with SleepError)
3528
+ // would be funneled into the registered task and logged as a spurious
3529
+ // "keep_awake promise rejected" warning.
3530
+ const trackedPromise = promise.then(
3531
+ () => null,
3532
+ () => null,
3533
+ );
2784
3534
  try {
2785
3535
  callNativeSync(() =>
2786
3536
  this.#runtime.actorRegisterTask(this.#ctx, trackedPromise),
@@ -2826,22 +3576,23 @@ export class ActorContextHandleAdapter {
2826
3576
  // need to keep an actor awake should use `keepAwake(promise)` or
2827
3577
  // `waitUntil(promise)` so the native counter machinery in rivetkit-core
2828
3578
  // owns the lifecycle.
2829
- /** @deprecated Use `keepAwake(promise)` or `waitUntil(promise)` instead. */
3579
+ /** @deprecated `setPreventSleep` was deprecated in 3.0 and will be removed in a future version. It is a no-op. Use `c.keepAwake(promise)` or `c.waitUntil(promise)`. See https://rivet.dev/actors/docs/deprecated/prevent-sleep */
2830
3580
  setPreventSleep(_preventSleep: boolean): void {
2831
3581
  logger().warn({
2832
- msg: "setPreventSleep is deprecated and is a no-op; use keepAwake(promise) or waitUntil(promise) instead",
3582
+ msg: "setPreventSleep was deprecated in 3.0 and will be removed in a future version. It is a no-op; use keepAwake(promise) or waitUntil(promise) instead. See https://rivet.dev/actors/docs/deprecated/prevent-sleep",
2833
3583
  });
2834
3584
  }
2835
3585
 
2836
- /** @deprecated Use `keepAwake(promise)` or `waitUntil(promise)` instead. */
3586
+ /** @deprecated `preventSleep` was deprecated in 3.0 and will be removed in a future version. It is a no-op that always returns `false`. Use `c.keepAwake(promise)` or `c.waitUntil(promise)`. See https://rivet.dev/actors/docs/deprecated/prevent-sleep */
2837
3587
  get preventSleep(): boolean {
2838
3588
  logger().warn({
2839
- msg: "preventSleep is deprecated and always returns false; use keepAwake(promise) or waitUntil(promise) instead",
3589
+ msg: "preventSleep was deprecated in 3.0 and will be removed in a future version. It always returns false; use keepAwake(promise) or waitUntil(promise) instead. See https://rivet.dev/actors/docs/deprecated/prevent-sleep",
2840
3590
  });
2841
3591
  return false;
2842
3592
  }
2843
3593
 
2844
3594
  sleep(): void {
3595
+ this.#flushStateChange();
2845
3596
  callNativeSync(() => this.#runtime.actorSleep(this.#ctx));
2846
3597
  }
2847
3598
 
@@ -2865,23 +3616,50 @@ export class ActorContextHandleAdapter {
2865
3616
  }
2866
3617
 
2867
3618
  async dispose(): Promise<void> {
3619
+ // Flush any save coalesced for this tick before the context is torn
3620
+ // down so the request-save and onStateChange always run. Shutdown
3621
+ // cleanup may already have cleared the generation, which leaves no
3622
+ // pending save to flush.
3623
+ if (!isNativeRuntimeStateCleared(this.#runtime, this.#ctx)) {
3624
+ this.#flushStateChange();
3625
+ }
2868
3626
  this.#abortSignalCleanup?.();
2869
- this.#sql = undefined;
2870
3627
  }
2871
3628
 
2872
- #createActorAbortSignal(): AbortSignal {
3629
+ #actorAbort(): NativeActorAbort {
3630
+ // An aborted cached signal may belong to a previous generation, so
3631
+ // only a live one is reused.
3632
+ const runtimeState = readNativeRuntimeStateBag(
3633
+ this.#runtime,
3634
+ this.#ctx,
3635
+ );
3636
+ const cached = runtimeState.actorAbort;
3637
+ if (cached && !cached.signal.aborted) {
3638
+ return cached;
3639
+ }
3640
+
2873
3641
  const nativeSignal = callNativeSync(() =>
2874
3642
  this.#runtime.actorAbortSignal(this.#ctx),
2875
3643
  );
2876
3644
  const controller = new AbortController();
2877
- if (nativeSignal.aborted) {
3645
+ const actorAbort: NativeActorAbort = {
3646
+ signal: controller.signal,
3647
+ listeners: new Set(),
3648
+ };
3649
+ const abort = () => {
2878
3650
  controller.abort();
3651
+ for (const listener of actorAbort.listeners) {
3652
+ listener();
3653
+ }
3654
+ actorAbort.listeners.clear();
3655
+ };
3656
+ if (nativeSignal.aborted) {
3657
+ abort();
2879
3658
  } else {
2880
- nativeSignal.addEventListener("abort", () => controller.abort(), {
2881
- once: true,
2882
- });
3659
+ nativeSignal.addEventListener("abort", abort, { once: true });
2883
3660
  }
2884
- return controller.signal;
3661
+ runtimeState.actorAbort = actorAbort;
3662
+ return actorAbort;
2885
3663
  }
2886
3664
 
2887
3665
  #readState(): unknown {
@@ -2900,13 +3678,12 @@ export class ActorContextHandleAdapter {
2900
3678
  scheduleSave: boolean;
2901
3679
  },
2902
3680
  ): void {
2903
- encodeValue(value);
2904
3681
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
2905
3682
  actorState.state = value;
2906
3683
  if (!options.scheduleSave) {
2907
3684
  return;
2908
3685
  }
2909
- this.#handleStateChange();
3686
+ this.#scheduleSave();
2910
3687
  }
2911
3688
 
2912
3689
  #assertCanMutateState(): void {
@@ -2914,11 +3691,57 @@ export class ActorContextHandleAdapter {
2914
3691
  if (actorState.isInOnStateChange) {
2915
3692
  throw stateMutationReentrantError();
2916
3693
  }
3694
+ if (
3695
+ actorState.activeStateTransactionOwner !==
3696
+ this.#stateTransactionOwner &&
3697
+ (actorState.activeStateTransactionOwner !== undefined ||
3698
+ (actorState.pendingStateTransactionOwners?.size ?? 0) > 0)
3699
+ ) {
3700
+ throw stateTransactionConflictError();
3701
+ }
3702
+ }
3703
+
3704
+ /** @internal */
3705
+ assertCanMutateState(): void {
3706
+ this.#assertCanMutateState();
3707
+ }
3708
+
3709
+ // Coalesce the request-save and onStateChange work to once per event loop
3710
+ // tick. A synchronous burst of mutations (for example
3711
+ // `Object.assign(c.state, ...)`) would otherwise cross the NAPI boundary and
3712
+ // run onStateChange once per field, re-serializing the whole state each time
3713
+ // and pinning the event loop on large state.
3714
+ #scheduleSave(): void {
3715
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
3716
+ if (actorState.saveScheduled) {
3717
+ return;
3718
+ }
3719
+ actorState.saveScheduled = true;
3720
+ actorState.pendingSaveHandle = setImmediate(() => {
3721
+ this.#flushStateChange();
3722
+ });
2917
3723
  }
2918
3724
 
2919
- #handleStateChange(): void {
3725
+ #flushStateChange(): void {
2920
3726
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
2921
- encodeValue(actorState.state);
3727
+ if (!actorState.saveScheduled) {
3728
+ return;
3729
+ }
3730
+ if (actorState.activeStateTransactionOwner !== undefined) {
3731
+ actorState.saveScheduled = false;
3732
+ if (actorState.pendingSaveHandle !== undefined) {
3733
+ clearImmediate(actorState.pendingSaveHandle);
3734
+ actorState.pendingSaveHandle = undefined;
3735
+ }
3736
+ actorState.stateTransactionSaveDeferred = true;
3737
+ return;
3738
+ }
3739
+ actorState.saveScheduled = false;
3740
+ if (actorState.pendingSaveHandle !== undefined) {
3741
+ clearImmediate(actorState.pendingSaveHandle);
3742
+ actorState.pendingSaveHandle = undefined;
3743
+ }
3744
+
2922
3745
  callNativeSync(() =>
2923
3746
  this.#runtime.actorRequestSave(this.#ctx, { immediate: false }),
2924
3747
  );
@@ -2968,6 +3791,7 @@ type NativeWorkflowQueueMessage = Awaited<
2968
3791
 
2969
3792
  class NativeWorkflowRuntimeAdapter {
2970
3793
  #ctx: ActorContextHandleAdapter;
3794
+ #onMessagesReceived: () => void;
2971
3795
  #completions = new Map<string, (response?: unknown) => Promise<void>>();
2972
3796
 
2973
3797
  readonly id: string;
@@ -3030,10 +3854,17 @@ class NativeWorkflowRuntimeAdapter {
3030
3854
  immediate?: boolean;
3031
3855
  maxWait?: number;
3032
3856
  }) => Promise<void>;
3857
+ saveStateAndWorkflowBatch: (
3858
+ writes: Array<{ key: Uint8Array; value: Uint8Array }>,
3859
+ ) => Promise<void>;
3033
3860
  };
3034
3861
 
3035
- constructor(ctx: ActorContextHandleAdapter) {
3862
+ constructor(
3863
+ ctx: ActorContextHandleAdapter,
3864
+ onMessagesReceived: () => void,
3865
+ ) {
3036
3866
  this.#ctx = ctx;
3867
+ this.#onMessagesReceived = onMessagesReceived;
3037
3868
  this.id = ctx.actorId;
3038
3869
  this.driver = {
3039
3870
  kvBatchGet: async (actorId, keys) => {
@@ -3079,6 +3910,9 @@ class NativeWorkflowRuntimeAdapter {
3079
3910
  timeout: timeout ?? 0,
3080
3911
  completable,
3081
3912
  });
3913
+ if (messages.length > 0) {
3914
+ this.#onMessagesReceived();
3915
+ }
3082
3916
  return messages.map((message) =>
3083
3917
  this.#wrapQueueMessage(message),
3084
3918
  );
@@ -3105,13 +3939,12 @@ class NativeWorkflowRuntimeAdapter {
3105
3939
  saveState: async (opts) => {
3106
3940
  await this.#ctx.saveState(opts);
3107
3941
  },
3942
+ saveStateAndWorkflowBatch: async (writes) => {
3943
+ await this.#ctx.saveStateAndWorkflowBatch(writes);
3944
+ },
3108
3945
  };
3109
3946
  }
3110
3947
 
3111
- isRunHandlerActive(): boolean {
3112
- return this.#ctx.runHandlerActive();
3113
- }
3114
-
3115
3948
  async restartRunHandler(): Promise<void> {
3116
3949
  await this.#ctx.restartRunHandler();
3117
3950
  }
@@ -3159,45 +3992,83 @@ function withConnContext(
3159
3992
  stateEnabled = true,
3160
3993
  onStateChange?: NativeOnStateChangeHandler,
3161
3994
  dispatchCancelToken?: CancellationTokenHandle,
3995
+ runHandlerConfigured = false,
3162
3996
  ) {
3163
- return Object.assign(
3164
- new ActorContextHandleAdapter(
3997
+ const actorContext = new ActorContextHandleAdapter(
3998
+ runtime,
3999
+ ctx,
4000
+ clientFactory,
4001
+ schemas,
4002
+ databaseProvider,
4003
+ request,
4004
+ stateEnabled,
4005
+ onStateChange,
4006
+ dispatchCancelToken,
4007
+ runHandlerConfigured,
4008
+ );
4009
+ return Object.assign(actorContext, {
4010
+ conn: new NativeConnAdapter(
3165
4011
  runtime,
3166
- ctx,
3167
- clientFactory,
4012
+ conn,
3168
4013
  schemas,
3169
- databaseProvider,
3170
- request,
3171
- stateEnabled,
3172
- undefined,
3173
- onStateChange,
3174
- dispatchCancelToken,
3175
- ),
3176
- {
3177
- conn: new NativeConnAdapter(runtime, conn, schemas, ctx, (connId) =>
4014
+ ctx,
4015
+ (connId) =>
3178
4016
  callNativeSync(() =>
3179
4017
  runtime.actorQueueHibernationRemoval(ctx, connId),
3180
4018
  ),
3181
- ),
3182
- },
4019
+ () => actorContext.assertCanMutateState(),
4020
+ ),
4021
+ });
4022
+ }
4023
+
4024
+ function buildActorTracingConfig(
4025
+ actions: unknown,
4026
+ tracing: { sampler?: number; actions?: ActionSampleRates } | undefined,
4027
+ ): RuntimeActorTracingConfig | undefined {
4028
+ if (tracing === undefined) return undefined;
4029
+ return {
4030
+ sampler: tracing.sampler,
4031
+ actions: flattenActionTraceSamplers(actions, tracing.actions),
4032
+ };
4033
+ }
4034
+
4035
+ const SQLITE_DEFERRED_COMMITS = Symbol.for("rivetkit.sqlite.deferredCommits");
4036
+
4037
+ // Internal opt-in for embedders, such as Open Orange, that gate outputs on `whenDurable`.
4038
+ function usesSqliteDeferredCommits(databaseProvider: unknown): boolean {
4039
+ return (
4040
+ (databaseProvider as Record<symbol, unknown> | undefined)?.[
4041
+ SQLITE_DEFERRED_COMMITS
4042
+ ] === true
3183
4043
  );
3184
4044
  }
3185
4045
 
3186
4046
  function buildActorConfig(
3187
4047
  definition: AnyActorDefinition,
3188
4048
  registryConfig: RegistryConfig,
4049
+ runtimeKind: "napi" | "wasm",
3189
4050
  ): RuntimeActorConfig {
3190
4051
  const config = definition.config as unknown as Record<string, unknown>;
3191
4052
  const options = (config.options ?? {}) as Record<string, unknown>;
3192
4053
  const canHibernate = options.canHibernateWebSocket;
4054
+ const usesRemoteSqlite =
4055
+ sqliteBackendForConfig(registryConfig) === "remote";
4056
+ const sqliteProfiling = (
4057
+ config.db as { sqliteProfiling?: SqliteProfilingOptions } | undefined
4058
+ )?.sqliteProfiling;
4059
+ const sqliteDeferredCommits = usesSqliteDeferredCommits(config.db);
3193
4060
 
3194
4061
  return {
3195
4062
  name: options.name as string | undefined,
3196
4063
  icon: options.icon as string | undefined,
3197
- hasDatabase: config.db !== undefined,
3198
- remoteSqlite:
3199
- config.db !== undefined &&
3200
- sqliteBackendForConfig(registryConfig) === "remote",
4064
+ hasDatabase: true,
4065
+ remoteSqlite: usesRemoteSqlite,
4066
+ sqliteDeferredCommits: sqliteDeferredCommits || undefined,
4067
+ sqliteProfiling,
4068
+ tracing: buildActorTracingConfig(
4069
+ definition.config.actions,
4070
+ definition.config.tracing,
4071
+ ),
3201
4072
  hasState:
3202
4073
  config.state !== undefined ||
3203
4074
  typeof config.createState === "function",
@@ -3224,6 +4095,7 @@ function buildActorConfig(
3224
4095
  | number
3225
4096
  | undefined,
3226
4097
  maxQueueSize: options.maxQueueSize as number | undefined,
4098
+ maxSchedules: options.maxSchedules as number | undefined,
3227
4099
  maxQueueMessageSize: options.maxQueueMessageSize as number | undefined,
3228
4100
  maxIncomingMessageSize: registryConfig.maxIncomingMessageSize as
3229
4101
  | number
@@ -3237,49 +4109,155 @@ function buildActorConfig(
3237
4109
  preloadMaxConnectionsBytes: options.preloadMaxConnectionsBytes as
3238
4110
  | number
3239
4111
  | undefined,
3240
- actions: Object.keys((config.actions ?? {}) as Record<string, unknown>)
4112
+ actions: Object.keys(flattenActionHandlers(config.actions))
3241
4113
  .sort()
3242
4114
  .map((name) => ({ name })),
4115
+ inspectorTabs: buildInspectorTabs(config.inspector, runtimeKind),
3243
4116
  };
3244
4117
  }
3245
4118
 
4119
+ function buildInspectorTabs(
4120
+ inspector: unknown,
4121
+ runtimeKind: "napi" | "wasm",
4122
+ ): Array<RuntimeInspectorTabEntry> | undefined {
4123
+ if (!inspector || typeof inspector !== "object") return undefined;
4124
+ const tabs = (inspector as { tabs?: unknown }).tabs;
4125
+ if (!Array.isArray(tabs) || tabs.length === 0) return undefined;
4126
+ return tabs.map((raw) => {
4127
+ const entry = raw as {
4128
+ id: string;
4129
+ label?: string;
4130
+ source?: string;
4131
+ icon?: string;
4132
+ hidden?: boolean;
4133
+ };
4134
+ if (entry.hidden === true) {
4135
+ return { id: entry.id, hidden: true };
4136
+ }
4137
+
4138
+ if (runtimeKind === "wasm") {
4139
+ if (entry.source !== undefined) {
4140
+ logger().warn(
4141
+ {
4142
+ tabId: entry.id,
4143
+ runtimeKind,
4144
+ },
4145
+ "inspector.tabs[].source is not supported on wasm runners (current host: wasm). Tab descriptors will still appear in the dashboard strip but the tab body will render a not-available placeholder.",
4146
+ );
4147
+ }
4148
+ return {
4149
+ id: entry.id,
4150
+ label: entry.label,
4151
+ icon: entry.icon,
4152
+ source: undefined,
4153
+ };
4154
+ }
4155
+
4156
+ const resolved =
4157
+ entry.source !== undefined
4158
+ ? getNodePath().resolve(entry.source)
4159
+ : undefined;
4160
+ if (resolved !== undefined) {
4161
+ validateInspectorTabSource(entry.id, resolved);
4162
+ }
4163
+ return {
4164
+ id: entry.id,
4165
+ label: entry.label,
4166
+ icon: entry.icon,
4167
+ source: resolved,
4168
+ };
4169
+ });
4170
+ }
4171
+
4172
+ function validateInspectorTabSource(tabId: string, resolved: string): void {
4173
+ if (resolved === getNodePath().parse(resolved).root) {
4174
+ throw new Error(
4175
+ `inspector.tabs[id="${tabId}"].source resolves to the filesystem root (${resolved}). ` +
4176
+ "Point it at the tab's own static-asset directory instead.",
4177
+ );
4178
+ }
4179
+ let stat: import("node:fs").Stats;
4180
+ try {
4181
+ stat = getNodeFsSync().statSync(resolved);
4182
+ } catch (err) {
4183
+ const code = (err as NodeJS.ErrnoException)?.code;
4184
+ if (code === "ENOENT") {
4185
+ throw new Error(
4186
+ `inspector.tabs[id="${tabId}"].source (${resolved}) does not exist.`,
4187
+ );
4188
+ }
4189
+ if (code === "EACCES") {
4190
+ throw new Error(
4191
+ `inspector.tabs[id="${tabId}"].source (${resolved}) is not readable (EACCES).`,
4192
+ );
4193
+ }
4194
+ throw new Error(
4195
+ `inspector.tabs[id="${tabId}"].source (${resolved}) could not be stat'd: ${
4196
+ (err as Error)?.message ?? err
4197
+ }`,
4198
+ );
4199
+ }
4200
+ if (!stat.isDirectory()) {
4201
+ throw new Error(
4202
+ `inspector.tabs[id="${tabId}"].source (${resolved}) must be a directory, got ${
4203
+ stat.isFile() ? "file" : "non-directory"
4204
+ }.`,
4205
+ );
4206
+ }
4207
+ }
4208
+
3246
4209
  export function buildNativeFactory(
3247
4210
  runtime: CoreRuntime,
3248
4211
  registryConfig: RegistryConfig,
3249
4212
  definition: AnyActorDefinition,
3250
4213
  ): ActorFactoryHandle {
3251
4214
  const config = definition.config as Record<string, any>;
3252
- const databaseProvider = config.db as AnyDatabaseProvider;
4215
+ const databaseProvider = (config.db ?? defaultDb()) as Exclude<
4216
+ AnyDatabaseProvider,
4217
+ undefined
4218
+ >;
4219
+ const actionHandlers = flattenActionHandlers(config.actions);
3253
4220
  const schemaConfig: NativeValidationConfig = {
3254
- actionInputSchemas: config.actionInputSchemas,
4221
+ actionInputSchemas: flattenActionInputSchemas(
4222
+ config.actions,
4223
+ config.actionInputSchemas,
4224
+ ),
3255
4225
  connParamsSchema: config.connParamsSchema,
3256
4226
  events: config.events,
3257
4227
  queues: config.queues,
3258
4228
  };
3259
- const actionHandlers = Object.fromEntries(
3260
- (
3261
- Object.entries(config.actions ?? {}) as Array<
3262
- [string, (...args: Array<any>) => any]
3263
- >
3264
- ).map(([name, handler]) => [name, handler]),
3265
- );
3266
- const createClient = () =>
4229
+ const createClient = (ctx: ActorContextHandle) =>
3267
4230
  createClientWithDriver(
3268
4231
  new RemoteEngineControlClient(
3269
4232
  convertRegistryConfigToClientConfig(registryConfig),
3270
4233
  ),
3271
- { encoding: "bare" },
4234
+ {
4235
+ encoding: "bare",
4236
+ currentActorInvocation: () =>
4237
+ callNativeSync(() =>
4238
+ runtime.actorInvocationTraceContext(ctx),
4239
+ ),
4240
+ startCallSpan: (actorName, actionName) =>
4241
+ callNativeSync(() =>
4242
+ runtime.startCallSpan(ctx, actorName, actionName),
4243
+ ),
4244
+ },
3272
4245
  );
3273
- const nativeRunHandlerActiveByActorId = new Map<string, boolean>();
3274
- const isNativeRunHandlerActive = (ctx: ActorContextHandle) =>
3275
- nativeRunHandlerActiveByActorId.get(
3276
- callNativeSync(() => runtime.actorId(ctx)),
3277
- ) ?? false;
3278
- const getNativeWorkflowInspector = (ctx: ActorContextHandle) =>
3279
- getRunInspectorConfig(
3280
- config.run,
3281
- callNativeSync(() => runtime.actorId(ctx)),
3282
- )?.workflow as NativeWorkflowInspectorConfig | undefined;
4246
+ const run = getRunFunction(config.run);
4247
+ const runHandlerCoordinator =
4248
+ getRunInspectorKind(config.run) === "workflow"
4249
+ ? new RunHandlerCoordinator(config.run)
4250
+ : undefined;
4251
+ const getNativeWorkflowInspector = (ctx: ActorContextHandle) => {
4252
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
4253
+ const restart = () =>
4254
+ callNativeSync(() => runtime.actorRestartRunHandler(ctx));
4255
+ return (runHandlerCoordinator?.getInspector(actorId, restart)
4256
+ ?.workflow ??
4257
+ getRunInspectorConfig(config.run, actorId)?.workflow) as
4258
+ | NativeWorkflowInspectorConfig
4259
+ | undefined;
4260
+ };
3283
4261
  const onStateChange =
3284
4262
  typeof config.onStateChange === "function"
3285
4263
  ? (actorCtx: ActorContextHandleAdapter, nextState: unknown) => {
@@ -3307,14 +4285,14 @@ export function buildNativeFactory(
3307
4285
  new ActorContextHandleAdapter(
3308
4286
  runtime,
3309
4287
  ctx,
3310
- createClient,
4288
+ () => createClient(ctx),
3311
4289
  schemaConfig,
3312
4290
  databaseProvider,
3313
4291
  request,
3314
4292
  stateEnabled,
3315
- () => isNativeRunHandlerActive(ctx),
3316
4293
  onStateChange,
3317
4294
  cancelToken,
4295
+ run !== undefined,
3318
4296
  );
3319
4297
  const makeConnCtx = (
3320
4298
  ctx: ActorContextHandle,
@@ -3326,29 +4304,33 @@ export function buildNativeFactory(
3326
4304
  runtime,
3327
4305
  ctx,
3328
4306
  conn,
3329
- createClient,
4307
+ () => createClient(ctx),
3330
4308
  schemaConfig,
3331
4309
  databaseProvider,
3332
4310
  request,
3333
4311
  stateEnabled,
3334
4312
  onStateChange,
3335
4313
  cancelToken,
4314
+ run !== undefined,
3336
4315
  );
3337
4316
  const maybeHandleNativeInspectorRequest = async (
3338
4317
  ctx: ActorContextHandle,
3339
- _rawRequest: {
4318
+ rawRequest: {
3340
4319
  method: string;
3341
4320
  uri: string;
3342
4321
  headers?: Record<string, string>;
3343
4322
  body?: RuntimeBytes;
3344
4323
  },
3345
- jsRequest: Request,
3346
4324
  ): Promise<Response | undefined> => {
3347
- const url = new URL(jsRequest.url);
4325
+ const rawUrl = rawRequest.uri.startsWith("http")
4326
+ ? rawRequest.uri
4327
+ : new URL(rawRequest.uri, "http://127.0.0.1").toString();
4328
+ const url = new URL(rawUrl);
3348
4329
  if (!url.pathname.startsWith("/inspector/")) {
3349
4330
  return undefined;
3350
4331
  }
3351
4332
 
4333
+ const jsRequest = buildNativeHttpRequest(rawRequest);
3352
4334
  const jsonResponse = (body: unknown, init?: ResponseInit) =>
3353
4335
  new Response(JSON.stringify(body), {
3354
4336
  status: init?.status ?? 200,
@@ -3374,15 +4356,24 @@ export function buildNativeFactory(
3374
4356
  },
3375
4357
  );
3376
4358
  };
3377
- try {
3378
- await runtime.actorVerifyInspectorAuth(
3379
- ctx,
3380
- jsRequest.headers
3381
- .get("authorization")
3382
- ?.replace(/^Bearer\s+/i, "") ?? null,
3383
- );
3384
- } catch (error) {
3385
- return errorResponse(error, 401);
4359
+
4360
+ // Tab config is delivered over the inspector WS `Init` message, not
4361
+ // HTTP. Only custom-tab assets remain a public per-actor path.
4362
+ const isPublicPerActorPath =
4363
+ jsRequest.method === "GET" &&
4364
+ url.pathname.startsWith("/inspector/custom-tabs/");
4365
+
4366
+ if (!isPublicPerActorPath) {
4367
+ try {
4368
+ await runtime.actorVerifyInspectorAuth(
4369
+ ctx,
4370
+ jsRequest.headers
4371
+ .get("authorization")
4372
+ ?.replace(/^Bearer\s+/i, "") ?? null,
4373
+ );
4374
+ } catch (error) {
4375
+ return errorResponse(error, 401);
4376
+ }
3386
4377
  }
3387
4378
 
3388
4379
  const workflowHistory = () =>
@@ -3392,6 +4383,7 @@ export function buildNativeFactory(
3392
4383
  const workflowState = async () =>
3393
4384
  (await getNativeWorkflowInspector(ctx)?.getState?.()) ?? null;
3394
4385
  const actorCtx = makeActorCtx(ctx, jsRequest);
4386
+ const sql = getOrCreateNativeSqlDatabase(runtime, ctx);
3395
4387
  try {
3396
4388
  if (
3397
4389
  url.pathname === "/inspector/state" &&
@@ -3465,6 +4457,56 @@ export function buildNativeFactory(
3465
4457
  messages,
3466
4458
  });
3467
4459
  }
4460
+ if (
4461
+ url.pathname === "/inspector/queue" &&
4462
+ jsRequest.method === "DELETE"
4463
+ ) {
4464
+ await runtime.actorQueueReset(ctx);
4465
+ return jsonResponse({});
4466
+ }
4467
+ if (
4468
+ url.pathname === "/inspector/queue" &&
4469
+ jsRequest.method === "POST"
4470
+ ) {
4471
+ let body: { name?: string; body?: unknown };
4472
+ try {
4473
+ body = (await jsRequest.json()) as {
4474
+ name?: string;
4475
+ body?: unknown;
4476
+ };
4477
+ } catch {
4478
+ return errorResponse(
4479
+ new RivetError(
4480
+ "actor",
4481
+ "invalid_request",
4482
+ "Invalid inspector JSON body",
4483
+ { public: true },
4484
+ ),
4485
+ 400,
4486
+ );
4487
+ }
4488
+ const name = body.name ?? "";
4489
+ if (name === "") {
4490
+ return errorResponse(
4491
+ new RivetError(
4492
+ "actor",
4493
+ "invalid_request",
4494
+ "Queue message name must not be empty",
4495
+ { public: true },
4496
+ ),
4497
+ 400,
4498
+ );
4499
+ }
4500
+ const cbor = encodeCborCompat(
4501
+ (body.body ?? null) as JsonCompatValue,
4502
+ );
4503
+ const message = await runtime.actorQueueSend(ctx, name, cbor);
4504
+ return jsonResponse({
4505
+ id: message.id().toString(),
4506
+ name: message.name(),
4507
+ createdAtMs: message.createdAt(),
4508
+ });
4509
+ }
3468
4510
  if (
3469
4511
  url.pathname === "/inspector/traces" &&
3470
4512
  jsRequest.method === "GET"
@@ -3502,6 +4544,10 @@ export function buildNativeFactory(
3502
4544
  getNativeWorkflowInspector(ctx) !== undefined,
3503
4545
  });
3504
4546
  } catch (error) {
4547
+ logger().error({
4548
+ msg: "error replaying workflow history",
4549
+ error,
4550
+ });
3505
4551
  return errorResponse(error);
3506
4552
  }
3507
4553
  }
@@ -3509,7 +4555,7 @@ export function buildNativeFactory(
3509
4555
  url.pathname === "/inspector/database/schema" &&
3510
4556
  jsRequest.method === "GET"
3511
4557
  ) {
3512
- const db = actorCtx.sql;
4558
+ const db = sql;
3513
4559
  const tables = queryRows(
3514
4560
  await db.query(
3515
4561
  "SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '__drizzle_%' ORDER BY name",
@@ -3563,7 +4609,7 @@ export function buildNativeFactory(
3563
4609
  );
3564
4610
  const quoted = `"${table.replace(/"/g, '""')}"`;
3565
4611
  const rows = queryRows(
3566
- await actorCtx.sql.query(
4612
+ await sql.query(
3567
4613
  `SELECT * FROM ${quoted} LIMIT ? OFFSET ?`,
3568
4614
  [
3569
4615
  Math.max(0, Math.min(limit, 500)),
@@ -3606,15 +4652,11 @@ export function buildNativeFactory(
3606
4652
  const bindings = normalizeSqlitePropertyBindings(
3607
4653
  body.properties as Record<string, unknown>,
3608
4654
  );
3609
- const rows = queryRows(
3610
- await actorCtx.sql.query(body.sql, bindings),
3611
- );
4655
+ const rows = queryRows(await sql.query(body.sql, bindings));
3612
4656
  return jsonResponse({ rows: jsonSafe(rows) });
3613
4657
  }
3614
4658
  const args = Array.isArray(body.args) ? body.args : [];
3615
- const rows = queryRows(
3616
- await actorCtx.sql.query(body.sql, args),
3617
- );
4659
+ const rows = queryRows(await sql.query(body.sql, args));
3618
4660
  return jsonResponse({ rows: jsonSafe(rows) });
3619
4661
  }
3620
4662
  if (
@@ -3643,7 +4685,7 @@ export function buildNativeFactory(
3643
4685
  rpcs: Object.keys(actionHandlers).sort(),
3644
4686
  queueSize: inspectorSnapshot.queueSize,
3645
4687
  isStateEnabled: stateEnabled,
3646
- isDatabaseEnabled: databaseProvider !== undefined,
4688
+ isDatabaseEnabled: true,
3647
4689
  isWorkflowEnabled:
3648
4690
  getNativeWorkflowInspector(ctx) !== undefined,
3649
4691
  workflowState: await workflowState(),
@@ -3669,18 +4711,46 @@ export function buildNativeFactory(
3669
4711
  404,
3670
4712
  );
3671
4713
  }
3672
- const body = (await jsRequest.json()) as { args?: unknown[] };
4714
+ const body = (await jsRequest.json()) as {
4715
+ args?: unknown;
4716
+ properties?: unknown;
4717
+ };
4718
+ if (body.args !== undefined && body.properties !== undefined) {
4719
+ return jsonResponse(
4720
+ { error: "use either args or properties, not both" },
4721
+ { status: 400 },
4722
+ );
4723
+ }
4724
+ if (
4725
+ body.properties !== undefined &&
4726
+ (body.properties === null ||
4727
+ typeof body.properties !== "object" ||
4728
+ Array.isArray(body.properties))
4729
+ ) {
4730
+ return jsonResponse(
4731
+ { error: "properties must be an object" },
4732
+ { status: 400 },
4733
+ );
4734
+ }
4735
+ const args =
4736
+ body.properties !== undefined
4737
+ ? [body.properties]
4738
+ : normalizeArgs(body.args);
3673
4739
  try {
3674
4740
  const output = await action(
3675
4741
  actorCtx,
3676
4742
  ...validateActionArgs(
3677
4743
  schemaConfig.actionInputSchemas,
3678
4744
  actionName,
3679
- body.args ?? [],
4745
+ args,
3680
4746
  ),
3681
4747
  );
3682
4748
  return jsonResponse({ output });
3683
4749
  } catch (error) {
4750
+ logger().error({
4751
+ msg: "Error handling inspector action request",
4752
+ error,
4753
+ });
3684
4754
  return errorResponse(error);
3685
4755
  }
3686
4756
  }
@@ -3695,6 +4765,10 @@ export function buildNativeFactory(
3695
4765
  { status: 404 },
3696
4766
  );
3697
4767
  } catch (error) {
4768
+ logger().error({
4769
+ msg: "Error handling inspector request",
4770
+ error,
4771
+ });
3698
4772
  return errorResponse(error);
3699
4773
  } finally {
3700
4774
  await actorCtx.dispose();
@@ -3824,6 +4898,39 @@ export function buildNativeFactory(
3824
4898
  },
3825
4899
  )
3826
4900
  : undefined,
4901
+ onFork:
4902
+ typeof config.onFork === "function"
4903
+ ? wrapNativeCallback(
4904
+ async (
4905
+ error: unknown,
4906
+ payload: {
4907
+ ctx: ActorContextHandle;
4908
+ fork: {
4909
+ actorId: string;
4910
+ key: RuntimeActorKeySegment[];
4911
+ forkedAt: number;
4912
+ input?: RuntimeBytes;
4913
+ };
4914
+ },
4915
+ ) => {
4916
+ const { ctx, fork } = unwrapTsfnPayload(
4917
+ error,
4918
+ payload,
4919
+ );
4920
+ const actorCtx = makeActorCtx(ctx);
4921
+ try {
4922
+ await config.onFork(actorCtx, {
4923
+ actorId: fork.actorId,
4924
+ key: toActorKey(fork.key),
4925
+ forkedAt: fork.forkedAt,
4926
+ input: decodeValue(fork.input),
4927
+ });
4928
+ } finally {
4929
+ await actorCtx.dispose();
4930
+ }
4931
+ },
4932
+ )
4933
+ : undefined,
3827
4934
  onWake:
3828
4935
  typeof config.onWake === "function"
3829
4936
  ? wrapNativeCallback(
@@ -3867,27 +4974,39 @@ export function buildNativeFactory(
3867
4974
  async (error: unknown, payload: { ctx: ActorContextHandle }) => {
3868
4975
  const { ctx } = unwrapTsfnPayload(error, payload);
3869
4976
  const actorCtx = makeActorCtx(ctx);
4977
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
4978
+ // TODO: Move this save hook into cleanupNativeSleepRuntimeState
4979
+ // so immediate and deferred sleep cleanup share one save-state
4980
+ // path instead of passing a callback through cleanup.
4981
+ const saveActorState = async () => {
4982
+ if (runtime.kind === "wasm") {
4983
+ // Wasm cannot use the native context save helper here because
4984
+ // the runtime owns the serialized state handoff.
4985
+ await runtime.actorSaveState(
4986
+ ctx,
4987
+ actorCtx.serializeForTick("save"),
4988
+ );
4989
+ } else {
4990
+ await actorCtx.saveState({
4991
+ immediate: true,
4992
+ });
4993
+ }
4994
+ };
3870
4995
  try {
3871
4996
  if (onSleep) {
3872
- try {
3873
- await onSleep(actorCtx);
3874
- } finally {
3875
- if (runtime.kind === "wasm") {
3876
- // Wasm cannot use the native context save helper here because
3877
- // the runtime owns the serialized state handoff.
3878
- await runtime.actorSaveState(
3879
- ctx,
3880
- actorCtx.serializeForTick("save"),
3881
- );
3882
- } else {
3883
- await actorCtx.saveState({ immediate: true });
3884
- }
3885
- }
4997
+ await onSleep(actorCtx);
3886
4998
  }
4999
+ await saveActorState();
3887
5000
  } finally {
3888
5001
  try {
3889
- await cleanupNativeSleepRuntimeState(runtime, ctx);
5002
+ await cleanupNativeSleepRuntimeState(
5003
+ runtime,
5004
+ ctx,
5005
+ saveActorState,
5006
+ );
3890
5007
  } finally {
5008
+ runHandlerCoordinator?.destroy(actorId);
5009
+ disposeRunInspector(config.run, actorId);
3891
5010
  await actorCtx.dispose();
3892
5011
  }
3893
5012
  }
@@ -3897,13 +5016,18 @@ export function buildNativeFactory(
3897
5016
  async (error: unknown, payload: { ctx: ActorContextHandle }) => {
3898
5017
  const { ctx } = unwrapTsfnPayload(error, payload);
3899
5018
  const actorCtx = makeActorCtx(ctx);
5019
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
5020
+ // Close run control before user cleanup so replay cannot race actor
5021
+ // destruction. Recreating this actor id receives a fresh controller.
5022
+ runHandlerCoordinator?.destroy(actorId);
5023
+ disposeRunInspector(config.run, actorId);
3900
5024
  try {
3901
5025
  if (typeof config.onDestroy === "function") {
3902
5026
  await config.onDestroy(actorCtx);
3903
5027
  }
3904
5028
  } finally {
3905
5029
  resolveNativeDestroy(runtime, ctx);
3906
- await actorCtx.closeDatabase();
5030
+ await detachNativeDatabaseForShutdown(runtime, ctx);
3907
5031
  clearNativeRuntimeState(runtime, ctx);
3908
5032
  await actorCtx.dispose();
3909
5033
  }
@@ -3931,7 +5055,9 @@ export function buildNativeFactory(
3931
5055
  );
3932
5056
  const actorCtx = makeActorCtx(
3933
5057
  ctx,
3934
- request ? buildRequest(request) : undefined,
5058
+ request
5059
+ ? buildNativeHttpRequest(request)
5060
+ : undefined,
3935
5061
  );
3936
5062
  try {
3937
5063
  await config.onBeforeConnect(
@@ -3968,7 +5094,9 @@ export function buildNativeFactory(
3968
5094
  unwrapTsfnPayload(error, payload);
3969
5095
  const actorCtx = makeActorCtx(
3970
5096
  ctx,
3971
- request ? buildRequest(request) : undefined,
5097
+ request
5098
+ ? buildNativeHttpRequest(request)
5099
+ : undefined,
3972
5100
  );
3973
5101
  const connAdapter = new NativeConnAdapter(
3974
5102
  runtime,
@@ -3982,6 +5110,7 @@ export function buildNativeFactory(
3982
5110
  connId,
3983
5111
  ),
3984
5112
  ),
5113
+ () => actorCtx.assertCanMutateState(),
3985
5114
  );
3986
5115
  try {
3987
5116
  const nextConnState = hasStaticConnState
@@ -4023,7 +5152,9 @@ export function buildNativeFactory(
4023
5152
  );
4024
5153
  const actorCtx = makeActorCtx(
4025
5154
  ctx,
4026
- request ? buildRequest(request) : undefined,
5155
+ request
5156
+ ? buildNativeHttpRequest(request)
5157
+ : undefined,
4027
5158
  );
4028
5159
  const connAdapter = new NativeConnAdapter(
4029
5160
  runtime,
@@ -4037,6 +5168,7 @@ export function buildNativeFactory(
4037
5168
  connId,
4038
5169
  ),
4039
5170
  ),
5171
+ () => actorCtx.assertCanMutateState(),
4040
5172
  );
4041
5173
  try {
4042
5174
  await config.onConnect(
@@ -4080,6 +5212,7 @@ export function buildNativeFactory(
4080
5212
  connId,
4081
5213
  ),
4082
5214
  ),
5215
+ () => actorCtx.assertCanMutateState(),
4083
5216
  ),
4084
5217
  );
4085
5218
  }
@@ -4173,74 +5306,156 @@ export function buildNativeFactory(
4173
5306
  uri: string;
4174
5307
  headers?: Record<string, string>;
4175
5308
  body?: RuntimeBytes;
5309
+ bodyStream?: NativeHttpRequestBodyStream;
4176
5310
  };
4177
5311
  cancelToken?: CancellationTokenHandle;
5312
+ responseBodyStream?: NativeHttpResponseBodyStream;
4178
5313
  },
4179
5314
  ) => {
4180
5315
  try {
4181
- const { ctx, request, cancelToken } = unwrapTsfnPayload(
4182
- error,
4183
- payload,
4184
- );
4185
- const jsRequest = buildRequest(request);
4186
- const inspectorResponse =
4187
- await maybeHandleNativeInspectorRequest(
4188
- ctx,
4189
- request,
4190
- jsRequest,
4191
- );
4192
- if (inspectorResponse) {
4193
- return await toRuntimeHttpResponse(inspectorResponse);
4194
- }
5316
+ const { ctx, request, cancelToken, responseBodyStream } =
5317
+ unwrapTsfnPayload(error, payload);
5318
+ return await runtime.runWithActorInvocationContext(
5319
+ ctx,
5320
+ async () => {
5321
+ const inspectorResponse =
5322
+ await maybeHandleNativeInspectorRequest(
5323
+ ctx,
5324
+ request,
5325
+ );
5326
+ if (inspectorResponse) {
5327
+ await cancelNativeHttpRequestBody(
5328
+ request.bodyStream,
5329
+ );
5330
+ return (
5331
+ await convertNativeHttpResponse(
5332
+ inspectorResponse,
5333
+ responseBodyStream,
5334
+ )
5335
+ ).response;
5336
+ }
4195
5337
 
4196
- if (typeof config.onRequest !== "function") {
4197
- return await toRuntimeHttpResponse(
4198
- new Response(null, { status: 404 }),
4199
- );
4200
- }
5338
+ if (typeof config.onRequest !== "function") {
5339
+ await cancelNativeHttpRequestBody(
5340
+ request.bodyStream,
5341
+ );
5342
+ return (
5343
+ await convertNativeHttpResponse(
5344
+ new Response(null, { status: 404 }),
5345
+ responseBodyStream,
5346
+ )
5347
+ ).response;
5348
+ }
4201
5349
 
4202
- const rawConnParams =
4203
- jsRequest.headers.get(HEADER_CONN_PARAMS);
4204
- let requestCtx:
4205
- | ReturnType<typeof withConnContext>
4206
- | undefined;
4207
- let conn: ConnHandle | undefined;
4208
- try {
4209
- const connParams = validateConnParams(
4210
- schemaConfig.connParamsSchema,
4211
- rawConnParams
4212
- ? JSON.parse(rawConnParams)
4213
- : undefined,
4214
- );
4215
- conn = await callNative(() =>
4216
- runtime.actorConnectConn(
4217
- ctx,
4218
- encodeValue(connParams),
4219
- request,
4220
- ),
4221
- );
4222
- requestCtx = makeConnCtx(
4223
- ctx,
4224
- conn,
4225
- jsRequest,
4226
- cancelToken,
4227
- );
4228
- const response = await config.onRequest(
4229
- requestCtx,
4230
- jsRequest,
4231
- );
4232
- if (!(response instanceof Response)) {
4233
- throw new Error(
4234
- "onRequest handler must return a Response",
4235
- );
4236
- }
4237
- return await toRuntimeHttpResponse(response);
4238
- } finally {
4239
- await requestCtx?.dispose();
4240
- if (conn) {
4241
- await runtime.connDisconnect(conn);
4242
- }
4243
- }
5350
+ const requestAbortController =
5351
+ new AbortController();
5352
+ const handlerRequest = buildNativeHttpRequest({
5353
+ ...request,
5354
+ abortController: requestAbortController,
5355
+ });
5356
+ const rawConnParams =
5357
+ handlerRequest.headers.get(HEADER_CONN_PARAMS);
5358
+ let requestCtx:
5359
+ | ReturnType<typeof withConnContext>
5360
+ | undefined;
5361
+ let conn: ConnHandle | undefined;
5362
+ let removeRequestAbortListener:
5363
+ | (() => void)
5364
+ | undefined;
5365
+ let cleanupDeferredToBody = false;
5366
+ let cleanedUp = false;
5367
+ const cleanupRequest = async () => {
5368
+ if (cleanedUp) return;
5369
+ cleanedUp = true;
5370
+ removeRequestAbortListener?.();
5371
+ try {
5372
+ await requestCtx?.dispose();
5373
+ } finally {
5374
+ if (conn) {
5375
+ await runtime.connDisconnect(conn);
5376
+ }
5377
+ }
5378
+ };
5379
+ try {
5380
+ const connParams = validateConnParams(
5381
+ schemaConfig.connParamsSchema,
5382
+ rawConnParams
5383
+ ? JSON.parse(rawConnParams)
5384
+ : undefined,
5385
+ );
5386
+ conn = await callNative(() =>
5387
+ runtime.actorConnectConn(
5388
+ ctx,
5389
+ encodeValue(connParams),
5390
+ request,
5391
+ ),
5392
+ );
5393
+ requestCtx = makeConnCtx(
5394
+ ctx,
5395
+ conn,
5396
+ handlerRequest,
5397
+ cancelToken,
5398
+ );
5399
+ const ctxAbortSignal = requestCtx.abortSignal;
5400
+ const abortRequest = () =>
5401
+ requestAbortController.abort(
5402
+ ctxAbortSignal.reason,
5403
+ );
5404
+ if (ctxAbortSignal.aborted) {
5405
+ abortRequest();
5406
+ } else {
5407
+ ctxAbortSignal.addEventListener(
5408
+ "abort",
5409
+ abortRequest,
5410
+ { once: true },
5411
+ );
5412
+ removeRequestAbortListener = () =>
5413
+ ctxAbortSignal.removeEventListener(
5414
+ "abort",
5415
+ abortRequest,
5416
+ );
5417
+ }
5418
+ const response = await config.onRequest(
5419
+ requestCtx,
5420
+ handlerRequest,
5421
+ );
5422
+ if (!isResponseLike(response)) {
5423
+ throw new Error(
5424
+ "onRequest handler must return a Response",
5425
+ );
5426
+ }
5427
+ const conversion =
5428
+ await convertNativeHttpResponse(
5429
+ response,
5430
+ responseBodyStream,
5431
+ );
5432
+ if (conversion.bodyCompletion) {
5433
+ cleanupDeferredToBody = true;
5434
+ void conversion.bodyCompletion
5435
+ .then(cleanupRequest)
5436
+ .catch((cleanupError) => {
5437
+ logger().error({
5438
+ msg: "failed to clean up native streaming http request",
5439
+ error: cleanupError,
5440
+ });
5441
+ });
5442
+ }
5443
+ return conversion.response;
5444
+ } finally {
5445
+ try {
5446
+ // Handler completion ends upload ownership even when
5447
+ // the Web Request body is locked or partly consumed.
5448
+ await cancelNativeHttpRequestBody(
5449
+ request.bodyStream,
5450
+ );
5451
+ } finally {
5452
+ if (!cleanupDeferredToBody) {
5453
+ await cleanupRequest();
5454
+ }
5455
+ }
5456
+ }
5457
+ },
5458
+ );
4244
5459
  } catch (error) {
4245
5460
  logger().error({
4246
5461
  msg: "native onRequest failed",
@@ -4270,7 +5485,7 @@ export function buildNativeFactory(
4270
5485
  const { ctx, conn, ws, request } =
4271
5486
  unwrapTsfnPayload(error, payload);
4272
5487
  const jsRequest = request
4273
- ? buildRequest(request)
5488
+ ? buildNativeHttpRequest(request)
4274
5489
  : undefined;
4275
5490
  const actorCtx = makeConnCtx(ctx, conn, jsRequest);
4276
5491
  try {
@@ -4288,7 +5503,6 @@ export function buildNativeFactory(
4288
5503
  )
4289
5504
  : undefined,
4290
5505
  run: (() => {
4291
- const run = getRunFunction(config.run);
4292
5506
  if (!run) {
4293
5507
  return undefined;
4294
5508
  }
@@ -4300,63 +5514,75 @@ export function buildNativeFactory(
4300
5514
  ) => {
4301
5515
  const { ctx } = unwrapTsfnPayload(error, payload);
4302
5516
  const actorId = callNativeSync(() => runtime.actorId(ctx));
4303
- const actorCtx = makeActorCtx(ctx);
4304
- nativeRunHandlerActiveByActorId.set(actorId, true);
4305
- try {
4306
- await run(actorCtx);
4307
- } finally {
4308
- nativeRunHandlerActiveByActorId.set(actorId, false);
4309
- await actorCtx.dispose();
5517
+ const executeRun = async () => {
5518
+ const actorCtx = makeActorCtx(ctx);
5519
+ try {
5520
+ await run(actorCtx);
5521
+ } finally {
5522
+ await actorCtx.dispose();
5523
+ }
5524
+ };
5525
+ if (runHandlerCoordinator) {
5526
+ const outcome = await runHandlerCoordinator.run(
5527
+ actorId,
5528
+ () =>
5529
+ callNativeSync(() =>
5530
+ runtime.actorRestartRunHandler(ctx),
5531
+ ),
5532
+ executeRun,
5533
+ );
5534
+ // Only a start suppressed behind a failed replay must preserve a
5535
+ // consumed durable wake. Closed actors must remain closed.
5536
+ return outcome !== "suppressed";
4310
5537
  }
5538
+ await executeRun();
5539
+ return true;
4311
5540
  },
4312
5541
  );
4313
5542
  })(),
4314
- getWorkflowHistory:
4315
- getRunInspectorConfig(config.run) !== undefined
4316
- ? wrapNativeCallback(
4317
- async (
4318
- error: unknown,
4319
- payload: { ctx: ActorContextHandle },
4320
- ) => {
4321
- const { ctx } = unwrapTsfnPayload(error, payload);
4322
- const history =
4323
- getNativeWorkflowInspector(ctx)?.getHistory();
4324
- return history == null
4325
- ? undefined
4326
- : encodeValue(history);
5543
+ getWorkflowHistory: hasRunInspectorConfig(config.run)
5544
+ ? wrapNativeCallback(
5545
+ async (
5546
+ error: unknown,
5547
+ payload: { ctx: ActorContextHandle },
5548
+ ) => {
5549
+ const { ctx } = unwrapTsfnPayload(error, payload);
5550
+ const history =
5551
+ getNativeWorkflowInspector(ctx)?.getHistory();
5552
+ return history == null
5553
+ ? undefined
5554
+ : toUint8Array(history);
5555
+ },
5556
+ )
5557
+ : undefined,
5558
+ replayWorkflow: hasRunInspectorConfig(config.run)
5559
+ ? wrapNativeCallback(
5560
+ async (
5561
+ error: unknown,
5562
+ payload: {
5563
+ ctx: ActorContextHandle;
5564
+ entryId?: string;
4327
5565
  },
4328
- )
4329
- : undefined,
4330
- replayWorkflow:
4331
- getRunInspectorConfig(config.run) !== undefined
4332
- ? wrapNativeCallback(
4333
- async (
4334
- error: unknown,
4335
- payload: {
4336
- ctx: ActorContextHandle;
4337
- entryId?: string;
4338
- },
4339
- ) => {
4340
- const { ctx, entryId } = unwrapTsfnPayload(
4341
- error,
4342
- payload,
4343
- );
4344
- const workflowInspector =
4345
- getNativeWorkflowInspector(ctx);
4346
- if (!workflowInspector?.replayFromStep) {
4347
- return undefined;
4348
- }
5566
+ ) => {
5567
+ const { ctx, entryId } = unwrapTsfnPayload(
5568
+ error,
5569
+ payload,
5570
+ );
5571
+ const workflowInspector =
5572
+ getNativeWorkflowInspector(ctx);
5573
+ if (!workflowInspector?.replayFromStep) {
5574
+ return undefined;
5575
+ }
4349
5576
 
4350
- const history =
4351
- (await workflowInspector.replayFromStep(
4352
- entryId,
4353
- )) ?? null;
4354
- return history == null
4355
- ? undefined
4356
- : encodeValue(history);
4357
- },
4358
- )
4359
- : undefined,
5577
+ const history =
5578
+ (await workflowInspector.replayFromStep(entryId)) ??
5579
+ null;
5580
+ return history == null
5581
+ ? undefined
5582
+ : toUint8Array(history);
5583
+ },
5584
+ )
5585
+ : undefined,
4360
5586
  actions: Object.fromEntries(
4361
5587
  Object.entries(actionHandlers).map(([name, handler]) => [
4362
5588
  name,
@@ -4368,29 +5594,44 @@ export function buildNativeFactory(
4368
5594
  conn: ConnHandle | null;
4369
5595
  name: string;
4370
5596
  args: RuntimeBytes;
5597
+ scheduledFire?: RuntimeScheduledFireInfo;
4371
5598
  cancelToken?: CancellationTokenHandle;
4372
5599
  },
4373
5600
  ) => {
4374
- const { ctx, conn, args, cancelToken } =
5601
+ const { ctx, conn, args, scheduledFire, cancelToken } =
4375
5602
  unwrapTsfnPayload(error, payload);
4376
5603
  const actorCtx =
4377
5604
  conn != null
4378
5605
  ? makeConnCtx(ctx, conn, undefined, cancelToken)
4379
5606
  : makeActorCtx(ctx, undefined, cancelToken);
4380
- try {
4381
- return encodeValue(
4382
- await handler(
4383
- actorCtx,
4384
- ...validateActionArgs(
4385
- schemaConfig.actionInputSchemas,
4386
- name,
4387
- decodeArgs(args),
4388
- ),
4389
- ),
4390
- );
4391
- } finally {
4392
- await actorCtx.dispose();
5607
+ if (scheduledFire) {
5608
+ Object.defineProperty(actorCtx, "scheduledFire", {
5609
+ value: scheduledFire,
5610
+ });
4393
5611
  }
5612
+ const runAction = async () => {
5613
+ try {
5614
+ return encodeValue(
5615
+ await handler(
5616
+ actorCtx,
5617
+ ...validateActionArgs(
5618
+ schemaConfig.actionInputSchemas,
5619
+ name,
5620
+ decodeArgs(args),
5621
+ ),
5622
+ ...(scheduledFire
5623
+ ? [scheduledFire]
5624
+ : []),
5625
+ ),
5626
+ );
5627
+ } finally {
5628
+ await actorCtx.dispose();
5629
+ }
5630
+ };
5631
+ return await runtime.runWithActorInvocationContext(
5632
+ ctx,
5633
+ runAction,
5634
+ );
4394
5635
  },
4395
5636
  ),
4396
5637
  ]),
@@ -4424,75 +5665,89 @@ export function buildNativeFactory(
4424
5665
  timeoutMs,
4425
5666
  cancelToken,
4426
5667
  } = unwrapTsfnPayload(error, payload);
4427
- const jsRequest = buildRequest(request);
5668
+ const jsRequest = buildNativeHttpRequest(request);
4428
5669
  const actorCtx = withConnContext(
4429
5670
  runtime,
4430
5671
  ctx,
4431
5672
  conn,
4432
- createClient,
5673
+ () => createClient(ctx),
4433
5674
  schemaConfig,
4434
5675
  databaseProvider,
4435
5676
  jsRequest,
4436
5677
  stateEnabled,
4437
5678
  onStateChange,
4438
5679
  cancelToken,
5680
+ run !== undefined,
4439
5681
  );
4440
- try {
4441
- if (
4442
- !schemaConfig.queues ||
4443
- !hasSchemaConfigKey(schemaConfig.queues, name)
4444
- ) {
4445
- return { status: "completed" };
4446
- }
4447
-
4448
- const canPublish = getQueueCanPublish(
4449
- schemaConfig.queues,
4450
- name,
4451
- );
4452
- if (canPublish && !(await canPublish(actorCtx))) {
4453
- throw forbiddenError();
4454
- }
4455
-
4456
- const decodedBody = decodeValue(body);
4457
- if (wait) {
5682
+ return await runtime.runWithActorInvocationContext(
5683
+ ctx,
5684
+ async () => {
4458
5685
  try {
4459
- const response =
4460
- await actorCtx.queue.enqueueAndWait(
4461
- name,
4462
- decodedBody,
4463
- {
4464
- timeout:
4465
- timeoutMs === undefined ||
4466
- timeoutMs === null
4467
- ? undefined
4468
- : Number(timeoutMs),
4469
- },
4470
- );
4471
- return {
4472
- status: "completed",
4473
- response:
4474
- response === undefined
4475
- ? undefined
4476
- : encodeValue(response),
4477
- };
4478
- } catch (error) {
4479
5686
  if (
4480
- (error as { group?: string; code?: string })
4481
- .group === "queue" &&
4482
- (error as { group?: string; code?: string })
4483
- .code === "timed_out"
5687
+ !schemaConfig.queues ||
5688
+ !hasSchemaConfigKey(schemaConfig.queues, name)
4484
5689
  ) {
4485
- return { status: "timedOut" };
5690
+ return { status: "completed" };
4486
5691
  }
4487
- throw error;
4488
- }
4489
- }
4490
5692
 
4491
- await actorCtx.queue.send(name, decodedBody);
4492
- return { status: "completed" };
4493
- } finally {
4494
- await actorCtx.dispose();
4495
- }
5693
+ const canPublish = getQueueCanPublish(
5694
+ schemaConfig.queues,
5695
+ name,
5696
+ );
5697
+ if (canPublish && !(await canPublish(actorCtx))) {
5698
+ throw forbiddenError();
5699
+ }
5700
+
5701
+ const decodedBody = decodeValue(body);
5702
+ if (wait) {
5703
+ try {
5704
+ const response =
5705
+ await actorCtx.queue.enqueueAndWait(
5706
+ name,
5707
+ decodedBody,
5708
+ {
5709
+ timeout:
5710
+ timeoutMs === undefined ||
5711
+ timeoutMs === null
5712
+ ? undefined
5713
+ : Number(timeoutMs),
5714
+ },
5715
+ );
5716
+ return {
5717
+ status: "completed",
5718
+ response:
5719
+ response === undefined
5720
+ ? undefined
5721
+ : encodeValue(response),
5722
+ };
5723
+ } catch (error) {
5724
+ if (
5725
+ (
5726
+ error as {
5727
+ group?: string;
5728
+ code?: string;
5729
+ }
5730
+ ).group === "queue" &&
5731
+ (
5732
+ error as {
5733
+ group?: string;
5734
+ code?: string;
5735
+ }
5736
+ ).code === "timed_out"
5737
+ ) {
5738
+ return { status: "timedOut" };
5739
+ }
5740
+ throw error;
5741
+ }
5742
+ }
5743
+
5744
+ await actorCtx.queue.send(name, decodedBody);
5745
+ return { status: "completed" };
5746
+ } finally {
5747
+ await actorCtx.dispose();
5748
+ }
5749
+ },
5750
+ );
4496
5751
  },
4497
5752
  ),
4498
5753
  serializeState: wrapNativeCallback(
@@ -4516,23 +5771,26 @@ export function buildNativeFactory(
4516
5771
 
4517
5772
  return runtime.createActorFactory(
4518
5773
  callbacks,
4519
- buildActorConfig(definition, registryConfig),
5774
+ buildActorConfig(definition, registryConfig, runtime.kind),
4520
5775
  );
4521
5776
  }
4522
5777
 
4523
5778
  export async function buildServeConfig(
4524
5779
  config: RegistryConfig,
5780
+ resolveNativeBinaries = true,
4525
5781
  ): Promise<RuntimeServeConfig> {
4526
5782
  if (!config.endpoint) {
4527
5783
  throw nativeEndpointNotConfiguredError();
4528
5784
  }
4529
5785
 
4530
5786
  const serveConfig: RuntimeServeConfig = {
4531
- version: config.envoy.version,
5787
+ version: config.node.version,
4532
5788
  endpoint: config.endpoint,
5789
+ engineSpawn: config.engineSpawn,
4533
5790
  token: config.token,
4534
5791
  namespace: config.namespace,
4535
- poolName: config.envoy.poolName,
5792
+ poolName: config.node.poolName,
5793
+ startServices: resolveNativeBinaries && config.startServices,
4536
5794
  handleInspectorHttpInRuntime: true,
4537
5795
  serverlessBasePath: config.serverless.basePath,
4538
5796
  serverlessPackageVersion: VERSION,
@@ -4543,10 +5801,44 @@ export async function buildServeConfig(
4543
5801
  serverlessMaxStartPayloadBytes: config.serverless.maxStartPayloadBytes,
4544
5802
  };
4545
5803
 
4546
- if (config.startEngine) {
4547
- const { getEnginePath } = await loadEngineCli();
4548
- serveConfig.engineBinaryPath = getEnginePath();
5804
+ // For native runtimes, best-effort resolve the npm-installed engine binary
5805
+ // and hand its path to the core. The core decides whether to spawn a local
5806
+ // engine using the resolved spawn decision, so
5807
+ // JS must not duplicate that decision here. Only JS knows the npm
5808
+ // `node_modules` layout, so it resolves the path; if no binary is available
5809
+ // (remote-only install, unsupported platform, optional deps skipped), leave
5810
+ // it unset and let the core report `engine.binary_unavailable` if it actually
5811
+ // needs one.
5812
+ if (resolveNativeBinaries) {
5813
+ try {
5814
+ const { getEnginePath } = await loadEngineCli();
5815
+ serveConfig.engineBinaryPath = getEnginePath();
5816
+ } catch (error) {
5817
+ // The npm-installed engine binary could not be resolved. The core still
5818
+ // decides whether it needs to spawn a local engine; if it does, it will
5819
+ // fail with engine.binary_unavailable (auto-download is off in the napi
5820
+ // runtime). Warn so the cause is actionable.
5821
+ logger().warn({
5822
+ msg: "could not resolve a local engine binary; if a local engine must be spawned it will fail with engine.binary_unavailable — set RIVET_ENGINE_BINARY_PATH or install the @rivetkit/engine-cli platform package",
5823
+ error: stringifyError(error),
5824
+ });
5825
+ }
5826
+ }
5827
+ if (resolveNativeBinaries && config.startServices) {
5828
+ const servicesBinary = getEnvUniversal("RIVET_SERVICES_BINARY");
5829
+ if (servicesBinary) {
5830
+ serveConfig.servicesBinaryPath = servicesBinary;
5831
+ } else {
5832
+ try {
5833
+ const { getServicesPath } = await loadServices();
5834
+ serveConfig.servicesBinaryPath = getServicesPath();
5835
+ } catch (error) {
5836
+ throw servicesBinaryUnavailable(error);
5837
+ }
5838
+ }
4549
5839
  }
5840
+ serveConfig.engineHost = config.engineHost;
5841
+ serveConfig.enginePort = config.enginePort;
4550
5842
  if (config.test?.enabled) {
4551
5843
  serveConfig.inspectorTestToken =
4552
5844
  getEnvUniversal("_RIVET_TEST_INSPECTOR_TOKEN") ?? "token";
@@ -4570,6 +5862,13 @@ export async function buildRegistryWithRuntime(
4570
5862
  trySetProcessEnv("_RIVET_TEST_INSPECTOR_TOKEN", "token");
4571
5863
  }
4572
5864
 
5865
+ // Custom inspector tab `source` paths are resolved with node:path while
5866
+ // building actor configs below, so the Node modules must be loaded first.
5867
+ // Native (napi) runtime only; wasm has no filesystem.
5868
+ if (runtime.kind === "napi") {
5869
+ importNodeDependencies();
5870
+ }
5871
+
4573
5872
  const registry = runtime.createRegistry();
4574
5873
 
4575
5874
  for (const [name, definition] of Object.entries(config.use)) {
@@ -4583,7 +5882,7 @@ export async function buildRegistryWithRuntime(
4583
5882
  return {
4584
5883
  runtime,
4585
5884
  registry,
4586
- serveConfig: await buildServeConfig(config),
5885
+ serveConfig: await buildServeConfig(config, runtime.kind === "napi"),
4587
5886
  };
4588
5887
  }
4589
5888