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
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Node.js runtime health metrics.
3
+ *
4
+ * Collects JS-internal data (event loop lag, GC, heap, libuv handles,
5
+ * event loop utilization, CPU) using Node built-ins (`node:perf_hooks`,
6
+ * `process`, `node:v8`, `PerformanceObserver`) and pushes them across NAPI
7
+ * into Rust-side prometheus collectors registered with
8
+ * `rivet_metrics::REGISTRY` so they appear on the existing `/metrics`
9
+ * endpoint.
10
+ *
11
+ * All data collection happens here in TypeScript. The NAPI bridge is pure
12
+ * type marshalling and the Rust side only registers + stores the metrics.
13
+ */
14
+ import {
15
+ monitorEventLoopDelay,
16
+ PerformanceObserver,
17
+ performance,
18
+ } from "node:perf_hooks";
19
+ import { getHeapStatistics } from "node:v8";
20
+ import * as napi from "@rivetkit/rivetkit-napi";
21
+
22
+ type OptionalProcessMetricsNapi = typeof napi & {
23
+ jsObserveGcDuration?: (kind: string, durationSeconds: number) => void;
24
+ jsSetEventloopHeartbeatTsMs?: (timestampMs: number) => void;
25
+ jsSetEventloopLagQuantile?: (
26
+ quantile: string,
27
+ valueSeconds: number,
28
+ ) => void;
29
+ jsSetEventloopUtilization?: (utilization: number) => void;
30
+ jsAddProcessCpuSeconds?: (mode: string, valueSeconds: number) => void;
31
+ jsSetProcessResidentMemoryBytes?: (bytes: number) => void;
32
+ jsSetHeapBytes?: (kind: string, bytes: number) => void;
33
+ jsSetActiveHandles?: (count: number) => void;
34
+ jsSetActiveRequests?: (count: number) => void;
35
+ };
36
+
37
+ type GcPerformanceEntry = {
38
+ duration: number;
39
+ detail?: { kind?: number };
40
+ kind?: number;
41
+ };
42
+
43
+ const processMetricsNapi = napi as OptionalProcessMetricsNapi;
44
+
45
+ // Some napi process-metrics symbols may be missing on older native binaries
46
+ // (the auto-generated index.js destructures them as `undefined` if the
47
+ // underlying `.node` was built before they were added). Guard each call so
48
+ // the metrics collection runs as a no-op instead of throwing
49
+ // `TypeError: napi.jsXxx is not a function` on every interval tick.
50
+ function callIfFn<T extends unknown[]>(
51
+ fn: ((...args: T) => void) | undefined,
52
+ ...args: T
53
+ ): void {
54
+ if (typeof fn === "function") {
55
+ fn(...args);
56
+ }
57
+ }
58
+
59
+ const SCRAPE_INTERVAL_MS = 5_000;
60
+ const HEARTBEAT_INTERVAL_MS = 100;
61
+ const EVENTLOOP_DELAY_RESOLUTION_MS = 20;
62
+ const NS_PER_SECOND = 1e9;
63
+ const US_PER_SECOND = 1e6;
64
+
65
+ // V8 GC kind bitfield from Node's perf_hooks documentation. A `gc` performance
66
+ // entry's `kind` field is one of these values.
67
+ const GC_KIND_NAMES: Record<number, string> = {
68
+ 1: "minor",
69
+ 2: "major",
70
+ 4: "incremental",
71
+ 8: "weakcb",
72
+ };
73
+
74
+ interface ProcessMetricsState {
75
+ scrapeInterval: NodeJS.Timeout;
76
+ heartbeatInterval: NodeJS.Timeout;
77
+ gcObserver: PerformanceObserver;
78
+ eventLoopHistogram: ReturnType<typeof monitorEventLoopDelay>;
79
+ lastCpuUsage: NodeJS.CpuUsage;
80
+ lastEventLoopUtilization: ReturnType<
81
+ typeof performance.eventLoopUtilization
82
+ >;
83
+ }
84
+
85
+ let state: ProcessMetricsState | undefined;
86
+
87
+ export function startProcessMetrics(): void {
88
+ if (state) {
89
+ return;
90
+ }
91
+
92
+ const eventLoopHistogram = monitorEventLoopDelay({
93
+ resolution: EVENTLOOP_DELAY_RESOLUTION_MS,
94
+ });
95
+ eventLoopHistogram.enable();
96
+
97
+ const gcObserver = new PerformanceObserver((list) => {
98
+ for (const entry of list.getEntries()) {
99
+ const gcEntry = entry as GcPerformanceEntry;
100
+ const kind = gcEntry.detail?.kind ?? gcEntry.kind;
101
+ if (typeof kind !== "number") continue;
102
+ const kindName = GC_KIND_NAMES[kind];
103
+ if (!kindName) continue;
104
+ // `entry.duration` is in milliseconds; convert to seconds.
105
+ callIfFn(
106
+ processMetricsNapi.jsObserveGcDuration,
107
+ kindName,
108
+ gcEntry.duration / 1000,
109
+ );
110
+ }
111
+ });
112
+ gcObserver.observe({ entryTypes: ["gc"], buffered: false });
113
+
114
+ const lastCpuUsage = process.cpuUsage();
115
+ const lastEventLoopUtilization = performance.eventLoopUtilization();
116
+
117
+ const heartbeatInterval = setInterval(() => {
118
+ callIfFn(processMetricsNapi.jsSetEventloopHeartbeatTsMs, Date.now());
119
+ }, HEARTBEAT_INTERVAL_MS);
120
+ heartbeatInterval.unref();
121
+
122
+ const scrapeInterval = setInterval(() => {
123
+ try {
124
+ collectAndPush();
125
+ } catch {
126
+ // Collection errors must never bring down the process; metrics
127
+ // are best-effort.
128
+ }
129
+ }, SCRAPE_INTERVAL_MS);
130
+ scrapeInterval.unref();
131
+
132
+ state = {
133
+ scrapeInterval,
134
+ heartbeatInterval,
135
+ gcObserver,
136
+ eventLoopHistogram,
137
+ lastCpuUsage,
138
+ lastEventLoopUtilization,
139
+ };
140
+
141
+ // Emit one snapshot immediately so freshly-scraped instances have data.
142
+ callIfFn(processMetricsNapi.jsSetEventloopHeartbeatTsMs, Date.now());
143
+ try {
144
+ collectAndPush();
145
+ } catch {
146
+ // As above; best-effort.
147
+ }
148
+ }
149
+
150
+ export function stopProcessMetrics(): void {
151
+ if (!state) {
152
+ return;
153
+ }
154
+ clearInterval(state.scrapeInterval);
155
+ clearInterval(state.heartbeatInterval);
156
+ state.gcObserver.disconnect();
157
+ state.eventLoopHistogram.disable();
158
+ state = undefined;
159
+ }
160
+
161
+ function collectAndPush(): void {
162
+ if (!state) return;
163
+
164
+ // Event loop delay quantiles. `monitorEventLoopDelay()` reports values in
165
+ // nanoseconds; convert to seconds. Reset after reading so the next window
166
+ // reflects only the new interval.
167
+ const hist = state.eventLoopHistogram;
168
+ callIfFn(
169
+ processMetricsNapi.jsSetEventloopLagQuantile,
170
+ "p50",
171
+ hist.percentile(50) / NS_PER_SECOND,
172
+ );
173
+ callIfFn(
174
+ processMetricsNapi.jsSetEventloopLagQuantile,
175
+ "p90",
176
+ hist.percentile(90) / NS_PER_SECOND,
177
+ );
178
+ callIfFn(
179
+ processMetricsNapi.jsSetEventloopLagQuantile,
180
+ "p99",
181
+ hist.percentile(99) / NS_PER_SECOND,
182
+ );
183
+ callIfFn(
184
+ processMetricsNapi.jsSetEventloopLagQuantile,
185
+ "max",
186
+ hist.max / NS_PER_SECOND,
187
+ );
188
+ hist.reset();
189
+
190
+ // Event loop utilization delta over the scrape window.
191
+ const nextElu = performance.eventLoopUtilization();
192
+ const eluDelta = performance.eventLoopUtilization(
193
+ nextElu,
194
+ state.lastEventLoopUtilization,
195
+ );
196
+ state.lastEventLoopUtilization = nextElu;
197
+ callIfFn(
198
+ processMetricsNapi.jsSetEventloopUtilization,
199
+ eluDelta.utilization,
200
+ );
201
+
202
+ // CPU usage delta. `process.cpuUsage()` returns microseconds.
203
+ const nextCpu = process.cpuUsage();
204
+ const userDeltaUs = nextCpu.user - state.lastCpuUsage.user;
205
+ const systemDeltaUs = nextCpu.system - state.lastCpuUsage.system;
206
+ state.lastCpuUsage = nextCpu;
207
+ if (userDeltaUs > 0) {
208
+ callIfFn(
209
+ processMetricsNapi.jsAddProcessCpuSeconds,
210
+ "user",
211
+ userDeltaUs / US_PER_SECOND,
212
+ );
213
+ }
214
+ if (systemDeltaUs > 0) {
215
+ callIfFn(
216
+ processMetricsNapi.jsAddProcessCpuSeconds,
217
+ "system",
218
+ systemDeltaUs / US_PER_SECOND,
219
+ );
220
+ }
221
+
222
+ // Memory + heap.
223
+ const mem = process.memoryUsage();
224
+ callIfFn(processMetricsNapi.jsSetProcessResidentMemoryBytes, mem.rss);
225
+ callIfFn(processMetricsNapi.jsSetHeapBytes, "used", mem.heapUsed);
226
+ callIfFn(processMetricsNapi.jsSetHeapBytes, "total", mem.heapTotal);
227
+ const heapLimit = getHeapStatistics().heap_size_limit;
228
+ callIfFn(processMetricsNapi.jsSetHeapBytes, "limit", heapLimit);
229
+
230
+ // libuv active handles + requests. These are unstable Node internals
231
+ // guarded behind underscore-prefixed names; if a future Node release
232
+ // removes them the try/catch above keeps the rest of the collection
233
+ // alive.
234
+ const proc = process as unknown as {
235
+ _getActiveHandles?: () => unknown[];
236
+ _getActiveRequests?: () => unknown[];
237
+ };
238
+ if (typeof proc._getActiveHandles === "function") {
239
+ callIfFn(
240
+ processMetricsNapi.jsSetActiveHandles,
241
+ proc._getActiveHandles().length,
242
+ );
243
+ }
244
+ if (typeof proc._getActiveRequests === "function") {
245
+ callIfFn(
246
+ processMetricsNapi.jsSetActiveRequests,
247
+ proc._getActiveRequests().length,
248
+ );
249
+ }
250
+ }
@@ -1,5 +1,7 @@
1
+ import { stringifyError } from "@/common/utils";
1
2
  import type { SqliteNativeMetrics } from "@/common/database/config";
2
3
  import type { RegistryConfig } from "./config";
4
+ import { logger } from "./log";
3
5
 
4
6
  declare const handleBrand: unique symbol;
5
7
 
@@ -150,6 +152,16 @@ export type RuntimeSqlBindParam =
150
152
 
151
153
  export type RuntimeSqlBindParams = RuntimeSqlBindParam[] | null;
152
154
 
155
+ export interface RuntimeSqlLeaseOptions {
156
+ key: string;
157
+ timeoutMs?: number;
158
+ }
159
+
160
+ export interface RuntimeActorUdsEndpointInfo {
161
+ path: string;
162
+ token: string;
163
+ }
164
+
153
165
  export interface RuntimeSqlQueryResult {
154
166
  columns: string[];
155
167
  rows: unknown[][];
@@ -199,6 +211,7 @@ export interface RuntimeActorConfig {
199
211
  icon?: string;
200
212
  hasDatabase?: boolean;
201
213
  remoteSqlite?: boolean;
214
+ experimentalActorUds?: boolean;
202
215
  hasState?: boolean;
203
216
  canHibernateWebsocket?: boolean;
204
217
  stateSaveIntervalMs?: number;
@@ -225,6 +238,22 @@ export interface RuntimeActorConfig {
225
238
  preloadMaxWorkflowBytes?: number;
226
239
  preloadMaxConnectionsBytes?: number;
227
240
  actions?: Array<{ name: string }>;
241
+ inspectorTabs?: Array<RuntimeInspectorTabEntry>;
242
+ }
243
+
244
+ export interface RuntimeInspectorTabEntry {
245
+ id: string;
246
+ /** Required for custom entries; omitted for built-in hides. */
247
+ label?: string;
248
+ /**
249
+ * Required for custom entries — absolute path to the source directory.
250
+ * Resolved on the TS side before being handed to the runtime.
251
+ */
252
+ source?: string;
253
+ /** Optional icon id for custom entries. */
254
+ icon?: string;
255
+ /** Set to true for built-in hide entries. */
256
+ hidden?: boolean;
228
257
  }
229
258
 
230
259
  export interface RuntimeServeConfig {
@@ -234,6 +263,8 @@ export interface RuntimeServeConfig {
234
263
  namespace: string;
235
264
  poolName: string;
236
265
  engineBinaryPath?: string;
266
+ engineHost?: string;
267
+ enginePort?: number;
237
268
  handleInspectorHttpInRuntime?: boolean;
238
269
  inspectorTestToken?: string;
239
270
  serverlessBasePath?: string;
@@ -245,6 +276,12 @@ export interface RuntimeServeConfig {
245
276
  serverlessMaxStartPayloadBytes: number;
246
277
  }
247
278
 
279
+ export interface RuntimeListenerConfig {
280
+ port: number;
281
+ host?: string;
282
+ publicDir?: string;
283
+ }
284
+
248
285
  export interface RuntimeServerlessRequest {
249
286
  method: string;
250
287
  url: string;
@@ -257,9 +294,10 @@ export interface RuntimeServerlessResponseHead {
257
294
  headers: Record<string, string>;
258
295
  }
259
296
 
260
- export interface RuntimeRegistryDiagnostics {
261
- mode: string;
262
- envoyActiveActorCount?: number | null;
297
+ export interface RuntimeRegistryRouteResponse {
298
+ status: number;
299
+ headers: Record<string, string>;
300
+ body: RuntimeBytes;
263
301
  }
264
302
 
265
303
  export type RuntimeServerlessStreamEvent =
@@ -309,6 +347,9 @@ export interface CoreRuntime {
309
347
  config: RuntimeServeConfig,
310
348
  ): Promise<void>;
311
349
  shutdownRegistry(registry: RegistryHandle): Promise<void>;
350
+ registryActorStopThresholdMs?(
351
+ registry: RegistryHandle,
352
+ ): Promise<number | undefined>;
312
353
  handleServerlessRequest(
313
354
  registry: RegistryHandle,
314
355
  req: RuntimeServerlessRequest,
@@ -316,9 +357,20 @@ export interface CoreRuntime {
316
357
  cancelToken: CancellationTokenHandle,
317
358
  config: RuntimeServeConfig,
318
359
  ): Promise<RuntimeServerlessResponseHead>;
319
- registryDiagnostics?(
360
+ serveListener(
361
+ registry: RegistryHandle,
362
+ listener: RuntimeListenerConfig,
363
+ config: RuntimeServeConfig,
364
+ ): Promise<void>;
365
+ registryHealth?(
366
+ registry: RegistryHandle,
367
+ ): Promise<RuntimeRegistryRouteResponse>;
368
+ registryMetadata?(
320
369
  registry: RegistryHandle,
321
- ): Promise<RuntimeRegistryDiagnostics>;
370
+ ): Promise<RuntimeRegistryRouteResponse>;
371
+ registryMetrics?(
372
+ registry: RegistryHandle,
373
+ ): Promise<RuntimeRegistryRouteResponse>;
322
374
  createActorFactory(
323
375
  callbacks: object,
324
376
  config?: RuntimeActorConfig | undefined | null,
@@ -388,6 +440,10 @@ export interface CoreRuntime {
388
440
  args: RuntimeBytes,
389
441
  ): void;
390
442
  actorWaitUntil(ctx: ActorContextHandle, promise: Promise<unknown>): void;
443
+ actorWaitForTrackedShutdownWork(ctx: ActorContextHandle): Promise<boolean>;
444
+ actorWaitForTrackedShutdownWorkUnbounded(
445
+ ctx: ActorContextHandle,
446
+ ): Promise<void>;
391
447
  actorKeepAwake(ctx: ActorContextHandle, promise: Promise<unknown>): void;
392
448
  actorBeginKeepAwake(ctx: ActorContextHandle): number;
393
449
  actorEndKeepAwake(ctx: ActorContextHandle, regionId: number): void;
@@ -440,11 +496,13 @@ export interface CoreRuntime {
440
496
  actorSqlExec(
441
497
  ctx: ActorContextHandle,
442
498
  sql: string,
499
+ lease?: RuntimeSqlLeaseOptions,
443
500
  ): Promise<RuntimeSqlExecResult>;
444
501
  actorSqlExecute(
445
502
  ctx: ActorContextHandle,
446
503
  sql: string,
447
504
  params?: RuntimeSqlBindParams,
505
+ lease?: RuntimeSqlLeaseOptions,
448
506
  ): Promise<RuntimeSqlExecuteResult>;
449
507
  actorSqlQuery(
450
508
  ctx: ActorContextHandle,
@@ -459,6 +517,9 @@ export interface CoreRuntime {
459
517
  actorSqlMetrics(ctx: ActorContextHandle): SqliteNativeMetrics | null;
460
518
  actorSqlTakeLastKvError(ctx: ActorContextHandle): string | null;
461
519
  actorSqlClose(ctx: ActorContextHandle): Promise<void>;
520
+ actorUdsProvision(
521
+ ctx: ActorContextHandle,
522
+ ): Promise<RuntimeActorUdsEndpointInfo>;
462
523
 
463
524
  actorQueueSend(
464
525
  ctx: ActorContextHandle,
@@ -480,6 +541,7 @@ export interface CoreRuntime {
480
541
  ctx: ActorContextHandle,
481
542
  names: string[],
482
543
  options?: RuntimeQueueWaitOptions | undefined | null,
544
+ signal?: CancellationTokenHandle | undefined | null,
483
545
  ): Promise<void>;
484
546
  actorQueueEnqueueAndWait(
485
547
  ctx: ActorContextHandle,
@@ -496,6 +558,7 @@ export interface CoreRuntime {
496
558
  actorQueueInspectMessages(
497
559
  ctx: ActorContextHandle,
498
560
  ): Promise<RuntimeQueueInspectMessage[]>;
561
+ actorQueueReset(ctx: ActorContextHandle): Promise<void>;
499
562
 
500
563
  actorScheduleAfter(
501
564
  ctx: ActorContextHandle,
@@ -566,9 +629,25 @@ export async function buildServeConfig(
566
629
  serverlessMaxStartPayloadBytes: config.serverless.maxStartPayloadBytes,
567
630
  };
568
631
 
569
- if (config.startEngine) {
632
+ // Always best-effort resolve the engine binary path and hand it to the core.
633
+ // The core alone decides whether to actually spawn a local engine, so JS must
634
+ // not duplicate that decision here. `loadEnginePath` throws when no binary is
635
+ // available (remote-only install, unsupported platform, optional deps
636
+ // skipped); in that case leave it unset and let the core report
637
+ // `engine.binary_unavailable` only if it actually needs one.
638
+ try {
570
639
  serveConfig.engineBinaryPath = await loadEnginePath();
640
+ } catch (error) {
641
+ // The engine binary could not be resolved. The core still decides whether
642
+ // it needs to spawn a local engine; if it does, it will fail with
643
+ // engine.binary_unavailable (auto-download is off in the napi runtime).
644
+ logger().warn({
645
+ 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",
646
+ error: stringifyError(error),
647
+ });
571
648
  }
649
+ serveConfig.engineHost = config.engineHost;
650
+ serveConfig.enginePort = config.enginePort;
572
651
  if (config.test?.enabled) {
573
652
  serveConfig.inspectorTestToken =
574
653
  process.env._RIVET_TEST_INSPECTOR_TOKEN ?? "token";
@@ -26,12 +26,14 @@ import type {
26
26
  RuntimeInspectorSnapshot,
27
27
  RuntimeKvEntry,
28
28
  RuntimeKvListOptions,
29
+ RuntimeListenerConfig,
29
30
  RuntimeQueueEnqueueAndWaitOptions,
30
31
  RuntimeQueueInspectMessage,
31
32
  RuntimeQueueMessage,
32
33
  RuntimeQueueNextBatchOptions,
33
34
  RuntimeQueueTryNextBatchOptions,
34
35
  RuntimeQueueWaitOptions,
36
+ RuntimeRegistryRouteResponse,
35
37
  RuntimeRequestSaveOpts,
36
38
  RuntimeServeConfig,
37
39
  RuntimeServerlessRequest,
@@ -41,6 +43,7 @@ import type {
41
43
  RuntimeSqlDatabase,
42
44
  RuntimeSqlExecResult,
43
45
  RuntimeSqlExecuteResult,
46
+ RuntimeSqlLeaseOptions,
44
47
  RuntimeSqlQueryResult,
45
48
  RuntimeSqlRunResult,
46
49
  RuntimeStateDeltaPayload,
@@ -270,8 +273,18 @@ export class WasmCoreRuntime implements CoreRuntime {
270
273
  await callWasm(() => asWasmRegistry(registry).shutdown());
271
274
  }
272
275
 
273
- async registryDiagnostics(): Promise<{ mode: string; envoyActiveActorCount: null }> {
274
- return { mode: "wasm", envoyActiveActorCount: null };
276
+ async registryHealth(): Promise<RuntimeRegistryRouteResponse> {
277
+ return {
278
+ status: 200,
279
+ headers: { "content-type": "application/json" },
280
+ body: new TextEncoder().encode(
281
+ JSON.stringify({
282
+ status: "ok",
283
+ runtime: "rivetkit",
284
+ version: "wasm",
285
+ }),
286
+ ),
287
+ };
275
288
  }
276
289
 
277
290
  async handleServerlessRequest(
@@ -291,6 +304,16 @@ export class WasmCoreRuntime implements CoreRuntime {
291
304
  );
292
305
  }
293
306
 
307
+ async serveListener(
308
+ _registry: RegistryHandle,
309
+ _listener: RuntimeListenerConfig,
310
+ _config: RuntimeServeConfig,
311
+ ): Promise<void> {
312
+ throw new Error(
313
+ "registry.listen() is not supported on the wasm runtime; use registry.serve() and mount the handler in your platform's HTTP server instead",
314
+ );
315
+ }
316
+
294
317
  createActorFactory(
295
318
  callbacks: object,
296
319
  config?: RuntimeActorConfig | undefined | null,
@@ -499,6 +522,24 @@ export class WasmCoreRuntime implements CoreRuntime {
499
522
  callHandle(asWasmActorContext(ctx), "waitUntil", promise);
500
523
  }
501
524
 
525
+ async actorWaitForTrackedShutdownWork(
526
+ ctx: ActorContextHandle,
527
+ ): Promise<boolean> {
528
+ return await callHandle<Promise<boolean>>(
529
+ asWasmActorContext(ctx),
530
+ "waitForTrackedShutdownWork",
531
+ );
532
+ }
533
+
534
+ async actorWaitForTrackedShutdownWorkUnbounded(
535
+ ctx: ActorContextHandle,
536
+ ): Promise<void> {
537
+ await callHandle<Promise<void>>(
538
+ asWasmActorContext(ctx),
539
+ "waitForTrackedShutdownWorkUnbounded",
540
+ );
541
+ }
542
+
502
543
  actorKeepAwake(ctx: ActorContextHandle, promise: Promise<unknown>): void {
503
544
  const wasmCtx = asWasmActorContext(ctx);
504
545
  const regionId = callHandle<number>(wasmCtx, "beginKeepAwake");
@@ -646,7 +687,13 @@ export class WasmCoreRuntime implements CoreRuntime {
646
687
  async actorSqlExec(
647
688
  ctx: ActorContextHandle,
648
689
  sql: string,
690
+ lease?: RuntimeSqlLeaseOptions,
649
691
  ): Promise<RuntimeSqlExecResult> {
692
+ if (lease) {
693
+ throw new Error(
694
+ "sqlite transaction leases are unavailable in the wasm runtime",
695
+ );
696
+ }
650
697
  return await callWasm(() => this.#actorSql(ctx).exec(sql));
651
698
  }
652
699
 
@@ -654,7 +701,13 @@ export class WasmCoreRuntime implements CoreRuntime {
654
701
  ctx: ActorContextHandle,
655
702
  sql: string,
656
703
  params?: RuntimeSqlBindParams,
704
+ lease?: RuntimeSqlLeaseOptions,
657
705
  ): Promise<RuntimeSqlExecuteResult> {
706
+ if (lease) {
707
+ throw new Error(
708
+ "sqlite transaction leases are unavailable in the wasm runtime",
709
+ );
710
+ }
658
711
  const result = await callWasm(() =>
659
712
  this.#actorSql(ctx).execute(sql, params),
660
713
  );
@@ -696,6 +749,10 @@ export class WasmCoreRuntime implements CoreRuntime {
696
749
  await callWasm(() => database.close());
697
750
  }
698
751
 
752
+ async actorUdsProvision(_ctx: ActorContextHandle): Promise<never> {
753
+ throw new Error("actor UDS endpoints require the native runtime");
754
+ }
755
+
699
756
  async actorQueueSend(
700
757
  ctx: ActorContextHandle,
701
758
  name: string,
@@ -744,9 +801,16 @@ export class WasmCoreRuntime implements CoreRuntime {
744
801
  ctx: ActorContextHandle,
745
802
  names: string[],
746
803
  options?: RuntimeQueueWaitOptions | undefined | null,
804
+ signal?: CancellationTokenHandle | undefined | null,
747
805
  ): Promise<void> {
748
806
  const queue = childHandle(asWasmActorContext(ctx), "queue");
749
- await callHandleAsync(queue, "waitForNamesAvailable", names, options);
807
+ await callHandleAsync(
808
+ queue,
809
+ "waitForNamesAvailable",
810
+ names,
811
+ options,
812
+ signal,
813
+ );
750
814
  }
751
815
 
752
816
  async actorQueueEnqueueAndWait(
@@ -793,6 +857,11 @@ export class WasmCoreRuntime implements CoreRuntime {
793
857
  return await callHandleAsync(queue, "inspectMessages");
794
858
  }
795
859
 
860
+ async actorQueueReset(ctx: ActorContextHandle): Promise<void> {
861
+ const queue = childHandle(asWasmActorContext(ctx), "queue");
862
+ await callHandleAsync(queue, "reset");
863
+ }
864
+
796
865
  actorScheduleAfter(
797
866
  ctx: ActorContextHandle,
798
867
  durationMs: number | bigint,
@@ -0,0 +1,40 @@
1
+ import onChange from "@rivetkit/on-change";
2
+
3
+ /**
4
+ * Creates a proxy that tracks deep mutations on an object and calls `commit`
5
+ * after every change. Uses `@rivetkit/on-change` internally, which correctly
6
+ * detects mutations via methods on Map, Set, Date, TypedArrays, and arrays.
7
+ *
8
+ * If the value is not an object (primitive, null, undefined), it is returned
9
+ * as-is since primitives cannot be proxied or mutated.
10
+ *
11
+ * @param value - The root value to watch.
12
+ * @param commit - Called after every detected mutation with the root object.
13
+ * @param beforeChange - Called before every mutation with the new value being
14
+ * assigned. Throw to reject the change.
15
+ */
16
+ export function createWriteThroughProxy<T>(
17
+ value: T,
18
+ commit: (next: T) => void,
19
+ beforeChange?: (newValue: unknown) => void,
20
+ ): T {
21
+ if (!value || typeof value !== "object") {
22
+ return value;
23
+ }
24
+
25
+ return onChange(
26
+ value as T & Record<string, any>,
27
+ () => {
28
+ commit(value);
29
+ },
30
+ {
31
+ // Rejection is throw-based: beforeChange throws to prevent the
32
+ // mutation. We always return true so on-change applies the change
33
+ // if beforeChange did not throw.
34
+ onValidate(_path: string, newValue: unknown) {
35
+ beforeChange?.(newValue);
36
+ return true;
37
+ },
38
+ },
39
+ ) as T;
40
+ }
package/src/serde.ts CHANGED
@@ -2,8 +2,8 @@ import * as cbor from "cbor-x";
2
2
  import invariant from "invariant";
3
3
  import type { VersionedDataHandler } from "vbare";
4
4
  import type { z } from "zod/v4";
5
+ import type { Encoding, JsonCompatValue } from "@/common/encoding";
5
6
  import { assertUnreachable } from "@/common/utils";
6
- import type { Encoding } from "@/common/encoding";
7
7
  import {
8
8
  encodeJsonCompatValue,
9
9
  jsonParseCompat,
@@ -46,7 +46,7 @@ export function contentTypeForEncoding(encoding: Encoding): string {
46
46
  }
47
47
  }
48
48
 
49
- export function encodeCborCompat(value: unknown): Uint8Array {
49
+ export function encodeCborCompat(value: JsonCompatValue): Uint8Array {
50
50
  return cbor.encode(encodeJsonCompatValue(value));
51
51
  }
52
52