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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (303) hide show
  1. package/dist/browser/client.d.ts +1286 -89
  2. package/dist/browser/client.js +1699 -704
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.d.ts +252 -129
  5. package/dist/browser/inspector/client.js +2083 -236
  6. package/dist/browser/inspector/client.js.map +1 -1
  7. package/dist/tsup/actor/errors.cjs +8 -2
  8. package/dist/tsup/actor/errors.cjs.map +1 -1
  9. package/dist/tsup/actor/errors.d.cts +1 -1
  10. package/dist/tsup/actor/errors.d.ts +1 -1
  11. package/dist/tsup/actor/errors.js +7 -1
  12. package/dist/tsup/agent-os/index.cjs +3 -2289
  13. package/dist/tsup/agent-os/index.cjs.map +1 -1
  14. package/dist/tsup/agent-os/index.d.cts +1 -1813
  15. package/dist/tsup/agent-os/index.d.ts +1 -1813
  16. package/dist/tsup/agent-os/index.js +3 -2289
  17. package/dist/tsup/agent-os/index.js.map +1 -1
  18. package/dist/tsup/chunk-2JJU7IQ7.cjs +14 -0
  19. package/dist/tsup/chunk-2JJU7IQ7.cjs.map +1 -0
  20. package/dist/tsup/{chunk-DZJZLZ4R.js → chunk-2MXBZGUP.js} +2 -2
  21. package/dist/tsup/{chunk-L4FVS7GY.js → chunk-47IS5ZFI.js} +6 -6
  22. package/dist/tsup/chunk-47IS5ZFI.js.map +1 -0
  23. package/dist/tsup/{chunk-DXWOGCZY.js → chunk-5XWY5CBA.js} +70 -8
  24. package/dist/tsup/chunk-5XWY5CBA.js.map +1 -0
  25. package/dist/tsup/{chunk-OQEEZDIK.cjs → chunk-6XVNZKKP.cjs} +506 -31
  26. package/dist/tsup/chunk-6XVNZKKP.cjs.map +1 -0
  27. package/dist/tsup/{chunk-3YY5S6TV.js → chunk-A2CF6PFH.js} +20 -12
  28. package/dist/tsup/chunk-A2CF6PFH.js.map +1 -0
  29. package/dist/tsup/{chunk-WQ4HNA4W.cjs → chunk-AQJFKHBK.cjs} +276 -27
  30. package/dist/tsup/chunk-AQJFKHBK.cjs.map +1 -0
  31. package/dist/tsup/chunk-DPWLASMC.cjs +244 -0
  32. package/dist/tsup/chunk-DPWLASMC.cjs.map +1 -0
  33. package/dist/tsup/{chunk-VUF2YEF4.cjs → chunk-DYJOU3MF.cjs} +10 -10
  34. package/dist/tsup/chunk-DYJOU3MF.cjs.map +1 -0
  35. package/dist/tsup/{chunk-7WXCRV25.cjs → chunk-ELZ6MT3V.cjs} +18 -11
  36. package/dist/tsup/chunk-ELZ6MT3V.cjs.map +1 -0
  37. package/dist/tsup/chunk-HYIVSH5X.js +244 -0
  38. package/dist/tsup/chunk-HYIVSH5X.js.map +1 -0
  39. package/dist/tsup/{chunk-T6YVRM4K.js → chunk-IHEO5OT3.js} +275 -26
  40. package/dist/tsup/chunk-IHEO5OT3.js.map +1 -0
  41. package/dist/tsup/chunk-IWACVNN5.js +14 -0
  42. package/dist/tsup/chunk-IWACVNN5.js.map +1 -0
  43. package/dist/tsup/{chunk-PCBNKI2J.js → chunk-JTHHCZCZ.js} +24 -1
  44. package/dist/tsup/chunk-JTHHCZCZ.js.map +1 -0
  45. package/dist/tsup/{chunk-V4JUWAT6.js → chunk-K3AJOPSF.js} +498 -23
  46. package/dist/tsup/chunk-K3AJOPSF.js.map +1 -0
  47. package/dist/tsup/{chunk-2NDZ7JCR.cjs → chunk-KVFIONKQ.cjs} +25 -2
  48. package/dist/tsup/chunk-KVFIONKQ.cjs.map +1 -0
  49. package/dist/tsup/{chunk-QAZLM4WT.cjs → chunk-MGI2VVF6.cjs} +45 -9
  50. package/dist/tsup/chunk-MGI2VVF6.cjs.map +1 -0
  51. package/dist/tsup/{chunk-QNLGOTQP.js → chunk-NPHTIUUJ.js} +1291 -420
  52. package/dist/tsup/chunk-NPHTIUUJ.js.map +1 -0
  53. package/dist/tsup/{chunk-7GKQJFSB.cjs → chunk-POCSZXPQ.cjs} +72 -10
  54. package/dist/tsup/chunk-POCSZXPQ.cjs.map +1 -0
  55. package/dist/tsup/{chunk-LD5YASJU.cjs → chunk-RTWH3AX3.cjs} +19 -11
  56. package/dist/tsup/chunk-RTWH3AX3.cjs.map +1 -0
  57. package/dist/tsup/{chunk-ARRBQTAR.cjs → chunk-X76BM5JS.cjs} +1420 -549
  58. package/dist/tsup/chunk-X76BM5JS.cjs.map +1 -0
  59. package/dist/tsup/{chunk-AGBP757I.js → chunk-X7SYKFPM.js} +16 -9
  60. package/dist/tsup/chunk-X7SYKFPM.js.map +1 -0
  61. package/dist/tsup/{chunk-GKAMEBTZ.cjs → chunk-XLDJSZ3B.cjs} +3 -3
  62. package/dist/tsup/{chunk-GKAMEBTZ.cjs.map → chunk-XLDJSZ3B.cjs.map} +1 -1
  63. package/dist/tsup/{chunk-KIWH5H3K.js → chunk-ZOVJDAOW.js} +44 -8
  64. package/dist/tsup/chunk-ZOVJDAOW.js.map +1 -0
  65. package/dist/tsup/client/mod.cjs +8 -9
  66. package/dist/tsup/client/mod.cjs.map +1 -1
  67. package/dist/tsup/client/mod.d.cts +33 -7
  68. package/dist/tsup/client/mod.d.ts +33 -7
  69. package/dist/tsup/client/mod.js +7 -8
  70. package/dist/tsup/common/log.cjs +5 -3
  71. package/dist/tsup/common/log.cjs.map +1 -1
  72. package/dist/tsup/common/log.d.cts +5 -1
  73. package/dist/tsup/common/log.d.ts +5 -1
  74. package/dist/tsup/common/log.js +6 -4
  75. package/dist/tsup/common/websocket.cjs +4 -4
  76. package/dist/tsup/common/websocket.js +3 -3
  77. package/dist/tsup/{config-nlTlOKaE.d.cts → config-BMGUEKMZ.d.cts} +1252 -75
  78. package/dist/tsup/config-CBTr4IhE.d.cts +224 -0
  79. package/dist/tsup/config-CBTr4IhE.d.ts +224 -0
  80. package/dist/tsup/{config-D7ykAntK.d.ts → config-iBpXyITj.d.ts} +1252 -75
  81. package/dist/tsup/context-hyVakgnU.d.ts +136 -0
  82. package/dist/tsup/context-qfvLuF0P.d.cts +136 -0
  83. package/dist/tsup/db/drizzle.cjs +127 -67
  84. package/dist/tsup/db/drizzle.cjs.map +1 -1
  85. package/dist/tsup/db/drizzle.d.cts +8 -4
  86. package/dist/tsup/db/drizzle.d.ts +8 -4
  87. package/dist/tsup/db/drizzle.js +127 -67
  88. package/dist/tsup/db/drizzle.js.map +1 -1
  89. package/dist/tsup/db/mod.cjs +6 -124
  90. package/dist/tsup/db/mod.cjs.map +1 -1
  91. package/dist/tsup/db/mod.d.cts +12 -4
  92. package/dist/tsup/db/mod.d.ts +12 -4
  93. package/dist/tsup/db/mod.js +5 -123
  94. package/dist/tsup/db/mod.js.map +1 -1
  95. package/dist/tsup/dynamic/mod.cjs +24 -0
  96. package/dist/tsup/dynamic/mod.cjs.map +1 -0
  97. package/dist/tsup/dynamic/mod.d.cts +39 -0
  98. package/dist/tsup/dynamic/mod.d.ts +39 -0
  99. package/dist/tsup/dynamic/mod.js +24 -0
  100. package/dist/tsup/dynamic/mod.js.map +1 -0
  101. package/dist/tsup/inspector/mod.cjs +47 -12
  102. package/dist/tsup/inspector/mod.cjs.map +1 -1
  103. package/dist/tsup/inspector/mod.d.cts +26 -136
  104. package/dist/tsup/inspector/mod.d.ts +26 -136
  105. package/dist/tsup/inspector/mod.js +46 -11
  106. package/dist/tsup/inspector/mod.js.map +1 -1
  107. package/dist/tsup/inspector/workflow.cjs +21 -0
  108. package/dist/tsup/inspector/workflow.cjs.map +1 -0
  109. package/dist/tsup/inspector/workflow.d.cts +144 -0
  110. package/dist/tsup/inspector/workflow.d.ts +144 -0
  111. package/dist/tsup/inspector/workflow.js +21 -0
  112. package/dist/tsup/inspector/workflow.js.map +1 -0
  113. package/dist/tsup/inspector-tab/mod.cjs +162 -0
  114. package/dist/tsup/inspector-tab/mod.cjs.map +1 -0
  115. package/dist/tsup/inspector-tab/mod.d.cts +242 -0
  116. package/dist/tsup/inspector-tab/mod.d.ts +242 -0
  117. package/dist/tsup/inspector-tab/mod.js +162 -0
  118. package/dist/tsup/inspector-tab/mod.js.map +1 -0
  119. package/dist/tsup/mod.cjs +3527 -753
  120. package/dist/tsup/mod.cjs.map +1 -1
  121. package/dist/tsup/mod.d.cts +11 -7
  122. package/dist/tsup/mod.d.ts +11 -7
  123. package/dist/tsup/mod.js +3468 -694
  124. package/dist/tsup/mod.js.map +1 -1
  125. package/dist/tsup/test/mod.cjs +26 -21
  126. package/dist/tsup/test/mod.cjs.map +1 -1
  127. package/dist/tsup/test/mod.d.cts +7 -5
  128. package/dist/tsup/test/mod.d.ts +7 -5
  129. package/dist/tsup/test/mod.js +25 -20
  130. package/dist/tsup/test/mod.js.map +1 -1
  131. package/dist/tsup/unstable/migrations.cjs +101 -0
  132. package/dist/tsup/unstable/migrations.cjs.map +1 -0
  133. package/dist/tsup/unstable/migrations.d.cts +29 -0
  134. package/dist/tsup/unstable/migrations.d.ts +29 -0
  135. package/dist/tsup/unstable/migrations.js +101 -0
  136. package/dist/tsup/unstable/migrations.js.map +1 -0
  137. package/dist/tsup/{utils-DVekpm4I.d.ts → utils-3rsE0JvI.d.cts} +26 -2
  138. package/dist/tsup/{utils-DVekpm4I.d.cts → utils-3rsE0JvI.d.ts} +26 -2
  139. package/dist/tsup/utils-C1O-SklO.d.ts +162 -0
  140. package/dist/tsup/utils-C6b0aYUM.d.cts +162 -0
  141. package/dist/tsup/utils.cjs +7 -3
  142. package/dist/tsup/utils.cjs.map +1 -1
  143. package/dist/tsup/utils.d.cts +4 -147
  144. package/dist/tsup/utils.d.ts +4 -147
  145. package/dist/tsup/utils.js +6 -2
  146. package/dist/tsup/workflow/mod.cjs +557 -410
  147. package/dist/tsup/workflow/mod.cjs.map +1 -1
  148. package/dist/tsup/workflow/mod.d.cts +11 -9
  149. package/dist/tsup/workflow/mod.d.ts +11 -9
  150. package/dist/tsup/workflow/mod.js +551 -404
  151. package/dist/tsup/workflow/mod.js.map +1 -1
  152. package/package.json +67 -18
  153. package/src/actor/actions.ts +155 -0
  154. package/src/actor/config.ts +679 -101
  155. package/src/actor/contexts/index.ts +9 -2
  156. package/src/actor/definition.ts +75 -26
  157. package/src/actor/errors.ts +107 -8
  158. package/src/actor/keys.ts +87 -1
  159. package/src/actor/mod.ts +36 -20
  160. package/src/actor/schema.ts +6 -2
  161. package/src/actor/tracing.ts +28 -0
  162. package/src/agent-os/index.ts +5 -64
  163. package/src/client/actor-common.ts +84 -54
  164. package/src/client/actor-conn.ts +231 -68
  165. package/src/client/actor-handle.ts +283 -89
  166. package/src/client/actor-query.ts +13 -6
  167. package/src/client/auth.ts +37 -0
  168. package/src/client/client.ts +182 -21
  169. package/src/client/config.ts +28 -3
  170. package/src/client/errors.ts +15 -2
  171. package/src/client/lifecycle-errors.ts +63 -5
  172. package/src/client/mod.ts +10 -0
  173. package/src/client/outbound-telemetry.ts +66 -0
  174. package/src/client/query.ts +3 -1
  175. package/src/client/queue.ts +13 -3
  176. package/src/client/raw-utils.ts +59 -14
  177. package/src/client/resolve-gateway-target.ts +3 -1
  178. package/src/client/retry-budget.ts +81 -0
  179. package/src/client/token-provider.ts +93 -0
  180. package/src/client/utils.ts +22 -9
  181. package/src/common/actor-router-consts.ts +6 -0
  182. package/src/common/actor-telemetry-context.ts +19 -0
  183. package/src/common/actor-websocket.ts +3 -1
  184. package/src/common/bare/actor-persist/v1.ts +205 -163
  185. package/src/common/bare/actor-persist/v2.ts +265 -213
  186. package/src/common/bare/actor-persist/v3.ts +176 -172
  187. package/src/common/bare/actor-persist/v4.ts +254 -253
  188. package/src/common/bare/generated/inspector/v5.ts +1016 -0
  189. package/src/common/bare/generated/inspector/v6.ts +1367 -0
  190. package/src/common/bare/transport/v1.ts +694 -542
  191. package/src/common/client-protocol-versioned.ts +66 -64
  192. package/src/common/database/config.ts +175 -9
  193. package/src/common/database/mod.ts +262 -77
  194. package/src/common/database/native-database.ts +442 -20
  195. package/src/common/database/shared.ts +25 -0
  196. package/src/common/encoding.ts +278 -34
  197. package/src/common/engine.ts +28 -1
  198. package/src/common/eventsource.ts +1 -1
  199. package/src/common/fetch-like.ts +63 -0
  200. package/src/common/inline-websocket-adapter.ts +14 -13
  201. package/src/common/inspector-transport.ts +12 -2
  202. package/src/common/log.ts +15 -8
  203. package/src/common/otel-context.ts +99 -0
  204. package/src/common/router.ts +14 -18
  205. package/src/common/utils.ts +8 -169
  206. package/src/common/websocket-interface.ts +1 -1
  207. package/src/db/drizzle.ts +182 -80
  208. package/src/db/mod.ts +5 -1
  209. package/src/devtools-loader/index.ts +4 -7
  210. package/src/devtools-loader/serve-devtools.ts +26 -0
  211. package/src/dynamic/instance.ts +32 -0
  212. package/src/dynamic/internal.ts +50 -0
  213. package/src/dynamic/isolate-runtime.ts +64 -0
  214. package/src/dynamic/mod.ts +32 -0
  215. package/src/engine-api/actors.ts +15 -3
  216. package/src/engine-client/actor-http-client.ts +37 -22
  217. package/src/engine-client/actor-websocket-client.ts +37 -9
  218. package/src/engine-client/api-endpoints.ts +128 -5
  219. package/src/engine-client/api-utils.ts +2 -2
  220. package/src/engine-client/driver.ts +21 -16
  221. package/src/engine-client/mod.ts +280 -111
  222. package/src/engine-client/ws-proxy.ts +9 -4
  223. package/src/inspector/client.browser.ts +127 -15
  224. package/src/inspector/mod.ts +2 -4
  225. package/src/inspector/workflow.ts +61 -0
  226. package/src/inspector-tab/mod.ts +301 -0
  227. package/src/registry/config/envoy.ts +3 -20
  228. package/src/registry/config/index.ts +91 -74
  229. package/src/registry/index.ts +702 -80
  230. package/src/registry/napi-runtime.ts +643 -42
  231. package/src/registry/native-http.ts +225 -0
  232. package/src/registry/native-validation.ts +10 -12
  233. package/src/registry/native.ts +1881 -582
  234. package/src/registry/run-handler-coordinator.ts +219 -0
  235. package/src/registry/runtime.ts +441 -7
  236. package/src/registry/wasm-runtime.ts +516 -23
  237. package/src/registry/write-through-proxy.ts +141 -0
  238. package/src/serde.ts +2 -2
  239. package/src/serverless/configure.ts +18 -7
  240. package/src/test/mod.ts +2 -17
  241. package/src/test/ready.ts +22 -0
  242. package/src/unstable/migrations.ts +141 -0
  243. package/src/utils/endpoint-parser.ts +1 -1
  244. package/src/utils/env-vars.ts +50 -2
  245. package/src/utils/node.ts +44 -28
  246. package/src/utils/router.ts +1 -1
  247. package/src/utils.ts +4 -2
  248. package/src/workflow/context.ts +703 -242
  249. package/src/workflow/driver.ts +284 -125
  250. package/src/workflow/inspector.ts +24 -24
  251. package/src/workflow/mod.ts +76 -84
  252. package/dist/tsup/chunk-2NDZ7JCR.cjs.map +0 -1
  253. package/dist/tsup/chunk-3YY5S6TV.js.map +0 -1
  254. package/dist/tsup/chunk-6NT2LIFN.cjs +0 -268
  255. package/dist/tsup/chunk-6NT2LIFN.cjs.map +0 -1
  256. package/dist/tsup/chunk-7GKQJFSB.cjs.map +0 -1
  257. package/dist/tsup/chunk-7WXCRV25.cjs.map +0 -1
  258. package/dist/tsup/chunk-AGBP757I.js.map +0 -1
  259. package/dist/tsup/chunk-ARRBQTAR.cjs.map +0 -1
  260. package/dist/tsup/chunk-DXWOGCZY.js.map +0 -1
  261. package/dist/tsup/chunk-JGIPV3QU.js +0 -268
  262. package/dist/tsup/chunk-JGIPV3QU.js.map +0 -1
  263. package/dist/tsup/chunk-KIWH5H3K.js.map +0 -1
  264. package/dist/tsup/chunk-L4FVS7GY.js.map +0 -1
  265. package/dist/tsup/chunk-LD5YASJU.cjs.map +0 -1
  266. package/dist/tsup/chunk-OQEEZDIK.cjs.map +0 -1
  267. package/dist/tsup/chunk-PCBNKI2J.js.map +0 -1
  268. package/dist/tsup/chunk-QAZLM4WT.cjs.map +0 -1
  269. package/dist/tsup/chunk-QNLGOTQP.js.map +0 -1
  270. package/dist/tsup/chunk-T6YVRM4K.js.map +0 -1
  271. package/dist/tsup/chunk-V4JUWAT6.js.map +0 -1
  272. package/dist/tsup/chunk-VUF2YEF4.cjs.map +0 -1
  273. package/dist/tsup/chunk-WQ4HNA4W.cjs.map +0 -1
  274. package/dist/tsup/config-CxjGYf4K.d.cts +0 -121
  275. package/dist/tsup/config-CxjGYf4K.d.ts +0 -121
  276. package/dist/tsup/context-88opQsfZ.d.cts +0 -92
  277. package/dist/tsup/context-CVEG5zfg.d.ts +0 -92
  278. package/src/actor/driver.ts +0 -141
  279. package/src/actor/instance/mod.ts +0 -2492
  280. package/src/actor/keys.test.ts +0 -275
  281. package/src/actor/utils.test.ts +0 -48
  282. package/src/agent-os/actor/cron.ts +0 -84
  283. package/src/agent-os/actor/db.ts +0 -54
  284. package/src/agent-os/actor/filesystem.ts +0 -131
  285. package/src/agent-os/actor/index.ts +0 -265
  286. package/src/agent-os/actor/network.ts +0 -58
  287. package/src/agent-os/actor/preview.ts +0 -191
  288. package/src/agent-os/actor/process.ts +0 -177
  289. package/src/agent-os/actor/session.ts +0 -518
  290. package/src/agent-os/actor/shell.ts +0 -60
  291. package/src/agent-os/config.ts +0 -79
  292. package/src/agent-os/fs/database-vfs.ts +0 -624
  293. package/src/agent-os/types.ts +0 -148
  294. package/src/client/test.ts +0 -44
  295. package/src/common/database/mod.test.ts +0 -137
  296. package/src/common/database/native-database.test.ts +0 -211
  297. package/src/common/inline-websocket-adapter.test.ts +0 -51
  298. package/src/drivers/engine/actor-driver.ts +0 -2460
  299. package/src/registry/runtime.test.ts +0 -50
  300. package/src/utils/endpoint-parser.test.ts +0 -206
  301. package/src/utils/serve.ts +0 -217
  302. package/src/utils.test.ts +0 -34
  303. /package/dist/tsup/{chunk-DZJZLZ4R.js.map → chunk-2MXBZGUP.js.map} +0 -0
@@ -1,6 +1,15 @@
1
- import { ENGINE_ENDPOINT } from "@/common/engine";
1
+ import { isLocalEngineEndpoint } from "@/common/engine";
2
+ import { isResponseLike } from "@/common/fetch-like";
3
+ import { configureBaseLogger } from "@/common/log";
2
4
  import { configureServerlessPool } from "@/serverless/configure";
3
5
  import { VERSION } from "@/utils";
6
+ import {
7
+ getNodeEnv,
8
+ getRivetEnvoyVersion,
9
+ getRivetkitPublicDir,
10
+ getRivetkitRuntimeMode,
11
+ parsePortEnv,
12
+ } from "@/utils/env-vars";
4
13
  import {
5
14
  type RegistryActors,
6
15
  type RegistryConfig,
@@ -9,10 +18,111 @@ import {
9
18
  } from "./config";
10
19
  import { logger } from "./log";
11
20
  import { buildConfiguredRegistry } from "./native";
12
- import type { RuntimeServerlessResponseHead } from "./runtime";
21
+ import { convertNativeHttpResponse } from "./native-http";
22
+ import type {
23
+ CancellationTokenHandle,
24
+ CoreRuntime,
25
+ RuntimeApplicationFetch,
26
+ RuntimeHttpResponseBodyStream,
27
+ RuntimeServerlessResponseHead,
28
+ } from "./runtime";
13
29
 
14
30
  type ShutdownSignal = "SIGINT" | "SIGTERM";
15
31
 
32
+ type ConfiguredRegistry = Awaited<ReturnType<typeof buildConfiguredRegistry>>;
33
+
34
+ const REGISTRY_READY_TIMEOUT_MS = 30_000;
35
+ // A managed Engine restart can wait for the old process to release storage and
36
+ // for its worker lease to expire before the replacement can register.
37
+ const LOCAL_ENGINE_READY_TIMEOUT_MS = 60_000;
38
+ // Core gives local actors three seconds to drain and acknowledge their stopped
39
+ // reports. Leave time to close the node connection after that, while staying
40
+ // below the five-second force-kill ceiling used by tsx watch.
41
+ const LOCAL_DEV_SHUTDOWN_GRACE_PERIOD_MS = 4_000;
42
+ // Matches the engine's default `pegboard.actor_stop_threshold`. Used only when the
43
+ // node has not received the engine's advertised threshold before shutdown begins.
44
+ const DEFAULT_ACTOR_STOP_THRESHOLD_MS = 30_000;
45
+
46
+ // Serverless is disabled for v3; keep the implementation for a later release.
47
+ function rejectServerless(): void {
48
+ throw new Error("serverless is disabled in this version");
49
+ }
50
+
51
+ function signalExitCode(signal: ShutdownSignal): number {
52
+ switch (signal) {
53
+ case "SIGINT":
54
+ return 130;
55
+ case "SIGTERM":
56
+ return 143;
57
+ }
58
+ }
59
+
60
+ function finishShutdownSignal(signal: ShutdownSignal): void {
61
+ if (process.pid === 1) {
62
+ process.exit(signalExitCode(signal));
63
+ }
64
+ process.kill(process.pid, signal);
65
+ }
66
+
67
+ function createApplicationFetch(
68
+ application: RegistryApplication,
69
+ runtime: CoreRuntime,
70
+ ): RuntimeApplicationFetch {
71
+ return async (
72
+ request,
73
+ responseBodyStream?: RuntimeHttpResponseBodyStream,
74
+ ) => {
75
+ const method = request.method.toUpperCase();
76
+ const body =
77
+ method === "GET" || method === "HEAD" || request.body.length === 0
78
+ ? undefined
79
+ : Uint8Array.from(request.body).buffer;
80
+ const abortController = new AbortController();
81
+ if (request.cancelToken) {
82
+ if (runtime.cancellationTokenAborted(request.cancelToken)) {
83
+ abortController.abort();
84
+ } else {
85
+ runtime.onCancellationTokenCancelled(request.cancelToken, () =>
86
+ abortController.abort(),
87
+ );
88
+ }
89
+ }
90
+ const response = await application.fetch(
91
+ new Request(request.url, {
92
+ method,
93
+ headers: request.headers,
94
+ body,
95
+ signal: abortController.signal,
96
+ }),
97
+ );
98
+ if (!isResponseLike(response)) {
99
+ throw new TypeError(
100
+ "registry.listen() application fetch must return a Response",
101
+ );
102
+ }
103
+ const conversion = await convertNativeHttpResponse(
104
+ response,
105
+ responseBodyStream,
106
+ );
107
+ if (conversion.bodyCompletion) {
108
+ void conversion.bodyCompletion.catch((error) => {
109
+ logger().error({
110
+ msg: "application response stream failed",
111
+ error,
112
+ });
113
+ });
114
+ }
115
+ return {
116
+ status: conversion.response.status ?? response.status,
117
+ headers:
118
+ conversion.response.headers ??
119
+ Object.fromEntries(response.headers.entries()),
120
+ body: conversion.response.body,
121
+ stream: conversion.response.stream,
122
+ };
123
+ };
124
+ }
125
+
16
126
  export type FetchHandler = (
17
127
  request: Request,
18
128
  ...args: any
@@ -22,14 +132,35 @@ export interface ServerlessHandler {
22
132
  fetch: FetchHandler;
23
133
  }
24
134
 
135
+ export interface RegistryApplication {
136
+ fetch: FetchHandler;
137
+ }
138
+
139
+ export interface RegistryListenOptions {
140
+ port?: number;
141
+ host?: string;
142
+ publicDir?: string;
143
+ application?: RegistryApplication;
144
+ }
145
+
25
146
  export interface RegistryRoutes {
26
147
  health(): Promise<Response>;
27
148
  metadata(): Promise<Response>;
28
149
  prometheusMetrics(request?: Request): Promise<Response>;
29
150
  }
30
151
 
152
+ /**
153
+ * Injectable dependencies for {@link Registry}. Production code uses the
154
+ * defaults. Tests override `buildConfiguredRegistry` to drive lifecycle
155
+ * orchestration against a fake `CoreRuntime` without an engine.
156
+ */
157
+ export interface RegistryDeps {
158
+ buildConfiguredRegistry: typeof buildConfiguredRegistry;
159
+ }
160
+
31
161
  export class Registry<A extends RegistryActors> {
32
162
  #config: RegistryConfigInput<A>;
163
+ #buildConfiguredRegistry: typeof buildConfiguredRegistry;
33
164
  public readonly routes: RegistryRoutes;
34
165
 
35
166
  get config(): RegistryConfigInput<A> {
@@ -41,16 +172,29 @@ export class Registry<A extends RegistryActors> {
41
172
  }
42
173
 
43
174
  #runtimeServePromise?: Promise<void>;
175
+ #runtimeServeLifecyclePromise?: Promise<void>;
176
+ #runtimeReadyPromise?: Promise<void>;
44
177
  #runtimeServeConfiguredPromise?: ReturnType<typeof buildConfiguredRegistry>;
45
178
  #runtimeServerlessPromise?: ReturnType<typeof buildConfiguredRegistry>;
179
+ #applicationListenerPromise?: Promise<void>;
46
180
  #configureServerlessPoolPromise?: Promise<void>;
47
181
  #welcomePrinted = false;
48
182
  #shutdownInstalled = false;
49
183
  #shutdownInFlight: Promise<void> | null = null;
50
184
  #signalHandlers: Partial<Record<ShutdownSignal, () => void>> = {};
185
+ #envoyConfiguredRegistry?: ConfiguredRegistry;
186
+ #activeActorCountListeners = new Set<(count: number) => void>();
187
+ #activeActorCountToken?: CancellationTokenHandle;
188
+ #lastActiveActorCount?: number;
189
+ #activeActorCountSupported?: boolean;
51
190
 
52
- constructor(config: RegistryConfigInput<A>) {
191
+ constructor(config: RegistryConfigInput<A>, deps?: Partial<RegistryDeps>) {
53
192
  this.#config = config;
193
+ if (config.logging?.baseLogger) {
194
+ configureBaseLogger(config.logging.baseLogger);
195
+ }
196
+ this.#buildConfiguredRegistry =
197
+ deps?.buildConfiguredRegistry ?? buildConfiguredRegistry;
54
198
  this.routes = {
55
199
  health: () => this.#healthRoute(),
56
200
  metadata: () => this.#metadataRoute(),
@@ -59,16 +203,25 @@ export class Registry<A extends RegistryActors> {
59
203
  };
60
204
  }
61
205
 
62
- #ensureServerlessPoolConfigured(config: RegistryConfig): Promise<void> | undefined {
206
+ /**
207
+ * Fires `configureServerlessPool` once per process when the registry
208
+ * config opts into it. Cached on the instance so repeated calls (from
209
+ * `handler()` and `listen()`) only run the upsert once. The retry loop
210
+ * inside `configureServerlessPool` tolerates the engine still warming up.
211
+ */
212
+ #ensureServerlessPoolConfigured(
213
+ config: RegistryConfig,
214
+ ): Promise<void> | undefined {
63
215
  if (!config.configurePool) return undefined;
216
+ rejectServerless();
64
217
 
65
218
  if (!this.#configureServerlessPoolPromise) {
66
- this.#configureServerlessPoolPromise = configureServerlessPool(config).catch(
67
- (error) => {
68
- this.#configureServerlessPoolPromise = undefined;
69
- throw error;
70
- },
71
- );
219
+ this.#configureServerlessPoolPromise = configureServerlessPool(
220
+ config,
221
+ ).catch((error) => {
222
+ this.#configureServerlessPoolPromise = undefined;
223
+ throw error;
224
+ });
72
225
  this.#configureServerlessPoolPromise.catch(() => {});
73
226
  }
74
227
 
@@ -86,11 +239,13 @@ export class Registry<A extends RegistryActors> {
86
239
  * ```
87
240
  */
88
241
  public async handler(request: Request): Promise<Response> {
242
+ rejectServerless();
89
243
  const config = this.parseConfig();
90
244
  this.#printWelcome(config, "serverless");
91
245
 
92
246
  if (!this.#runtimeServerlessPromise) {
93
- this.#runtimeServerlessPromise = buildConfiguredRegistry(config);
247
+ this.#runtimeServerlessPromise =
248
+ this.#buildConfiguredRegistry(config);
94
249
  }
95
250
 
96
251
  const { runtime, registry, serveConfig } =
@@ -104,12 +259,13 @@ export class Registry<A extends RegistryActors> {
104
259
  serveConfig.serverlessBasePath ?? "/api/rivet",
105
260
  );
106
261
  const isEngineMetadataRequest =
107
- request.headers.get("user-agent")?.startsWith("RivetEngine/") ?? false;
262
+ request.headers.get("user-agent")?.startsWith("RivetEngine/") ??
263
+ false;
108
264
 
109
265
  if (isStartRequest) {
110
266
  try {
111
267
  await this.#ensureServerlessPoolConfigured(config);
112
- } catch (error) {
268
+ } catch (_error) {
113
269
  return new Response(
114
270
  JSON.stringify({
115
271
  group: "guard",
@@ -251,7 +407,7 @@ export class Registry<A extends RegistryActors> {
251
407
  if (isMetadataRequest && !isEngineMetadataRequest) {
252
408
  try {
253
409
  await this.#ensureServerlessPoolConfigured(config);
254
- } catch (error) {
410
+ } catch (_error) {
255
411
  return new Response(
256
412
  JSON.stringify({
257
413
  group: "guard",
@@ -282,11 +438,118 @@ export class Registry<A extends RegistryActors> {
282
438
  * ```
283
439
  */
284
440
  public serve(): ServerlessHandler {
441
+ rejectServerless();
285
442
  return {
286
443
  fetch: (request) => this.handler(request),
287
444
  };
288
445
  }
289
446
 
447
+ /**
448
+ * Bind an HTTP listener provided by the native (Rust) runtime and serve
449
+ * the registry's serverless endpoints over it. Resolves only after the
450
+ * registry is shut down (SIGINT/SIGTERM or `nativeRegistry.shutdown()`).
451
+ *
452
+ * @param opts.port Port to listen on. Defaults to `process.env.RIVET_PORT`
453
+ * if set, otherwise 3000.
454
+ * @param opts.host Address to bind. Defaults to `0.0.0.0`.
455
+ * @param opts.publicDir If set, serves static files from this directory
456
+ * as a fallback below the framework routes.
457
+ * @param opts.application If set, handles requests that do not match a
458
+ * framework route.
459
+ *
460
+ * @example
461
+ * ```ts
462
+ * await registry.listen();
463
+ * await registry.listen({ application: app });
464
+ * ```
465
+ */
466
+ public async listen(opts: RegistryListenOptions = {}): Promise<void> {
467
+ if (!opts.application) {
468
+ rejectServerless();
469
+ }
470
+ const port = opts.port ?? parsePortEnv(process.env.RIVET_PORT) ?? 3000;
471
+ const publicDir = opts.publicDir ?? getRivetkitPublicDir();
472
+ const config = this.parseConfig();
473
+
474
+ if (opts.application && getRivetkitRuntimeMode() !== "serverless") {
475
+ if (config.runtime === "wasm") {
476
+ throw new Error(
477
+ "registry.listen() requires the native runtime; use an application-owned HTTP server with WebAssembly",
478
+ );
479
+ }
480
+ this.#installSignalHandlers(config);
481
+ this.#printWelcome(config, "serverful", {
482
+ port,
483
+ host: opts.host,
484
+ publicDir,
485
+ });
486
+ this.#startEnvoy(config, true);
487
+ const readyPromise = this.startAndWait();
488
+ const configuredRegistryPromise =
489
+ this.#runtimeServeConfiguredPromise;
490
+ if (!configuredRegistryPromise) {
491
+ throw new Error("registry envoy startup did not initialize");
492
+ }
493
+ const { runtime, registry, serveConfig } =
494
+ await configuredRegistryPromise;
495
+ const application = createApplicationFetch(
496
+ opts.application,
497
+ runtime,
498
+ );
499
+ await readyPromise;
500
+ const listenerPromise = runtime.serveApplicationListener(
501
+ registry,
502
+ {
503
+ port,
504
+ host: opts.host,
505
+ publicDir,
506
+ application,
507
+ },
508
+ serveConfig,
509
+ );
510
+ this.#applicationListenerPromise = listenerPromise;
511
+ const serveLifecyclePromise = this.#runtimeServeLifecyclePromise;
512
+ if (!serveLifecyclePromise) {
513
+ throw new Error(
514
+ "registry envoy serve lifecycle did not initialize",
515
+ );
516
+ }
517
+ await Promise.all([listenerPromise, serveLifecyclePromise]);
518
+ return;
519
+ }
520
+
521
+ // Cache on both promise fields so the shutdown drain sees Mode A and B.
522
+ const configuredRegistryPromise = this.#buildConfiguredRegistry(config);
523
+ this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
524
+ this.#runtimeServerlessPromise = configuredRegistryPromise;
525
+ this.#installSignalHandlers(config);
526
+
527
+ this.#printWelcome(config, "serverless", {
528
+ port,
529
+ host: opts.host,
530
+ publicDir,
531
+ });
532
+
533
+ // Background fire; the retry loop tolerates engine warm-up.
534
+ this.#ensureServerlessPoolConfigured(config);
535
+
536
+ const { runtime, registry, serveConfig } =
537
+ await configuredRegistryPromise;
538
+ const application = opts.application
539
+ ? createApplicationFetch(opts.application, runtime)
540
+ : undefined;
541
+ await runtime.serveListener(
542
+ registry,
543
+ {
544
+ port,
545
+ host: opts.host,
546
+ publicDir,
547
+ application,
548
+ },
549
+ serveConfig,
550
+ );
551
+ }
552
+
290
553
  /**
291
554
  * Returns a health response suitable for mounting in a user-owned router.
292
555
  */
@@ -320,6 +583,7 @@ export class Registry<A extends RegistryActors> {
320
583
  * Returns serverless metadata suitable for mounting in a user-owned router.
321
584
  */
322
585
  async #metadataRoute(): Promise<Response> {
586
+ rejectServerless();
323
587
  const configured = await this.#activeConfiguredRegistry();
324
588
  if (!configured) {
325
589
  return new Response("registry not started\n", {
@@ -376,8 +640,11 @@ export class Registry<A extends RegistryActors> {
376
640
  const candidates = [
377
641
  this.#runtimeServerlessPromise,
378
642
  this.#runtimeServeConfiguredPromise,
379
- ].filter((candidate): candidate is ReturnType<typeof buildConfiguredRegistry> =>
380
- candidate !== undefined
643
+ ].filter(
644
+ (
645
+ candidate,
646
+ ): candidate is ReturnType<typeof buildConfiguredRegistry> =>
647
+ candidate !== undefined,
381
648
  );
382
649
 
383
650
  if (candidates.length === 0) return undefined;
@@ -389,35 +656,82 @@ export class Registry<A extends RegistryActors> {
389
656
  */
390
657
  #startEnvoy(config: RegistryConfig, printWelcome: boolean) {
391
658
  if (!this.#runtimeServePromise) {
392
- const configuredRegistryPromise = buildConfiguredRegistry(config);
659
+ const configuredEnvoyVersion = this.#config.node?.version;
660
+ const envoyVersionSource =
661
+ configuredEnvoyVersion !== undefined
662
+ ? "config"
663
+ : getRivetEnvoyVersion() !== undefined
664
+ ? "environment"
665
+ : "default";
666
+
667
+ logger().info({
668
+ msg: "starting rivetkit envoy",
669
+ rivetkitVersion: VERSION,
670
+ envoyVersion: config.node.version,
671
+ envoyVersionSource,
672
+ });
673
+
674
+ if (
675
+ envoyVersionSource === "default" &&
676
+ getNodeEnv() === "production"
677
+ ) {
678
+ logger().error({
679
+ msg: "node version defaulted because neither config.node.version nor RIVET_NODE_VERSION is set; actors will not drain automatically across deploys. See https://rivet.dev/docs/actors/versions",
680
+ envoyVersion: config.node.version,
681
+ envoyVersionSource,
682
+ });
683
+ }
684
+
685
+ const configuredRegistryPromise =
686
+ this.#buildConfiguredRegistry(config);
393
687
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
394
- this.#runtimeServePromise = configuredRegistryPromise
395
- .then(async ({ runtime, registry, serveConfig }) => {
688
+ configuredRegistryPromise.then(
689
+ (configured) => {
690
+ this.#envoyConfiguredRegistry = configured;
691
+ try {
692
+ this.#syncActiveActorCountSubscription();
693
+ } catch (error) {
694
+ logger().error(
695
+ { error },
696
+ "failed to subscribe to the active actor count",
697
+ );
698
+ }
699
+ },
700
+ // The serve lifecycle below reports build failures.
701
+ () => undefined,
702
+ );
703
+ this.#runtimeServeLifecyclePromise = configuredRegistryPromise.then(
704
+ async ({ runtime, registry, serveConfig }) => {
396
705
  await runtime.serveRegistry(registry, serveConfig);
397
- })
398
- .catch((err) => {
706
+ },
707
+ );
708
+ this.#runtimeServePromise =
709
+ this.#runtimeServeLifecyclePromise.catch((error) => {
399
710
  // Always-attached catch so the stored promise never leaves a
400
711
  // rejection unhandled. Downstream awaits (e.g. #runShutdown's
401
712
  // Promise.race) attach their own catches and still observe
402
713
  // resolution via the race.
403
- logger().warn({ err }, "runtime registry serve errored");
714
+ logger().error({ error }, "runtime registry serve errored");
715
+ if (
716
+ typeof process !== "undefined" &&
717
+ typeof process.exit === "function"
718
+ ) {
719
+ process.exit(1);
720
+ }
404
721
  });
405
722
  // Install signal handlers once an envoy lifecycle has begun. Only
406
723
  // Mode A ever reaches here. Mode B (handler(request)) intentionally
407
724
  // does not install handlers because it runs on Workers/Vercel/Deno
408
725
  // Deploy where `process.on` is absent or forbidden; those platforms
409
726
  // own their own signal policy.
410
- this.#installSignalHandlers(config, configuredRegistryPromise);
727
+ this.#installSignalHandlers(config);
411
728
  }
412
729
  if (printWelcome) {
413
730
  this.#printWelcome(config, "serverful");
414
731
  }
415
732
  }
416
733
 
417
- #installSignalHandlers(
418
- config: RegistryConfig,
419
- configuredRegistryPromise: ReturnType<typeof buildConfiguredRegistry>,
420
- ): void {
734
+ #installSignalHandlers(config: RegistryConfig): void {
421
735
  if (this.#shutdownInstalled) return;
422
736
  if (config.shutdown?.disableSignalHandlers) return;
423
737
  // Guard against non-Node runtimes (Workers/Edge) where `process` may
@@ -432,12 +746,7 @@ export class Registry<A extends RegistryActors> {
432
746
  this.#shutdownInstalled = true;
433
747
 
434
748
  const install = (signal: ShutdownSignal) => {
435
- const handler = () =>
436
- this.#onShutdownSignal(
437
- signal,
438
- config,
439
- configuredRegistryPromise,
440
- );
749
+ const handler = () => this.#onShutdownSignal(signal, config);
441
750
  this.#signalHandlers[signal] = handler;
442
751
  process.on(signal, handler);
443
752
  };
@@ -445,68 +754,114 @@ export class Registry<A extends RegistryActors> {
445
754
  install("SIGTERM");
446
755
  }
447
756
 
448
- #onShutdownSignal(
449
- signal: ShutdownSignal,
450
- config: RegistryConfig,
451
- configuredRegistryPromise: ReturnType<typeof buildConfiguredRegistry>,
452
- ): void {
757
+ #onShutdownSignal(signal: ShutdownSignal, config: RegistryConfig): void {
453
758
  if (this.#shutdownInFlight !== null) {
454
- // Second delivery of the same (or another) shutdown signal.
455
- // Remove our handler only (preserving any user-installed listeners)
456
- // and re-raise so Node proceeds with its default exit path.
759
+ // Second delivery of the same (or another) shutdown signal, or a
760
+ // drain already started by an explicit `shutdown()` call. Remove
761
+ // our handler only, preserving any user-installed listeners. PID 1
762
+ // must exit directly because re-raised default signals can be
763
+ // swallowed by the container signal path.
457
764
  this.#removeSignalHandlers();
458
- process.kill(process.pid, signal);
765
+ finishShutdownSignal(signal);
459
766
  return;
460
767
  }
461
- this.#shutdownInFlight = this.#runShutdown(
462
- signal,
463
- config,
464
- configuredRegistryPromise,
465
- ).catch((err) => {
768
+ this.#shutdownInFlight = this.#drain(config, true)
769
+ .catch((err) => {
770
+ logger().warn({ err }, "shutdown error");
771
+ })
772
+ .then(() => {
773
+ this.#removeSignalHandlers();
774
+ finishShutdownSignal(signal);
775
+ });
776
+ }
777
+
778
+ /**
779
+ * Gracefully drains all live registries.
780
+ *
781
+ * Programmatic counterpart to the SIGINT/SIGTERM handlers: tears down
782
+ * every live `CoreRegistry` (both `start()` and `handler()` modes) and
783
+ * waits for the serve promise to resolve, all bounded by the shutdown
784
+ * grace period. Unlike a signal-driven shutdown, this does not re-raise a
785
+ * signal or exit the process. The caller owns process lifetime.
786
+ *
787
+ * Idempotent: concurrent or repeated calls share a single drain. Safe to
788
+ * call even if nothing has been started.
789
+ *
790
+ * @example
791
+ * ```ts
792
+ * const registry = setup({ use: { counter } });
793
+ * registry.start();
794
+ * // ...later, on your own shutdown trigger:
795
+ * await registry.shutdown();
796
+ * ```
797
+ */
798
+ public async shutdown(): Promise<void> {
799
+ if (this.#shutdownInFlight !== null) return this.#shutdownInFlight;
800
+ const config = this.parseConfig();
801
+ // Uninstall our signal handlers so a later SIGINT/SIGTERM does not
802
+ // re-trigger a drain on already-torn-down registries. Subsequent
803
+ // signals fall back to Node's default termination behavior.
804
+ this.#removeSignalHandlers();
805
+ this.#shutdownInFlight = this.#drain(config).catch((err) => {
466
806
  logger().warn({ err }, "shutdown error");
467
807
  });
808
+ return this.#shutdownInFlight;
468
809
  }
469
810
 
470
- async #runShutdown(
471
- signal: ShutdownSignal,
472
- config: RegistryConfig,
473
- configuredRegistryPromise: ReturnType<typeof buildConfiguredRegistry>,
474
- ): Promise<void> {
475
- const gracePeriodMs = config.shutdown?.gracePeriodMs ?? 30_000;
811
+ async #drain(config: RegistryConfig, signalDriven = false): Promise<void> {
812
+ const modeAPromise = this.#runtimeServeConfiguredPromise;
813
+ const modeBPromise = this.#runtimeServerlessPromise;
814
+ const runtimes = new Set<CoreRuntime>();
815
+
816
+ const localDevSignal =
817
+ signalDriven &&
818
+ getNodeEnv() !== "production" &&
819
+ config.engineSpawn &&
820
+ config.endpoint !== undefined &&
821
+ isLocalEngineEndpoint(config.endpoint);
822
+ let gracePeriodMs = config.shutdown?.gracePeriodMs;
823
+ if (gracePeriodMs === undefined) {
824
+ gracePeriodMs = localDevSignal
825
+ ? LOCAL_DEV_SHUTDOWN_GRACE_PERIOD_MS
826
+ : ((await this.#actorStopThresholdMs(
827
+ modeAPromise ?? modeBPromise,
828
+ )) ?? DEFAULT_ACTOR_STOP_THRESHOLD_MS);
829
+ }
476
830
  // Race the entire drain sequence (both modes + serve promise) against
477
- // a single grace ceiling. Without this, each mode's Rust-side drain
478
- // (20s) could stack sequentially and blow past gracePeriodMs before
479
- // we re-raise the signal.
831
+ // a single grace ceiling. Local dev signal shutdowns allow the watcher
832
+ // to restart promptly; other shutdowns use the engine's actor stop threshold.
480
833
  const drain = async () => {
481
834
  // Shut down every live `CoreRegistry` we know about. Mode A
482
835
  // (`start()`) and Mode B (`handler()`) each build a separate
483
- // runtime registry, so one signal handler fans out to both to
484
- // honor the spec invariant "single shutdown tears down both modes".
485
- const registries: Promise<void>[] = [
486
- (async () => {
487
- try {
488
- const { runtime, registry } =
489
- await configuredRegistryPromise;
490
- await runtime.shutdownRegistry(registry);
491
- } catch (err) {
492
- logger().warn(
493
- { err },
494
- "runtime registry shutdown errored (mode A)",
495
- );
496
- }
497
- })(),
498
- ];
499
- const runtimeServerlessPromise = this.#runtimeServerlessPromise;
500
- if (runtimeServerlessPromise !== undefined) {
836
+ // runtime registry, so one drain fans out to both to honor the
837
+ // spec invariant "single shutdown tears down both modes".
838
+ const registries: Promise<void>[] = [];
839
+ if (modeAPromise !== undefined) {
501
840
  registries.push(
502
841
  (async () => {
503
842
  try {
504
- const { runtime, registry } =
505
- await runtimeServerlessPromise;
843
+ const { runtime, registry } = await modeAPromise;
844
+ runtimes.add(runtime);
506
845
  await runtime.shutdownRegistry(registry);
507
846
  } catch (err) {
508
847
  logger().warn(
509
848
  { err },
849
+ "runtime registry shutdown errored (mode A)",
850
+ );
851
+ }
852
+ })(),
853
+ );
854
+ }
855
+ if (modeBPromise !== undefined) {
856
+ registries.push(
857
+ (async () => {
858
+ try {
859
+ const { runtime, registry } = await modeBPromise;
860
+ runtimes.add(runtime);
861
+ await runtime.shutdownRegistry(registry);
862
+ } catch (err) {
863
+ logger().warn(
864
+ { error: err },
510
865
  "runtime registry shutdown errored (mode B)",
511
866
  );
512
867
  }
@@ -522,6 +877,9 @@ export class Registry<A extends RegistryActors> {
522
877
  // already logged any serve-side error.
523
878
  await runtimeServePromise.catch(() => undefined);
524
879
  }
880
+ if (this.#applicationListenerPromise !== undefined) {
881
+ await this.#applicationListenerPromise.catch(() => undefined);
882
+ }
525
883
  };
526
884
  await Promise.race([
527
885
  drain(),
@@ -529,8 +887,35 @@ export class Registry<A extends RegistryActors> {
529
887
  setTimeout(resolve, gracePeriodMs).unref?.(),
530
888
  ),
531
889
  ]);
532
- this.#removeSignalHandlers();
533
- process.kill(process.pid, signal);
890
+ await Promise.all(
891
+ [...runtimes].map((runtime) => runtime.shutdownTelemetry?.()),
892
+ );
893
+ }
894
+
895
+ async #actorStopThresholdMs(
896
+ configuredRegistryPromise:
897
+ | ReturnType<typeof buildConfiguredRegistry>
898
+ | undefined,
899
+ ): Promise<number | undefined> {
900
+ if (configuredRegistryPromise === undefined) return undefined;
901
+ try {
902
+ const { runtime, registry } = await configuredRegistryPromise;
903
+ const thresholdMs =
904
+ await runtime.registryActorStopThresholdMs?.(registry);
905
+ if (
906
+ thresholdMs !== undefined &&
907
+ Number.isFinite(thresholdMs) &&
908
+ thresholdMs > 0
909
+ ) {
910
+ return thresholdMs;
911
+ }
912
+ } catch (err) {
913
+ logger().warn(
914
+ { err },
915
+ "failed to read actor stop threshold for shutdown grace",
916
+ );
917
+ }
918
+ return undefined;
534
919
  }
535
920
 
536
921
  #removeSignalHandlers(): void {
@@ -546,9 +931,101 @@ export class Registry<A extends RegistryActors> {
546
931
  this.#startEnvoy(this.parseConfig(), true);
547
932
  }
548
933
 
934
+ /**
935
+ * Starts the serverful registry if needed and waits until its envoy has
936
+ * registered with the Engine. Repeated and concurrent calls share one
937
+ * startup lifecycle and readiness promise.
938
+ *
939
+ * Unlike {@link start}, this reports startup failures and does not resolve
940
+ * merely because an HTTP health endpoint is listening.
941
+ */
942
+ public startAndWait(): Promise<void> {
943
+ if (this.#shutdownInFlight !== null) {
944
+ return Promise.reject(
945
+ new Error(
946
+ "registry.startAndWait() cannot run after shutdown has begun",
947
+ ),
948
+ );
949
+ }
950
+ if (this.#runtimeReadyPromise) return this.#runtimeReadyPromise;
951
+ try {
952
+ if (getRivetkitRuntimeMode() === "serverless") {
953
+ return Promise.reject(
954
+ new Error(
955
+ "registry.startAndWait() requires envoy runtime mode; serverless registries become ready per request",
956
+ ),
957
+ );
958
+ }
959
+ } catch (error) {
960
+ return Promise.reject(error);
961
+ }
962
+
963
+ const config = this.parseConfig();
964
+ if (config.runtime === "wasm") {
965
+ return Promise.reject(
966
+ new Error(
967
+ "registry.startAndWait() requires the native runtime; WebAssembly registries do not host an envoy",
968
+ ),
969
+ );
970
+ }
971
+ this.#startEnvoy(config, true);
972
+ const configuredRegistryPromise = this.#runtimeServeConfiguredPromise;
973
+ const serveLifecyclePromise = this.#runtimeServeLifecyclePromise;
974
+ if (!configuredRegistryPromise || !serveLifecyclePromise) {
975
+ throw new Error("registry envoy startup did not initialize");
976
+ }
977
+
978
+ const readyTimeoutMs =
979
+ config.engineSpawn &&
980
+ config.endpoint !== undefined &&
981
+ isLocalEngineEndpoint(config.endpoint)
982
+ ? LOCAL_ENGINE_READY_TIMEOUT_MS
983
+ : REGISTRY_READY_TIMEOUT_MS;
984
+ let timeout: ReturnType<typeof setTimeout> | undefined;
985
+ const timeoutPromise = new Promise<never>((_resolve, reject) => {
986
+ timeout = setTimeout(
987
+ () =>
988
+ reject(
989
+ new Error(
990
+ `RivetKit registry did not register with the Engine within ${readyTimeoutMs}ms`,
991
+ ),
992
+ ),
993
+ readyTimeoutMs,
994
+ );
995
+ timeout.unref?.();
996
+ });
997
+ const readinessPromise = (async () => {
998
+ const { runtime, registry } = await configuredRegistryPromise;
999
+ const stoppedBeforeReady = serveLifecyclePromise.then(() => {
1000
+ throw new Error(
1001
+ "RivetKit registry stopped before becoming ready",
1002
+ );
1003
+ });
1004
+ await Promise.race([
1005
+ runtime.waitRegistryReady(registry),
1006
+ stoppedBeforeReady,
1007
+ ]);
1008
+ })();
1009
+ this.#runtimeReadyPromise = Promise.race([
1010
+ readinessPromise,
1011
+ timeoutPromise,
1012
+ ]).finally(() => {
1013
+ if (timeout !== undefined) clearTimeout(timeout);
1014
+ });
1015
+ // The native registry is consumed once serve begins. Retrying the same
1016
+ // instance after failure could duplicate partially-created resources, so
1017
+ // retain the rejected promise and return the same failure to later calls.
1018
+ this.#runtimeReadyPromise.catch(() => {});
1019
+ return this.#runtimeReadyPromise;
1020
+ }
1021
+
549
1022
  /**
550
1023
  * Starts the actor envoy for standalone server deployments.
551
1024
  *
1025
+ * Set `RIVETKIT_RUNTIME_MODE=serverless` to instead bind an HTTP listener
1026
+ * via `listen()` (Mode B). Mode A (envoy) and Mode B (listener) are
1027
+ * mutually exclusive per registry instance.
1028
+ *
552
1029
  * @example
553
1030
  * ```ts
554
1031
  * const registry = setup({ use: { counter } });
@@ -556,13 +1033,144 @@ export class Registry<A extends RegistryActors> {
556
1033
  * ```
557
1034
  */
558
1035
  public start() {
1036
+ if (getRivetkitRuntimeMode() === "serverless") {
1037
+ // start() defaults publicDir to "/public" unless overridden by env.
1038
+ const publicDir = getRivetkitPublicDir() ?? "/public";
1039
+ // Detached listener; bind failures are fatal so exit hard.
1040
+ this.listen({ publicDir }).catch((error) => {
1041
+ logger().error({ error }, "auto-listen failed; exiting");
1042
+ if (
1043
+ typeof process !== "undefined" &&
1044
+ typeof process.exit === "function"
1045
+ ) {
1046
+ process.exit(1);
1047
+ }
1048
+ });
1049
+ return;
1050
+ }
559
1051
  const config = this.parseConfig();
560
1052
  this.#startEnvoy(config, true);
561
1053
  }
562
1054
 
1055
+ /**
1056
+ * Returns the number of actors hosted by this process's envoy, which is zero
1057
+ * while it is not serving. Requires the native runtime.
1058
+ */
1059
+ public activeActorCount(): number {
1060
+ this.#assertActiveActorCountSupported("activeActorCount");
1061
+ const configured = this.#envoyConfiguredRegistry;
1062
+ if (!configured) return 0;
1063
+ const { runtime, registry } = configured;
1064
+ if (!runtime.registryActiveActorCount) {
1065
+ throw new Error(
1066
+ "registry.activeActorCount() is not supported by this runtime",
1067
+ );
1068
+ }
1069
+ return runtime.registryActiveActorCount(registry);
1070
+ }
1071
+
1072
+ /**
1073
+ * Calls `callback` with the number of actors hosted by this process's envoy
1074
+ * and again whenever it changes. Rapid changes may coalesce.
1075
+ * Returns a function that unsubscribes. Requires the native runtime.
1076
+ *
1077
+ * @example
1078
+ * ```ts
1079
+ * const unsubscribe = registry.onActiveActorCountChange((count) => {
1080
+ * setTaskProtection(count > 0);
1081
+ * });
1082
+ * ```
1083
+ */
1084
+ public onActiveActorCountChange(
1085
+ callback: (count: number) => void,
1086
+ ): () => void {
1087
+ this.#assertActiveActorCountSupported("onActiveActorCountChange");
1088
+ // Wrap so the same callback can subscribe twice and unsubscribe independently.
1089
+ const listener = (count: number) => callback(count);
1090
+ this.#activeActorCountListeners.add(listener);
1091
+ this.#syncActiveActorCountSubscription();
1092
+
1093
+ // Start late listeners from the stream, not a direct read, which could see a
1094
+ // change the stream coalesced away and never corrects.
1095
+ const lastCount = this.#lastActiveActorCount;
1096
+ if (lastCount !== undefined) {
1097
+ queueMicrotask(() => {
1098
+ if (this.#activeActorCountListeners.has(listener)) {
1099
+ this.#deliverActiveActorCount(listener, lastCount);
1100
+ }
1101
+ });
1102
+ }
1103
+
1104
+ return () => {
1105
+ this.#activeActorCountListeners.delete(listener);
1106
+ this.#syncActiveActorCountSubscription();
1107
+ };
1108
+ }
1109
+
1110
+ #assertActiveActorCountSupported(method: string): void {
1111
+ this.#activeActorCountSupported ??=
1112
+ this.parseConfig().runtime !== "wasm";
1113
+ if (!this.#activeActorCountSupported) {
1114
+ throw new Error(
1115
+ `registry.${method}() requires the native runtime; WebAssembly registries do not host an envoy`,
1116
+ );
1117
+ }
1118
+ }
1119
+
1120
+ /** Holds one native subscription while any listener is registered. */
1121
+ #syncActiveActorCountSubscription(): void {
1122
+ const configured = this.#envoyConfiguredRegistry;
1123
+ if (!configured) return;
1124
+ const { runtime, registry } = configured;
1125
+ const token = this.#activeActorCountToken;
1126
+
1127
+ if (this.#activeActorCountListeners.size === 0) {
1128
+ if (token !== undefined) {
1129
+ this.#activeActorCountToken = undefined;
1130
+ this.#lastActiveActorCount = undefined;
1131
+ runtime.cancelCancellationToken(token);
1132
+ }
1133
+ return;
1134
+ }
1135
+ if (token !== undefined) return;
1136
+
1137
+ if (!runtime.onRegistryActiveActorCountChange) {
1138
+ throw new Error(
1139
+ "active actor count subscriptions are not supported by this runtime",
1140
+ );
1141
+ }
1142
+ const nextToken = runtime.createCancellationToken();
1143
+ this.#activeActorCountToken = nextToken;
1144
+ runtime.onRegistryActiveActorCountChange(
1145
+ registry,
1146
+ (count) => {
1147
+ // Drop calls still queued from a released subscription.
1148
+ if (this.#activeActorCountToken !== nextToken) return;
1149
+ this.#lastActiveActorCount = count;
1150
+ // Iterate a copy so listeners added by a callback are not called twice.
1151
+ for (const listener of [...this.#activeActorCountListeners]) {
1152
+ this.#deliverActiveActorCount(listener, count);
1153
+ }
1154
+ },
1155
+ nextToken,
1156
+ );
1157
+ }
1158
+
1159
+ #deliverActiveActorCount(
1160
+ listener: (count: number) => void,
1161
+ count: number,
1162
+ ): void {
1163
+ try {
1164
+ listener(count);
1165
+ } catch (error) {
1166
+ logger().error({ error }, "active actor count listener threw");
1167
+ }
1168
+ }
1169
+
563
1170
  #printWelcome(
564
1171
  config: RegistryConfig,
565
1172
  kind: "serverless" | "serverful",
1173
+ listener?: { port: number; host?: string; publicDir?: string },
566
1174
  ): void {
567
1175
  if (config.noWelcome || this.#welcomePrinted) return;
568
1176
  this.#welcomePrinted = true;
@@ -583,7 +1191,9 @@ export class Registry<A extends RegistryActors> {
583
1191
 
584
1192
  if (config.endpoint) {
585
1193
  const endpointType =
586
- config.endpoint === ENGINE_ENDPOINT ? "local native" : "remote";
1194
+ config.startEngine || isLocalEngineEndpoint(config.endpoint)
1195
+ ? "local native"
1196
+ : "remote";
587
1197
  logLine("Endpoint", `${config.endpoint} (${endpointType})`);
588
1198
  }
589
1199
 
@@ -592,6 +1202,15 @@ export class Registry<A extends RegistryActors> {
592
1202
  }
593
1203
 
594
1204
  logLine("Actors", Object.keys(config.use).length.toString());
1205
+
1206
+ if (listener) {
1207
+ const host = listener.host ?? "0.0.0.0";
1208
+ logLine("Listening", `http://${host}:${listener.port}`);
1209
+ if (listener.publicDir) {
1210
+ logLine("Public Dir", listener.publicDir);
1211
+ }
1212
+ }
1213
+
595
1214
  console.log();
596
1215
  }
597
1216
  }
@@ -604,7 +1223,10 @@ function isServerlessStartRequest(request: Request, basePath: string): boolean {
604
1223
  return parsed.pathname === `${normalizedBase}/start`;
605
1224
  }
606
1225
 
607
- function isServerlessMetadataRequest(request: Request, basePath: string): boolean {
1226
+ function isServerlessMetadataRequest(
1227
+ request: Request,
1228
+ basePath: string,
1229
+ ): boolean {
608
1230
  if (request.method !== "GET") return false;
609
1231
  const parsed = new URL(request.url);
610
1232
  const normalizedBase =