rivetkit 0.0.0-sqlite-profiling-compat.87d61c0 → 0.0.0-sqlite-sync-3x-release.a00b07f

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 (277) hide show
  1. package/dist/browser/client.d.ts +1317 -765
  2. package/dist/browser/client.js +1457 -737
  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 +2042 -228
  6. package/dist/browser/inspector/client.js.map +1 -1
  7. package/dist/tsup/actor/errors.cjs +6 -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 +5 -1
  12. package/dist/tsup/agent-os/index.cjs +3 -2367
  13. package/dist/tsup/agent-os/index.cjs.map +1 -1
  14. package/dist/tsup/agent-os/index.d.cts +1 -2277
  15. package/dist/tsup/agent-os/index.d.ts +1 -2277
  16. package/dist/tsup/agent-os/index.js +3 -2367
  17. package/dist/tsup/agent-os/index.js.map +1 -1
  18. package/dist/tsup/{chunk-E4LNLI3W.cjs → chunk-2MOLY6AM.cjs} +444 -29
  19. package/dist/tsup/chunk-2MOLY6AM.cjs.map +1 -0
  20. package/dist/tsup/{chunk-OAUFXOG7.js → chunk-3DONDAMG.js} +2 -2
  21. package/dist/tsup/{chunk-XIX5DOZN.js → chunk-6FEYCVZC.js} +196 -20
  22. package/dist/tsup/chunk-6FEYCVZC.js.map +1 -0
  23. package/dist/tsup/chunk-6KXVLIXL.cjs +14 -0
  24. package/dist/tsup/chunk-6KXVLIXL.cjs.map +1 -0
  25. package/dist/tsup/chunk-73RNTXHB.cjs +243 -0
  26. package/dist/tsup/chunk-73RNTXHB.cjs.map +1 -0
  27. package/dist/tsup/{chunk-HXUEHHJF.js → chunk-A2CF6PFH.js} +19 -11
  28. package/dist/tsup/chunk-A2CF6PFH.js.map +1 -0
  29. package/dist/tsup/{chunk-EFU4JW3T.js → chunk-BRH4PQS5.js} +436 -21
  30. package/dist/tsup/chunk-BRH4PQS5.js.map +1 -0
  31. package/dist/tsup/{chunk-GM45LG7L.cjs → chunk-BTSDFFDC.cjs} +18 -11
  32. package/dist/tsup/chunk-BTSDFFDC.cjs.map +1 -0
  33. package/dist/tsup/{chunk-B3GLD4IN.js → chunk-D5WUPE47.js} +50 -3
  34. package/dist/tsup/chunk-D5WUPE47.js.map +1 -0
  35. package/dist/tsup/{chunk-O3ZUMAN7.js → chunk-DJUBJQEQ.js} +3 -3
  36. package/dist/tsup/chunk-DJUBJQEQ.js.map +1 -0
  37. package/dist/tsup/{chunk-3MHDOUD7.cjs → chunk-HDVZ6YZG.cjs} +197 -21
  38. package/dist/tsup/chunk-HDVZ6YZG.cjs.map +1 -0
  39. package/dist/tsup/{chunk-JZ7TWV65.js → chunk-JTHHCZCZ.js} +24 -1
  40. package/dist/tsup/chunk-JTHHCZCZ.js.map +1 -0
  41. package/dist/tsup/{chunk-D363DMNH.cjs → chunk-JUHXV3HF.cjs} +3 -3
  42. package/dist/tsup/chunk-JUHXV3HF.cjs.map +1 -0
  43. package/dist/tsup/chunk-JUWMP5O3.js +14 -0
  44. package/dist/tsup/chunk-JUWMP5O3.js.map +1 -0
  45. package/dist/tsup/{chunk-ZA7FLHKH.cjs → chunk-KVFIONKQ.cjs} +25 -2
  46. package/dist/tsup/chunk-KVFIONKQ.cjs.map +1 -0
  47. package/dist/tsup/{chunk-4FC7TVS6.cjs → chunk-MGI2VVF6.cjs} +39 -7
  48. package/dist/tsup/chunk-MGI2VVF6.cjs.map +1 -0
  49. package/dist/tsup/{chunk-BWERJMV6.cjs → chunk-OTVJYZ2L.cjs} +1139 -470
  50. package/dist/tsup/chunk-OTVJYZ2L.cjs.map +1 -0
  51. package/dist/tsup/{chunk-VE2X4KMG.cjs → chunk-RTWH3AX3.cjs} +18 -10
  52. package/dist/tsup/chunk-RTWH3AX3.cjs.map +1 -0
  53. package/dist/tsup/{chunk-DTRDGPHU.cjs → chunk-TM76Z7XT.cjs} +7 -7
  54. package/dist/tsup/chunk-TM76Z7XT.cjs.map +1 -0
  55. package/dist/tsup/{chunk-3GVMLSND.js → chunk-TRUHDXOU.js} +1023 -354
  56. package/dist/tsup/chunk-TRUHDXOU.js.map +1 -0
  57. package/dist/tsup/{chunk-PT7AC5PC.js → chunk-TSQTI6H6.js} +16 -9
  58. package/dist/tsup/chunk-TSQTI6H6.js.map +1 -0
  59. package/dist/tsup/{chunk-FNAXD5BQ.cjs → chunk-Z7E2G3JZ.cjs} +52 -5
  60. package/dist/tsup/chunk-Z7E2G3JZ.cjs.map +1 -0
  61. package/dist/tsup/{chunk-ZZ3WBRPD.js → chunk-ZOVJDAOW.js} +38 -6
  62. package/dist/tsup/chunk-ZOVJDAOW.js.map +1 -0
  63. package/dist/tsup/chunk-ZYK4B5WV.js +243 -0
  64. package/dist/tsup/chunk-ZYK4B5WV.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 +32 -6
  68. package/dist/tsup/client/mod.d.ts +32 -6
  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.cjs.map +1 -1
  77. package/dist/tsup/common/websocket.js +3 -3
  78. package/dist/tsup/{config-BR1Nn0QQ.d.ts → config-B4erdavw.d.ts} +571 -65
  79. package/dist/tsup/{config-B0LNDrLY.d.cts → config-BfG1qpYz.d.cts} +80 -14
  80. package/dist/tsup/{config-B0LNDrLY.d.ts → config-BfG1qpYz.d.ts} +80 -14
  81. package/dist/tsup/{config-tCvkwzyN.d.cts → config-DK144OAw.d.cts} +571 -65
  82. package/dist/tsup/{context-D4WDwf9m.d.cts → context-Cvnf3BRe.d.cts} +3 -2
  83. package/dist/tsup/{context-oc9zhA3x.d.ts → context-Oxi6YWcG.d.ts} +3 -2
  84. package/dist/tsup/db/drizzle.cjs +127 -67
  85. package/dist/tsup/db/drizzle.cjs.map +1 -1
  86. package/dist/tsup/db/drizzle.d.cts +8 -4
  87. package/dist/tsup/db/drizzle.d.ts +8 -4
  88. package/dist/tsup/db/drizzle.js +127 -67
  89. package/dist/tsup/db/drizzle.js.map +1 -1
  90. package/dist/tsup/db/mod.cjs +6 -126
  91. package/dist/tsup/db/mod.cjs.map +1 -1
  92. package/dist/tsup/db/mod.d.cts +8 -4
  93. package/dist/tsup/db/mod.d.ts +8 -4
  94. package/dist/tsup/db/mod.js +5 -125
  95. package/dist/tsup/db/mod.js.map +1 -1
  96. package/dist/tsup/dynamic/mod.cjs +2 -2
  97. package/dist/tsup/dynamic/mod.cjs.map +1 -1
  98. package/dist/tsup/dynamic/mod.d.cts +6 -4
  99. package/dist/tsup/dynamic/mod.d.ts +6 -4
  100. package/dist/tsup/dynamic/mod.js +1 -1
  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 +2 -13
  114. package/dist/tsup/inspector-tab/mod.cjs.map +1 -1
  115. package/dist/tsup/inspector-tab/mod.d.cts +9 -17
  116. package/dist/tsup/inspector-tab/mod.d.ts +9 -17
  117. package/dist/tsup/inspector-tab/mod.js +1 -12
  118. package/dist/tsup/inspector-tab/mod.js.map +1 -1
  119. package/dist/tsup/mod.cjs +2724 -611
  120. package/dist/tsup/mod.cjs.map +1 -1
  121. package/dist/tsup/mod.d.cts +9 -7
  122. package/dist/tsup/mod.d.ts +9 -7
  123. package/dist/tsup/mod.js +2641 -528
  124. package/dist/tsup/mod.js.map +1 -1
  125. package/dist/tsup/test/mod.cjs +19 -17
  126. package/dist/tsup/test/mod.cjs.map +1 -1
  127. package/dist/tsup/test/mod.d.cts +6 -4
  128. package/dist/tsup/test/mod.d.ts +6 -4
  129. package/dist/tsup/test/mod.js +18 -16
  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-CqDnC_PS.d.cts → utils-3rsE0JvI.d.cts} +25 -2
  138. package/dist/tsup/{utils-CqDnC_PS.d.ts → utils-3rsE0JvI.d.ts} +25 -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 +260 -200
  147. package/dist/tsup/workflow/mod.cjs.map +1 -1
  148. package/dist/tsup/workflow/mod.d.cts +8 -6
  149. package/dist/tsup/workflow/mod.d.ts +8 -6
  150. package/dist/tsup/workflow/mod.js +249 -189
  151. package/dist/tsup/workflow/mod.js.map +1 -1
  152. package/package.json +34 -14
  153. package/src/actor/actions.ts +155 -0
  154. package/src/actor/config.ts +403 -43
  155. package/src/actor/definition.ts +26 -7
  156. package/src/actor/errors.ts +87 -5
  157. package/src/actor/keys.ts +86 -0
  158. package/src/actor/mod.ts +15 -1
  159. package/src/actor/tracing.ts +28 -0
  160. package/src/agent-os/index.ts +5 -65
  161. package/src/client/actor-common.ts +8 -15
  162. package/src/client/actor-conn.ts +135 -8
  163. package/src/client/actor-handle.ts +180 -42
  164. package/src/client/actor-query.ts +8 -1
  165. package/src/client/auth.ts +37 -0
  166. package/src/client/client.ts +89 -21
  167. package/src/client/config.ts +27 -2
  168. package/src/client/errors.ts +2 -1
  169. package/src/client/lifecycle-errors.ts +16 -1
  170. package/src/client/mod.ts +9 -0
  171. package/src/client/outbound-telemetry.ts +66 -0
  172. package/src/client/query.ts +2 -0
  173. package/src/client/queue.ts +3 -0
  174. package/src/client/raw-utils.ts +37 -8
  175. package/src/client/resolve-gateway-target.ts +2 -0
  176. package/src/client/retry-budget.ts +78 -0
  177. package/src/client/token-provider.ts +93 -0
  178. package/src/client/utils.ts +16 -2
  179. package/src/common/actor-router-consts.ts +5 -0
  180. package/src/common/actor-telemetry-context.ts +19 -0
  181. package/src/common/bare/generated/actor-runtime-socket-protocol/v1.ts +848 -0
  182. package/src/common/bare/generated/inspector/v5.ts +1016 -0
  183. package/src/common/bare/generated/inspector/v6.ts +1367 -0
  184. package/src/common/bare/transport/v1.ts +36 -0
  185. package/src/common/database/config.ts +108 -15
  186. package/src/common/database/mod.ts +247 -76
  187. package/src/common/database/native-database.ts +433 -23
  188. package/src/common/database/shared.ts +24 -0
  189. package/src/common/encoding.ts +31 -21
  190. package/src/common/fetch-like.ts +63 -0
  191. package/src/common/inspector-transport.ts +12 -2
  192. package/src/common/log.ts +14 -8
  193. package/src/common/otel-context.ts +99 -0
  194. package/src/common/router.ts +1 -1
  195. package/src/common/utils.ts +7 -19
  196. package/src/db/drizzle.ts +182 -80
  197. package/src/db/mod.ts +2 -0
  198. package/src/dynamic/isolate-runtime.ts +0 -2
  199. package/src/engine-api/actors.ts +3 -3
  200. package/src/engine-client/actor-http-client.ts +29 -20
  201. package/src/engine-client/actor-websocket-client.ts +6 -3
  202. package/src/engine-client/api-endpoints.ts +72 -14
  203. package/src/engine-client/driver.ts +8 -15
  204. package/src/engine-client/mod.ts +248 -112
  205. package/src/inspector/client.browser.ts +134 -16
  206. package/src/inspector/mod.ts +1 -1
  207. package/src/inspector/workflow.ts +61 -0
  208. package/src/inspector-tab/mod.ts +1 -15
  209. package/src/registry/config/envoy.ts +2 -18
  210. package/src/registry/config/index.ts +53 -61
  211. package/src/registry/index.ts +311 -21
  212. package/src/registry/napi-runtime.ts +583 -39
  213. package/src/registry/native-http.ts +225 -0
  214. package/src/registry/native.ts +1365 -414
  215. package/src/registry/run-handler-coordinator.ts +219 -0
  216. package/src/registry/runtime.ts +372 -7
  217. package/src/registry/wasm-runtime.ts +490 -21
  218. package/src/registry/write-through-proxy.ts +101 -0
  219. package/src/test/mod.ts +1 -19
  220. package/src/test/ready.ts +22 -0
  221. package/src/unstable/migrations.ts +141 -0
  222. package/src/utils/env-vars.ts +15 -6
  223. package/src/utils/node.ts +44 -28
  224. package/src/utils.ts +3 -0
  225. package/src/workflow/context.ts +9 -27
  226. package/src/workflow/driver.ts +253 -116
  227. package/src/workflow/inspector.ts +23 -24
  228. package/src/workflow/mod.ts +50 -72
  229. package/dist/tsup/chunk-3GVMLSND.js.map +0 -1
  230. package/dist/tsup/chunk-3MHDOUD7.cjs.map +0 -1
  231. package/dist/tsup/chunk-4FC7TVS6.cjs.map +0 -1
  232. package/dist/tsup/chunk-B3GLD4IN.js.map +0 -1
  233. package/dist/tsup/chunk-BWERJMV6.cjs.map +0 -1
  234. package/dist/tsup/chunk-D363DMNH.cjs.map +0 -1
  235. package/dist/tsup/chunk-DTRDGPHU.cjs.map +0 -1
  236. package/dist/tsup/chunk-E4LNLI3W.cjs.map +0 -1
  237. package/dist/tsup/chunk-EFU4JW3T.js.map +0 -1
  238. package/dist/tsup/chunk-FNAXD5BQ.cjs.map +0 -1
  239. package/dist/tsup/chunk-GM45LG7L.cjs.map +0 -1
  240. package/dist/tsup/chunk-HXUEHHJF.js.map +0 -1
  241. package/dist/tsup/chunk-JZ7TWV65.js.map +0 -1
  242. package/dist/tsup/chunk-O3ZUMAN7.js.map +0 -1
  243. package/dist/tsup/chunk-P6F5MEWX.cjs +0 -382
  244. package/dist/tsup/chunk-P6F5MEWX.cjs.map +0 -1
  245. package/dist/tsup/chunk-PT7AC5PC.js.map +0 -1
  246. package/dist/tsup/chunk-UV7INX3N.js +0 -382
  247. package/dist/tsup/chunk-UV7INX3N.js.map +0 -1
  248. package/dist/tsup/chunk-VE2X4KMG.cjs.map +0 -1
  249. package/dist/tsup/chunk-XIX5DOZN.js.map +0 -1
  250. package/dist/tsup/chunk-ZA7FLHKH.cjs.map +0 -1
  251. package/dist/tsup/chunk-ZZ3WBRPD.js.map +0 -1
  252. package/src/actor/driver.ts +0 -141
  253. package/src/actor/instance/mod.ts +0 -2484
  254. package/src/actor/keys.test.ts +0 -275
  255. package/src/actor/utils.test.ts +0 -48
  256. package/src/agent-os/actor/cron.ts +0 -84
  257. package/src/agent-os/actor/db.ts +0 -54
  258. package/src/agent-os/actor/filesystem.ts +0 -131
  259. package/src/agent-os/actor/index.ts +0 -285
  260. package/src/agent-os/actor/network.ts +0 -58
  261. package/src/agent-os/actor/preview.ts +0 -190
  262. package/src/agent-os/actor/process.ts +0 -177
  263. package/src/agent-os/actor/session.ts +0 -518
  264. package/src/agent-os/actor/shell.ts +0 -60
  265. package/src/agent-os/config.ts +0 -79
  266. package/src/agent-os/fs/database-vfs.ts +0 -624
  267. package/src/agent-os/types.ts +0 -148
  268. package/src/client/test.ts +0 -44
  269. package/src/common/database/mod.test.ts +0 -137
  270. package/src/common/database/native-database.test.ts +0 -211
  271. package/src/common/inline-websocket-adapter.test.ts +0 -51
  272. package/src/drivers/engine/actor-driver.ts +0 -2473
  273. package/src/registry/process-metrics.ts +0 -250
  274. package/src/registry/runtime.test.ts +0 -50
  275. package/src/utils/endpoint-parser.test.ts +0 -206
  276. package/src/utils.test.ts +0 -34
  277. /package/dist/tsup/{chunk-OAUFXOG7.js.map → chunk-3DONDAMG.js.map} +0 -0
@@ -1,15 +1,32 @@
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 ActorLogger,
13
+ type ActorRun,
14
+ type ActorSchedule,
4
15
  CONN_STATE_MANAGER_SYMBOL,
16
+ type CronFire,
17
+ type CronJobInfo,
5
18
  disposeRunInspector,
6
19
  getRunFunction,
7
20
  getRunInspectorConfig,
21
+ getRunInspectorKind,
22
+ hasRunInspectorConfig,
8
23
  RAW_STATE_SYMBOL,
24
+ type ScheduledEventInfo,
9
25
  type WorkflowInspectorConfig,
10
26
  } from "@/actor/config";
11
27
  import type { AnyActorDefinition } from "@/actor/definition";
12
28
  import {
29
+ actorStopping,
13
30
  decodeBridgeRivetError,
14
31
  encodeBridgeRivetError,
15
32
  forbiddenError,
@@ -26,6 +43,7 @@ import {
26
43
  getQueueCanPublish,
27
44
  hasSchemaConfigKey,
28
45
  } from "@/actor/schema";
46
+ import type { ActionSampleRates } from "@/actor/tracing";
29
47
  import {
30
48
  type AnyClient,
31
49
  type Client,
@@ -33,13 +51,27 @@ import {
33
51
  } from "@/client/client";
34
52
  import { convertRegistryConfigToClientConfig } from "@/client/config";
35
53
  import { HEADER_CONN_PARAMS } from "@/common/actor-router-consts";
54
+ import type { ActorInvocationTraceContext } from "@/common/actor-telemetry-context";
36
55
  import type {
37
56
  AnyDatabaseProvider,
38
57
  SqliteProfilingOptions,
39
58
  } from "@/common/database/config";
40
- import { wrapJsNativeDatabase } from "@/common/database/native-database";
59
+ import {
60
+ bindNativeStateTransactionContext,
61
+ db as defaultDb,
62
+ registerNativeStateTransactionOpener,
63
+ } from "@/common/database/mod";
64
+ import {
65
+ type JsNativeDatabaseLike,
66
+ type JsNativeSynchronousTransactionLike,
67
+ wrapJsNativeDatabase,
68
+ } from "@/common/database/native-database";
41
69
  import { assertJsonCompatValue, type JsonCompatValue } from "@/common/encoding";
42
- import { decodeWorkflowHistoryTransport } from "@/common/inspector-transport";
70
+ import { isResponseLike } from "@/common/fetch-like";
71
+ import {
72
+ decodeWorkflowHistoryTransport,
73
+ type WorkflowHistoryBytes,
74
+ } from "@/common/inspector-transport";
43
75
  import { deconstructError, stringifyError } from "@/common/utils";
44
76
  import type {
45
77
  RivetCloseEvent,
@@ -55,7 +87,7 @@ import type {
55
87
  SqliteBackend,
56
88
  } from "@/registry/config";
57
89
  import { decodeCborCompat, encodeCborCompat } from "@/serde";
58
- import { getEnvUniversal, VERSION } from "@/utils";
90
+ import { getEnvUniversal, toUint8Array, VERSION } from "@/utils";
59
91
  import {
60
92
  getNodeFsSync,
61
93
  getNodePath,
@@ -63,6 +95,13 @@ import {
63
95
  } from "@/utils/node";
64
96
  import { logger } from "./log";
65
97
  import { loadNapiRuntime } from "./napi-runtime";
98
+ import {
99
+ buildNativeHttpRequest,
100
+ cancelNativeHttpRequestBody,
101
+ convertNativeHttpResponse,
102
+ type NativeHttpRequestBodyStream,
103
+ type NativeHttpResponseBodyStream,
104
+ } from "./native-http";
66
105
  import {
67
106
  type NativeValidationConfig,
68
107
  validateActionArgs,
@@ -71,6 +110,7 @@ import {
71
110
  validateQueueBody,
72
111
  validateQueueComplete,
73
112
  } from "./native-validation";
113
+ import { RunHandlerCoordinator } from "./run-handler-coordinator";
74
114
  import type {
75
115
  ActorContextHandle,
76
116
  ActorFactoryHandle,
@@ -79,16 +119,25 @@ import type {
79
119
  CoreRuntime,
80
120
  RegistryHandle,
81
121
  RuntimeActorConfig,
122
+ RuntimeActorTracingConfig,
82
123
  RuntimeBytes,
83
- RuntimeHttpResponse,
124
+ RuntimeCronFire,
125
+ RuntimeCronJobInfo,
84
126
  RuntimeInspectorTabEntry,
85
127
  RuntimeQueueMessage,
128
+ RuntimeScheduledEventInfo,
129
+ RuntimeScheduledFireInfo,
86
130
  RuntimeServeConfig,
87
131
  RuntimeStateDeltaPayload,
132
+ SqliteTransactionHandle,
88
133
  WebSocketHandle,
89
134
  } from "./runtime";
135
+ import { servicesBinaryUnavailable } from "./runtime";
90
136
  import { loadWasmRuntime } from "./wasm-runtime";
91
- import { createWriteThroughProxy } from "./write-through-proxy";
137
+ import {
138
+ createWriteThroughProxy,
139
+ unwrapWriteThroughProxy,
140
+ } from "./write-through-proxy";
92
141
 
93
142
  const textEncoder = new TextEncoder();
94
143
  const textDecoder = new TextDecoder();
@@ -112,6 +161,14 @@ type NativePersistConnState = {
112
161
  state: unknown;
113
162
  };
114
163
 
164
+ type NativeStateTransactionScope = {
165
+ actorContext: ActorContextHandleAdapter;
166
+ actorStateBaseline: unknown;
167
+ connectionStateBaselines: Map<string, Uint8Array>;
168
+ committed: boolean;
169
+ release: () => void;
170
+ };
171
+
115
172
  const defaultRuntimeLoaders: RuntimeLoaders = {
116
173
  loadNative: loadNapiRuntime,
117
174
  loadWasm: loadWasmRuntime,
@@ -180,10 +237,36 @@ export async function loadAutoRuntime(
180
237
  return (await loaders.loadWasm(config.wasm)).runtime;
181
238
  }
182
239
 
240
+ let nativeError: unknown;
183
241
  try {
184
242
  return (await loaders.loadNative()).runtime;
185
- } catch {
243
+ } catch (error) {
244
+ nativeError = error;
245
+ // Native is the expected runtime on a node-like host, so this is the
246
+ // actionable error even when the wasm fallback goes on to succeed.
247
+ // Discarding it hides causes such as a platform binding that npm
248
+ // silently skipped, which then resurfaces as an unrelated wasm error.
249
+ logger().warn({
250
+ msg: "native runtime failed to load; falling back to wasm",
251
+ error: stringifyError(error),
252
+ });
253
+ }
254
+
255
+ try {
186
256
  return (await loaders.loadWasm(config.wasm)).runtime;
257
+ } catch (wasmError) {
258
+ // Report both, native first. The wasm failure on a node-like host is
259
+ // usually just its loader fetching over `file://`, which says nothing
260
+ // about why native was unavailable.
261
+ throw new RivetError(
262
+ "config",
263
+ "runtime_unavailable",
264
+ `RivetKit could not load a core runtime. Native runtime: ${stringifyError(nativeError)} Wasm runtime: ${stringifyError(wasmError)}`,
265
+ {
266
+ public: true,
267
+ statusCode: 500,
268
+ },
269
+ );
187
270
  }
188
271
  }
189
272
 
@@ -255,14 +338,14 @@ type NativePersistActorState = {
255
338
  state: unknown;
256
339
  isInOnStateChange: boolean;
257
340
  connStates: Map<string, NativePersistConnState>;
258
- // Memoized deep write-through proxy and the state object it wraps. Rebuilt
259
- // only when the underlying state object identity changes.
260
- stateProxy?: unknown;
261
- stateProxyTarget?: unknown;
262
341
  // Set when a coalesced save and onStateChange flush is pending for the
263
342
  // current event loop tick.
264
343
  saveScheduled?: boolean;
265
344
  pendingSaveHandle?: ReturnType<typeof setImmediate>;
345
+ activeStateTransactionOwner?: symbol;
346
+ pendingStateTransactionOwners?: Set<symbol>;
347
+ stateTransactionTail?: Promise<void>;
348
+ stateTransactionSaveDeferred?: boolean;
266
349
  };
267
350
  type NativeDestroyGate = {
268
351
  destroyCompletion?: Promise<void>;
@@ -271,6 +354,11 @@ type NativeDestroyGate = {
271
354
  type NativeDatabaseClientState = {
272
355
  client: unknown;
273
356
  };
357
+ type NativeActorAbort = {
358
+ signal: AbortSignal;
359
+ listeners: Set<() => void>;
360
+ };
361
+
274
362
  type NativeActorRuntimeState = {
275
363
  sql?: ReturnType<typeof wrapJsNativeDatabase>;
276
364
  databaseClient?: NativeDatabaseClientState;
@@ -278,6 +366,17 @@ type NativeActorRuntimeState = {
278
366
  vars?: unknown;
279
367
  destroyGate?: NativeDestroyGate;
280
368
  persistState?: NativePersistActorState;
369
+ // One native actor abort signal shared by every context of the actor. Each
370
+ // native signal parks a task and a callback handle until the actor stops,
371
+ // so creating one per request or action leaks both. Per-context listeners
372
+ // live in `listeners` so the shared signal never collects one listener per
373
+ // in-flight request.
374
+ actorAbort?: NativeActorAbort;
375
+ // Set once shutdown cleanup has cleared this generation's caches. Work that
376
+ // outlives the generation, such as an untracked timer or a late WebSocket
377
+ // message handler, then fails with `actor.stopping` instead of reading an
378
+ // empty bag as if `vars` or the database were never initialized.
379
+ cleared?: true;
281
380
  };
282
381
 
283
382
  // Keep JS-only actor caches on the NAPI ActorContext runtime-state bag instead
@@ -287,9 +386,10 @@ function getNativeRuntimeState(
287
386
  runtime: CoreRuntime,
288
387
  ctx: ActorContextHandle,
289
388
  ): NativeActorRuntimeState {
290
- const runtimeState = callNativeSync(() =>
291
- runtime.actorRuntimeState(ctx),
292
- ) as NativeActorRuntimeState;
389
+ const runtimeState = readNativeRuntimeStateBag(runtime, ctx);
390
+ if (runtimeState.cleared) {
391
+ throw actorStopping(callNativeSync(() => runtime.actorId(ctx)));
392
+ }
293
393
  if (!runtimeState.destroyGate) {
294
394
  runtimeState.destroyGate = {};
295
395
  }
@@ -303,6 +403,22 @@ function getNativeRuntimeState(
303
403
  return runtimeState;
304
404
  }
305
405
 
406
+ function readNativeRuntimeStateBag(
407
+ runtime: CoreRuntime,
408
+ ctx: ActorContextHandle,
409
+ ): NativeActorRuntimeState {
410
+ return callNativeSync(() =>
411
+ runtime.actorRuntimeState(ctx),
412
+ ) as NativeActorRuntimeState;
413
+ }
414
+
415
+ function isNativeRuntimeStateCleared(
416
+ runtime: CoreRuntime,
417
+ ctx: ActorContextHandle,
418
+ ): boolean {
419
+ return readNativeRuntimeStateBag(runtime, ctx).cleared === true;
420
+ }
421
+
306
422
  function getNativePersistState(
307
423
  runtime: CoreRuntime,
308
424
  ctx: ActorContextHandle,
@@ -348,6 +464,15 @@ function stateMutationReentrantError(): RivetError {
348
464
  );
349
465
  }
350
466
 
467
+ function stateTransactionConflictError(): RivetError {
468
+ return new RivetError(
469
+ "actor",
470
+ "state_transaction_conflict",
471
+ "State cannot be mutated by another action while an experimental state-aware database transaction is active.",
472
+ { public: true, statusCode: 409 },
473
+ );
474
+ }
475
+
351
476
  function databaseNotConfiguredError(): RivetError {
352
477
  return new RivetError(
353
478
  "actor",
@@ -365,6 +490,14 @@ function databaseClientNotReadyError(): RivetError {
365
490
  { public: true },
366
491
  );
367
492
  }
493
+ function runHandlerNotConfiguredError(): RivetError {
494
+ return new RivetError(
495
+ "actor",
496
+ "run_handler_unavailable",
497
+ "Cannot schedule a run wake because this actor does not define a run handler.",
498
+ { public: true, statusCode: 409 },
499
+ );
500
+ }
368
501
 
369
502
  function stateNotEnabledError(): RivetError {
370
503
  return new RivetError(
@@ -428,7 +561,18 @@ function clearNativeRuntimeState(
428
561
  runtime: CoreRuntime,
429
562
  ctx: ActorContextHandle,
430
563
  ) {
564
+ // A coalesced save armed before the clear would otherwise fire against the
565
+ // cleared bag and throw outside any caller.
566
+ const pendingSaveHandle = readNativeRuntimeStateBag(runtime, ctx)
567
+ .persistState?.pendingSaveHandle;
568
+ if (pendingSaveHandle !== undefined) {
569
+ clearImmediate(pendingSaveHandle);
570
+ }
431
571
  callNativeSync(() => runtime.actorClearRuntimeState(ctx));
572
+ // The runtime hands out a fresh bag after a clear. Each generation has its
573
+ // own bag, so marking it makes later access from this generation fail typed
574
+ // without touching any newer generation of the same actor.
575
+ readNativeRuntimeStateBag(runtime, ctx).cleared = true;
432
576
  }
433
577
 
434
578
  async function cleanupNativeSleepRuntimeState(
@@ -443,8 +587,7 @@ async function cleanupNativeSleepRuntimeState(
443
587
  // the tracked work finishes without a deadline.
444
588
  const drained = await runtime.actorWaitForTrackedShutdownWork(ctx);
445
589
  if (!drained) {
446
- await closeNativeDatabaseClient(runtime, ctx);
447
- await closeNativeSqlDatabase(runtime, ctx);
590
+ await detachNativeDatabaseForShutdown(runtime, ctx);
448
591
  void runtime
449
592
  .actorWaitForTrackedShutdownWorkUnbounded(ctx)
450
593
  .then(async () => {
@@ -461,11 +604,26 @@ async function cleanupNativeSleepRuntimeState(
461
604
  }
462
605
 
463
606
  await afterTrackedWorkDrained?.();
464
- await closeNativeDatabaseClient(runtime, ctx);
465
- await closeNativeSqlDatabase(runtime, ctx);
607
+ await detachNativeDatabaseForShutdown(runtime, ctx);
466
608
  clearNativeRuntimeState(runtime, ctx);
467
609
  }
468
610
 
611
+ async function detachNativeDatabaseForShutdown(
612
+ runtime: CoreRuntime,
613
+ ctx: ActorContextHandle,
614
+ ): Promise<void> {
615
+ const runtimeState = getNativeRuntimeState(runtime, ctx);
616
+ // Stop JS access without closing the runtime-owned SQLite backend. Rust still
617
+ // needs it to reconcile scheduled alarms and performs the physical close after
618
+ // this lifecycle callback returns.
619
+ await runtimeState.sql?.detachForShutdown();
620
+ try {
621
+ await closeNativeDatabaseClient(runtime, ctx);
622
+ } finally {
623
+ runtimeState.sql = undefined;
624
+ }
625
+ }
626
+
469
627
  function closeNativeSqlDatabase(
470
628
  runtime: CoreRuntime,
471
629
  ctx: ActorContextHandle,
@@ -502,6 +660,26 @@ async function closeNativeDatabaseClient(
502
660
  }
503
661
  }
504
662
 
663
+ function createNativeSqlTransaction(
664
+ runtime: CoreRuntime,
665
+ transaction: SqliteTransactionHandle,
666
+ ): JsNativeSynchronousTransactionLike {
667
+ return {
668
+ exec: (sql) => runtime.actorSqlTransactionExec(transaction, sql),
669
+ execSync: (sql) =>
670
+ runtime.actorSqlTransactionExecSync(transaction, sql),
671
+ execute: (sql, params) =>
672
+ runtime.actorSqlTransactionExecute(transaction, sql, params),
673
+ executeSync: (sql, params) =>
674
+ runtime.actorSqlTransactionExecuteSync(transaction, sql, params),
675
+ commit: () => runtime.actorSqlTransactionCommit(transaction),
676
+ commitSync: () => runtime.actorSqlTransactionCommitSync(transaction),
677
+ rollback: () => runtime.actorSqlTransactionRollback(transaction),
678
+ rollbackSync: () =>
679
+ runtime.actorSqlTransactionRollbackSync(transaction),
680
+ };
681
+ }
682
+
505
683
  function getOrCreateNativeSqlDatabase(
506
684
  runtime: CoreRuntime,
507
685
  ctx: ActorContextHandle,
@@ -512,15 +690,76 @@ function getOrCreateNativeSqlDatabase(
512
690
  return cachedDatabase;
513
691
  }
514
692
 
515
- const database = wrapJsNativeDatabase({
693
+ const bindings: JsNativeDatabaseLike = {
516
694
  exec: (sql) => runtime.actorSqlExec(ctx, sql),
695
+ execSync: (sql) => runtime.actorSqlExecSync(ctx, sql),
517
696
  execute: (sql, params) => runtime.actorSqlExecute(ctx, sql, params),
697
+ executeSync: (sql, params) =>
698
+ runtime.actorSqlExecuteSync(ctx, sql, params),
699
+ executeBatch: (statements) =>
700
+ runtime.actorSqlExecuteBatch(ctx, statements),
701
+ beginTransaction: async (timeoutMs, name) => {
702
+ const transaction = await runtime.actorSqlBeginTransaction(
703
+ ctx,
704
+ timeoutMs,
705
+ name,
706
+ );
707
+ return createNativeSqlTransaction(runtime, transaction);
708
+ },
709
+ beginTransactionSync: (timeoutMs, name) => {
710
+ const transaction = runtime.actorSqlBeginTransactionSync(
711
+ ctx,
712
+ timeoutMs,
713
+ name,
714
+ );
715
+ return createNativeSqlTransaction(runtime, transaction);
716
+ },
717
+ beginStateTransaction: async (timeoutMs, context) => {
718
+ const scope = context as NativeStateTransactionScope | undefined;
719
+ if (!scope) {
720
+ throw new Error(
721
+ "actor state transaction context is not configured",
722
+ );
723
+ }
724
+ const transaction = await runtime.actorBeginStateTransaction(
725
+ ctx,
726
+ timeoutMs,
727
+ );
728
+ return {
729
+ exec: async () => {
730
+ throw new Error(
731
+ "actor state transactions only support single-statement execute calls",
732
+ );
733
+ },
734
+ execute: (sql, params) =>
735
+ runtime.actorStateTransactionExecute(
736
+ transaction,
737
+ sql,
738
+ params,
739
+ ),
740
+ commit: async () => {
741
+ await runtime.actorStateTransactionCommit(
742
+ transaction,
743
+ scope.actorContext.serializeForTick("save"),
744
+ );
745
+ scope.committed = true;
746
+ },
747
+ rollback: () =>
748
+ runtime.actorStateTransactionRollback(transaction),
749
+ };
750
+ },
518
751
  query: (sql, params) => runtime.actorSqlQuery(ctx, sql, params),
519
752
  run: (sql, params) => runtime.actorSqlRun(ctx, sql, params),
520
753
  metrics: () => runtime.actorSqlMetrics(ctx),
521
754
  takeLastKvError: () => runtime.actorSqlTakeLastKvError(ctx),
755
+ open: () => runtime.actorSqlOpen(ctx),
756
+ commitTicket: () => runtime.actorSqlCommitTicket(ctx),
757
+ whenDurable: (ticket) => runtime.actorSqlWhenDurable(ctx, ticket),
758
+ abortGeneration: (reason) =>
759
+ runtime.actorSqlAbortGeneration(ctx, reason),
522
760
  close: () => runtime.actorSqlClose(ctx),
523
- });
761
+ };
762
+ const database = wrapJsNativeDatabase(bindings);
524
763
  runtimeState.sql = database;
525
764
  return database;
526
765
  }
@@ -625,9 +864,22 @@ function decodeNativeKvValue<T extends NativeKvValueType = "text">(
625
864
  }
626
865
 
627
866
  async function loadEngineCli(): Promise<typeof import("@rivetkit/engine-cli")> {
867
+ // LOAD-BEARING: the specifier is computed (`.join("/")`) on purpose. Do NOT
868
+ // "simplify" it to a literal `import("@rivetkit/engine-cli")`. Edge adapters
869
+ // (e.g. @rivetkit/supabase) pre-bundle this module for Deno; a literal
870
+ // dynamic import is statically resolvable, so Deno's eszip bundler would
871
+ // snapshot the ~117 MB engine-cli binary into the deploy and 413. The
872
+ // computed specifier keeps it opaque to static analysis so it is never
873
+ // bundled. Enforced by scripts/ci/check-edge-native-closure.mjs.
628
874
  return import(["@rivetkit", "engine-cli"].join("/"));
629
875
  }
630
876
 
877
+ async function loadServices(): Promise<{ getServicesPath: () => string }> {
878
+ // Keep the native binary opaque to edge bundlers for the same reason as
879
+ // engine-cli above.
880
+ return import(["@rivet-dev", "services"].join("/"));
881
+ }
882
+
631
883
  function decodeValue<T>(value?: RuntimeBytes | null): T {
632
884
  if (!value || value.length === 0) {
633
885
  return undefined as T;
@@ -636,7 +888,15 @@ function decodeValue<T>(value?: RuntimeBytes | null): T {
636
888
  return decodeCborCompat(value);
637
889
  }
638
890
 
639
- function encodeValue(value: unknown): RuntimeBytes {
891
+ // Rejects `WorkflowHistoryBytes`: the compat layer rewrites an ArrayBuffer as
892
+ // `["$ArrayBuffer", "<base64>"]`, and the inspector wire field carries raw BARE.
893
+ // The conditional distributes, so it catches the branded type on its own but
894
+ // only strips it from a union that also has other members. A non-distributive
895
+ // `[T] extends [...]` resolves to `never` for the `any` arguments this takes
896
+ // elsewhere, so the union case stays uncovered.
897
+ function encodeValue<T>(
898
+ value: T extends WorkflowHistoryBytes ? never : T,
899
+ ): RuntimeBytes {
640
900
  return encodeCborCompat(value as JsonCompatValue);
641
901
  }
642
902
 
@@ -702,13 +962,26 @@ function encodeNativeCallbackError(error: unknown): Error {
702
962
  ? error
703
963
  : deconstructError(error, true);
704
964
 
705
- const bridgeError = new Error(encodeBridgeRivetError(structuredError), {
965
+ const { encoded, droppedMetadataCause } =
966
+ encodeBridgeRivetError(structuredError);
967
+ if (droppedMetadataCause !== undefined) {
968
+ logger().warn(
969
+ {
970
+ group: structuredError.group,
971
+ code: structuredError.code,
972
+ error: String(droppedMetadataCause),
973
+ },
974
+ "dropped error metadata that JSON cannot encode",
975
+ );
976
+ }
977
+ const bridgeError = new Error(encoded, {
706
978
  cause: error instanceof Error ? error : undefined,
707
979
  });
708
980
  return Object.assign(bridgeError, {
709
981
  group: structuredError.group,
710
982
  code: structuredError.code,
711
983
  metadata: structuredError.metadata,
984
+ rayId: structuredError.rayId,
712
985
  });
713
986
  }
714
987
 
@@ -728,16 +1001,10 @@ function callNativeSync<T>(invoke: () => T): T {
728
1001
  }
729
1002
  }
730
1003
 
731
- function actorAbortedError(): Error & { group: string; code: string } {
732
- return Object.assign(new Error("Actor aborted"), {
733
- group: "actor",
734
- code: "aborted",
735
- });
736
- }
737
-
738
- type NativeWorkflowInspectorConfig = WorkflowInspectorConfig<ArrayBuffer> & {
739
- getState?: () => Promise<unknown> | unknown;
740
- };
1004
+ type NativeWorkflowInspectorConfig =
1005
+ WorkflowInspectorConfig<WorkflowHistoryBytes> & {
1006
+ getState?: () => Promise<unknown> | unknown;
1007
+ };
741
1008
 
742
1009
  function isClosedTaskRegistrationError(error: unknown): boolean {
743
1010
  const metadata = error instanceof RivetError ? error.metadata : undefined;
@@ -910,6 +1177,10 @@ function serializeWorkflowEntryKind(
910
1177
  | {
911
1178
  tag: "WorkflowRemovedEntry";
912
1179
  val: { originalType: string; originalName: string | null };
1180
+ }
1181
+ | {
1182
+ tag: "WorkflowVersionCheckEntry";
1183
+ val: { resolved: number; latest: number };
913
1184
  } {
914
1185
  switch (kind.tag) {
915
1186
  case "WorkflowStepEntry":
@@ -975,6 +1246,14 @@ function serializeWorkflowEntryKind(
975
1246
  originalName: kind.val.originalName,
976
1247
  },
977
1248
  };
1249
+ case "WorkflowVersionCheckEntry":
1250
+ return {
1251
+ tag: kind.tag,
1252
+ val: {
1253
+ resolved: kind.val.resolved,
1254
+ latest: kind.val.latest,
1255
+ },
1256
+ };
978
1257
  }
979
1258
  }
980
1259
 
@@ -1117,38 +1396,6 @@ function decodeArgs(value?: RuntimeBytes | null): unknown[] {
1117
1396
  return normalizeArgs(decoded);
1118
1397
  }
1119
1398
 
1120
- function buildRequest(init: {
1121
- method: string;
1122
- uri: string;
1123
- headers?: Record<string, string>;
1124
- body?: RuntimeBytes;
1125
- }): Request {
1126
- const url = init.uri.startsWith("http")
1127
- ? init.uri
1128
- : new URL(init.uri, "http://127.0.0.1").toString();
1129
- const body =
1130
- init.body && init.body.length > 0
1131
- ? runtimeBytesToArrayBuffer(init.body)
1132
- : undefined;
1133
- return new Request(url, {
1134
- method: init.method,
1135
- headers: init.headers,
1136
- body,
1137
- });
1138
- }
1139
-
1140
- async function toRuntimeHttpResponse(
1141
- response: Response,
1142
- ): Promise<RuntimeHttpResponse> {
1143
- const headers = Object.fromEntries(response.headers.entries());
1144
- const body = new Uint8Array(await response.arrayBuffer());
1145
- return {
1146
- status: response.status,
1147
- headers,
1148
- body,
1149
- };
1150
- }
1151
-
1152
1399
  function toActorKey(
1153
1400
  segments: Array<{
1154
1401
  kind: string;
@@ -1169,6 +1416,9 @@ class NativeConnAdapter {
1169
1416
  #schemas: NativeValidationConfig;
1170
1417
  #ctx?: ActorContextHandle;
1171
1418
  #queueHibernationRemoval?: (connId: string) => void;
1419
+ #assertCanMutateState?: () => void;
1420
+ #stateProxy?: unknown;
1421
+ #stateProxyTarget?: unknown;
1172
1422
 
1173
1423
  constructor(
1174
1424
  runtime: CoreRuntime,
@@ -1176,12 +1426,14 @@ class NativeConnAdapter {
1176
1426
  schemas: NativeValidationConfig = {},
1177
1427
  ctx?: ActorContextHandle,
1178
1428
  queueHibernationRemoval?: (connId: string) => void,
1429
+ assertCanMutateState?: () => void,
1179
1430
  ) {
1180
1431
  this.#runtime = runtime;
1181
1432
  this.#conn = conn;
1182
1433
  this.#schemas = schemas;
1183
1434
  this.#ctx = ctx;
1184
1435
  this.#queueHibernationRemoval = queueHibernationRemoval;
1436
+ this.#assertCanMutateState = assertCanMutateState;
1185
1437
  (
1186
1438
  this as NativeConnAdapter & {
1187
1439
  [CONN_STATE_MANAGER_SYMBOL]?: unknown;
@@ -1212,24 +1464,55 @@ class NativeConnAdapter {
1212
1464
 
1213
1465
  get state(): unknown {
1214
1466
  const nextState = this.#readState();
1467
+ if (!this.#ctx) {
1468
+ return this.#createStateProxy(nextState);
1469
+ }
1470
+
1471
+ // Reading `conn.state` rebuilds the deep write-through proxy, which
1472
+ // allocates fresh on-change caches and rewraps the whole tree. Memoize
1473
+ // the proxy keyed on the underlying state object so repeated reads and
1474
+ // deep read cascades reuse a single proxy.
1475
+ if (
1476
+ this.#stateProxy === undefined ||
1477
+ this.#stateProxyTarget !== nextState
1478
+ ) {
1479
+ this.#stateProxyTarget = nextState;
1480
+ this.#stateProxy = this.#createStateProxy(nextState);
1481
+ }
1482
+ return this.#stateProxy;
1483
+ }
1484
+
1485
+ #createStateProxy(state: unknown): unknown {
1486
+ const assertCurrentState = () => {
1487
+ this.#assertCanMutateState?.();
1488
+ if (this.#ctx && this.#readState() !== state) {
1489
+ throw stateTransactionConflictError();
1490
+ }
1491
+ };
1215
1492
  return createWriteThroughProxy(
1216
- nextState,
1493
+ state,
1217
1494
  (nextValue) => {
1495
+ assertCurrentState();
1218
1496
  this.#writeState(nextValue, { writeNative: true });
1219
1497
  },
1220
1498
  (newValue) => {
1499
+ assertCurrentState();
1221
1500
  assertJsonCompatValue(newValue);
1222
1501
  },
1223
1502
  );
1224
1503
  }
1225
1504
 
1226
1505
  set state(value: unknown) {
1227
- assertJsonCompatValue(value);
1228
- this.#writeState(value, { writeNative: true });
1506
+ this.#assertCanMutateState?.();
1507
+ const nextValue = unwrapWriteThroughProxy(value);
1508
+ assertJsonCompatValue(nextValue);
1509
+ this.#writeState(nextValue, { writeNative: true });
1229
1510
  }
1230
1511
 
1231
1512
  initializeState(value: unknown): void {
1232
- this.#writeState(value, { writeNative: false });
1513
+ this.#writeState(unwrapWriteThroughProxy(value), {
1514
+ writeNative: false,
1515
+ });
1233
1516
  }
1234
1517
 
1235
1518
  get isHibernatable(): boolean {
@@ -1303,7 +1586,7 @@ class NativeConnAdapter {
1303
1586
  }
1304
1587
  }
1305
1588
 
1306
- class NativeScheduleAdapter {
1589
+ class NativeScheduleAdapter implements ActorSchedule {
1307
1590
  #runtime: CoreRuntime;
1308
1591
  #ctx: ActorContextHandle;
1309
1592
 
@@ -1316,14 +1599,12 @@ class NativeScheduleAdapter {
1316
1599
  duration: number,
1317
1600
  action: string,
1318
1601
  ...args: unknown[]
1319
- ): Promise<void> {
1320
- callNativeSync(() =>
1321
- this.#runtime.actorScheduleAfter(
1322
- this.#ctx,
1323
- duration,
1324
- action,
1325
- encodeValue(args),
1326
- ),
1602
+ ): Promise<string> {
1603
+ return await this.#runtime.actorScheduleAfter(
1604
+ this.#ctx,
1605
+ duration,
1606
+ action,
1607
+ encodeValue(args),
1327
1608
  );
1328
1609
  }
1329
1610
 
@@ -1331,16 +1612,129 @@ class NativeScheduleAdapter {
1331
1612
  timestamp: number,
1332
1613
  action: string,
1333
1614
  ...args: unknown[]
1334
- ): Promise<void> {
1335
- callNativeSync(() =>
1336
- this.#runtime.actorScheduleAt(
1337
- this.#ctx,
1338
- timestamp,
1339
- action,
1340
- encodeValue(args),
1341
- ),
1615
+ ): Promise<string> {
1616
+ return await this.#runtime.actorScheduleAt(
1617
+ this.#ctx,
1618
+ timestamp,
1619
+ action,
1620
+ encodeValue(args),
1621
+ );
1622
+ }
1623
+
1624
+ async cancel(id: string): Promise<boolean> {
1625
+ return await this.#runtime.actorScheduleCancel(this.#ctx, id);
1626
+ }
1627
+
1628
+ async get(id: string): Promise<ScheduledEventInfo | undefined> {
1629
+ const event = await this.#runtime.actorScheduleGet(this.#ctx, id);
1630
+ return event ? decodeScheduledEventInfo(event) : undefined;
1631
+ }
1632
+
1633
+ async list(): Promise<ScheduledEventInfo[]> {
1634
+ return (await this.#runtime.actorScheduleList(this.#ctx)).map(
1635
+ decodeScheduledEventInfo,
1636
+ );
1637
+ }
1638
+ }
1639
+
1640
+ class NativeCronAdapter implements ActorCron {
1641
+ #runtime: CoreRuntime;
1642
+ #ctx: ActorContextHandle;
1643
+
1644
+ constructor(runtime: CoreRuntime, ctx: ActorContextHandle) {
1645
+ this.#runtime = runtime;
1646
+ this.#ctx = ctx;
1647
+ }
1648
+
1649
+ async set(options: ActorCronSetOptions): Promise<void> {
1650
+ await this.#runtime.actorCronSet(
1651
+ this.#ctx,
1652
+ options.name,
1653
+ options.expression,
1654
+ options.timezone,
1655
+ options.action,
1656
+ encodeValue(options.args ?? []),
1657
+ options.maxHistory,
1658
+ );
1659
+ }
1660
+
1661
+ async every(options: ActorCronEveryOptions): Promise<void> {
1662
+ await this.#runtime.actorCronEvery(
1663
+ this.#ctx,
1664
+ options.name,
1665
+ options.interval,
1666
+ options.action,
1667
+ encodeValue(options.args ?? []),
1668
+ options.maxHistory,
1669
+ );
1670
+ }
1671
+
1672
+ async get(name: string): Promise<CronJobInfo | undefined> {
1673
+ const job = await this.#runtime.actorCronGet(this.#ctx, name);
1674
+ return job ? decodeCronJobInfo(job) : undefined;
1675
+ }
1676
+
1677
+ async list(): Promise<CronJobInfo[]> {
1678
+ return (await this.#runtime.actorCronList(this.#ctx)).map(
1679
+ decodeCronJobInfo,
1342
1680
  );
1343
1681
  }
1682
+
1683
+ async delete(name: string): Promise<boolean> {
1684
+ return await this.#runtime.actorCronDelete(this.#ctx, name);
1685
+ }
1686
+
1687
+ async history(
1688
+ name: string,
1689
+ options?: { limit?: number },
1690
+ ): Promise<CronFire[]> {
1691
+ return (
1692
+ await this.#runtime.actorCronHistory(
1693
+ this.#ctx,
1694
+ name,
1695
+ options?.limit,
1696
+ )
1697
+ ).map(decodeCronFire);
1698
+ }
1699
+ }
1700
+
1701
+ function decodeScheduledEventInfo(
1702
+ event: RuntimeScheduledEventInfo,
1703
+ ): ScheduledEventInfo {
1704
+ return {
1705
+ id: event.id,
1706
+ action: event.action,
1707
+ args: decodeArgs(event.args),
1708
+ runAt: event.runAt,
1709
+ };
1710
+ }
1711
+
1712
+ function decodeCronJobInfo(job: RuntimeCronJobInfo): CronJobInfo {
1713
+ const base = {
1714
+ name: job.name,
1715
+ action: job.action,
1716
+ args: decodeArgs(job.args),
1717
+ nextRunAt: job.nextRunAt,
1718
+ lastRunAt: job.lastRunAt,
1719
+ maxHistory: job.maxHistory,
1720
+ };
1721
+ if (job.kind === "cron") {
1722
+ return {
1723
+ ...base,
1724
+ kind: "cron",
1725
+ expression: job.expression as string,
1726
+ timezone: job.timezone as string,
1727
+ };
1728
+ }
1729
+ return {
1730
+ ...base,
1731
+ kind: "every",
1732
+ interval: job.intervalMs as number,
1733
+ };
1734
+ }
1735
+
1736
+ function decodeCronFire(fire: RuntimeCronFire): CronFire {
1737
+ return { ...fire };
1344
1738
  }
1345
1739
 
1346
1740
  class NativeKvAdapter {
@@ -1531,8 +1925,9 @@ function wrapQueueMessage(
1531
1925
  schemas: NativeValidationConfig["queues"],
1532
1926
  ) {
1533
1927
  const name = callNativeSync(() => message.name());
1928
+ const id = callNativeSync(() => message.id());
1534
1929
  return {
1535
- id: Number(callNativeSync(() => message.id())),
1930
+ id: id <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(id) : id,
1536
1931
  name,
1537
1932
  body: validateQueueBody(
1538
1933
  schemas,
@@ -1716,6 +2111,32 @@ class NativeQueueAdapter {
1716
2111
  cleanup?.();
1717
2112
  }
1718
2113
  }
2114
+ async waitForAvailable(
2115
+ names?: readonly string[],
2116
+ options?: { timeout?: number; signal?: AbortSignal },
2117
+ ): Promise<void> {
2118
+ await this.waitForNamesAvailable(names ?? [], options);
2119
+ }
2120
+
2121
+ async complete(
2122
+ message: { id: number | bigint; name: string },
2123
+ response?: unknown,
2124
+ ): Promise<void> {
2125
+ const validatedResponse = validateQueueComplete(
2126
+ this.#schemas,
2127
+ message.name,
2128
+ response,
2129
+ );
2130
+ await callNative(() =>
2131
+ this.#runtime.actorQueueCompletePersisted(
2132
+ this.#ctx,
2133
+ BigInt(message.id),
2134
+ message.name,
2135
+ encodeValue(validatedResponse),
2136
+ ),
2137
+ );
2138
+ this.#pendingCompletableMessageIds.delete(message.id.toString());
2139
+ }
1719
2140
 
1720
2141
  async enqueueAndWait(
1721
2142
  name: string,
@@ -2295,15 +2716,18 @@ class NativeConnectionMap implements ReadonlyMap<string, NativeConnAdapter> {
2295
2716
  #runtime: CoreRuntime;
2296
2717
  #ctx: ActorContextHandle;
2297
2718
  #schemas: NativeValidationConfig;
2719
+ #assertCanMutateState: () => void;
2298
2720
 
2299
2721
  constructor(
2300
2722
  runtime: CoreRuntime,
2301
2723
  ctx: ActorContextHandle,
2302
2724
  schemas: NativeValidationConfig,
2725
+ assertCanMutateState: () => void,
2303
2726
  ) {
2304
2727
  this.#runtime = runtime;
2305
2728
  this.#ctx = ctx;
2306
2729
  this.#schemas = schemas;
2730
+ this.#assertCanMutateState = assertCanMutateState;
2307
2731
  }
2308
2732
 
2309
2733
  #connToAdapter(conn: ConnHandle): NativeConnAdapter {
@@ -2319,6 +2743,7 @@ class NativeConnectionMap implements ReadonlyMap<string, NativeConnAdapter> {
2319
2743
  connId,
2320
2744
  ),
2321
2745
  ),
2746
+ this.#assertCanMutateState,
2322
2747
  );
2323
2748
  }
2324
2749
 
@@ -2389,6 +2814,9 @@ class NativeConnectionMap implements ReadonlyMap<string, NativeConnAdapter> {
2389
2814
  readonly [Symbol.toStringTag] = "NativeConnectionMap";
2390
2815
  }
2391
2816
 
2817
+ /** Logger cache key for code that runs outside any invocation. */
2818
+ const NO_INVOCATION_SCOPE = {};
2819
+
2392
2820
  export class ActorContextHandleAdapter {
2393
2821
  #runtime: CoreRuntime;
2394
2822
  #ctx: ActorContextHandle;
@@ -2398,17 +2826,22 @@ export class ActorContextHandleAdapter {
2398
2826
  #client?: AnyClient;
2399
2827
  #clientFactory?: () => AnyClient;
2400
2828
  #connMap?: NativeConnectionMap;
2829
+ #cron?: NativeCronAdapter;
2401
2830
  #databaseProvider?: Exclude<AnyDatabaseProvider, undefined>;
2402
2831
  #db?: unknown;
2403
2832
  #dispatchCancelToken?: CancellationTokenHandle;
2404
2833
  #kv?: NativeKvAdapter;
2834
+ #logByInvocationScope = new WeakMap<object, ActorLogger>();
2405
2835
  #queue?: NativeQueueAdapter;
2406
2836
  #request?: Request;
2407
2837
  #schedule?: NativeScheduleAdapter;
2408
- #sql?: ReturnType<typeof wrapJsNativeDatabase>;
2409
- #runHandlerActiveProvider?: () => boolean;
2838
+ #run?: ActorRun;
2839
+ #runHandlerConfigured: boolean;
2410
2840
  #onStateChange?: NativeOnStateChangeHandler;
2411
2841
  #stateEnabled: boolean;
2842
+ #stateProxy?: unknown;
2843
+ #stateProxyTarget?: unknown;
2844
+ readonly #stateTransactionOwner = Symbol("actor-state-transaction-owner");
2412
2845
 
2413
2846
  constructor(
2414
2847
  runtime: CoreRuntime,
@@ -2418,16 +2851,16 @@ export class ActorContextHandleAdapter {
2418
2851
  databaseProvider?: AnyDatabaseProvider,
2419
2852
  request?: Request,
2420
2853
  stateEnabled = true,
2421
- runHandlerActiveProvider?: () => boolean,
2422
2854
  onStateChange?: NativeOnStateChangeHandler,
2423
2855
  dispatchCancelToken?: CancellationTokenHandle,
2856
+ runHandlerConfigured = false,
2424
2857
  ) {
2425
2858
  this.#runtime = runtime;
2426
2859
  this.#ctx = ctx;
2427
2860
  this.#clientFactory = clientFactory;
2428
2861
  this.#schemas = schemas;
2429
2862
  this.#dispatchCancelToken = dispatchCancelToken;
2430
- this.#runHandlerActiveProvider = runHandlerActiveProvider;
2863
+ this.#runHandlerConfigured = runHandlerConfigured;
2431
2864
  this.#onStateChange = onStateChange;
2432
2865
  this.#stateEnabled = stateEnabled;
2433
2866
  if (databaseProvider) {
@@ -2440,6 +2873,11 @@ export class ActorContextHandleAdapter {
2440
2873
  }
2441
2874
  )[ACTOR_CONTEXT_INTERNAL_SYMBOL] = new NativeWorkflowRuntimeAdapter(
2442
2875
  this,
2876
+ () =>
2877
+ this.#logByInvocationScope.delete(
2878
+ this.#runtime.currentInvocationScope() ??
2879
+ NO_INVOCATION_SCOPE,
2880
+ ),
2443
2881
  );
2444
2882
  }
2445
2883
 
@@ -2450,11 +2888,10 @@ export class ActorContextHandleAdapter {
2450
2888
  return this.#kv;
2451
2889
  }
2452
2890
 
2453
- get sql() {
2454
- if (!this.#sql) {
2455
- this.#sql = getOrCreateNativeSqlDatabase(this.#runtime, this.#ctx);
2456
- }
2457
- return this.#sql;
2891
+ async actorRuntimeSocket(): Promise<{ path: string }> {
2892
+ return await callNative(() =>
2893
+ this.#runtime.actorRuntimeSocketProvision(this.#ctx),
2894
+ );
2458
2895
  }
2459
2896
 
2460
2897
  get db() {
@@ -2469,7 +2906,7 @@ export class ActorContextHandleAdapter {
2469
2906
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
2470
2907
  const cachedClient = runtimeState.databaseClient;
2471
2908
  if (cachedClient) {
2472
- this.#db = cachedClient.client;
2909
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
2473
2910
  return this.#db;
2474
2911
  }
2475
2912
 
@@ -2487,29 +2924,35 @@ export class ActorContextHandleAdapter {
2487
2924
  if (!this.#stateEnabled) {
2488
2925
  throw stateNotEnabledError();
2489
2926
  }
2490
- const actorState = getNativePersistState(this.#runtime, this.#ctx);
2491
2927
  const nextState = this.#readState();
2492
2928
  // Reading `c.state` rebuilds the deep write-through proxy, which
2493
2929
  // allocates fresh on-change caches and rewraps the whole tree. Memoize
2494
2930
  // the proxy keyed on the underlying state object so repeated reads and
2495
2931
  // deep read cascades reuse a single proxy.
2496
2932
  if (
2497
- actorState.stateProxy === undefined ||
2498
- actorState.stateProxyTarget !== nextState
2933
+ this.#stateProxy === undefined ||
2934
+ this.#stateProxyTarget !== nextState
2499
2935
  ) {
2500
- actorState.stateProxyTarget = nextState;
2501
- actorState.stateProxy = createWriteThroughProxy(
2936
+ const assertCurrentState = () => {
2937
+ this.#assertCanMutateState();
2938
+ if (this.#readState() !== nextState) {
2939
+ throw stateTransactionConflictError();
2940
+ }
2941
+ };
2942
+ this.#stateProxyTarget = nextState;
2943
+ this.#stateProxy = createWriteThroughProxy(
2502
2944
  nextState,
2503
2945
  (nextValue) => {
2946
+ assertCurrentState();
2504
2947
  this.#writeState(nextValue, { scheduleSave: true });
2505
2948
  },
2506
2949
  (newValue) => {
2507
- this.#assertCanMutateState();
2950
+ assertCurrentState();
2508
2951
  assertJsonCompatValue(newValue);
2509
2952
  },
2510
2953
  );
2511
2954
  }
2512
- return actorState.stateProxy;
2955
+ return this.#stateProxy;
2513
2956
  }
2514
2957
 
2515
2958
  set state(value: unknown) {
@@ -2517,15 +2960,18 @@ export class ActorContextHandleAdapter {
2517
2960
  throw stateNotEnabledError();
2518
2961
  }
2519
2962
  this.#assertCanMutateState();
2520
- assertJsonCompatValue(value);
2521
- this.#writeState(value, { scheduleSave: true });
2963
+ const nextValue = unwrapWriteThroughProxy(value);
2964
+ assertJsonCompatValue(nextValue);
2965
+ this.#writeState(nextValue, { scheduleSave: true });
2522
2966
  }
2523
2967
 
2524
2968
  initializeState(value: unknown): void {
2525
2969
  if (!this.#stateEnabled) {
2526
2970
  return;
2527
2971
  }
2528
- this.#writeState(value, { scheduleSave: false });
2972
+ this.#writeState(unwrapWriteThroughProxy(value), {
2973
+ scheduleSave: false,
2974
+ });
2529
2975
  }
2530
2976
 
2531
2977
  get vars(): unknown {
@@ -2556,6 +3002,36 @@ export class ActorContextHandleAdapter {
2556
3002
  return this.#queue;
2557
3003
  }
2558
3004
 
3005
+ get run() {
3006
+ if (!this.#run) {
3007
+ this.#run = {
3008
+ setWakeAt: async (timestamp: number | null) => {
3009
+ if (timestamp !== null && !this.#runHandlerConfigured) {
3010
+ throw runHandlerNotConfiguredError();
3011
+ }
3012
+ if (
3013
+ timestamp !== null &&
3014
+ (!Number.isSafeInteger(timestamp) || timestamp < 0)
3015
+ ) {
3016
+ throw new TypeError(
3017
+ "Run wake timestamp must be a non-negative safe integer or null",
3018
+ );
3019
+ }
3020
+ await callNative(() =>
3021
+ this.#runtime.actorSetRunWakeAt(this.#ctx, timestamp),
3022
+ );
3023
+ },
3024
+ startWorkflowSpan: () =>
3025
+ callNative(() =>
3026
+ this.#runtime.startWorkflowSpan(this.#ctx),
3027
+ ),
3028
+ runOutsideWorkflowSpan: (body) =>
3029
+ this.#runtime.runOutsideActorInvocationContext(body),
3030
+ };
3031
+ }
3032
+ return this.#run;
3033
+ }
3034
+
2559
3035
  get schedule(): NativeScheduleAdapter {
2560
3036
  if (!this.#schedule) {
2561
3037
  this.#schedule = new NativeScheduleAdapter(
@@ -2566,6 +3042,13 @@ export class ActorContextHandleAdapter {
2566
3042
  return this.#schedule;
2567
3043
  }
2568
3044
 
3045
+ get cron(): NativeCronAdapter {
3046
+ if (!this.#cron) {
3047
+ this.#cron = new NativeCronAdapter(this.#runtime, this.#ctx);
3048
+ }
3049
+ return this.#cron;
3050
+ }
3051
+
2569
3052
  get actorId(): string {
2570
3053
  return callNativeSync(() => this.#runtime.actorId(this.#ctx));
2571
3054
  }
@@ -2590,33 +3073,67 @@ export class ActorContextHandleAdapter {
2590
3073
  this.#runtime,
2591
3074
  this.#ctx,
2592
3075
  this.#schemas,
3076
+ () => this.#assertCanMutateState(),
2593
3077
  );
2594
3078
  }
2595
3079
  return this.#connMap;
2596
3080
  }
2597
3081
 
3082
+ #invocationTraceContext(): ActorInvocationTraceContext | undefined {
3083
+ return callNativeSync(() =>
3084
+ this.#runtime.actorInvocationTraceContext(this.#ctx),
3085
+ );
3086
+ }
3087
+
3088
+ /**
3089
+ * Cached per invocation, because the `run` context outlives workflow runs and steps.
3090
+ * A workflow queue receive clears the entry, because the run's ray becomes the message's ray.
3091
+ */
2598
3092
  get log() {
2599
- return logger();
3093
+ const scope =
3094
+ this.#runtime.currentInvocationScope() ?? NO_INVOCATION_SCOPE;
3095
+ const cached = this.#logByInvocationScope.get(scope);
3096
+ if (cached) return cached;
3097
+
3098
+ const invocation = this.#invocationTraceContext();
3099
+ const log = logger().child({
3100
+ actorId: this.actorId,
3101
+ actorName: this.name,
3102
+ actorKey: this.key,
3103
+ ...(invocation?.rayId && { rayId: invocation.rayId }),
3104
+ ...(invocation?.span && {
3105
+ traceId: invocation.span.traceId,
3106
+ spanId: invocation.span.spanId,
3107
+ }),
3108
+ });
3109
+ this.#logByInvocationScope.set(scope, log);
3110
+ return log;
2600
3111
  }
2601
3112
 
2602
3113
  get abortSignal(): AbortSignal {
2603
3114
  if (!this.#abortSignal) {
2604
- const actorSignal = this.#createActorAbortSignal();
3115
+ const actorAbort = this.#actorAbort();
3116
+ const actorSignal = actorAbort.signal;
2605
3117
  if (this.#dispatchCancelToken === undefined) {
2606
3118
  this.#abortSignal = actorSignal;
2607
3119
  } else {
2608
3120
  const controller = new AbortController();
2609
3121
  let cleanedUp = false;
3122
+ let releaseDispatchListener: (() => void) | undefined;
2610
3123
  const onActorAbort = () => {
2611
3124
  cleanup();
2612
3125
  controller.abort();
2613
3126
  };
3127
+ // Releasing the native listener on dispose frees it even when the
3128
+ // dispatch token is never cancelled.
2614
3129
  const cleanup = () => {
2615
3130
  if (cleanedUp) {
2616
3131
  return;
2617
3132
  }
2618
3133
  cleanedUp = true;
2619
- actorSignal.removeEventListener("abort", onActorAbort);
3134
+ actorAbort.listeners.delete(onActorAbort);
3135
+ releaseDispatchListener?.();
3136
+ releaseDispatchListener = undefined;
2620
3137
  this.#abortSignalCleanup = undefined;
2621
3138
  };
2622
3139
 
@@ -2630,10 +3147,8 @@ export class ActorContextHandleAdapter {
2630
3147
  } else {
2631
3148
  const dispatchCancelToken = this.#dispatchCancelToken;
2632
3149
  this.#abortSignalCleanup = cleanup;
2633
- actorSignal.addEventListener("abort", onActorAbort, {
2634
- once: true,
2635
- });
2636
- callNativeSync(() =>
3150
+ actorAbort.listeners.add(onActorAbort);
3151
+ releaseDispatchListener = callNativeSync(() =>
2637
3152
  this.#runtime.onCancellationTokenCancelled(
2638
3153
  dispatchCancelToken,
2639
3154
  () => {
@@ -2670,12 +3185,12 @@ export class ActorContextHandleAdapter {
2670
3185
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
2671
3186
  const cachedClient = runtimeState.databaseClient;
2672
3187
  if (cachedClient) {
2673
- this.#db = cachedClient.client;
3188
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
2674
3189
  return this.#db;
2675
3190
  }
2676
3191
 
2677
3192
  const actorId = this.actorId;
2678
- const client = await this.#databaseProvider.createClient({
3193
+ const createdClient = await this.#databaseProvider.createClient({
2679
3194
  actorId,
2680
3195
  kv: {
2681
3196
  batchPut: async (entries) => {
@@ -2696,44 +3211,171 @@ export class ActorContextHandleAdapter {
2696
3211
  log: {
2697
3212
  debug: (obj) => logger().debug(obj),
2698
3213
  },
2699
- nativeDatabaseProvider: {
2700
- open: async (requestedActorId) => {
2701
- void requestedActorId;
2702
- return getOrCreateNativeSqlDatabase(
3214
+ nativeDatabaseProvider: registerNativeStateTransactionOpener(
3215
+ {
3216
+ open: async (requestedActorId) => {
3217
+ void requestedActorId;
3218
+ const database = getOrCreateNativeSqlDatabase(
3219
+ this.#runtime,
3220
+ this.#ctx,
3221
+ );
3222
+ await database.open();
3223
+ return database;
3224
+ },
3225
+ },
3226
+ async (timeoutMs, context) =>
3227
+ await getOrCreateNativeSqlDatabase(
2703
3228
  this.#runtime,
2704
3229
  this.#ctx,
2705
- );
2706
- },
2707
- },
3230
+ ).beginStateTransaction(timeoutMs, context),
3231
+ ),
2708
3232
  });
2709
3233
  runtimeState.databaseClient = {
2710
- client,
3234
+ client: createdClient,
2711
3235
  };
2712
- this.#db = client;
2713
- return client;
3236
+ this.#db = this.#bindDatabaseClient(createdClient);
3237
+ return this.#db;
2714
3238
  }
2715
3239
 
2716
- async prepare(): Promise<void> {
2717
- if (!this.#databaseProvider) {
2718
- return;
2719
- }
2720
-
2721
- await this.ensureDatabaseClient();
3240
+ #bindDatabaseClient(client: unknown): unknown {
3241
+ return bindNativeStateTransactionContext(client, {
3242
+ enter: async () => await this.#enterStateTransaction(),
3243
+ exit: (scope) =>
3244
+ this.#exitStateTransaction(
3245
+ scope as NativeStateTransactionScope,
3246
+ ),
3247
+ });
2722
3248
  }
2723
3249
 
2724
- async runDatabaseMigrations(): Promise<void> {
2725
- if (!this.#databaseProvider) {
2726
- return;
3250
+ async #enterStateTransaction(): Promise<NativeStateTransactionScope> {
3251
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
3252
+ let pendingOwners = actorState.pendingStateTransactionOwners;
3253
+ if (!pendingOwners) {
3254
+ pendingOwners = new Set();
3255
+ actorState.pendingStateTransactionOwners = pendingOwners;
2727
3256
  }
2728
-
2729
- await this.#databaseProvider.onMigrate(
2730
- (await this.ensureDatabaseClient()) as never,
3257
+ if (
3258
+ actorState.activeStateTransactionOwner ===
3259
+ this.#stateTransactionOwner ||
3260
+ pendingOwners.has(this.#stateTransactionOwner)
3261
+ ) {
3262
+ throw stateTransactionConflictError();
3263
+ }
3264
+ pendingOwners.add(this.#stateTransactionOwner);
3265
+ const predecessor =
3266
+ actorState.stateTransactionTail ?? Promise.resolve();
3267
+ let release!: () => void;
3268
+ const hold = new Promise<void>((resolve) => {
3269
+ release = resolve;
3270
+ });
3271
+ actorState.stateTransactionTail = predecessor.then(
3272
+ async () => await hold,
2731
3273
  );
2732
- }
3274
+ try {
3275
+ await predecessor;
3276
+ pendingOwners.delete(this.#stateTransactionOwner);
3277
+ actorState.activeStateTransactionOwner =
3278
+ this.#stateTransactionOwner;
3279
+ return {
3280
+ actorContext: this,
3281
+ actorStateBaseline: this.#stateEnabled
3282
+ ? structuredClone(this.#readState())
3283
+ : undefined,
3284
+ connectionStateBaselines: new Map(
3285
+ callNativeSync(() =>
3286
+ this.#runtime.actorConns(this.#ctx),
3287
+ ).map((conn) => [
3288
+ callNativeSync(() => this.#runtime.connId(conn)),
3289
+ new Uint8Array(
3290
+ callNativeSync(() => this.#runtime.connState(conn)),
3291
+ ),
3292
+ ]),
3293
+ ),
3294
+ committed: false,
3295
+ release,
3296
+ };
3297
+ } catch (error) {
3298
+ pendingOwners.delete(this.#stateTransactionOwner);
3299
+ if (
3300
+ actorState.activeStateTransactionOwner ===
3301
+ this.#stateTransactionOwner
3302
+ ) {
3303
+ actorState.activeStateTransactionOwner = undefined;
3304
+ }
3305
+ release();
3306
+ throw error;
3307
+ }
3308
+ }
3309
+
3310
+ #exitStateTransaction(scope: NativeStateTransactionScope): void {
3311
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
3312
+ try {
3313
+ if (!scope.committed) {
3314
+ this.#restoreStateTransactionBaseline(scope);
3315
+ }
3316
+ } finally {
3317
+ if (
3318
+ actorState.activeStateTransactionOwner ===
3319
+ this.#stateTransactionOwner
3320
+ ) {
3321
+ actorState.activeStateTransactionOwner = undefined;
3322
+ }
3323
+ if (actorState.stateTransactionSaveDeferred) {
3324
+ actorState.stateTransactionSaveDeferred = false;
3325
+ this.#scheduleSave();
3326
+ }
3327
+ scope.release();
3328
+ }
3329
+ }
3330
+
3331
+ #restoreStateTransactionBaseline(scope: NativeStateTransactionScope): void {
3332
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
3333
+ if (actorState.pendingSaveHandle !== undefined) {
3334
+ clearImmediate(actorState.pendingSaveHandle);
3335
+ }
3336
+ actorState.pendingSaveHandle = undefined;
3337
+ actorState.saveScheduled = false;
3338
+
3339
+ if (this.#stateEnabled) {
3340
+ actorState.state = structuredClone(scope.actorStateBaseline);
3341
+ }
3342
+ for (const conn of callNativeSync(() =>
3343
+ this.#runtime.actorConns(this.#ctx),
3344
+ )) {
3345
+ const connId = callNativeSync(() => this.#runtime.connId(conn));
3346
+ const baseline = scope.connectionStateBaselines.get(connId);
3347
+ if (baseline === undefined) {
3348
+ continue;
3349
+ }
3350
+ callNativeSync(() => this.#runtime.connSetState(conn, baseline));
3351
+ const cached = actorState.connStates.get(connId);
3352
+ if (cached) {
3353
+ cached.state = decodeValue(baseline);
3354
+ }
3355
+ }
3356
+ this.#scheduleSave();
3357
+ }
3358
+
3359
+ async prepare(): Promise<void> {
3360
+ if (!this.#databaseProvider) {
3361
+ return;
3362
+ }
3363
+
3364
+ await this.ensureDatabaseClient();
3365
+ }
3366
+
3367
+ async runDatabaseMigrations(): Promise<void> {
3368
+ if (!this.#databaseProvider) {
3369
+ return;
3370
+ }
3371
+
3372
+ await this.#databaseProvider.onMigrate(
3373
+ (await this.ensureDatabaseClient()) as never,
3374
+ );
3375
+ }
2733
3376
 
2734
3377
  async closeDatabase(): Promise<void> {
2735
3378
  this.#db = undefined;
2736
- this.#sql = undefined;
2737
3379
  await closeNativeDatabaseClient(this.#runtime, this.#ctx);
2738
3380
  await closeNativeSqlDatabase(this.#runtime, this.#ctx);
2739
3381
  }
@@ -2758,6 +3400,7 @@ export class ActorContextHandleAdapter {
2758
3400
  maxWait?: number;
2759
3401
  }): Promise<void> {
2760
3402
  if (opts?.immediate) {
3403
+ this.#assertCanAwaitStateSave();
2761
3404
  await callNative(() =>
2762
3405
  this.#runtime.actorRequestSaveAndWait(this.#ctx, {
2763
3406
  immediate: true,
@@ -2780,6 +3423,25 @@ export class ActorContextHandleAdapter {
2780
3423
  );
2781
3424
  }
2782
3425
 
3426
+ async saveStateAndWorkflowBatch(
3427
+ writes: Array<{ key: Uint8Array; value: Uint8Array }>,
3428
+ ): Promise<void> {
3429
+ this.#assertCanAwaitStateSave();
3430
+ await callNative(() =>
3431
+ this.#runtime.actorSaveStateAndWorkflowBatch(this.#ctx, writes),
3432
+ );
3433
+ }
3434
+
3435
+ #assertCanAwaitStateSave(): void {
3436
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
3437
+ if (
3438
+ actorState.activeStateTransactionOwner ===
3439
+ this.#stateTransactionOwner
3440
+ ) {
3441
+ throw stateTransactionConflictError();
3442
+ }
3443
+ }
3444
+
2783
3445
  serializeForTick(reason: SerializeStateReason): RuntimeStateDeltaPayload {
2784
3446
  void reason;
2785
3447
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -2843,10 +3505,6 @@ export class ActorContextHandleAdapter {
2843
3505
  return promise;
2844
3506
  }
2845
3507
 
2846
- runHandlerActive(): boolean {
2847
- return this.#runHandlerActiveProvider?.() ?? false;
2848
- }
2849
-
2850
3508
  internalKeepAwake<T>(run: Promise<T> | (() => Promise<T>)): Promise<T> {
2851
3509
  const promise = typeof run === "function" ? run() : run;
2852
3510
  // Track only completion, swallowing the outcome. The real result/error
@@ -2944,25 +3602,49 @@ export class ActorContextHandleAdapter {
2944
3602
 
2945
3603
  async dispose(): Promise<void> {
2946
3604
  // Flush any save coalesced for this tick before the context is torn
2947
- // down so the request-save and onStateChange always run.
2948
- this.#flushStateChange();
3605
+ // down so the request-save and onStateChange always run. Shutdown
3606
+ // cleanup may already have cleared the generation, which leaves no
3607
+ // pending save to flush.
3608
+ if (!isNativeRuntimeStateCleared(this.#runtime, this.#ctx)) {
3609
+ this.#flushStateChange();
3610
+ }
2949
3611
  this.#abortSignalCleanup?.();
2950
- this.#sql = undefined;
2951
3612
  }
2952
3613
 
2953
- #createActorAbortSignal(): AbortSignal {
3614
+ #actorAbort(): NativeActorAbort {
3615
+ // An aborted cached signal may belong to a previous generation, so
3616
+ // only a live one is reused.
3617
+ const runtimeState = readNativeRuntimeStateBag(
3618
+ this.#runtime,
3619
+ this.#ctx,
3620
+ );
3621
+ const cached = runtimeState.actorAbort;
3622
+ if (cached && !cached.signal.aborted) {
3623
+ return cached;
3624
+ }
3625
+
2954
3626
  const nativeSignal = callNativeSync(() =>
2955
3627
  this.#runtime.actorAbortSignal(this.#ctx),
2956
3628
  );
2957
3629
  const controller = new AbortController();
2958
- if (nativeSignal.aborted) {
3630
+ const actorAbort: NativeActorAbort = {
3631
+ signal: controller.signal,
3632
+ listeners: new Set(),
3633
+ };
3634
+ const abort = () => {
2959
3635
  controller.abort();
3636
+ for (const listener of actorAbort.listeners) {
3637
+ listener();
3638
+ }
3639
+ actorAbort.listeners.clear();
3640
+ };
3641
+ if (nativeSignal.aborted) {
3642
+ abort();
2960
3643
  } else {
2961
- nativeSignal.addEventListener("abort", () => controller.abort(), {
2962
- once: true,
2963
- });
3644
+ nativeSignal.addEventListener("abort", abort, { once: true });
2964
3645
  }
2965
- return controller.signal;
3646
+ runtimeState.actorAbort = actorAbort;
3647
+ return actorAbort;
2966
3648
  }
2967
3649
 
2968
3650
  #readState(): unknown {
@@ -2994,6 +3676,19 @@ export class ActorContextHandleAdapter {
2994
3676
  if (actorState.isInOnStateChange) {
2995
3677
  throw stateMutationReentrantError();
2996
3678
  }
3679
+ if (
3680
+ actorState.activeStateTransactionOwner !==
3681
+ this.#stateTransactionOwner &&
3682
+ (actorState.activeStateTransactionOwner !== undefined ||
3683
+ (actorState.pendingStateTransactionOwners?.size ?? 0) > 0)
3684
+ ) {
3685
+ throw stateTransactionConflictError();
3686
+ }
3687
+ }
3688
+
3689
+ /** @internal */
3690
+ assertCanMutateState(): void {
3691
+ this.#assertCanMutateState();
2997
3692
  }
2998
3693
 
2999
3694
  // Coalesce the request-save and onStateChange work to once per event loop
@@ -3017,6 +3712,15 @@ export class ActorContextHandleAdapter {
3017
3712
  if (!actorState.saveScheduled) {
3018
3713
  return;
3019
3714
  }
3715
+ if (actorState.activeStateTransactionOwner !== undefined) {
3716
+ actorState.saveScheduled = false;
3717
+ if (actorState.pendingSaveHandle !== undefined) {
3718
+ clearImmediate(actorState.pendingSaveHandle);
3719
+ actorState.pendingSaveHandle = undefined;
3720
+ }
3721
+ actorState.stateTransactionSaveDeferred = true;
3722
+ return;
3723
+ }
3020
3724
  actorState.saveScheduled = false;
3021
3725
  if (actorState.pendingSaveHandle !== undefined) {
3022
3726
  clearImmediate(actorState.pendingSaveHandle);
@@ -3072,6 +3776,7 @@ type NativeWorkflowQueueMessage = Awaited<
3072
3776
 
3073
3777
  class NativeWorkflowRuntimeAdapter {
3074
3778
  #ctx: ActorContextHandleAdapter;
3779
+ #onMessagesReceived: () => void;
3075
3780
  #completions = new Map<string, (response?: unknown) => Promise<void>>();
3076
3781
 
3077
3782
  readonly id: string;
@@ -3134,10 +3839,17 @@ class NativeWorkflowRuntimeAdapter {
3134
3839
  immediate?: boolean;
3135
3840
  maxWait?: number;
3136
3841
  }) => Promise<void>;
3842
+ saveStateAndWorkflowBatch: (
3843
+ writes: Array<{ key: Uint8Array; value: Uint8Array }>,
3844
+ ) => Promise<void>;
3137
3845
  };
3138
3846
 
3139
- constructor(ctx: ActorContextHandleAdapter) {
3847
+ constructor(
3848
+ ctx: ActorContextHandleAdapter,
3849
+ onMessagesReceived: () => void,
3850
+ ) {
3140
3851
  this.#ctx = ctx;
3852
+ this.#onMessagesReceived = onMessagesReceived;
3141
3853
  this.id = ctx.actorId;
3142
3854
  this.driver = {
3143
3855
  kvBatchGet: async (actorId, keys) => {
@@ -3183,6 +3895,9 @@ class NativeWorkflowRuntimeAdapter {
3183
3895
  timeout: timeout ?? 0,
3184
3896
  completable,
3185
3897
  });
3898
+ if (messages.length > 0) {
3899
+ this.#onMessagesReceived();
3900
+ }
3186
3901
  return messages.map((message) =>
3187
3902
  this.#wrapQueueMessage(message),
3188
3903
  );
@@ -3209,13 +3924,12 @@ class NativeWorkflowRuntimeAdapter {
3209
3924
  saveState: async (opts) => {
3210
3925
  await this.#ctx.saveState(opts);
3211
3926
  },
3927
+ saveStateAndWorkflowBatch: async (writes) => {
3928
+ await this.#ctx.saveStateAndWorkflowBatch(writes);
3929
+ },
3212
3930
  };
3213
3931
  }
3214
3932
 
3215
- isRunHandlerActive(): boolean {
3216
- return this.#ctx.runHandlerActive();
3217
- }
3218
-
3219
3933
  async restartRunHandler(): Promise<void> {
3220
3934
  await this.#ctx.restartRunHandler();
3221
3935
  }
@@ -3263,30 +3977,48 @@ function withConnContext(
3263
3977
  stateEnabled = true,
3264
3978
  onStateChange?: NativeOnStateChangeHandler,
3265
3979
  dispatchCancelToken?: CancellationTokenHandle,
3980
+ runHandlerConfigured = false,
3266
3981
  ) {
3267
- return Object.assign(
3268
- new ActorContextHandleAdapter(
3982
+ const actorContext = new ActorContextHandleAdapter(
3983
+ runtime,
3984
+ ctx,
3985
+ clientFactory,
3986
+ schemas,
3987
+ databaseProvider,
3988
+ request,
3989
+ stateEnabled,
3990
+ onStateChange,
3991
+ dispatchCancelToken,
3992
+ runHandlerConfigured,
3993
+ );
3994
+ return Object.assign(actorContext, {
3995
+ conn: new NativeConnAdapter(
3269
3996
  runtime,
3270
- ctx,
3271
- clientFactory,
3997
+ conn,
3272
3998
  schemas,
3273
- databaseProvider,
3274
- request,
3275
- stateEnabled,
3276
- undefined,
3277
- onStateChange,
3278
- dispatchCancelToken,
3279
- ),
3280
- {
3281
- conn: new NativeConnAdapter(runtime, conn, schemas, ctx, (connId) =>
3999
+ ctx,
4000
+ (connId) =>
3282
4001
  callNativeSync(() =>
3283
4002
  runtime.actorQueueHibernationRemoval(ctx, connId),
3284
4003
  ),
3285
- ),
3286
- },
3287
- );
4004
+ () => actorContext.assertCanMutateState(),
4005
+ ),
4006
+ });
3288
4007
  }
3289
4008
 
4009
+ function buildActorTracingConfig(
4010
+ actions: unknown,
4011
+ tracing: { sampler?: number; actions?: ActionSampleRates } | undefined,
4012
+ ): RuntimeActorTracingConfig | undefined {
4013
+ if (tracing === undefined) return undefined;
4014
+ return {
4015
+ sampler: tracing.sampler,
4016
+ actions: flattenActionTraceSamplers(actions, tracing.actions),
4017
+ };
4018
+ }
4019
+
4020
+ const SQLITE_DEFERRED_COMMITS = Symbol.for("rivetkit.sqlite.deferredCommits");
4021
+
3290
4022
  function buildActorConfig(
3291
4023
  definition: AnyActorDefinition,
3292
4024
  registryConfig: RegistryConfig,
@@ -3295,19 +4027,29 @@ function buildActorConfig(
3295
4027
  const config = definition.config as unknown as Record<string, unknown>;
3296
4028
  const options = (config.options ?? {}) as Record<string, unknown>;
3297
4029
  const canHibernate = options.canHibernateWebSocket;
3298
-
4030
+ const usesRemoteSqlite =
4031
+ sqliteBackendForConfig(registryConfig) === "remote";
3299
4032
  const sqliteProfiling = (
3300
4033
  config.db as { sqliteProfiling?: SqliteProfilingOptions } | undefined
3301
4034
  )?.sqliteProfiling;
4035
+ // Internal opt-in for embedders, such as Open Orange, that gate outputs on `whenDurable`.
4036
+ const sqliteDeferredCommits =
4037
+ (config.db as Record<symbol, unknown> | undefined)?.[
4038
+ SQLITE_DEFERRED_COMMITS
4039
+ ] === true;
3302
4040
 
3303
4041
  return {
3304
4042
  name: options.name as string | undefined,
3305
4043
  icon: options.icon as string | undefined,
3306
- hasDatabase: config.db !== undefined,
4044
+ hasDatabase: true,
4045
+ remoteSqlite: usesRemoteSqlite,
4046
+ sqliteDeferredCommits: sqliteDeferredCommits || undefined,
3307
4047
  sqliteProfiling,
3308
- remoteSqlite:
3309
- config.db !== undefined &&
3310
- sqliteBackendForConfig(registryConfig) === "remote",
4048
+ tracing: buildActorTracingConfig(
4049
+ definition.config.actions,
4050
+ definition.config.tracing,
4051
+ ),
4052
+ enableActorRuntimeSocket: options.enableActorRuntimeSocket === true,
3311
4053
  hasState:
3312
4054
  config.state !== undefined ||
3313
4055
  typeof config.createState === "function",
@@ -3334,6 +4076,7 @@ function buildActorConfig(
3334
4076
  | number
3335
4077
  | undefined,
3336
4078
  maxQueueSize: options.maxQueueSize as number | undefined,
4079
+ maxSchedules: options.maxSchedules as number | undefined,
3337
4080
  maxQueueMessageSize: options.maxQueueMessageSize as number | undefined,
3338
4081
  maxIncomingMessageSize: registryConfig.maxIncomingMessageSize as
3339
4082
  | number
@@ -3347,7 +4090,7 @@ function buildActorConfig(
3347
4090
  preloadMaxConnectionsBytes: options.preloadMaxConnectionsBytes as
3348
4091
  | number
3349
4092
  | undefined,
3350
- actions: Object.keys((config.actions ?? {}) as Record<string, unknown>)
4093
+ actions: Object.keys(flattenActionHandlers(config.actions))
3351
4094
  .sort()
3352
4095
  .map((name) => ({ name })),
3353
4096
  inspectorTabs: buildInspectorTabs(config.inspector, runtimeKind),
@@ -3450,37 +4193,52 @@ export function buildNativeFactory(
3450
4193
  definition: AnyActorDefinition,
3451
4194
  ): ActorFactoryHandle {
3452
4195
  const config = definition.config as Record<string, any>;
3453
- const databaseProvider = config.db as AnyDatabaseProvider;
4196
+ const databaseProvider = (config.db ?? defaultDb()) as Exclude<
4197
+ AnyDatabaseProvider,
4198
+ undefined
4199
+ >;
4200
+ const actionHandlers = flattenActionHandlers(config.actions);
3454
4201
  const schemaConfig: NativeValidationConfig = {
3455
- actionInputSchemas: config.actionInputSchemas,
4202
+ actionInputSchemas: flattenActionInputSchemas(
4203
+ config.actions,
4204
+ config.actionInputSchemas,
4205
+ ),
3456
4206
  connParamsSchema: config.connParamsSchema,
3457
4207
  events: config.events,
3458
4208
  queues: config.queues,
3459
4209
  };
3460
- const actionHandlers = Object.fromEntries(
3461
- (
3462
- Object.entries(config.actions ?? {}) as Array<
3463
- [string, (...args: Array<any>) => any]
3464
- >
3465
- ).map(([name, handler]) => [name, handler]),
3466
- );
3467
- const createClient = () =>
4210
+ const createClient = (ctx: ActorContextHandle) =>
3468
4211
  createClientWithDriver(
3469
4212
  new RemoteEngineControlClient(
3470
4213
  convertRegistryConfigToClientConfig(registryConfig),
3471
4214
  ),
3472
- { encoding: "bare" },
4215
+ {
4216
+ encoding: "bare",
4217
+ currentActorInvocation: () =>
4218
+ callNativeSync(() =>
4219
+ runtime.actorInvocationTraceContext(ctx),
4220
+ ),
4221
+ startCallSpan: (actorName, actionName) =>
4222
+ callNativeSync(() =>
4223
+ runtime.startCallSpan(ctx, actorName, actionName),
4224
+ ),
4225
+ },
3473
4226
  );
3474
- const nativeRunHandlerActiveByActorId = new Map<string, boolean>();
3475
- const isNativeRunHandlerActive = (ctx: ActorContextHandle) =>
3476
- nativeRunHandlerActiveByActorId.get(
3477
- callNativeSync(() => runtime.actorId(ctx)),
3478
- ) ?? false;
3479
- const getNativeWorkflowInspector = (ctx: ActorContextHandle) =>
3480
- getRunInspectorConfig(
3481
- config.run,
3482
- callNativeSync(() => runtime.actorId(ctx)),
3483
- )?.workflow as NativeWorkflowInspectorConfig | undefined;
4227
+ const run = getRunFunction(config.run);
4228
+ const runHandlerCoordinator =
4229
+ getRunInspectorKind(config.run) === "workflow"
4230
+ ? new RunHandlerCoordinator(config.run)
4231
+ : undefined;
4232
+ const getNativeWorkflowInspector = (ctx: ActorContextHandle) => {
4233
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
4234
+ const restart = () =>
4235
+ callNativeSync(() => runtime.actorRestartRunHandler(ctx));
4236
+ return (runHandlerCoordinator?.getInspector(actorId, restart)
4237
+ ?.workflow ??
4238
+ getRunInspectorConfig(config.run, actorId)?.workflow) as
4239
+ | NativeWorkflowInspectorConfig
4240
+ | undefined;
4241
+ };
3484
4242
  const onStateChange =
3485
4243
  typeof config.onStateChange === "function"
3486
4244
  ? (actorCtx: ActorContextHandleAdapter, nextState: unknown) => {
@@ -3508,14 +4266,14 @@ export function buildNativeFactory(
3508
4266
  new ActorContextHandleAdapter(
3509
4267
  runtime,
3510
4268
  ctx,
3511
- createClient,
4269
+ () => createClient(ctx),
3512
4270
  schemaConfig,
3513
4271
  databaseProvider,
3514
4272
  request,
3515
4273
  stateEnabled,
3516
- () => isNativeRunHandlerActive(ctx),
3517
4274
  onStateChange,
3518
4275
  cancelToken,
4276
+ run !== undefined,
3519
4277
  );
3520
4278
  const makeConnCtx = (
3521
4279
  ctx: ActorContextHandle,
@@ -3527,29 +4285,33 @@ export function buildNativeFactory(
3527
4285
  runtime,
3528
4286
  ctx,
3529
4287
  conn,
3530
- createClient,
4288
+ () => createClient(ctx),
3531
4289
  schemaConfig,
3532
4290
  databaseProvider,
3533
4291
  request,
3534
4292
  stateEnabled,
3535
4293
  onStateChange,
3536
4294
  cancelToken,
4295
+ run !== undefined,
3537
4296
  );
3538
4297
  const maybeHandleNativeInspectorRequest = async (
3539
4298
  ctx: ActorContextHandle,
3540
- _rawRequest: {
4299
+ rawRequest: {
3541
4300
  method: string;
3542
4301
  uri: string;
3543
4302
  headers?: Record<string, string>;
3544
4303
  body?: RuntimeBytes;
3545
4304
  },
3546
- jsRequest: Request,
3547
4305
  ): Promise<Response | undefined> => {
3548
- const url = new URL(jsRequest.url);
4306
+ const rawUrl = rawRequest.uri.startsWith("http")
4307
+ ? rawRequest.uri
4308
+ : new URL(rawRequest.uri, "http://127.0.0.1").toString();
4309
+ const url = new URL(rawUrl);
3549
4310
  if (!url.pathname.startsWith("/inspector/")) {
3550
4311
  return undefined;
3551
4312
  }
3552
4313
 
4314
+ const jsRequest = buildNativeHttpRequest(rawRequest);
3553
4315
  const jsonResponse = (body: unknown, init?: ResponseInit) =>
3554
4316
  new Response(JSON.stringify(body), {
3555
4317
  status: init?.status ?? 200,
@@ -3576,10 +4338,11 @@ export function buildNativeFactory(
3576
4338
  );
3577
4339
  };
3578
4340
 
4341
+ // Tab config is delivered over the inspector WS `Init` message, not
4342
+ // HTTP. Only custom-tab assets remain a public per-actor path.
3579
4343
  const isPublicPerActorPath =
3580
4344
  jsRequest.method === "GET" &&
3581
- (url.pathname === "/inspector/tab-config" ||
3582
- url.pathname.startsWith("/inspector/custom-tabs/"));
4345
+ url.pathname.startsWith("/inspector/custom-tabs/");
3583
4346
 
3584
4347
  if (!isPublicPerActorPath) {
3585
4348
  try {
@@ -3601,6 +4364,7 @@ export function buildNativeFactory(
3601
4364
  const workflowState = async () =>
3602
4365
  (await getNativeWorkflowInspector(ctx)?.getState?.()) ?? null;
3603
4366
  const actorCtx = makeActorCtx(ctx, jsRequest);
4367
+ const sql = getOrCreateNativeSqlDatabase(runtime, ctx);
3604
4368
  try {
3605
4369
  if (
3606
4370
  url.pathname === "/inspector/state" &&
@@ -3674,6 +4438,56 @@ export function buildNativeFactory(
3674
4438
  messages,
3675
4439
  });
3676
4440
  }
4441
+ if (
4442
+ url.pathname === "/inspector/queue" &&
4443
+ jsRequest.method === "DELETE"
4444
+ ) {
4445
+ await runtime.actorQueueReset(ctx);
4446
+ return jsonResponse({});
4447
+ }
4448
+ if (
4449
+ url.pathname === "/inspector/queue" &&
4450
+ jsRequest.method === "POST"
4451
+ ) {
4452
+ let body: { name?: string; body?: unknown };
4453
+ try {
4454
+ body = (await jsRequest.json()) as {
4455
+ name?: string;
4456
+ body?: unknown;
4457
+ };
4458
+ } catch {
4459
+ return errorResponse(
4460
+ new RivetError(
4461
+ "actor",
4462
+ "invalid_request",
4463
+ "Invalid inspector JSON body",
4464
+ { public: true },
4465
+ ),
4466
+ 400,
4467
+ );
4468
+ }
4469
+ const name = body.name ?? "";
4470
+ if (name === "") {
4471
+ return errorResponse(
4472
+ new RivetError(
4473
+ "actor",
4474
+ "invalid_request",
4475
+ "Queue message name must not be empty",
4476
+ { public: true },
4477
+ ),
4478
+ 400,
4479
+ );
4480
+ }
4481
+ const cbor = encodeCborCompat(
4482
+ (body.body ?? null) as JsonCompatValue,
4483
+ );
4484
+ const message = await runtime.actorQueueSend(ctx, name, cbor);
4485
+ return jsonResponse({
4486
+ id: message.id().toString(),
4487
+ name: message.name(),
4488
+ createdAtMs: message.createdAt(),
4489
+ });
4490
+ }
3677
4491
  if (
3678
4492
  url.pathname === "/inspector/traces" &&
3679
4493
  jsRequest.method === "GET"
@@ -3722,7 +4536,7 @@ export function buildNativeFactory(
3722
4536
  url.pathname === "/inspector/database/schema" &&
3723
4537
  jsRequest.method === "GET"
3724
4538
  ) {
3725
- const db = actorCtx.sql;
4539
+ const db = sql;
3726
4540
  const tables = queryRows(
3727
4541
  await db.query(
3728
4542
  "SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '__drizzle_%' ORDER BY name",
@@ -3776,7 +4590,7 @@ export function buildNativeFactory(
3776
4590
  );
3777
4591
  const quoted = `"${table.replace(/"/g, '""')}"`;
3778
4592
  const rows = queryRows(
3779
- await actorCtx.sql.query(
4593
+ await sql.query(
3780
4594
  `SELECT * FROM ${quoted} LIMIT ? OFFSET ?`,
3781
4595
  [
3782
4596
  Math.max(0, Math.min(limit, 500)),
@@ -3819,15 +4633,11 @@ export function buildNativeFactory(
3819
4633
  const bindings = normalizeSqlitePropertyBindings(
3820
4634
  body.properties as Record<string, unknown>,
3821
4635
  );
3822
- const rows = queryRows(
3823
- await actorCtx.sql.query(body.sql, bindings),
3824
- );
4636
+ const rows = queryRows(await sql.query(body.sql, bindings));
3825
4637
  return jsonResponse({ rows: jsonSafe(rows) });
3826
4638
  }
3827
4639
  const args = Array.isArray(body.args) ? body.args : [];
3828
- const rows = queryRows(
3829
- await actorCtx.sql.query(body.sql, args),
3830
- );
4640
+ const rows = queryRows(await sql.query(body.sql, args));
3831
4641
  return jsonResponse({ rows: jsonSafe(rows) });
3832
4642
  }
3833
4643
  if (
@@ -3856,7 +4666,7 @@ export function buildNativeFactory(
3856
4666
  rpcs: Object.keys(actionHandlers).sort(),
3857
4667
  queueSize: inspectorSnapshot.queueSize,
3858
4668
  isStateEnabled: stateEnabled,
3859
- isDatabaseEnabled: databaseProvider !== undefined,
4669
+ isDatabaseEnabled: true,
3860
4670
  isWorkflowEnabled:
3861
4671
  getNativeWorkflowInspector(ctx) !== undefined,
3862
4672
  workflowState: await workflowState(),
@@ -4112,6 +4922,7 @@ export function buildNativeFactory(
4112
4922
  async (error: unknown, payload: { ctx: ActorContextHandle }) => {
4113
4923
  const { ctx } = unwrapTsfnPayload(error, payload);
4114
4924
  const actorCtx = makeActorCtx(ctx);
4925
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
4115
4926
  // TODO: Move this save hook into cleanupNativeSleepRuntimeState
4116
4927
  // so immediate and deferred sleep cleanup share one save-state
4117
4928
  // path instead of passing a callback through cleanup.
@@ -4142,6 +4953,8 @@ export function buildNativeFactory(
4142
4953
  saveActorState,
4143
4954
  );
4144
4955
  } finally {
4956
+ runHandlerCoordinator?.destroy(actorId);
4957
+ disposeRunInspector(config.run, actorId);
4145
4958
  await actorCtx.dispose();
4146
4959
  }
4147
4960
  }
@@ -4151,18 +4964,18 @@ export function buildNativeFactory(
4151
4964
  async (error: unknown, payload: { ctx: ActorContextHandle }) => {
4152
4965
  const { ctx } = unwrapTsfnPayload(error, payload);
4153
4966
  const actorCtx = makeActorCtx(ctx);
4967
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
4968
+ // Close run control before user cleanup so replay cannot race actor
4969
+ // destruction. Recreating this actor id receives a fresh controller.
4970
+ runHandlerCoordinator?.destroy(actorId);
4971
+ disposeRunInspector(config.run, actorId);
4154
4972
  try {
4155
4973
  if (typeof config.onDestroy === "function") {
4156
4974
  await config.onDestroy(actorCtx);
4157
4975
  }
4158
4976
  } finally {
4159
- const actorId = callNativeSync(() => runtime.actorId(ctx));
4160
- // Release actorId-keyed state so it does not accumulate per
4161
- // destroyed actor.
4162
- nativeRunHandlerActiveByActorId.delete(actorId);
4163
- disposeRunInspector(config.run, actorId);
4164
4977
  resolveNativeDestroy(runtime, ctx);
4165
- await actorCtx.closeDatabase();
4978
+ await detachNativeDatabaseForShutdown(runtime, ctx);
4166
4979
  clearNativeRuntimeState(runtime, ctx);
4167
4980
  await actorCtx.dispose();
4168
4981
  }
@@ -4190,7 +5003,9 @@ export function buildNativeFactory(
4190
5003
  );
4191
5004
  const actorCtx = makeActorCtx(
4192
5005
  ctx,
4193
- request ? buildRequest(request) : undefined,
5006
+ request
5007
+ ? buildNativeHttpRequest(request)
5008
+ : undefined,
4194
5009
  );
4195
5010
  try {
4196
5011
  await config.onBeforeConnect(
@@ -4227,7 +5042,9 @@ export function buildNativeFactory(
4227
5042
  unwrapTsfnPayload(error, payload);
4228
5043
  const actorCtx = makeActorCtx(
4229
5044
  ctx,
4230
- request ? buildRequest(request) : undefined,
5045
+ request
5046
+ ? buildNativeHttpRequest(request)
5047
+ : undefined,
4231
5048
  );
4232
5049
  const connAdapter = new NativeConnAdapter(
4233
5050
  runtime,
@@ -4241,6 +5058,7 @@ export function buildNativeFactory(
4241
5058
  connId,
4242
5059
  ),
4243
5060
  ),
5061
+ () => actorCtx.assertCanMutateState(),
4244
5062
  );
4245
5063
  try {
4246
5064
  const nextConnState = hasStaticConnState
@@ -4282,7 +5100,9 @@ export function buildNativeFactory(
4282
5100
  );
4283
5101
  const actorCtx = makeActorCtx(
4284
5102
  ctx,
4285
- request ? buildRequest(request) : undefined,
5103
+ request
5104
+ ? buildNativeHttpRequest(request)
5105
+ : undefined,
4286
5106
  );
4287
5107
  const connAdapter = new NativeConnAdapter(
4288
5108
  runtime,
@@ -4296,6 +5116,7 @@ export function buildNativeFactory(
4296
5116
  connId,
4297
5117
  ),
4298
5118
  ),
5119
+ () => actorCtx.assertCanMutateState(),
4299
5120
  );
4300
5121
  try {
4301
5122
  await config.onConnect(
@@ -4339,6 +5160,7 @@ export function buildNativeFactory(
4339
5160
  connId,
4340
5161
  ),
4341
5162
  ),
5163
+ () => actorCtx.assertCanMutateState(),
4342
5164
  ),
4343
5165
  );
4344
5166
  }
@@ -4432,74 +5254,156 @@ export function buildNativeFactory(
4432
5254
  uri: string;
4433
5255
  headers?: Record<string, string>;
4434
5256
  body?: RuntimeBytes;
5257
+ bodyStream?: NativeHttpRequestBodyStream;
4435
5258
  };
4436
5259
  cancelToken?: CancellationTokenHandle;
5260
+ responseBodyStream?: NativeHttpResponseBodyStream;
4437
5261
  },
4438
5262
  ) => {
4439
5263
  try {
4440
- const { ctx, request, cancelToken } = unwrapTsfnPayload(
4441
- error,
4442
- payload,
4443
- );
4444
- const jsRequest = buildRequest(request);
4445
- const inspectorResponse =
4446
- await maybeHandleNativeInspectorRequest(
4447
- ctx,
4448
- request,
4449
- jsRequest,
4450
- );
4451
- if (inspectorResponse) {
4452
- return await toRuntimeHttpResponse(inspectorResponse);
4453
- }
5264
+ const { ctx, request, cancelToken, responseBodyStream } =
5265
+ unwrapTsfnPayload(error, payload);
5266
+ return await runtime.runWithActorInvocationContext(
5267
+ ctx,
5268
+ async () => {
5269
+ const inspectorResponse =
5270
+ await maybeHandleNativeInspectorRequest(
5271
+ ctx,
5272
+ request,
5273
+ );
5274
+ if (inspectorResponse) {
5275
+ await cancelNativeHttpRequestBody(
5276
+ request.bodyStream,
5277
+ );
5278
+ return (
5279
+ await convertNativeHttpResponse(
5280
+ inspectorResponse,
5281
+ responseBodyStream,
5282
+ )
5283
+ ).response;
5284
+ }
4454
5285
 
4455
- if (typeof config.onRequest !== "function") {
4456
- return await toRuntimeHttpResponse(
4457
- new Response(null, { status: 404 }),
4458
- );
4459
- }
5286
+ if (typeof config.onRequest !== "function") {
5287
+ await cancelNativeHttpRequestBody(
5288
+ request.bodyStream,
5289
+ );
5290
+ return (
5291
+ await convertNativeHttpResponse(
5292
+ new Response(null, { status: 404 }),
5293
+ responseBodyStream,
5294
+ )
5295
+ ).response;
5296
+ }
4460
5297
 
4461
- const rawConnParams =
4462
- jsRequest.headers.get(HEADER_CONN_PARAMS);
4463
- let requestCtx:
4464
- | ReturnType<typeof withConnContext>
4465
- | undefined;
4466
- let conn: ConnHandle | undefined;
4467
- try {
4468
- const connParams = validateConnParams(
4469
- schemaConfig.connParamsSchema,
4470
- rawConnParams
4471
- ? JSON.parse(rawConnParams)
4472
- : undefined,
4473
- );
4474
- conn = await callNative(() =>
4475
- runtime.actorConnectConn(
4476
- ctx,
4477
- encodeValue(connParams),
4478
- request,
4479
- ),
4480
- );
4481
- requestCtx = makeConnCtx(
4482
- ctx,
4483
- conn,
4484
- jsRequest,
4485
- cancelToken,
4486
- );
4487
- const response = await config.onRequest(
4488
- requestCtx,
4489
- jsRequest,
4490
- );
4491
- if (!(response instanceof Response)) {
4492
- throw new Error(
4493
- "onRequest handler must return a Response",
4494
- );
4495
- }
4496
- return await toRuntimeHttpResponse(response);
4497
- } finally {
4498
- await requestCtx?.dispose();
4499
- if (conn) {
4500
- await runtime.connDisconnect(conn);
4501
- }
4502
- }
5298
+ const requestAbortController =
5299
+ new AbortController();
5300
+ const handlerRequest = buildNativeHttpRequest({
5301
+ ...request,
5302
+ abortController: requestAbortController,
5303
+ });
5304
+ const rawConnParams =
5305
+ handlerRequest.headers.get(HEADER_CONN_PARAMS);
5306
+ let requestCtx:
5307
+ | ReturnType<typeof withConnContext>
5308
+ | undefined;
5309
+ let conn: ConnHandle | undefined;
5310
+ let removeRequestAbortListener:
5311
+ | (() => void)
5312
+ | undefined;
5313
+ let cleanupDeferredToBody = false;
5314
+ let cleanedUp = false;
5315
+ const cleanupRequest = async () => {
5316
+ if (cleanedUp) return;
5317
+ cleanedUp = true;
5318
+ removeRequestAbortListener?.();
5319
+ try {
5320
+ await requestCtx?.dispose();
5321
+ } finally {
5322
+ if (conn) {
5323
+ await runtime.connDisconnect(conn);
5324
+ }
5325
+ }
5326
+ };
5327
+ try {
5328
+ const connParams = validateConnParams(
5329
+ schemaConfig.connParamsSchema,
5330
+ rawConnParams
5331
+ ? JSON.parse(rawConnParams)
5332
+ : undefined,
5333
+ );
5334
+ conn = await callNative(() =>
5335
+ runtime.actorConnectConn(
5336
+ ctx,
5337
+ encodeValue(connParams),
5338
+ request,
5339
+ ),
5340
+ );
5341
+ requestCtx = makeConnCtx(
5342
+ ctx,
5343
+ conn,
5344
+ handlerRequest,
5345
+ cancelToken,
5346
+ );
5347
+ const ctxAbortSignal = requestCtx.abortSignal;
5348
+ const abortRequest = () =>
5349
+ requestAbortController.abort(
5350
+ ctxAbortSignal.reason,
5351
+ );
5352
+ if (ctxAbortSignal.aborted) {
5353
+ abortRequest();
5354
+ } else {
5355
+ ctxAbortSignal.addEventListener(
5356
+ "abort",
5357
+ abortRequest,
5358
+ { once: true },
5359
+ );
5360
+ removeRequestAbortListener = () =>
5361
+ ctxAbortSignal.removeEventListener(
5362
+ "abort",
5363
+ abortRequest,
5364
+ );
5365
+ }
5366
+ const response = await config.onRequest(
5367
+ requestCtx,
5368
+ handlerRequest,
5369
+ );
5370
+ if (!isResponseLike(response)) {
5371
+ throw new Error(
5372
+ "onRequest handler must return a Response",
5373
+ );
5374
+ }
5375
+ const conversion =
5376
+ await convertNativeHttpResponse(
5377
+ response,
5378
+ responseBodyStream,
5379
+ );
5380
+ if (conversion.bodyCompletion) {
5381
+ cleanupDeferredToBody = true;
5382
+ void conversion.bodyCompletion
5383
+ .then(cleanupRequest)
5384
+ .catch((cleanupError) => {
5385
+ logger().error({
5386
+ msg: "failed to clean up native streaming http request",
5387
+ error: cleanupError,
5388
+ });
5389
+ });
5390
+ }
5391
+ return conversion.response;
5392
+ } finally {
5393
+ try {
5394
+ // Handler completion ends upload ownership even when
5395
+ // the Web Request body is locked or partly consumed.
5396
+ await cancelNativeHttpRequestBody(
5397
+ request.bodyStream,
5398
+ );
5399
+ } finally {
5400
+ if (!cleanupDeferredToBody) {
5401
+ await cleanupRequest();
5402
+ }
5403
+ }
5404
+ }
5405
+ },
5406
+ );
4503
5407
  } catch (error) {
4504
5408
  logger().error({
4505
5409
  msg: "native onRequest failed",
@@ -4529,7 +5433,7 @@ export function buildNativeFactory(
4529
5433
  const { ctx, conn, ws, request } =
4530
5434
  unwrapTsfnPayload(error, payload);
4531
5435
  const jsRequest = request
4532
- ? buildRequest(request)
5436
+ ? buildNativeHttpRequest(request)
4533
5437
  : undefined;
4534
5438
  const actorCtx = makeConnCtx(ctx, conn, jsRequest);
4535
5439
  try {
@@ -4547,7 +5451,6 @@ export function buildNativeFactory(
4547
5451
  )
4548
5452
  : undefined,
4549
5453
  run: (() => {
4550
- const run = getRunFunction(config.run);
4551
5454
  if (!run) {
4552
5455
  return undefined;
4553
5456
  }
@@ -4559,67 +5462,75 @@ export function buildNativeFactory(
4559
5462
  ) => {
4560
5463
  const { ctx } = unwrapTsfnPayload(error, payload);
4561
5464
  const actorId = callNativeSync(() => runtime.actorId(ctx));
4562
- const actorCtx = makeActorCtx(ctx);
4563
- nativeRunHandlerActiveByActorId.set(actorId, true);
4564
- try {
4565
- await run(actorCtx);
4566
- } finally {
4567
- // Delete rather than set(false): an absent entry already
4568
- // reads as inactive, and deleting keeps this map bounded
4569
- // to currently-running handlers instead of accumulating an
4570
- // entry per actor id forever.
4571
- nativeRunHandlerActiveByActorId.delete(actorId);
4572
- await actorCtx.dispose();
5465
+ const executeRun = async () => {
5466
+ const actorCtx = makeActorCtx(ctx);
5467
+ try {
5468
+ await run(actorCtx);
5469
+ } finally {
5470
+ await actorCtx.dispose();
5471
+ }
5472
+ };
5473
+ if (runHandlerCoordinator) {
5474
+ const outcome = await runHandlerCoordinator.run(
5475
+ actorId,
5476
+ () =>
5477
+ callNativeSync(() =>
5478
+ runtime.actorRestartRunHandler(ctx),
5479
+ ),
5480
+ executeRun,
5481
+ );
5482
+ // Only a start suppressed behind a failed replay must preserve a
5483
+ // consumed durable wake. Closed actors must remain closed.
5484
+ return outcome !== "suppressed";
4573
5485
  }
5486
+ await executeRun();
5487
+ return true;
4574
5488
  },
4575
5489
  );
4576
5490
  })(),
4577
- getWorkflowHistory:
4578
- getRunInspectorConfig(config.run) !== undefined
4579
- ? wrapNativeCallback(
4580
- async (
4581
- error: unknown,
4582
- payload: { ctx: ActorContextHandle },
4583
- ) => {
4584
- const { ctx } = unwrapTsfnPayload(error, payload);
4585
- const history =
4586
- getNativeWorkflowInspector(ctx)?.getHistory();
4587
- return history == null
4588
- ? undefined
4589
- : encodeValue(history);
5491
+ getWorkflowHistory: hasRunInspectorConfig(config.run)
5492
+ ? wrapNativeCallback(
5493
+ async (
5494
+ error: unknown,
5495
+ payload: { ctx: ActorContextHandle },
5496
+ ) => {
5497
+ const { ctx } = unwrapTsfnPayload(error, payload);
5498
+ const history =
5499
+ getNativeWorkflowInspector(ctx)?.getHistory();
5500
+ return history == null
5501
+ ? undefined
5502
+ : toUint8Array(history);
5503
+ },
5504
+ )
5505
+ : undefined,
5506
+ replayWorkflow: hasRunInspectorConfig(config.run)
5507
+ ? wrapNativeCallback(
5508
+ async (
5509
+ error: unknown,
5510
+ payload: {
5511
+ ctx: ActorContextHandle;
5512
+ entryId?: string;
4590
5513
  },
4591
- )
4592
- : undefined,
4593
- replayWorkflow:
4594
- getRunInspectorConfig(config.run) !== undefined
4595
- ? wrapNativeCallback(
4596
- async (
4597
- error: unknown,
4598
- payload: {
4599
- ctx: ActorContextHandle;
4600
- entryId?: string;
4601
- },
4602
- ) => {
4603
- const { ctx, entryId } = unwrapTsfnPayload(
4604
- error,
4605
- payload,
4606
- );
4607
- const workflowInspector =
4608
- getNativeWorkflowInspector(ctx);
4609
- if (!workflowInspector?.replayFromStep) {
4610
- return undefined;
4611
- }
5514
+ ) => {
5515
+ const { ctx, entryId } = unwrapTsfnPayload(
5516
+ error,
5517
+ payload,
5518
+ );
5519
+ const workflowInspector =
5520
+ getNativeWorkflowInspector(ctx);
5521
+ if (!workflowInspector?.replayFromStep) {
5522
+ return undefined;
5523
+ }
4612
5524
 
4613
- const history =
4614
- (await workflowInspector.replayFromStep(
4615
- entryId,
4616
- )) ?? null;
4617
- return history == null
4618
- ? undefined
4619
- : encodeValue(history);
4620
- },
4621
- )
4622
- : undefined,
5525
+ const history =
5526
+ (await workflowInspector.replayFromStep(entryId)) ??
5527
+ null;
5528
+ return history == null
5529
+ ? undefined
5530
+ : toUint8Array(history);
5531
+ },
5532
+ )
5533
+ : undefined,
4623
5534
  actions: Object.fromEntries(
4624
5535
  Object.entries(actionHandlers).map(([name, handler]) => [
4625
5536
  name,
@@ -4631,29 +5542,39 @@ export function buildNativeFactory(
4631
5542
  conn: ConnHandle | null;
4632
5543
  name: string;
4633
5544
  args: RuntimeBytes;
5545
+ scheduledFire?: RuntimeScheduledFireInfo;
4634
5546
  cancelToken?: CancellationTokenHandle;
4635
5547
  },
4636
5548
  ) => {
4637
- const { ctx, conn, args, cancelToken } =
5549
+ const { ctx, conn, args, scheduledFire, cancelToken } =
4638
5550
  unwrapTsfnPayload(error, payload);
4639
5551
  const actorCtx =
4640
5552
  conn != null
4641
5553
  ? makeConnCtx(ctx, conn, undefined, cancelToken)
4642
5554
  : makeActorCtx(ctx, undefined, cancelToken);
4643
- try {
4644
- return encodeValue(
4645
- await handler(
4646
- actorCtx,
4647
- ...validateActionArgs(
4648
- schemaConfig.actionInputSchemas,
4649
- name,
4650
- decodeArgs(args),
5555
+ const runAction = async () => {
5556
+ try {
5557
+ return encodeValue(
5558
+ await handler(
5559
+ actorCtx,
5560
+ ...validateActionArgs(
5561
+ schemaConfig.actionInputSchemas,
5562
+ name,
5563
+ decodeArgs(args),
5564
+ ),
5565
+ ...(scheduledFire
5566
+ ? [scheduledFire]
5567
+ : []),
4651
5568
  ),
4652
- ),
4653
- );
4654
- } finally {
4655
- await actorCtx.dispose();
4656
- }
5569
+ );
5570
+ } finally {
5571
+ await actorCtx.dispose();
5572
+ }
5573
+ };
5574
+ return await runtime.runWithActorInvocationContext(
5575
+ ctx,
5576
+ runAction,
5577
+ );
4657
5578
  },
4658
5579
  ),
4659
5580
  ]),
@@ -4687,75 +5608,89 @@ export function buildNativeFactory(
4687
5608
  timeoutMs,
4688
5609
  cancelToken,
4689
5610
  } = unwrapTsfnPayload(error, payload);
4690
- const jsRequest = buildRequest(request);
5611
+ const jsRequest = buildNativeHttpRequest(request);
4691
5612
  const actorCtx = withConnContext(
4692
5613
  runtime,
4693
5614
  ctx,
4694
5615
  conn,
4695
- createClient,
5616
+ () => createClient(ctx),
4696
5617
  schemaConfig,
4697
5618
  databaseProvider,
4698
5619
  jsRequest,
4699
5620
  stateEnabled,
4700
5621
  onStateChange,
4701
5622
  cancelToken,
5623
+ run !== undefined,
4702
5624
  );
4703
- try {
4704
- if (
4705
- !schemaConfig.queues ||
4706
- !hasSchemaConfigKey(schemaConfig.queues, name)
4707
- ) {
4708
- return { status: "completed" };
4709
- }
4710
-
4711
- const canPublish = getQueueCanPublish(
4712
- schemaConfig.queues,
4713
- name,
4714
- );
4715
- if (canPublish && !(await canPublish(actorCtx))) {
4716
- throw forbiddenError();
4717
- }
4718
-
4719
- const decodedBody = decodeValue(body);
4720
- if (wait) {
5625
+ return await runtime.runWithActorInvocationContext(
5626
+ ctx,
5627
+ async () => {
4721
5628
  try {
4722
- const response =
4723
- await actorCtx.queue.enqueueAndWait(
4724
- name,
4725
- decodedBody,
4726
- {
4727
- timeout:
4728
- timeoutMs === undefined ||
4729
- timeoutMs === null
4730
- ? undefined
4731
- : Number(timeoutMs),
4732
- },
4733
- );
4734
- return {
4735
- status: "completed",
4736
- response:
4737
- response === undefined
4738
- ? undefined
4739
- : encodeValue(response),
4740
- };
4741
- } catch (error) {
4742
5629
  if (
4743
- (error as { group?: string; code?: string })
4744
- .group === "queue" &&
4745
- (error as { group?: string; code?: string })
4746
- .code === "timed_out"
5630
+ !schemaConfig.queues ||
5631
+ !hasSchemaConfigKey(schemaConfig.queues, name)
4747
5632
  ) {
4748
- return { status: "timedOut" };
5633
+ return { status: "completed" };
4749
5634
  }
4750
- throw error;
4751
- }
4752
- }
4753
5635
 
4754
- await actorCtx.queue.send(name, decodedBody);
4755
- return { status: "completed" };
4756
- } finally {
4757
- await actorCtx.dispose();
4758
- }
5636
+ const canPublish = getQueueCanPublish(
5637
+ schemaConfig.queues,
5638
+ name,
5639
+ );
5640
+ if (canPublish && !(await canPublish(actorCtx))) {
5641
+ throw forbiddenError();
5642
+ }
5643
+
5644
+ const decodedBody = decodeValue(body);
5645
+ if (wait) {
5646
+ try {
5647
+ const response =
5648
+ await actorCtx.queue.enqueueAndWait(
5649
+ name,
5650
+ decodedBody,
5651
+ {
5652
+ timeout:
5653
+ timeoutMs === undefined ||
5654
+ timeoutMs === null
5655
+ ? undefined
5656
+ : Number(timeoutMs),
5657
+ },
5658
+ );
5659
+ return {
5660
+ status: "completed",
5661
+ response:
5662
+ response === undefined
5663
+ ? undefined
5664
+ : encodeValue(response),
5665
+ };
5666
+ } catch (error) {
5667
+ if (
5668
+ (
5669
+ error as {
5670
+ group?: string;
5671
+ code?: string;
5672
+ }
5673
+ ).group === "queue" &&
5674
+ (
5675
+ error as {
5676
+ group?: string;
5677
+ code?: string;
5678
+ }
5679
+ ).code === "timed_out"
5680
+ ) {
5681
+ return { status: "timedOut" };
5682
+ }
5683
+ throw error;
5684
+ }
5685
+ }
5686
+
5687
+ await actorCtx.queue.send(name, decodedBody);
5688
+ return { status: "completed" };
5689
+ } finally {
5690
+ await actorCtx.dispose();
5691
+ }
5692
+ },
5693
+ );
4759
5694
  },
4760
5695
  ),
4761
5696
  serializeState: wrapNativeCallback(
@@ -4785,17 +5720,20 @@ export function buildNativeFactory(
4785
5720
 
4786
5721
  export async function buildServeConfig(
4787
5722
  config: RegistryConfig,
5723
+ resolveServicesBinary = true,
4788
5724
  ): Promise<RuntimeServeConfig> {
4789
5725
  if (!config.endpoint) {
4790
5726
  throw nativeEndpointNotConfiguredError();
4791
5727
  }
4792
5728
 
4793
5729
  const serveConfig: RuntimeServeConfig = {
4794
- version: config.envoy.version,
5730
+ version: config.node.version,
4795
5731
  endpoint: config.endpoint,
5732
+ engineSpawn: config.engineSpawn,
4796
5733
  token: config.token,
4797
5734
  namespace: config.namespace,
4798
- poolName: config.envoy.poolName,
5735
+ poolName: config.node.poolName,
5736
+ startServices: resolveServicesBinary && config.startServices,
4799
5737
  handleInspectorHttpInRuntime: true,
4800
5738
  serverlessBasePath: config.serverless.basePath,
4801
5739
  serverlessPackageVersion: VERSION,
@@ -4808,7 +5746,7 @@ export async function buildServeConfig(
4808
5746
 
4809
5747
  // Always best-effort resolve the npm-installed engine binary and hand its
4810
5748
  // path to the core. The core alone decides whether to actually spawn a local
4811
- // engine (its `should_manage_engine`, based on the endpoint + spawn mode), so
5749
+ // engine using the resolved spawn decision, so
4812
5750
  // JS must not duplicate that decision here. Only JS knows the npm
4813
5751
  // `node_modules` layout, so it resolves the path; if no binary is available
4814
5752
  // (remote-only install, unsupported platform, optional deps skipped), leave
@@ -4827,6 +5765,19 @@ export async function buildServeConfig(
4827
5765
  error: stringifyError(error),
4828
5766
  });
4829
5767
  }
5768
+ if (resolveServicesBinary && config.startServices) {
5769
+ const servicesBinary = getEnvUniversal("RIVET_SERVICES_BINARY");
5770
+ if (servicesBinary) {
5771
+ serveConfig.servicesBinaryPath = servicesBinary;
5772
+ } else {
5773
+ try {
5774
+ const { getServicesPath } = await loadServices();
5775
+ serveConfig.servicesBinaryPath = getServicesPath();
5776
+ } catch (error) {
5777
+ throw servicesBinaryUnavailable(error);
5778
+ }
5779
+ }
5780
+ }
4830
5781
  serveConfig.engineHost = config.engineHost;
4831
5782
  serveConfig.enginePort = config.enginePort;
4832
5783
  if (config.test?.enabled) {
@@ -4872,7 +5823,7 @@ export async function buildRegistryWithRuntime(
4872
5823
  return {
4873
5824
  runtime,
4874
5825
  registry,
4875
- serveConfig: await buildServeConfig(config),
5826
+ serveConfig: await buildServeConfig(config, runtime.kind === "napi"),
4876
5827
  };
4877
5828
  }
4878
5829