rivetkit 0.0.0-skip-ready-wait-flatten-client-options.1cae221 → 0.0.0-sqlite-uds.ea644f1

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 (254) hide show
  1. package/dist/browser/client.d.ts +561 -89
  2. package/dist/browser/client.js +1063 -430
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.d.ts +22 -2
  5. package/dist/browser/inspector/client.js +1036 -232
  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 -74
  10. package/dist/tsup/actor/errors.d.ts +1 -74
  11. package/dist/tsup/actor/errors.js +5 -1
  12. package/dist/tsup/agent-os/index.cjs +2232 -2082
  13. package/dist/tsup/agent-os/index.cjs.map +1 -1
  14. package/dist/tsup/agent-os/index.d.cts +556 -85
  15. package/dist/tsup/agent-os/index.d.ts +556 -85
  16. package/dist/tsup/agent-os/index.js +2234 -2084
  17. package/dist/tsup/agent-os/index.js.map +1 -1
  18. package/dist/tsup/{chunk-7MRGNVSR.js → chunk-3GLNEWGY.js} +78 -6
  19. package/dist/tsup/chunk-3GLNEWGY.js.map +1 -0
  20. package/dist/tsup/{chunk-V3QNBJ7N.cjs → chunk-4FC7TVS6.cjs} +35 -10
  21. package/dist/tsup/chunk-4FC7TVS6.cjs.map +1 -0
  22. package/dist/tsup/{chunk-XNZR7UD2.cjs → chunk-7DDQA6KN.cjs} +90 -65
  23. package/dist/tsup/chunk-7DDQA6KN.cjs.map +1 -0
  24. package/dist/tsup/{chunk-NFC5VU36.cjs → chunk-AESHILFV.cjs} +18 -10
  25. package/dist/tsup/chunk-AESHILFV.cjs.map +1 -0
  26. package/dist/tsup/{chunk-D4TSTM6C.js → chunk-EFQCNJ23.js} +83 -58
  27. package/dist/tsup/chunk-EFQCNJ23.js.map +1 -0
  28. package/dist/tsup/{chunk-OIKOPSXQ.js → chunk-FUS4OFX5.js} +12 -4
  29. package/dist/tsup/chunk-FUS4OFX5.js.map +1 -0
  30. package/dist/tsup/{chunk-IOYKCB6Y.cjs → chunk-GUCITCR3.cjs} +44 -9
  31. package/dist/tsup/chunk-GUCITCR3.cjs.map +1 -0
  32. package/dist/tsup/{chunk-3BFYSYRU.js → chunk-HXUEHHJF.js} +3 -2
  33. package/dist/tsup/chunk-HXUEHHJF.js.map +1 -0
  34. package/dist/tsup/{chunk-PCBNKI2J.js → chunk-JZ7TWV65.js} +1 -1
  35. package/dist/tsup/chunk-JZ7TWV65.js.map +1 -0
  36. package/dist/tsup/{chunk-KSG2COSQ.js → chunk-KYBAXJRA.js} +6 -6
  37. package/dist/tsup/chunk-KYBAXJRA.js.map +1 -0
  38. package/dist/tsup/{chunk-LNMB25HW.js → chunk-LMUEIJUM.js} +780 -183
  39. package/dist/tsup/chunk-LMUEIJUM.js.map +1 -0
  40. package/dist/tsup/{chunk-RZEJJJKU.js → chunk-LTMSYD2A.js} +42 -7
  41. package/dist/tsup/chunk-LTMSYD2A.js.map +1 -0
  42. package/dist/tsup/{chunk-AK57AL7S.cjs → chunk-OAPVVVTX.cjs} +79 -7
  43. package/dist/tsup/chunk-OAPVVVTX.cjs.map +1 -0
  44. package/dist/tsup/{chunk-D2TLG75Y.cjs → chunk-TIUL6FNF.cjs} +10 -10
  45. package/dist/tsup/chunk-TIUL6FNF.cjs.map +1 -0
  46. package/dist/tsup/{chunk-POTPHU3P.cjs → chunk-UYT2CIWO.cjs} +3 -3
  47. package/dist/tsup/{chunk-POTPHU3P.cjs.map → chunk-UYT2CIWO.cjs.map} +1 -1
  48. package/dist/tsup/{chunk-TPBHXFB2.cjs → chunk-VDTC257X.cjs} +138 -24
  49. package/dist/tsup/chunk-VDTC257X.cjs.map +1 -0
  50. package/dist/tsup/{chunk-LLD2D5LO.cjs → chunk-VE2X4KMG.cjs} +3 -2
  51. package/dist/tsup/chunk-VE2X4KMG.cjs.map +1 -0
  52. package/dist/tsup/{chunk-22XU3BVY.cjs → chunk-VWOA7DRK.cjs} +925 -328
  53. package/dist/tsup/chunk-VWOA7DRK.cjs.map +1 -0
  54. package/dist/tsup/{chunk-4ZIWB4CQ.js → chunk-VYQASICJ.js} +2 -2
  55. package/dist/tsup/{chunk-W54QCENI.js → chunk-X4BXYDTG.js} +134 -20
  56. package/dist/tsup/chunk-X4BXYDTG.js.map +1 -0
  57. package/dist/tsup/{chunk-2NDZ7JCR.cjs → chunk-ZA7FLHKH.cjs} +1 -1
  58. package/dist/tsup/chunk-ZA7FLHKH.cjs.map +1 -0
  59. package/dist/tsup/{chunk-K34B3OVG.js → chunk-ZZ3WBRPD.js} +34 -9
  60. package/dist/tsup/chunk-ZZ3WBRPD.js.map +1 -0
  61. package/dist/tsup/client/mod.cjs +9 -9
  62. package/dist/tsup/client/mod.cjs.map +1 -1
  63. package/dist/tsup/client/mod.d.cts +8 -9
  64. package/dist/tsup/client/mod.d.ts +8 -9
  65. package/dist/tsup/client/mod.js +8 -8
  66. package/dist/tsup/common/log.cjs +5 -3
  67. package/dist/tsup/common/log.cjs.map +1 -1
  68. package/dist/tsup/common/log.d.cts +5 -1
  69. package/dist/tsup/common/log.d.ts +5 -1
  70. package/dist/tsup/common/log.js +6 -4
  71. package/dist/tsup/common/websocket.cjs +4 -4
  72. package/dist/tsup/common/websocket.js +3 -3
  73. package/dist/tsup/{config-CRdGwwbr.d.cts → config-CxG53eQo.d.cts} +577 -36
  74. package/dist/tsup/{config-kxXbtrJU.d.ts → config-DLOxy81E.d.cts} +5 -5
  75. package/dist/tsup/{config-kxXbtrJU.d.cts → config-DLOxy81E.d.ts} +5 -5
  76. package/dist/tsup/{config-DIpBWm5C.d.ts → config-Ds6DCRhV.d.ts} +577 -36
  77. package/dist/tsup/context-8KlcOYIs.d.cts +129 -0
  78. package/dist/tsup/context-Cfbm4QLr.d.ts +129 -0
  79. package/dist/tsup/db/drizzle.cjs +164 -78
  80. package/dist/tsup/db/drizzle.cjs.map +1 -1
  81. package/dist/tsup/db/drizzle.d.cts +4 -2
  82. package/dist/tsup/db/drizzle.d.ts +4 -2
  83. package/dist/tsup/db/drizzle.js +164 -78
  84. package/dist/tsup/db/drizzle.js.map +1 -1
  85. package/dist/tsup/db/mod.cjs +93 -24
  86. package/dist/tsup/db/mod.cjs.map +1 -1
  87. package/dist/tsup/db/mod.d.cts +2 -2
  88. package/dist/tsup/db/mod.d.ts +2 -2
  89. package/dist/tsup/db/mod.js +92 -23
  90. package/dist/tsup/db/mod.js.map +1 -1
  91. package/dist/tsup/dynamic/mod.cjs +24 -0
  92. package/dist/tsup/dynamic/mod.cjs.map +1 -0
  93. package/dist/tsup/dynamic/mod.d.cts +37 -0
  94. package/dist/tsup/dynamic/mod.d.ts +37 -0
  95. package/dist/tsup/dynamic/mod.js +24 -0
  96. package/dist/tsup/dynamic/mod.js.map +1 -0
  97. package/dist/tsup/inspector/mod.cjs +47 -12
  98. package/dist/tsup/inspector/mod.cjs.map +1 -1
  99. package/dist/tsup/inspector/mod.d.cts +37 -15
  100. package/dist/tsup/inspector/mod.d.ts +37 -15
  101. package/dist/tsup/inspector/mod.js +46 -11
  102. package/dist/tsup/inspector/mod.js.map +1 -1
  103. package/dist/tsup/inspector-tab/mod.cjs +162 -0
  104. package/dist/tsup/inspector-tab/mod.cjs.map +1 -0
  105. package/dist/tsup/inspector-tab/mod.d.cts +240 -0
  106. package/dist/tsup/inspector-tab/mod.d.ts +240 -0
  107. package/dist/tsup/inspector-tab/mod.js +162 -0
  108. package/dist/tsup/inspector-tab/mod.js.map +1 -0
  109. package/dist/tsup/mod.cjs +1078 -479
  110. package/dist/tsup/mod.cjs.map +1 -1
  111. package/dist/tsup/mod.d.cts +5 -6
  112. package/dist/tsup/mod.d.ts +5 -6
  113. package/dist/tsup/mod.js +996 -397
  114. package/dist/tsup/mod.js.map +1 -1
  115. package/dist/tsup/test/mod.cjs +21 -18
  116. package/dist/tsup/test/mod.cjs.map +1 -1
  117. package/dist/tsup/test/mod.d.cts +4 -5
  118. package/dist/tsup/test/mod.d.ts +4 -5
  119. package/dist/tsup/test/mod.js +18 -15
  120. package/dist/tsup/test/mod.js.map +1 -1
  121. package/dist/tsup/utils-CqDnC_PS.d.cts +104 -0
  122. package/dist/tsup/utils-CqDnC_PS.d.ts +104 -0
  123. package/dist/tsup/utils.cjs +3 -3
  124. package/dist/tsup/utils.d.cts +1 -1
  125. package/dist/tsup/utils.d.ts +1 -1
  126. package/dist/tsup/utils.js +2 -2
  127. package/dist/tsup/workflow/mod.cjs +386 -322
  128. package/dist/tsup/workflow/mod.cjs.map +1 -1
  129. package/dist/tsup/workflow/mod.d.cts +8 -9
  130. package/dist/tsup/workflow/mod.d.ts +8 -9
  131. package/dist/tsup/workflow/mod.js +363 -299
  132. package/dist/tsup/workflow/mod.js.map +1 -1
  133. package/package.json +35 -14
  134. package/src/actor/config.ts +188 -59
  135. package/src/actor/contexts/index.ts +7 -2
  136. package/src/actor/definition.ts +17 -19
  137. package/src/actor/driver.ts +3 -3
  138. package/src/actor/errors.ts +70 -7
  139. package/src/actor/instance/mod.ts +39 -56
  140. package/src/actor/keys.ts +2 -1
  141. package/src/actor/mod.ts +22 -20
  142. package/src/actor/schema.ts +2 -2
  143. package/src/agent-os/actor/index.ts +38 -18
  144. package/src/agent-os/actor/preview.ts +1 -2
  145. package/src/agent-os/actor/session.ts +2 -2
  146. package/src/agent-os/config.ts +1 -1
  147. package/src/agent-os/fs/database-vfs.ts +1 -1
  148. package/src/agent-os/index.ts +16 -15
  149. package/src/client/actor-common.ts +88 -62
  150. package/src/client/actor-conn.ts +58 -63
  151. package/src/client/actor-handle.ts +125 -71
  152. package/src/client/actor-query.ts +5 -5
  153. package/src/client/config.ts +3 -3
  154. package/src/client/errors.ts +2 -1
  155. package/src/client/lifecycle-errors.ts +2 -4
  156. package/src/client/query.ts +1 -1
  157. package/src/client/queue.ts +8 -3
  158. package/src/client/raw-utils.ts +10 -10
  159. package/src/client/resolve-gateway-target.ts +1 -1
  160. package/src/client/utils.ts +34 -10
  161. package/src/common/actor-router-consts.ts +7 -4
  162. package/src/common/actor-websocket.ts +3 -1
  163. package/src/common/bare/actor-persist/v1.ts +205 -163
  164. package/src/common/bare/actor-persist/v2.ts +265 -213
  165. package/src/common/bare/actor-persist/v3.ts +176 -172
  166. package/src/common/bare/actor-persist/v4.ts +254 -253
  167. package/src/common/bare/generated/actor-uds-protocol/v1.ts +802 -0
  168. package/src/common/bare/generated/client-protocol/v4.ts +599 -0
  169. package/src/common/bare/generated/inspector/v5.ts +1016 -0
  170. package/src/common/bare/transport/v1.ts +694 -542
  171. package/src/common/client-protocol-versioned.ts +176 -67
  172. package/src/common/client-protocol-zod.ts +7 -0
  173. package/src/common/client-protocol.ts +1 -1
  174. package/src/common/database/config.ts +16 -5
  175. package/src/common/database/mod.test.ts +137 -16
  176. package/src/common/database/mod.ts +100 -30
  177. package/src/common/database/native-database.test.ts +35 -22
  178. package/src/common/database/native-database.ts +26 -10
  179. package/src/common/database/shared.ts +1 -0
  180. package/src/common/encoding.ts +250 -16
  181. package/src/common/engine.ts +28 -1
  182. package/src/common/eventsource.ts +1 -1
  183. package/src/common/inline-websocket-adapter.ts +14 -13
  184. package/src/common/log.ts +15 -8
  185. package/src/common/router.ts +49 -23
  186. package/src/common/utils.ts +10 -202
  187. package/src/common/websocket-interface.ts +1 -1
  188. package/src/db/drizzle.ts +194 -95
  189. package/src/db/mod.ts +1 -1
  190. package/src/devtools-loader/index.ts +4 -7
  191. package/src/devtools-loader/serve-devtools.ts +26 -0
  192. package/src/drivers/engine/actor-driver.ts +76 -73
  193. package/src/dynamic/instance.ts +32 -0
  194. package/src/dynamic/internal.ts +50 -0
  195. package/src/dynamic/isolate-runtime.ts +66 -0
  196. package/src/dynamic/mod.ts +32 -0
  197. package/src/engine-client/actor-http-client.ts +6 -9
  198. package/src/engine-client/actor-websocket-client.ts +14 -13
  199. package/src/engine-client/api-endpoints.ts +51 -2
  200. package/src/engine-client/api-utils.ts +2 -2
  201. package/src/engine-client/driver.ts +3 -4
  202. package/src/engine-client/mod.ts +17 -10
  203. package/src/engine-client/ws-proxy.ts +9 -4
  204. package/src/inspector/client.browser.ts +66 -15
  205. package/src/inspector/mod.ts +2 -4
  206. package/src/inspector-tab/mod.ts +300 -0
  207. package/src/registry/config/envoy.ts +1 -2
  208. package/src/registry/config/index.ts +46 -20
  209. package/src/registry/index.ts +364 -87
  210. package/src/registry/napi-runtime.ts +97 -8
  211. package/src/registry/native-validation.ts +10 -12
  212. package/src/registry/native.ts +592 -343
  213. package/src/registry/process-metrics.ts +250 -0
  214. package/src/registry/runtime.ts +85 -6
  215. package/src/registry/wasm-runtime.ts +72 -3
  216. package/src/registry/write-through-proxy.ts +40 -0
  217. package/src/serde.ts +2 -2
  218. package/src/serverless/configure.ts +19 -8
  219. package/src/test/mod.ts +11 -8
  220. package/src/utils/crypto.ts +14 -0
  221. package/src/utils/endpoint-parser.ts +1 -1
  222. package/src/utils/env-vars.ts +37 -0
  223. package/src/utils/router.ts +1 -1
  224. package/src/utils.ts +1 -2
  225. package/src/workflow/context.ts +703 -240
  226. package/src/workflow/driver.ts +23 -12
  227. package/src/workflow/inspector.ts +12 -3
  228. package/src/workflow/mod.ts +37 -23
  229. package/dist/tsup/chunk-22XU3BVY.cjs.map +0 -1
  230. package/dist/tsup/chunk-2NDZ7JCR.cjs.map +0 -1
  231. package/dist/tsup/chunk-3BFYSYRU.js.map +0 -1
  232. package/dist/tsup/chunk-7MRGNVSR.js.map +0 -1
  233. package/dist/tsup/chunk-AK57AL7S.cjs.map +0 -1
  234. package/dist/tsup/chunk-D2TLG75Y.cjs.map +0 -1
  235. package/dist/tsup/chunk-D4TSTM6C.js.map +0 -1
  236. package/dist/tsup/chunk-IOYKCB6Y.cjs.map +0 -1
  237. package/dist/tsup/chunk-K34B3OVG.js.map +0 -1
  238. package/dist/tsup/chunk-KSG2COSQ.js.map +0 -1
  239. package/dist/tsup/chunk-LLD2D5LO.cjs.map +0 -1
  240. package/dist/tsup/chunk-LNMB25HW.js.map +0 -1
  241. package/dist/tsup/chunk-NFC5VU36.cjs.map +0 -1
  242. package/dist/tsup/chunk-OIKOPSXQ.js.map +0 -1
  243. package/dist/tsup/chunk-PCBNKI2J.js.map +0 -1
  244. package/dist/tsup/chunk-RZEJJJKU.js.map +0 -1
  245. package/dist/tsup/chunk-TPBHXFB2.cjs.map +0 -1
  246. package/dist/tsup/chunk-V3QNBJ7N.cjs.map +0 -1
  247. package/dist/tsup/chunk-W54QCENI.js.map +0 -1
  248. package/dist/tsup/chunk-XNZR7UD2.cjs.map +0 -1
  249. package/dist/tsup/context-B7G6sk7x.d.ts +0 -92
  250. package/dist/tsup/context-DzMRHkjC.d.cts +0 -92
  251. package/dist/tsup/utils-fwx3o3K9.d.cts +0 -18
  252. package/dist/tsup/utils-fwx3o3K9.d.ts +0 -18
  253. package/src/utils/serve.ts +0 -217
  254. /package/dist/tsup/{chunk-4ZIWB4CQ.js.map → chunk-VYQASICJ.js.map} +0 -0
@@ -2,8 +2,10 @@ import { VirtualWebSocket } from "@rivetkit/virtual-websocket";
2
2
  import {
3
3
  ACTOR_CONTEXT_INTERNAL_SYMBOL,
4
4
  CONN_STATE_MANAGER_SYMBOL,
5
+ disposeRunInspector,
5
6
  getRunFunction,
6
7
  getRunInspectorConfig,
8
+ RAW_STATE_SYMBOL,
7
9
  type WorkflowInspectorConfig,
8
10
  } from "@/actor/config";
9
11
  import type { AnyActorDefinition } from "@/actor/definition";
@@ -12,6 +14,7 @@ import {
12
14
  encodeBridgeRivetError,
13
15
  forbiddenError,
14
16
  INTERNAL_ERROR_CODE,
17
+ isActorAbortedError,
15
18
  isRivetErrorLike,
16
19
  RivetError,
17
20
  type RivetErrorLike,
@@ -29,22 +32,10 @@ import {
29
32
  createClientWithDriver,
30
33
  } from "@/client/client";
31
34
  import { convertRegistryConfigToClientConfig } from "@/client/config";
32
- import {
33
- HEADER_CONN_PARAMS,
34
- HEADER_ENCODING,
35
- } from "@/common/actor-router-consts";
36
- import type * as protocol from "@/common/client-protocol";
37
- import {
38
- CURRENT_VERSION as CLIENT_PROTOCOL_CURRENT_VERSION,
39
- HTTP_RESPONSE_ERROR_VERSIONED,
40
- } from "@/common/client-protocol-versioned";
41
- import {
42
- type HttpResponseError as HttpResponseErrorJson,
43
- HttpResponseErrorSchema,
44
- } from "@/common/client-protocol-zod";
35
+ import { HEADER_CONN_PARAMS } from "@/common/actor-router-consts";
45
36
  import type { AnyDatabaseProvider } from "@/common/database/config";
46
37
  import { wrapJsNativeDatabase } from "@/common/database/native-database";
47
- import type { Encoding } from "@/common/encoding";
38
+ import { assertJsonCompatValue, type JsonCompatValue } from "@/common/encoding";
48
39
  import { decodeWorkflowHistoryTransport } from "@/common/inspector-transport";
49
40
  import { deconstructError, stringifyError } from "@/common/utils";
50
41
  import type {
@@ -60,14 +51,13 @@ import type {
60
51
  RuntimeKind,
61
52
  SqliteBackend,
62
53
  } from "@/registry/config";
63
- import {
64
- contentTypeForEncoding,
65
- decodeCborCompat,
66
- decodeCborJsonCompat,
67
- encodeCborCompat,
68
- serializeWithEncoding,
69
- } from "@/serde";
54
+ import { decodeCborCompat, encodeCborCompat } from "@/serde";
70
55
  import { getEnvUniversal, VERSION } from "@/utils";
56
+ import {
57
+ getNodeFsSync,
58
+ getNodePath,
59
+ importNodeDependencies,
60
+ } from "@/utils/node";
71
61
  import { logger } from "./log";
72
62
  import { loadNapiRuntime } from "./napi-runtime";
73
63
  import {
@@ -88,15 +78,18 @@ import type {
88
78
  RuntimeActorConfig,
89
79
  RuntimeBytes,
90
80
  RuntimeHttpResponse,
81
+ RuntimeInspectorTabEntry,
91
82
  RuntimeQueueMessage,
92
83
  RuntimeServeConfig,
93
84
  RuntimeStateDeltaPayload,
94
85
  WebSocketHandle,
95
86
  } from "./runtime";
96
87
  import { loadWasmRuntime } from "./wasm-runtime";
88
+ import { createWriteThroughProxy } from "./write-through-proxy";
97
89
 
98
90
  const textEncoder = new TextEncoder();
99
91
  const textDecoder = new TextDecoder();
92
+
100
93
  type ResolvedRuntimeKind = Exclude<RuntimeKind, "auto">;
101
94
  type RuntimeHostKind = "node-like" | "edge-like";
102
95
  export type RuntimeLoaders = {
@@ -106,6 +99,7 @@ export type RuntimeLoaders = {
106
99
  ) => ReturnType<typeof loadWasmRuntime>;
107
100
  detectHost: () => RuntimeHostKind;
108
101
  };
102
+
109
103
  type SerializeStateReason = "save" | "inspector";
110
104
  type NativeOnStateChangeHandler = (
111
105
  ctx: ActorContextHandleAdapter,
@@ -258,6 +252,14 @@ type NativePersistActorState = {
258
252
  state: unknown;
259
253
  isInOnStateChange: boolean;
260
254
  connStates: Map<string, NativePersistConnState>;
255
+ // Memoized deep write-through proxy and the state object it wraps. Rebuilt
256
+ // only when the underlying state object identity changes.
257
+ stateProxy?: unknown;
258
+ stateProxyTarget?: unknown;
259
+ // Set when a coalesced save and onStateChange flush is pending for the
260
+ // current event loop tick.
261
+ saveScheduled?: boolean;
262
+ pendingSaveHandle?: ReturnType<typeof setImmediate>;
261
263
  };
262
264
  type NativeDestroyGate = {
263
265
  destroyCompletion?: Promise<void>;
@@ -269,8 +271,6 @@ type NativeDatabaseClientState = {
269
271
  type NativeActorRuntimeState = {
270
272
  sql?: ReturnType<typeof wrapJsNativeDatabase>;
271
273
  databaseClient?: NativeDatabaseClientState;
272
- keepAwakeCount?: number;
273
- deferSleepCleanupUntilKeepAwakeIdle?: boolean;
274
274
  varsInitialized?: boolean;
275
275
  vars?: unknown;
276
276
  destroyGate?: NativeDestroyGate;
@@ -354,6 +354,15 @@ function databaseNotConfiguredError(): RivetError {
354
354
  );
355
355
  }
356
356
 
357
+ function databaseClientNotReadyError(): RivetError {
358
+ return new RivetError(
359
+ "actor",
360
+ "database_client_not_ready",
361
+ "actor database client was not initialized before user code ran. this is an internal lifecycle error; the migration callback should have pre-warmed the client. file an issue if you can reproduce.",
362
+ { public: true },
363
+ );
364
+ }
365
+
357
366
  function stateNotEnabledError(): RivetError {
358
367
  return new RivetError(
359
368
  "actor",
@@ -412,14 +421,43 @@ function resolveNativeDestroy(runtime: CoreRuntime, ctx: ActorContextHandle) {
412
421
  gate.destroyCompletion = undefined;
413
422
  }
414
423
 
415
- function clearNativeRuntimeState(runtime: CoreRuntime, ctx: ActorContextHandle) {
424
+ function clearNativeRuntimeState(
425
+ runtime: CoreRuntime,
426
+ ctx: ActorContextHandle,
427
+ ) {
416
428
  callNativeSync(() => runtime.actorClearRuntimeState(ctx));
417
429
  }
418
430
 
419
431
  async function cleanupNativeSleepRuntimeState(
420
432
  runtime: CoreRuntime,
421
433
  ctx: ActorContextHandle,
434
+ afterTrackedWorkDrained?: () => Promise<void>,
422
435
  ): Promise<void> {
436
+ // The bounded wait gives shutdown work one grace-period chance to finish.
437
+ // Drained means all tracked shutdown work completed before the deadline, so
438
+ // we can save final state and clear runtime state immediately. If it did not
439
+ // drain, close database handles now, then defer the final save and clear until
440
+ // the tracked work finishes without a deadline.
441
+ const drained = await runtime.actorWaitForTrackedShutdownWork(ctx);
442
+ if (!drained) {
443
+ await closeNativeDatabaseClient(runtime, ctx);
444
+ await closeNativeSqlDatabase(runtime, ctx);
445
+ void runtime
446
+ .actorWaitForTrackedShutdownWorkUnbounded(ctx)
447
+ .then(async () => {
448
+ await afterTrackedWorkDrained?.();
449
+ clearNativeRuntimeState(runtime, ctx);
450
+ })
451
+ .catch((error) => {
452
+ logger().warn({
453
+ msg: "deferred native sleep cleanup failed",
454
+ error: stringifyError(error),
455
+ });
456
+ });
457
+ return;
458
+ }
459
+
460
+ await afterTrackedWorkDrained?.();
423
461
  await closeNativeDatabaseClient(runtime, ctx);
424
462
  await closeNativeSqlDatabase(runtime, ctx);
425
463
  clearNativeRuntimeState(runtime, ctx);
@@ -472,8 +510,23 @@ function getOrCreateNativeSqlDatabase(
472
510
  }
473
511
 
474
512
  const database = wrapJsNativeDatabase({
475
- exec: (sql) => runtime.actorSqlExec(ctx, sql),
476
- execute: (sql, params) => runtime.actorSqlExecute(ctx, sql, params),
513
+ exec: (sql, leaseKey, leaseTimeoutMs) =>
514
+ runtime.actorSqlExec(
515
+ ctx,
516
+ sql,
517
+ leaseKey === undefined
518
+ ? undefined
519
+ : { key: leaseKey, timeoutMs: leaseTimeoutMs },
520
+ ),
521
+ execute: (sql, params, leaseKey, leaseTimeoutMs) =>
522
+ runtime.actorSqlExecute(
523
+ ctx,
524
+ sql,
525
+ params,
526
+ leaseKey === undefined
527
+ ? undefined
528
+ : { key: leaseKey, timeoutMs: leaseTimeoutMs },
529
+ ),
477
530
  query: (sql, params) => runtime.actorSqlQuery(ctx, sql, params),
478
531
  run: (sql, params) => runtime.actorSqlRun(ctx, sql, params),
479
532
  metrics: () => runtime.actorSqlMetrics(ctx),
@@ -584,6 +637,13 @@ function decodeNativeKvValue<T extends NativeKvValueType = "text">(
584
637
  }
585
638
 
586
639
  async function loadEngineCli(): Promise<typeof import("@rivetkit/engine-cli")> {
640
+ // LOAD-BEARING: the specifier is computed (`.join("/")`) on purpose. Do NOT
641
+ // "simplify" it to a literal `import("@rivetkit/engine-cli")`. Edge adapters
642
+ // (e.g. @rivetkit/supabase) pre-bundle this module for Deno; a literal
643
+ // dynamic import is statically resolvable, so Deno's eszip bundler would
644
+ // snapshot the ~117 MB engine-cli binary into the deploy and 413. The
645
+ // computed specifier keeps it opaque to static analysis so it is never
646
+ // bundled. Enforced by scripts/ci/check-edge-native-closure.mjs.
587
647
  return import(["@rivetkit", "engine-cli"].join("/"));
588
648
  }
589
649
 
@@ -592,11 +652,19 @@ function decodeValue<T>(value?: RuntimeBytes | null): T {
592
652
  return undefined as T;
593
653
  }
594
654
 
595
- return decodeCborJsonCompat(value);
655
+ return decodeCborCompat(value);
596
656
  }
597
657
 
598
658
  function encodeValue(value: unknown): RuntimeBytes {
599
- return encodeCborCompat(value);
659
+ return encodeCborCompat(value as JsonCompatValue);
660
+ }
661
+
662
+ function normalizeArgs(value: unknown): unknown[] {
663
+ return Array.isArray(value)
664
+ ? value
665
+ : value === undefined || value === null
666
+ ? []
667
+ : [value];
600
668
  }
601
669
 
602
670
  function unwrapTsfnPayload<T>(error: unknown, payload: T): T {
@@ -651,28 +719,7 @@ function isStructuredBridgeError(
651
719
  function encodeNativeCallbackError(error: unknown): Error {
652
720
  const structuredError = isStructuredBridgeError(error)
653
721
  ? error
654
- : deconstructError(error, logger(), {
655
- bridge: "native_callback",
656
- });
657
- let stack: string | undefined;
658
- if (error instanceof Error) {
659
- try {
660
- stack = error.stack;
661
- } catch {
662
- stack = undefined;
663
- }
664
- }
665
-
666
- logger().warn({
667
- msg: "native callback error encoded for bridge",
668
- group: structuredError.group,
669
- code: structuredError.code,
670
- message: structuredError.message,
671
- metadata: structuredError.metadata,
672
- originalError: stringifyError(error),
673
- stack,
674
- bridge: "native_callback",
675
- });
722
+ : deconstructError(error, true);
676
723
 
677
724
  const bridgeError = new Error(encodeBridgeRivetError(structuredError), {
678
725
  cause: error instanceof Error ? error : undefined,
@@ -882,6 +929,10 @@ function serializeWorkflowEntryKind(
882
929
  | {
883
930
  tag: "WorkflowRemovedEntry";
884
931
  val: { originalType: string; originalName: string | null };
932
+ }
933
+ | {
934
+ tag: "WorkflowVersionCheckEntry";
935
+ val: { resolved: number; latest: number };
885
936
  } {
886
937
  switch (kind.tag) {
887
938
  case "WorkflowStepEntry":
@@ -947,9 +998,18 @@ function serializeWorkflowEntryKind(
947
998
  originalName: kind.val.originalName,
948
999
  },
949
1000
  };
1001
+ case "WorkflowVersionCheckEntry":
1002
+ return {
1003
+ tag: kind.tag,
1004
+ val: {
1005
+ resolved: kind.val.resolved,
1006
+ latest: kind.val.latest,
1007
+ },
1008
+ };
950
1009
  }
951
1010
  }
952
1011
 
1012
+ // TODO: Switch inspector routes to CBOR encoding
953
1013
  function serializeWorkflowHistoryForJson(data: ArrayBuffer | null): {
954
1014
  nameRegistry: string[];
955
1015
  entries: Array<{
@@ -983,7 +1043,7 @@ function serializeWorkflowHistoryForJson(data: ArrayBuffer | null): {
983
1043
 
984
1044
  const history = decodeWorkflowHistoryTransport(data);
985
1045
 
986
- return {
1046
+ return jsonSafe({
987
1047
  nameRegistry: [...history.nameRegistry],
988
1048
  entries: history.entries.map((entry) => ({
989
1049
  id: entry.id,
@@ -1013,7 +1073,7 @@ function serializeWorkflowHistoryForJson(data: ArrayBuffer | null): {
1013
1073
  ],
1014
1074
  ),
1015
1075
  ),
1016
- };
1076
+ });
1017
1077
  }
1018
1078
 
1019
1079
  function toHttpJsonCompatible<T>(value: T): T {
@@ -1085,60 +1145,7 @@ function wrapNativeCallback<Args extends Array<unknown>, Result>(
1085
1145
 
1086
1146
  function decodeArgs(value?: RuntimeBytes | null): unknown[] {
1087
1147
  const decoded = decodeValue<unknown>(value);
1088
- return Array.isArray(decoded)
1089
- ? decoded
1090
- : decoded === undefined
1091
- ? []
1092
- : [decoded];
1093
- }
1094
-
1095
- function createWriteThroughProxy<T>(
1096
- value: T,
1097
- commit: (next: T) => void,
1098
- beforeChange?: () => void,
1099
- ): T {
1100
- if (!value || typeof value !== "object") {
1101
- return value;
1102
- }
1103
-
1104
- const proxies = new WeakMap<object, object>();
1105
- const wrap = (target: object): object => {
1106
- const cached = proxies.get(target);
1107
- if (cached) {
1108
- return cached;
1109
- }
1110
-
1111
- const proxy = new Proxy(target, {
1112
- get(innerTarget, property, receiver) {
1113
- const result = Reflect.get(innerTarget, property, receiver);
1114
- return result && typeof result === "object"
1115
- ? wrap(result as object)
1116
- : result;
1117
- },
1118
- set(innerTarget, property, nextValue, receiver) {
1119
- beforeChange?.();
1120
- const updated = Reflect.set(
1121
- innerTarget,
1122
- property,
1123
- nextValue,
1124
- receiver,
1125
- );
1126
- commit(value);
1127
- return updated;
1128
- },
1129
- deleteProperty(innerTarget, property) {
1130
- beforeChange?.();
1131
- const updated = Reflect.deleteProperty(innerTarget, property);
1132
- commit(value);
1133
- return updated;
1134
- },
1135
- });
1136
-
1137
- proxies.set(target, proxy);
1138
- return proxy;
1139
- };
1140
-
1141
- return wrap(value as object) as T;
1148
+ return normalizeArgs(decoded);
1142
1149
  }
1143
1150
 
1144
1151
  function buildRequest(init: {
@@ -1230,14 +1237,25 @@ class NativeConnAdapter {
1230
1237
  );
1231
1238
  }
1232
1239
 
1240
+ [RAW_STATE_SYMBOL](): unknown {
1241
+ return this.#readState();
1242
+ }
1243
+
1233
1244
  get state(): unknown {
1234
1245
  const nextState = this.#readState();
1235
- return createWriteThroughProxy(nextState, (nextValue) => {
1236
- this.#writeState(nextValue, { writeNative: true });
1237
- });
1246
+ return createWriteThroughProxy(
1247
+ nextState,
1248
+ (nextValue) => {
1249
+ this.#writeState(nextValue, { writeNative: true });
1250
+ },
1251
+ (newValue) => {
1252
+ assertJsonCompatValue(newValue);
1253
+ },
1254
+ );
1238
1255
  }
1239
1256
 
1240
1257
  set state(value: unknown) {
1258
+ assertJsonCompatValue(value);
1241
1259
  this.#writeState(value, { writeNative: true });
1242
1260
  }
1243
1261
 
@@ -1709,7 +1727,12 @@ class NativeQueueAdapter {
1709
1727
  signal?: AbortSignal;
1710
1728
  },
1711
1729
  ) {
1712
- if (!options?.signal) {
1730
+ const { token, cleanup } = await createCancellationTokenHandle(
1731
+ this.#runtime,
1732
+ options?.signal,
1733
+ );
1734
+
1735
+ try {
1713
1736
  await callNative(() =>
1714
1737
  this.#runtime.actorQueueWaitForNamesAvailable(
1715
1738
  this.#ctx,
@@ -1717,57 +1740,11 @@ class NativeQueueAdapter {
1717
1740
  {
1718
1741
  timeoutMs: options?.timeout,
1719
1742
  },
1743
+ token,
1720
1744
  ),
1721
1745
  );
1722
- return;
1723
- }
1724
-
1725
- const deadline =
1726
- options.timeout === undefined
1727
- ? undefined
1728
- : Date.now() + options.timeout;
1729
-
1730
- for (;;) {
1731
- if (options.signal.aborted) {
1732
- throw actorAbortedError();
1733
- }
1734
-
1735
- const remainingTimeout =
1736
- deadline === undefined
1737
- ? undefined
1738
- : Math.max(0, deadline - Date.now());
1739
- const sliceTimeout =
1740
- remainingTimeout === undefined
1741
- ? 100
1742
- : Math.min(remainingTimeout, 100);
1743
-
1744
- try {
1745
- await callNative(() =>
1746
- this.#runtime.actorQueueWaitForNamesAvailable(
1747
- this.#ctx,
1748
- [...names],
1749
- {
1750
- timeoutMs: sliceTimeout,
1751
- },
1752
- ),
1753
- );
1754
- return;
1755
- } catch (error) {
1756
- if (
1757
- (error as { group?: string; code?: string }).group ===
1758
- "queue" &&
1759
- (error as { group?: string; code?: string }).code ===
1760
- "timed_out"
1761
- ) {
1762
- if (
1763
- remainingTimeout === undefined ||
1764
- remainingTimeout > 100
1765
- ) {
1766
- continue;
1767
- }
1768
- }
1769
- throw error;
1770
- }
1746
+ } finally {
1747
+ cleanup?.();
1771
1748
  }
1772
1749
  }
1773
1750
 
@@ -1870,11 +1847,7 @@ class NativeQueueAdapter {
1870
1847
  }
1871
1848
  yield message;
1872
1849
  } catch (error) {
1873
- if (
1874
- isRivetErrorLike(error) &&
1875
- error.group === "actor" &&
1876
- error.code === "aborted"
1877
- ) {
1850
+ if (isActorAbortedError(error)) {
1878
1851
  return;
1879
1852
  }
1880
1853
  throw error;
@@ -2349,6 +2322,104 @@ class TrackedWebSocketHandleAdapter implements UniversalWebSocket {
2349
2322
  }
2350
2323
  }
2351
2324
 
2325
+ class NativeConnectionMap implements ReadonlyMap<string, NativeConnAdapter> {
2326
+ #runtime: CoreRuntime;
2327
+ #ctx: ActorContextHandle;
2328
+ #schemas: NativeValidationConfig;
2329
+
2330
+ constructor(
2331
+ runtime: CoreRuntime,
2332
+ ctx: ActorContextHandle,
2333
+ schemas: NativeValidationConfig,
2334
+ ) {
2335
+ this.#runtime = runtime;
2336
+ this.#ctx = ctx;
2337
+ this.#schemas = schemas;
2338
+ }
2339
+
2340
+ #connToAdapter(conn: ConnHandle): NativeConnAdapter {
2341
+ return new NativeConnAdapter(
2342
+ this.#runtime,
2343
+ conn,
2344
+ this.#schemas,
2345
+ this.#ctx,
2346
+ (connId) =>
2347
+ callNativeSync(() =>
2348
+ this.#runtime.actorQueueHibernationRemoval(
2349
+ this.#ctx,
2350
+ connId,
2351
+ ),
2352
+ ),
2353
+ );
2354
+ }
2355
+
2356
+ get size(): number {
2357
+ return callNativeSync(() => this.#runtime.actorConns(this.#ctx)).length;
2358
+ }
2359
+
2360
+ get(key: string): NativeConnAdapter | undefined {
2361
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
2362
+ const conn = conns.find((c) => this.#runtime.connId(c) === key);
2363
+ if (!conn) return undefined;
2364
+ return this.#connToAdapter(conn);
2365
+ }
2366
+
2367
+ has(key: string): boolean {
2368
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
2369
+ return conns.some((c) => this.#runtime.connId(c) === key);
2370
+ }
2371
+
2372
+ keys(): MapIterator<string> {
2373
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
2374
+ return conns
2375
+ .map((c) => this.#runtime.connId(c))
2376
+ [Symbol.iterator]() satisfies MapIterator<string>;
2377
+ }
2378
+
2379
+ values(): MapIterator<NativeConnAdapter> {
2380
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
2381
+ return conns
2382
+ .map((c) => this.#connToAdapter(c))
2383
+ [Symbol.iterator]() satisfies MapIterator<NativeConnAdapter>;
2384
+ }
2385
+
2386
+ entries(): MapIterator<[string, NativeConnAdapter]> {
2387
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
2388
+ return conns
2389
+ .map(
2390
+ (c) =>
2391
+ [this.#runtime.connId(c), this.#connToAdapter(c)] as [
2392
+ string,
2393
+ NativeConnAdapter,
2394
+ ],
2395
+ )
2396
+ [Symbol.iterator]() satisfies MapIterator<
2397
+ [string, NativeConnAdapter]
2398
+ >;
2399
+ }
2400
+
2401
+ forEach(
2402
+ callback: (
2403
+ value: NativeConnAdapter,
2404
+ key: string,
2405
+ map: ReadonlyMap<string, NativeConnAdapter>,
2406
+ ) => void,
2407
+ thisArg?: unknown,
2408
+ ): void {
2409
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
2410
+ for (const conn of conns) {
2411
+ const id = this.#runtime.connId(conn);
2412
+ callback.call(thisArg, this.#connToAdapter(conn), id, this);
2413
+ }
2414
+ }
2415
+
2416
+ [Symbol.iterator](): MapIterator<[string, NativeConnAdapter]> {
2417
+ return this.entries();
2418
+ }
2419
+
2420
+ readonly [Symbol.toStringTag] = "NativeConnectionMap";
2421
+ }
2422
+
2352
2423
  export class ActorContextHandleAdapter {
2353
2424
  #runtime: CoreRuntime;
2354
2425
  #ctx: ActorContextHandle;
@@ -2357,9 +2428,9 @@ export class ActorContextHandleAdapter {
2357
2428
  #abortSignalCleanup?: () => void;
2358
2429
  #client?: AnyClient;
2359
2430
  #clientFactory?: () => AnyClient;
2431
+ #connMap?: NativeConnectionMap;
2360
2432
  #databaseProvider?: Exclude<AnyDatabaseProvider, undefined>;
2361
2433
  #db?: unknown;
2362
- #dbProxy?: unknown;
2363
2434
  #dispatchCancelToken?: CancellationTokenHandle;
2364
2435
  #kv?: NativeKvAdapter;
2365
2436
  #queue?: NativeQueueAdapter;
@@ -2417,53 +2488,63 @@ export class ActorContextHandleAdapter {
2417
2488
  return this.#sql;
2418
2489
  }
2419
2490
 
2491
+ async actorUds(): Promise<{ path: string; token: string }> {
2492
+ return await this.#runtime.actorUdsProvision(this.#ctx);
2493
+ }
2494
+
2420
2495
  get db() {
2421
2496
  if (!this.#databaseProvider) {
2422
2497
  throw databaseNotConfiguredError();
2423
2498
  }
2424
2499
 
2425
- if (!this.#dbProxy) {
2426
- this.#dbProxy = new Proxy(
2427
- {},
2428
- {
2429
- get: (_target, property) => {
2430
- if (property === "then") {
2431
- return undefined;
2432
- }
2500
+ if (this.#db) {
2501
+ return this.#db;
2502
+ }
2433
2503
 
2434
- return async (...args: Array<unknown>) => {
2435
- const client = await this.ensureDatabaseClient();
2436
- const value = Reflect.get(
2437
- client as object,
2438
- property,
2439
- );
2440
- if (typeof value !== "function") {
2441
- return value;
2442
- }
2443
- return await value.apply(client, args);
2444
- };
2445
- },
2446
- },
2447
- );
2504
+ const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
2505
+ const cachedClient = runtimeState.databaseClient;
2506
+ if (cachedClient) {
2507
+ this.#db = cachedClient.client;
2508
+ return this.#db;
2448
2509
  }
2449
2510
 
2450
- return this.#dbProxy;
2511
+ throw databaseClientNotReadyError();
2512
+ }
2513
+
2514
+ [RAW_STATE_SYMBOL](): unknown {
2515
+ if (!this.#stateEnabled) {
2516
+ throw stateNotEnabledError();
2517
+ }
2518
+ return this.#readState();
2451
2519
  }
2452
2520
 
2453
2521
  get state(): unknown {
2454
2522
  if (!this.#stateEnabled) {
2455
2523
  throw stateNotEnabledError();
2456
2524
  }
2525
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
2457
2526
  const nextState = this.#readState();
2458
- return createWriteThroughProxy(
2459
- nextState,
2460
- (nextValue) => {
2461
- this.#writeState(nextValue, { scheduleSave: true });
2462
- },
2463
- () => {
2464
- this.#assertCanMutateState();
2465
- },
2466
- );
2527
+ // Reading `c.state` rebuilds the deep write-through proxy, which
2528
+ // allocates fresh on-change caches and rewraps the whole tree. Memoize
2529
+ // the proxy keyed on the underlying state object so repeated reads and
2530
+ // deep read cascades reuse a single proxy.
2531
+ if (
2532
+ actorState.stateProxy === undefined ||
2533
+ actorState.stateProxyTarget !== nextState
2534
+ ) {
2535
+ actorState.stateProxyTarget = nextState;
2536
+ actorState.stateProxy = createWriteThroughProxy(
2537
+ nextState,
2538
+ (nextValue) => {
2539
+ this.#writeState(nextValue, { scheduleSave: true });
2540
+ },
2541
+ (newValue) => {
2542
+ this.#assertCanMutateState();
2543
+ assertJsonCompatValue(newValue);
2544
+ },
2545
+ );
2546
+ }
2547
+ return actorState.stateProxy;
2467
2548
  }
2468
2549
 
2469
2550
  set state(value: unknown) {
@@ -2471,6 +2552,7 @@ export class ActorContextHandleAdapter {
2471
2552
  throw stateNotEnabledError();
2472
2553
  }
2473
2554
  this.#assertCanMutateState();
2555
+ assertJsonCompatValue(value);
2474
2556
  this.#writeState(value, { scheduleSave: true });
2475
2557
  }
2476
2558
 
@@ -2537,27 +2619,15 @@ export class ActorContextHandleAdapter {
2537
2619
  return callNativeSync(() => this.#runtime.actorRegion(this.#ctx));
2538
2620
  }
2539
2621
 
2540
- get conns(): Map<string, NativeConnAdapter> {
2541
- return new Map(
2542
- callNativeSync(() => this.#runtime.actorConns(this.#ctx)).map(
2543
- (conn) => [
2544
- this.#runtime.connId(conn),
2545
- new NativeConnAdapter(
2546
- this.#runtime,
2547
- conn,
2548
- this.#schemas,
2549
- this.#ctx,
2550
- (connId) =>
2551
- callNativeSync(() =>
2552
- this.#runtime.actorQueueHibernationRemoval(
2553
- this.#ctx,
2554
- connId,
2555
- ),
2556
- ),
2557
- ),
2558
- ],
2559
- ),
2560
- );
2622
+ get conns(): ReadonlyMap<string, NativeConnAdapter> {
2623
+ if (!this.#connMap) {
2624
+ this.#connMap = new NativeConnectionMap(
2625
+ this.#runtime,
2626
+ this.#ctx,
2627
+ this.#schemas,
2628
+ );
2629
+ }
2630
+ return this.#connMap;
2561
2631
  }
2562
2632
 
2563
2633
  get log() {
@@ -2788,9 +2858,6 @@ export class ActorContextHandleAdapter {
2788
2858
  }
2789
2859
 
2790
2860
  keepAwake<T>(promise: Promise<T>): Promise<T> {
2791
- const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
2792
- runtimeState.keepAwakeCount =
2793
- (runtimeState.keepAwakeCount ?? 0) + 1;
2794
2861
  const trackedPromise = Promise.resolve(promise)
2795
2862
  .catch((error) => {
2796
2863
  logger().warn({
@@ -2798,32 +2865,12 @@ export class ActorContextHandleAdapter {
2798
2865
  error: stringifyError(error),
2799
2866
  });
2800
2867
  })
2801
- .finally(async () => {
2802
- runtimeState.keepAwakeCount = Math.max(
2803
- (runtimeState.keepAwakeCount ?? 1) - 1,
2804
- 0,
2805
- );
2806
- if (
2807
- runtimeState.keepAwakeCount === 0 &&
2808
- runtimeState.deferSleepCleanupUntilKeepAwakeIdle
2809
- ) {
2810
- runtimeState.deferSleepCleanupUntilKeepAwakeIdle = false;
2811
- await cleanupNativeSleepRuntimeState(
2812
- this.#runtime,
2813
- this.#ctx,
2814
- );
2815
- }
2816
- })
2817
2868
  .then(() => null);
2818
2869
  try {
2819
2870
  callNativeSync(() =>
2820
2871
  this.#runtime.actorKeepAwake(this.#ctx, trackedPromise),
2821
2872
  );
2822
2873
  } catch (error) {
2823
- runtimeState.keepAwakeCount = Math.max(
2824
- (runtimeState.keepAwakeCount ?? 1) - 1,
2825
- 0,
2826
- );
2827
2874
  if (!isClosedTaskRegistrationError(error)) {
2828
2875
  throw error;
2829
2876
  }
@@ -2837,7 +2884,15 @@ export class ActorContextHandleAdapter {
2837
2884
 
2838
2885
  internalKeepAwake<T>(run: Promise<T> | (() => Promise<T>)): Promise<T> {
2839
2886
  const promise = typeof run === "function" ? run() : run;
2840
- const trackedPromise = promise.then(() => null);
2887
+ // Track only completion, swallowing the outcome. The real result/error
2888
+ // is delivered through the returned `promise`; without a rejection
2889
+ // handler here every workflow yield (which rejects with SleepError)
2890
+ // would be funneled into the registered task and logged as a spurious
2891
+ // "keep_awake promise rejected" warning.
2892
+ const trackedPromise = promise.then(
2893
+ () => null,
2894
+ () => null,
2895
+ );
2841
2896
  try {
2842
2897
  callNativeSync(() =>
2843
2898
  this.#runtime.actorRegisterTask(this.#ctx, trackedPromise),
@@ -2899,6 +2954,7 @@ export class ActorContextHandleAdapter {
2899
2954
  }
2900
2955
 
2901
2956
  sleep(): void {
2957
+ this.#flushStateChange();
2902
2958
  callNativeSync(() => this.#runtime.actorSleep(this.#ctx));
2903
2959
  }
2904
2960
 
@@ -2922,6 +2978,9 @@ export class ActorContextHandleAdapter {
2922
2978
  }
2923
2979
 
2924
2980
  async dispose(): Promise<void> {
2981
+ // Flush any save coalesced for this tick before the context is torn
2982
+ // down so the request-save and onStateChange always run.
2983
+ this.#flushStateChange();
2925
2984
  this.#abortSignalCleanup?.();
2926
2985
  this.#sql = undefined;
2927
2986
  }
@@ -2957,13 +3016,12 @@ export class ActorContextHandleAdapter {
2957
3016
  scheduleSave: boolean;
2958
3017
  },
2959
3018
  ): void {
2960
- encodeValue(value);
2961
3019
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
2962
3020
  actorState.state = value;
2963
3021
  if (!options.scheduleSave) {
2964
3022
  return;
2965
3023
  }
2966
- this.#handleStateChange();
3024
+ this.#scheduleSave();
2967
3025
  }
2968
3026
 
2969
3027
  #assertCanMutateState(): void {
@@ -2973,9 +3031,33 @@ export class ActorContextHandleAdapter {
2973
3031
  }
2974
3032
  }
2975
3033
 
2976
- #handleStateChange(): void {
3034
+ // Coalesce the request-save and onStateChange work to once per event loop
3035
+ // tick. A synchronous burst of mutations (for example
3036
+ // `Object.assign(c.state, ...)`) would otherwise cross the NAPI boundary and
3037
+ // run onStateChange once per field, re-serializing the whole state each time
3038
+ // and pinning the event loop on large state.
3039
+ #scheduleSave(): void {
2977
3040
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
2978
- encodeValue(actorState.state);
3041
+ if (actorState.saveScheduled) {
3042
+ return;
3043
+ }
3044
+ actorState.saveScheduled = true;
3045
+ actorState.pendingSaveHandle = setImmediate(() => {
3046
+ this.#flushStateChange();
3047
+ });
3048
+ }
3049
+
3050
+ #flushStateChange(): void {
3051
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
3052
+ if (!actorState.saveScheduled) {
3053
+ return;
3054
+ }
3055
+ actorState.saveScheduled = false;
3056
+ if (actorState.pendingSaveHandle !== undefined) {
3057
+ clearImmediate(actorState.pendingSaveHandle);
3058
+ actorState.pendingSaveHandle = undefined;
3059
+ }
3060
+
2979
3061
  callNativeSync(() =>
2980
3062
  this.#runtime.actorRequestSave(this.#ctx, { immediate: false }),
2981
3063
  );
@@ -3240,55 +3322,10 @@ function withConnContext(
3240
3322
  );
3241
3323
  }
3242
3324
 
3243
- function buildNativeRequestErrorResponse(
3244
- encoding: Encoding,
3245
- path: string,
3246
- error: unknown,
3247
- ): Response {
3248
- const { statusCode, group, code, message, metadata } = deconstructError(
3249
- error,
3250
- logger(),
3251
- {
3252
- path,
3253
- runtime: "native",
3254
- },
3255
- false,
3256
- );
3257
- const body = serializeWithEncoding<
3258
- protocol.HttpResponseError,
3259
- HttpResponseErrorJson,
3260
- { group: string; code: string; message: string; metadata?: unknown }
3261
- >(
3262
- encoding,
3263
- { group, code, message, metadata },
3264
- HTTP_RESPONSE_ERROR_VERSIONED,
3265
- CLIENT_PROTOCOL_CURRENT_VERSION,
3266
- HttpResponseErrorSchema,
3267
- (value) => value,
3268
- (value) => ({
3269
- group: value.group,
3270
- code: value.code,
3271
- message: value.message,
3272
- metadata:
3273
- value.metadata === undefined
3274
- ? null
3275
- : runtimeBytesToArrayBuffer(
3276
- encodeCborCompat(value.metadata),
3277
- ),
3278
- }),
3279
- );
3280
-
3281
- return new Response(body, {
3282
- status: statusCode,
3283
- headers: {
3284
- "Content-Type": contentTypeForEncoding(encoding),
3285
- },
3286
- });
3287
- }
3288
-
3289
3325
  function buildActorConfig(
3290
3326
  definition: AnyActorDefinition,
3291
3327
  registryConfig: RegistryConfig,
3328
+ runtimeKind: "napi" | "wasm",
3292
3329
  ): RuntimeActorConfig {
3293
3330
  const config = definition.config as unknown as Record<string, unknown>;
3294
3331
  const options = (config.options ?? {}) as Record<string, unknown>;
@@ -3301,6 +3338,7 @@ function buildActorConfig(
3301
3338
  remoteSqlite:
3302
3339
  config.db !== undefined &&
3303
3340
  sqliteBackendForConfig(registryConfig) === "remote",
3341
+ experimentalActorUds: registryConfig.experimentalActorUds,
3304
3342
  hasState:
3305
3343
  config.state !== undefined ||
3306
3344
  typeof config.createState === "function",
@@ -3343,9 +3381,100 @@ function buildActorConfig(
3343
3381
  actions: Object.keys((config.actions ?? {}) as Record<string, unknown>)
3344
3382
  .sort()
3345
3383
  .map((name) => ({ name })),
3384
+ inspectorTabs: buildInspectorTabs(config.inspector, runtimeKind),
3346
3385
  };
3347
3386
  }
3348
3387
 
3388
+ function buildInspectorTabs(
3389
+ inspector: unknown,
3390
+ runtimeKind: "napi" | "wasm",
3391
+ ): Array<RuntimeInspectorTabEntry> | undefined {
3392
+ if (!inspector || typeof inspector !== "object") return undefined;
3393
+ const tabs = (inspector as { tabs?: unknown }).tabs;
3394
+ if (!Array.isArray(tabs) || tabs.length === 0) return undefined;
3395
+ return tabs.map((raw) => {
3396
+ const entry = raw as {
3397
+ id: string;
3398
+ label?: string;
3399
+ source?: string;
3400
+ icon?: string;
3401
+ hidden?: boolean;
3402
+ };
3403
+ if (entry.hidden === true) {
3404
+ return { id: entry.id, hidden: true };
3405
+ }
3406
+
3407
+ if (runtimeKind === "wasm") {
3408
+ if (entry.source !== undefined) {
3409
+ logger().warn(
3410
+ {
3411
+ tabId: entry.id,
3412
+ runtimeKind,
3413
+ },
3414
+ "inspector.tabs[].source is not supported on wasm runners (current host: wasm). Tab descriptors will still appear in the dashboard strip but the tab body will render a not-available placeholder.",
3415
+ );
3416
+ }
3417
+ return {
3418
+ id: entry.id,
3419
+ label: entry.label,
3420
+ icon: entry.icon,
3421
+ source: undefined,
3422
+ };
3423
+ }
3424
+
3425
+ const resolved =
3426
+ entry.source !== undefined
3427
+ ? getNodePath().resolve(entry.source)
3428
+ : undefined;
3429
+ if (resolved !== undefined) {
3430
+ validateInspectorTabSource(entry.id, resolved);
3431
+ }
3432
+ return {
3433
+ id: entry.id,
3434
+ label: entry.label,
3435
+ icon: entry.icon,
3436
+ source: resolved,
3437
+ };
3438
+ });
3439
+ }
3440
+
3441
+ function validateInspectorTabSource(tabId: string, resolved: string): void {
3442
+ if (resolved === getNodePath().parse(resolved).root) {
3443
+ throw new Error(
3444
+ `inspector.tabs[id="${tabId}"].source resolves to the filesystem root (${resolved}). ` +
3445
+ "Point it at the tab's own static-asset directory instead.",
3446
+ );
3447
+ }
3448
+ let stat: import("node:fs").Stats;
3449
+ try {
3450
+ stat = getNodeFsSync().statSync(resolved);
3451
+ } catch (err) {
3452
+ const code = (err as NodeJS.ErrnoException)?.code;
3453
+ if (code === "ENOENT") {
3454
+ throw new Error(
3455
+ `inspector.tabs[id="${tabId}"].source (${resolved}) does not exist.`,
3456
+ );
3457
+ }
3458
+ if (code === "EACCES") {
3459
+ throw new Error(
3460
+ `inspector.tabs[id="${tabId}"].source (${resolved}) is not readable (EACCES).`,
3461
+ );
3462
+ }
3463
+ throw new Error(
3464
+ `inspector.tabs[id="${tabId}"].source (${resolved}) could not be stat'd: ${
3465
+ (err as Error)?.message ?? err
3466
+ }`,
3467
+ );
3468
+ }
3469
+ if (!stat.isDirectory()) {
3470
+ throw new Error(
3471
+ `inspector.tabs[id="${tabId}"].source (${resolved}) must be a directory, got ${
3472
+ stat.isFile() ? "file" : "non-directory"
3473
+ }.`,
3474
+ );
3475
+ }
3476
+ }
3477
+
3349
3478
  export function buildNativeFactory(
3350
3479
  runtime: CoreRuntime,
3351
3480
  registryConfig: RegistryConfig,
@@ -3477,15 +3606,24 @@ export function buildNativeFactory(
3477
3606
  },
3478
3607
  );
3479
3608
  };
3480
- try {
3481
- await runtime.actorVerifyInspectorAuth(
3482
- ctx,
3483
- jsRequest.headers
3484
- .get("authorization")
3485
- ?.replace(/^Bearer\s+/i, "") ?? null,
3486
- );
3487
- } catch (error) {
3488
- return errorResponse(error, 401);
3609
+
3610
+ // Tab config is delivered over the inspector WS `Init` message, not
3611
+ // HTTP. Only custom-tab assets remain a public per-actor path.
3612
+ const isPublicPerActorPath =
3613
+ jsRequest.method === "GET" &&
3614
+ url.pathname.startsWith("/inspector/custom-tabs/");
3615
+
3616
+ if (!isPublicPerActorPath) {
3617
+ try {
3618
+ await runtime.actorVerifyInspectorAuth(
3619
+ ctx,
3620
+ jsRequest.headers
3621
+ .get("authorization")
3622
+ ?.replace(/^Bearer\s+/i, "") ?? null,
3623
+ );
3624
+ } catch (error) {
3625
+ return errorResponse(error, 401);
3626
+ }
3489
3627
  }
3490
3628
 
3491
3629
  const workflowHistory = () =>
@@ -3568,6 +3706,56 @@ export function buildNativeFactory(
3568
3706
  messages,
3569
3707
  });
3570
3708
  }
3709
+ if (
3710
+ url.pathname === "/inspector/queue" &&
3711
+ jsRequest.method === "DELETE"
3712
+ ) {
3713
+ await runtime.actorQueueReset(ctx);
3714
+ return jsonResponse({});
3715
+ }
3716
+ if (
3717
+ url.pathname === "/inspector/queue" &&
3718
+ jsRequest.method === "POST"
3719
+ ) {
3720
+ let body: { name?: string; body?: unknown };
3721
+ try {
3722
+ body = (await jsRequest.json()) as {
3723
+ name?: string;
3724
+ body?: unknown;
3725
+ };
3726
+ } catch {
3727
+ return errorResponse(
3728
+ new RivetError(
3729
+ "actor",
3730
+ "invalid_request",
3731
+ "Invalid inspector JSON body",
3732
+ { public: true },
3733
+ ),
3734
+ 400,
3735
+ );
3736
+ }
3737
+ const name = body.name ?? "";
3738
+ if (name === "") {
3739
+ return errorResponse(
3740
+ new RivetError(
3741
+ "actor",
3742
+ "invalid_request",
3743
+ "Queue message name must not be empty",
3744
+ { public: true },
3745
+ ),
3746
+ 400,
3747
+ );
3748
+ }
3749
+ const cbor = encodeCborCompat(
3750
+ (body.body ?? null) as JsonCompatValue,
3751
+ );
3752
+ const message = await runtime.actorQueueSend(ctx, name, cbor);
3753
+ return jsonResponse({
3754
+ id: message.id().toString(),
3755
+ name: message.name(),
3756
+ createdAtMs: message.createdAt(),
3757
+ });
3758
+ }
3571
3759
  if (
3572
3760
  url.pathname === "/inspector/traces" &&
3573
3761
  jsRequest.method === "GET"
@@ -3605,6 +3793,10 @@ export function buildNativeFactory(
3605
3793
  getNativeWorkflowInspector(ctx) !== undefined,
3606
3794
  });
3607
3795
  } catch (error) {
3796
+ logger().error({
3797
+ msg: "error replaying workflow history",
3798
+ error,
3799
+ });
3608
3800
  return errorResponse(error);
3609
3801
  }
3610
3802
  }
@@ -3772,18 +3964,46 @@ export function buildNativeFactory(
3772
3964
  404,
3773
3965
  );
3774
3966
  }
3775
- const body = (await jsRequest.json()) as { args?: unknown[] };
3967
+ const body = (await jsRequest.json()) as {
3968
+ args?: unknown;
3969
+ properties?: unknown;
3970
+ };
3971
+ if (body.args !== undefined && body.properties !== undefined) {
3972
+ return jsonResponse(
3973
+ { error: "use either args or properties, not both" },
3974
+ { status: 400 },
3975
+ );
3976
+ }
3977
+ if (
3978
+ body.properties !== undefined &&
3979
+ (body.properties === null ||
3980
+ typeof body.properties !== "object" ||
3981
+ Array.isArray(body.properties))
3982
+ ) {
3983
+ return jsonResponse(
3984
+ { error: "properties must be an object" },
3985
+ { status: 400 },
3986
+ );
3987
+ }
3988
+ const args =
3989
+ body.properties !== undefined
3990
+ ? [body.properties]
3991
+ : normalizeArgs(body.args);
3776
3992
  try {
3777
3993
  const output = await action(
3778
3994
  actorCtx,
3779
3995
  ...validateActionArgs(
3780
3996
  schemaConfig.actionInputSchemas,
3781
3997
  actionName,
3782
- body.args ?? [],
3998
+ args,
3783
3999
  ),
3784
4000
  );
3785
4001
  return jsonResponse({ output });
3786
4002
  } catch (error) {
4003
+ logger().error({
4004
+ msg: "Error handling inspector action request",
4005
+ error,
4006
+ });
3787
4007
  return errorResponse(error);
3788
4008
  }
3789
4009
  }
@@ -3798,6 +4018,10 @@ export function buildNativeFactory(
3798
4018
  { status: 404 },
3799
4019
  );
3800
4020
  } catch (error) {
4021
+ logger().error({
4022
+ msg: "Error handling inspector request",
4023
+ error,
4024
+ });
3801
4025
  return errorResponse(error);
3802
4026
  } finally {
3803
4027
  await actorCtx.dispose();
@@ -3970,32 +4194,38 @@ export function buildNativeFactory(
3970
4194
  async (error: unknown, payload: { ctx: ActorContextHandle }) => {
3971
4195
  const { ctx } = unwrapTsfnPayload(error, payload);
3972
4196
  const actorCtx = makeActorCtx(ctx);
4197
+ // TODO: Move this save hook into cleanupNativeSleepRuntimeState
4198
+ // so immediate and deferred sleep cleanup share one save-state
4199
+ // path instead of passing a callback through cleanup.
4200
+ const saveActorState = async () => {
4201
+ if (runtime.kind === "wasm") {
4202
+ // Wasm cannot use the native context save helper here because
4203
+ // the runtime owns the serialized state handoff.
4204
+ await runtime.actorSaveState(
4205
+ ctx,
4206
+ actorCtx.serializeForTick("save"),
4207
+ );
4208
+ } else {
4209
+ await actorCtx.saveState({
4210
+ immediate: true,
4211
+ });
4212
+ }
4213
+ };
3973
4214
  try {
3974
4215
  if (onSleep) {
3975
- try {
3976
- await onSleep(actorCtx);
3977
- } finally {
3978
- if (runtime.kind === "wasm") {
3979
- // Wasm cannot use the native context save helper here because
3980
- // the runtime owns the serialized state handoff.
3981
- await runtime.actorSaveState(
3982
- ctx,
3983
- actorCtx.serializeForTick("save"),
3984
- );
3985
- } else {
3986
- await actorCtx.saveState({ immediate: true });
3987
- }
3988
- }
4216
+ await onSleep(actorCtx);
3989
4217
  }
4218
+ await saveActorState();
3990
4219
  } finally {
3991
- const runtimeState = getNativeRuntimeState(runtime, ctx);
3992
- if ((runtimeState.keepAwakeCount ?? 0) > 0) {
3993
- runtimeState.deferSleepCleanupUntilKeepAwakeIdle =
3994
- true;
3995
- } else {
3996
- await cleanupNativeSleepRuntimeState(runtime, ctx);
4220
+ try {
4221
+ await cleanupNativeSleepRuntimeState(
4222
+ runtime,
4223
+ ctx,
4224
+ saveActorState,
4225
+ );
4226
+ } finally {
4227
+ await actorCtx.dispose();
3997
4228
  }
3998
- await actorCtx.dispose();
3999
4229
  }
4000
4230
  },
4001
4231
  ),
@@ -4008,6 +4238,11 @@ export function buildNativeFactory(
4008
4238
  await config.onDestroy(actorCtx);
4009
4239
  }
4010
4240
  } finally {
4241
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
4242
+ // Release actorId-keyed state so it does not accumulate per
4243
+ // destroyed actor.
4244
+ nativeRunHandlerActiveByActorId.delete(actorId);
4245
+ disposeRunInspector(config.run, actorId);
4011
4246
  resolveNativeDestroy(runtime, ctx);
4012
4247
  await actorCtx.closeDatabase();
4013
4248
  clearNativeRuntimeState(runtime, ctx);
@@ -4341,22 +4576,6 @@ export function buildNativeFactory(
4341
4576
  );
4342
4577
  }
4343
4578
  return await toRuntimeHttpResponse(response);
4344
- } catch (error) {
4345
- const encodingHeader =
4346
- jsRequest.headers.get(HEADER_ENCODING);
4347
- const encoding: Encoding =
4348
- encodingHeader === "cbor" ||
4349
- encodingHeader === "bare"
4350
- ? encodingHeader
4351
- : "json";
4352
- const path = new URL(jsRequest.url).pathname;
4353
- return await toRuntimeHttpResponse(
4354
- buildNativeRequestErrorResponse(
4355
- encoding,
4356
- path,
4357
- error,
4358
- ),
4359
- );
4360
4579
  } finally {
4361
4580
  await requestCtx?.dispose();
4362
4581
  if (conn) {
@@ -4427,7 +4646,11 @@ export function buildNativeFactory(
4427
4646
  try {
4428
4647
  await run(actorCtx);
4429
4648
  } finally {
4430
- nativeRunHandlerActiveByActorId.set(actorId, false);
4649
+ // Delete rather than set(false): an absent entry already
4650
+ // reads as inactive, and deleting keeps this map bounded
4651
+ // to currently-running handlers instead of accumulating an
4652
+ // entry per actor id forever.
4653
+ nativeRunHandlerActiveByActorId.delete(actorId);
4431
4654
  await actorCtx.dispose();
4432
4655
  }
4433
4656
  },
@@ -4638,7 +4861,7 @@ export function buildNativeFactory(
4638
4861
 
4639
4862
  return runtime.createActorFactory(
4640
4863
  callbacks,
4641
- buildActorConfig(definition, registryConfig),
4864
+ buildActorConfig(definition, registryConfig, runtime.kind),
4642
4865
  );
4643
4866
  }
4644
4867
 
@@ -4665,10 +4888,29 @@ export async function buildServeConfig(
4665
4888
  serverlessMaxStartPayloadBytes: config.serverless.maxStartPayloadBytes,
4666
4889
  };
4667
4890
 
4668
- if (config.startEngine) {
4891
+ // Always best-effort resolve the npm-installed engine binary and hand its
4892
+ // path to the core. The core alone decides whether to actually spawn a local
4893
+ // engine (its `should_manage_engine`, based on the endpoint + spawn mode), so
4894
+ // JS must not duplicate that decision here. Only JS knows the npm
4895
+ // `node_modules` layout, so it resolves the path; if no binary is available
4896
+ // (remote-only install, unsupported platform, optional deps skipped), leave
4897
+ // it unset and let the core report `engine.binary_unavailable` if it actually
4898
+ // needs one.
4899
+ try {
4669
4900
  const { getEnginePath } = await loadEngineCli();
4670
4901
  serveConfig.engineBinaryPath = getEnginePath();
4902
+ } catch (error) {
4903
+ // The npm-installed engine binary could not be resolved. The core still
4904
+ // decides whether it needs to spawn a local engine; if it does, it will
4905
+ // fail with engine.binary_unavailable (auto-download is off in the napi
4906
+ // runtime). Warn so the cause is actionable.
4907
+ logger().warn({
4908
+ msg: "could not resolve a local engine binary; if a local engine must be spawned it will fail with engine.binary_unavailable — set RIVET_ENGINE_BINARY_PATH or install the @rivetkit/engine-cli platform package",
4909
+ error: stringifyError(error),
4910
+ });
4671
4911
  }
4912
+ serveConfig.engineHost = config.engineHost;
4913
+ serveConfig.enginePort = config.enginePort;
4672
4914
  if (config.test?.enabled) {
4673
4915
  serveConfig.inspectorTestToken =
4674
4916
  getEnvUniversal("_RIVET_TEST_INSPECTOR_TOKEN") ?? "token";
@@ -4692,6 +4934,13 @@ export async function buildRegistryWithRuntime(
4692
4934
  trySetProcessEnv("_RIVET_TEST_INSPECTOR_TOKEN", "token");
4693
4935
  }
4694
4936
 
4937
+ // Custom inspector tab `source` paths are resolved with node:path while
4938
+ // building actor configs below, so the Node modules must be loaded first.
4939
+ // Native (napi) runtime only; wasm has no filesystem.
4940
+ if (runtime.kind === "napi") {
4941
+ importNodeDependencies();
4942
+ }
4943
+
4695
4944
  const registry = runtime.createRegistry();
4696
4945
 
4697
4946
  for (const [name, definition] of Object.entries(config.use)) {