rivetkit 0.0.0-main.41efcce → 0.0.0-main.49693dc

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 (299) hide show
  1. package/dist/browser/client.d.ts +939 -104
  2. package/dist/browser/client.js +1867 -900
  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 +2079 -233
  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 +2408 -2029
  13. package/dist/tsup/agent-os/index.cjs.map +1 -1
  14. package/dist/tsup/agent-os/index.d.cts +932 -114
  15. package/dist/tsup/agent-os/index.d.ts +932 -114
  16. package/dist/tsup/agent-os/index.js +2412 -2033
  17. package/dist/tsup/agent-os/index.js.map +1 -1
  18. package/dist/tsup/{chunk-J27CEW6F.js → chunk-2OBVQZX6.js} +6 -6
  19. package/dist/tsup/chunk-2OBVQZX6.js.map +1 -0
  20. package/dist/tsup/chunk-3ZWHWMFJ.js +14 -0
  21. package/dist/tsup/chunk-3ZWHWMFJ.js.map +1 -0
  22. package/dist/tsup/{chunk-AK57AL7S.cjs → chunk-4KGXFC6M.cjs} +238 -22
  23. package/dist/tsup/chunk-4KGXFC6M.cjs.map +1 -0
  24. package/dist/tsup/{chunk-CVHUXINE.js → chunk-5IU3MI7X.js} +594 -72
  25. package/dist/tsup/chunk-5IU3MI7X.js.map +1 -0
  26. package/dist/tsup/{chunk-VD7AZIBR.js → chunk-6CXQMHZR.js} +1161 -361
  27. package/dist/tsup/chunk-6CXQMHZR.js.map +1 -0
  28. package/dist/tsup/{chunk-SBEFJ4IQ.js → chunk-6W2UIH3X.js} +70 -8
  29. package/dist/tsup/chunk-6W2UIH3X.js.map +1 -0
  30. package/dist/tsup/{chunk-7MRGNVSR.js → chunk-6W5VGLFT.js} +237 -21
  31. package/dist/tsup/chunk-6W5VGLFT.js.map +1 -0
  32. package/dist/tsup/{chunk-RF3MEJV6.cjs → chunk-B73TBMMG.cjs} +18 -11
  33. package/dist/tsup/chunk-B73TBMMG.cjs.map +1 -0
  34. package/dist/tsup/chunk-D6TORRA4.js +243 -0
  35. package/dist/tsup/chunk-D6TORRA4.js.map +1 -0
  36. package/dist/tsup/{chunk-PXLJOMJD.js → chunk-FXT3HN32.js} +2 -2
  37. package/dist/tsup/{chunk-ZGWSH7YV.js → chunk-IXBD7BXC.js} +48 -72
  38. package/dist/tsup/chunk-IXBD7BXC.js.map +1 -0
  39. package/dist/tsup/{chunk-3BFYSYRU.js → chunk-JI6GZ2C2.js} +4 -12
  40. package/dist/tsup/chunk-JI6GZ2C2.js.map +1 -0
  41. package/dist/tsup/{chunk-PCBNKI2J.js → chunk-JTHHCZCZ.js} +24 -1
  42. package/dist/tsup/chunk-JTHHCZCZ.js.map +1 -0
  43. package/dist/tsup/{chunk-2NDZ7JCR.cjs → chunk-KVFIONKQ.cjs} +25 -2
  44. package/dist/tsup/chunk-KVFIONKQ.cjs.map +1 -0
  45. package/dist/tsup/{chunk-SPMMF6TR.cjs → chunk-LGOWPZJ5.cjs} +3 -3
  46. package/dist/tsup/chunk-LGOWPZJ5.cjs.map +1 -0
  47. package/dist/tsup/chunk-LYNWTX6R.cjs +14 -0
  48. package/dist/tsup/chunk-LYNWTX6R.cjs.map +1 -0
  49. package/dist/tsup/{chunk-LLD2D5LO.cjs → chunk-MYWZCDML.cjs} +4 -12
  50. package/dist/tsup/chunk-MYWZCDML.cjs.map +1 -0
  51. package/dist/tsup/{chunk-XSC2WWXD.js → chunk-NYDZLWHZ.js} +16 -9
  52. package/dist/tsup/chunk-NYDZLWHZ.js.map +1 -0
  53. package/dist/tsup/{chunk-AV54CVAG.cjs → chunk-RB7WUDX6.cjs} +1290 -490
  54. package/dist/tsup/chunk-RB7WUDX6.cjs.map +1 -0
  55. package/dist/tsup/{chunk-JTL6Y2UN.cjs → chunk-SPJORZMM.cjs} +49 -73
  56. package/dist/tsup/chunk-SPJORZMM.cjs.map +1 -0
  57. package/dist/tsup/chunk-SSMKIYEX.cjs +243 -0
  58. package/dist/tsup/chunk-SSMKIYEX.cjs.map +1 -0
  59. package/dist/tsup/{chunk-TQSL4NJ3.cjs → chunk-TQ4HSX2U.cjs} +72 -10
  60. package/dist/tsup/chunk-TQ4HSX2U.cjs.map +1 -0
  61. package/dist/tsup/{chunk-EVADNK6Z.cjs → chunk-U6ZQELGJ.cjs} +10 -10
  62. package/dist/tsup/chunk-U6ZQELGJ.cjs.map +1 -0
  63. package/dist/tsup/chunk-XLBMKZD3.cjs +1257 -0
  64. package/dist/tsup/chunk-XLBMKZD3.cjs.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 +18 -7
  68. package/dist/tsup/client/mod.d.ts +18 -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.cjs.map +1 -1
  77. package/dist/tsup/common/websocket.js +3 -3
  78. package/dist/tsup/{config-B3RIidaJ.d.ts → config-BXSV17G7.d.cts} +987 -72
  79. package/dist/tsup/{config-D6WxBYjV.d.cts → config-Bi1r6gI7.d.ts} +987 -72
  80. package/dist/tsup/{config-B9qUIHX4.d.ts → config-ey2I2zz5.d.cts} +82 -15
  81. package/dist/tsup/{config-B9qUIHX4.d.cts → config-ey2I2zz5.d.ts} +82 -15
  82. package/dist/tsup/context-4fJemY0D.d.cts +129 -0
  83. package/dist/tsup/context-D4sNYboo.d.ts +129 -0
  84. package/dist/tsup/db/drizzle.cjs +168 -103
  85. package/dist/tsup/db/drizzle.cjs.map +1 -1
  86. package/dist/tsup/db/drizzle.d.cts +8 -4
  87. package/dist/tsup/db/drizzle.d.ts +8 -4
  88. package/dist/tsup/db/drizzle.js +170 -105
  89. package/dist/tsup/db/drizzle.js.map +1 -1
  90. package/dist/tsup/db/mod.cjs +6 -163
  91. package/dist/tsup/db/mod.cjs.map +1 -1
  92. package/dist/tsup/db/mod.d.cts +12 -4
  93. package/dist/tsup/db/mod.d.ts +12 -4
  94. package/dist/tsup/db/mod.js +5 -162
  95. package/dist/tsup/db/mod.js.map +1 -1
  96. package/dist/tsup/dynamic/mod.cjs +24 -0
  97. package/dist/tsup/dynamic/mod.cjs.map +1 -0
  98. package/dist/tsup/dynamic/mod.d.cts +38 -0
  99. package/dist/tsup/dynamic/mod.d.ts +38 -0
  100. package/dist/tsup/dynamic/mod.js +24 -0
  101. package/dist/tsup/dynamic/mod.js.map +1 -0
  102. package/dist/tsup/inspector/mod.cjs +47 -12
  103. package/dist/tsup/inspector/mod.cjs.map +1 -1
  104. package/dist/tsup/inspector/mod.d.cts +26 -136
  105. package/dist/tsup/inspector/mod.d.ts +26 -136
  106. package/dist/tsup/inspector/mod.js +46 -11
  107. package/dist/tsup/inspector/mod.js.map +1 -1
  108. package/dist/tsup/inspector/workflow.cjs +21 -0
  109. package/dist/tsup/inspector/workflow.cjs.map +1 -0
  110. package/dist/tsup/inspector/workflow.d.cts +144 -0
  111. package/dist/tsup/inspector/workflow.d.ts +144 -0
  112. package/dist/tsup/inspector/workflow.js +21 -0
  113. package/dist/tsup/inspector/workflow.js.map +1 -0
  114. package/dist/tsup/inspector-tab/mod.cjs +162 -0
  115. package/dist/tsup/inspector-tab/mod.cjs.map +1 -0
  116. package/dist/tsup/inspector-tab/mod.d.cts +241 -0
  117. package/dist/tsup/inspector-tab/mod.d.ts +241 -0
  118. package/dist/tsup/inspector-tab/mod.js +162 -0
  119. package/dist/tsup/inspector-tab/mod.js.map +1 -0
  120. package/dist/tsup/mod.cjs +4268 -944
  121. package/dist/tsup/mod.cjs.map +1 -1
  122. package/dist/tsup/mod.d.cts +9 -8
  123. package/dist/tsup/mod.d.ts +9 -8
  124. package/dist/tsup/mod.js +4229 -905
  125. package/dist/tsup/mod.js.map +1 -1
  126. package/dist/tsup/test/mod.cjs +26 -21
  127. package/dist/tsup/test/mod.cjs.map +1 -1
  128. package/dist/tsup/test/mod.d.cts +7 -6
  129. package/dist/tsup/test/mod.d.ts +7 -6
  130. package/dist/tsup/test/mod.js +25 -20
  131. package/dist/tsup/test/mod.js.map +1 -1
  132. package/dist/tsup/unstable/migrations.cjs +101 -0
  133. package/dist/tsup/unstable/migrations.cjs.map +1 -0
  134. package/dist/tsup/unstable/migrations.d.cts +29 -0
  135. package/dist/tsup/unstable/migrations.d.ts +29 -0
  136. package/dist/tsup/unstable/migrations.js +101 -0
  137. package/dist/tsup/unstable/migrations.js.map +1 -0
  138. package/dist/tsup/utils-Bbz-3411.d.cts +162 -0
  139. package/dist/tsup/utils-BqdWVlzm.d.ts +162 -0
  140. package/dist/tsup/utils-vvJQyygr.d.cts +109 -0
  141. package/dist/tsup/utils-vvJQyygr.d.ts +109 -0
  142. package/dist/tsup/utils.cjs +7 -3
  143. package/dist/tsup/utils.cjs.map +1 -1
  144. package/dist/tsup/utils.d.cts +4 -147
  145. package/dist/tsup/utils.d.ts +4 -147
  146. package/dist/tsup/utils.js +6 -2
  147. package/dist/tsup/workflow/mod.cjs +517 -412
  148. package/dist/tsup/workflow/mod.cjs.map +1 -1
  149. package/dist/tsup/workflow/mod.d.cts +11 -10
  150. package/dist/tsup/workflow/mod.d.ts +11 -10
  151. package/dist/tsup/workflow/mod.js +511 -406
  152. package/dist/tsup/workflow/mod.js.map +1 -1
  153. package/package.json +62 -14
  154. package/src/actor/actions.ts +119 -0
  155. package/src/actor/config.test.ts +78 -0
  156. package/src/actor/config.ts +518 -96
  157. package/src/actor/contexts/index.ts +7 -2
  158. package/src/actor/definition.ts +38 -26
  159. package/src/actor/errors.ts +101 -89
  160. package/src/actor/keys.ts +2 -1
  161. package/src/actor/mod.ts +32 -21
  162. package/src/actor/schema.ts +2 -2
  163. package/src/agent-os/actor/cron.ts +37 -2
  164. package/src/agent-os/actor/index.ts +39 -19
  165. package/src/agent-os/actor/preview.ts +1 -2
  166. package/src/agent-os/actor/session.ts +2 -2
  167. package/src/agent-os/config.ts +1 -1
  168. package/src/agent-os/fs/database-vfs.ts +1 -1
  169. package/src/agent-os/index.ts +16 -15
  170. package/src/agent-os/types.ts +11 -0
  171. package/src/client/actor-common.ts +106 -53
  172. package/src/client/actor-conn.ts +94 -45
  173. package/src/client/actor-handle.ts +198 -79
  174. package/src/client/actor-query.ts +13 -6
  175. package/src/client/client.ts +43 -15
  176. package/src/client/config.ts +8 -0
  177. package/src/client/errors.ts +4 -2
  178. package/src/client/lifecycle-errors.ts +28 -4
  179. package/src/client/mod.ts +9 -4
  180. package/src/client/query.ts +3 -1
  181. package/src/client/queue.ts +8 -3
  182. package/src/client/raw-utils.ts +24 -16
  183. package/src/client/resolve-gateway-target.ts +3 -1
  184. package/src/client/utils.ts +36 -10
  185. package/src/common/actor-router-consts.ts +7 -0
  186. package/src/common/actor-websocket.ts +3 -1
  187. package/src/common/bare/actor-persist/v1.ts +205 -163
  188. package/src/common/bare/actor-persist/v2.ts +265 -213
  189. package/src/common/bare/actor-persist/v3.ts +176 -172
  190. package/src/common/bare/actor-persist/v4.ts +254 -253
  191. package/src/common/bare/generated/actor-runtime-socket-protocol/v1.ts +848 -0
  192. package/src/common/bare/generated/client-protocol/v4.ts +599 -0
  193. package/src/common/bare/generated/inspector/v5.ts +1016 -0
  194. package/src/common/bare/generated/inspector/v6.ts +1367 -0
  195. package/src/common/bare/transport/v1.ts +694 -542
  196. package/src/common/client-protocol-versioned.ts +176 -67
  197. package/src/common/client-protocol-zod.ts +7 -0
  198. package/src/common/client-protocol.ts +1 -1
  199. package/src/common/database/config.ts +103 -10
  200. package/src/common/database/mod.test.ts +364 -0
  201. package/src/common/database/mod.ts +278 -149
  202. package/src/common/database/native-database.test.ts +220 -0
  203. package/src/common/database/native-database.ts +394 -58
  204. package/src/common/database/shared.ts +25 -0
  205. package/src/common/encoding.ts +302 -38
  206. package/src/common/engine.ts +28 -1
  207. package/src/common/eventsource.ts +1 -1
  208. package/src/common/fetch-like.ts +49 -0
  209. package/src/common/inline-websocket-adapter.ts +14 -13
  210. package/src/common/inspector-transport.ts +12 -2
  211. package/src/common/log.ts +117 -14
  212. package/src/common/router.ts +49 -23
  213. package/src/common/utils.ts +23 -203
  214. package/src/common/websocket-interface.ts +1 -1
  215. package/src/db/drizzle.test.ts +164 -0
  216. package/src/db/drizzle.ts +207 -121
  217. package/src/db/mod.ts +6 -1
  218. package/src/devtools-loader/index.ts +4 -7
  219. package/src/devtools-loader/serve-devtools.ts +26 -0
  220. package/src/dynamic/instance.ts +32 -0
  221. package/src/dynamic/internal.ts +50 -0
  222. package/src/dynamic/isolate-runtime.ts +64 -0
  223. package/src/dynamic/mod.ts +32 -0
  224. package/src/engine-client/actor-http-client.ts +23 -4
  225. package/src/engine-client/actor-websocket-client.ts +32 -5
  226. package/src/engine-client/api-endpoints.ts +52 -2
  227. package/src/engine-client/api-utils.ts +2 -2
  228. package/src/engine-client/driver.ts +21 -17
  229. package/src/engine-client/mod.ts +116 -64
  230. package/src/engine-client/ws-proxy.ts +9 -4
  231. package/src/globals.d.ts +4 -0
  232. package/src/inspector/client.browser.ts +127 -15
  233. package/src/inspector/mod.ts +2 -4
  234. package/src/inspector/workflow.ts +61 -0
  235. package/src/inspector-tab/mod.ts +301 -0
  236. package/src/registry/config/envoy.ts +1 -2
  237. package/src/registry/config/index.ts +160 -53
  238. package/src/registry/config/serverless.ts +7 -1
  239. package/src/registry/index.ts +659 -96
  240. package/src/registry/napi-runtime.ts +1154 -0
  241. package/src/registry/native-validation.ts +10 -12
  242. package/src/registry/native.ts +2005 -955
  243. package/src/registry/process-metrics.ts +250 -0
  244. package/src/registry/run-handler-coordinator.test.ts +252 -0
  245. package/src/registry/run-handler-coordinator.ts +219 -0
  246. package/src/registry/runtime.test.ts +50 -0
  247. package/src/registry/runtime.ts +839 -0
  248. package/src/registry/wasm-runtime.ts +1283 -0
  249. package/src/registry/write-through-proxy.ts +141 -0
  250. package/src/serde.ts +8 -2
  251. package/src/serverless/configure.ts +102 -49
  252. package/src/test/mod.ts +2 -17
  253. package/src/test/ready.ts +22 -0
  254. package/src/unstable/migrations.test.ts +170 -0
  255. package/src/unstable/migrations.ts +141 -0
  256. package/src/utils/crypto.ts +14 -0
  257. package/src/utils/endpoint-parser.ts +1 -1
  258. package/src/utils/env-vars.ts +39 -0
  259. package/src/utils/node.ts +44 -28
  260. package/src/utils/router.ts +1 -1
  261. package/src/utils.ts +4 -2
  262. package/src/workflow/context.ts +683 -242
  263. package/src/workflow/driver.test.ts +62 -0
  264. package/src/workflow/driver.ts +246 -119
  265. package/src/workflow/inspector.ts +24 -24
  266. package/src/workflow/mod.ts +76 -84
  267. package/dist/tsup/chunk-2NDZ7JCR.cjs.map +0 -1
  268. package/dist/tsup/chunk-3BFYSYRU.js.map +0 -1
  269. package/dist/tsup/chunk-6AVUJ52Q.cjs +0 -253
  270. package/dist/tsup/chunk-6AVUJ52Q.cjs.map +0 -1
  271. package/dist/tsup/chunk-7MRGNVSR.js.map +0 -1
  272. package/dist/tsup/chunk-7X7RVTFF.cjs +0 -735
  273. package/dist/tsup/chunk-7X7RVTFF.cjs.map +0 -1
  274. package/dist/tsup/chunk-AK57AL7S.cjs.map +0 -1
  275. package/dist/tsup/chunk-AV54CVAG.cjs.map +0 -1
  276. package/dist/tsup/chunk-CVHUXINE.js.map +0 -1
  277. package/dist/tsup/chunk-EVADNK6Z.cjs.map +0 -1
  278. package/dist/tsup/chunk-J27CEW6F.js.map +0 -1
  279. package/dist/tsup/chunk-JTL6Y2UN.cjs.map +0 -1
  280. package/dist/tsup/chunk-LLD2D5LO.cjs.map +0 -1
  281. package/dist/tsup/chunk-PCBNKI2J.js.map +0 -1
  282. package/dist/tsup/chunk-RF3MEJV6.cjs.map +0 -1
  283. package/dist/tsup/chunk-SB4MXRN2.js +0 -253
  284. package/dist/tsup/chunk-SB4MXRN2.js.map +0 -1
  285. package/dist/tsup/chunk-SBEFJ4IQ.js.map +0 -1
  286. package/dist/tsup/chunk-SPMMF6TR.cjs.map +0 -1
  287. package/dist/tsup/chunk-TQSL4NJ3.cjs.map +0 -1
  288. package/dist/tsup/chunk-VD7AZIBR.js.map +0 -1
  289. package/dist/tsup/chunk-XSC2WWXD.js.map +0 -1
  290. package/dist/tsup/chunk-ZGWSH7YV.js.map +0 -1
  291. package/dist/tsup/context-BxvHh9wi.d.cts +0 -92
  292. package/dist/tsup/context-CNIZBIKl.d.ts +0 -92
  293. package/dist/tsup/utils-fwx3o3K9.d.cts +0 -18
  294. package/dist/tsup/utils-fwx3o3K9.d.ts +0 -18
  295. package/src/actor/driver.ts +0 -141
  296. package/src/actor/instance/mod.ts +0 -2501
  297. package/src/drivers/engine/actor-driver.ts +0 -2470
  298. package/src/utils/serve.ts +0 -217
  299. /package/dist/tsup/{chunk-PXLJOMJD.js.map → chunk-FXT3HN32.js.map} +0 -0
@@ -1,17 +1,75 @@
1
+ import { isLocalEngineEndpoint } from "@/common/engine";
2
+ import { isResponseLike } from "@/common/fetch-like";
3
+ import { configureBaseLogger } from "@/common/log";
4
+ import { configureServerlessPool } from "@/serverless/configure";
5
+ import { VERSION } from "@/utils";
6
+ import {
7
+ getRivetkitPublicDir,
8
+ getRivetkitRuntimeMode,
9
+ parsePortEnv,
10
+ } from "@/utils/env-vars";
1
11
  import {
2
12
  type RegistryActors,
3
13
  type RegistryConfig,
4
14
  type RegistryConfigInput,
5
15
  RegistryConfigSchema,
6
16
  } from "./config";
7
- import { ENGINE_ENDPOINT } from "@/common/engine";
8
17
  import { logger } from "./log";
9
- import { buildNativeRegistry } from "./native";
10
- import { configureServerlessPool } from "@/serverless/configure";
11
- import { VERSION } from "@/utils";
18
+ import { buildConfiguredRegistry } from "./native";
19
+ import type {
20
+ RuntimeApplicationFetch,
21
+ RuntimeServerlessResponseHead,
22
+ } from "./runtime";
12
23
 
13
24
  type ShutdownSignal = "SIGINT" | "SIGTERM";
14
25
 
26
+ const REGISTRY_READY_TIMEOUT_MS = 30_000;
27
+
28
+ function signalExitCode(signal: ShutdownSignal): number {
29
+ switch (signal) {
30
+ case "SIGINT":
31
+ return 130;
32
+ case "SIGTERM":
33
+ return 143;
34
+ }
35
+ }
36
+
37
+ function finishShutdownSignal(signal: ShutdownSignal): void {
38
+ if (process.pid === 1) {
39
+ process.exit(signalExitCode(signal));
40
+ }
41
+ process.kill(process.pid, signal);
42
+ }
43
+
44
+ function createApplicationFetch(
45
+ application: RegistryApplication,
46
+ ): RuntimeApplicationFetch {
47
+ return async (request) => {
48
+ const method = request.method.toUpperCase();
49
+ const body =
50
+ method === "GET" || method === "HEAD" || request.body.length === 0
51
+ ? undefined
52
+ : Uint8Array.from(request.body).buffer;
53
+ const response = await application.fetch(
54
+ new Request(request.url, {
55
+ method,
56
+ headers: request.headers,
57
+ body,
58
+ }),
59
+ );
60
+ if (!isResponseLike(response)) {
61
+ throw new TypeError(
62
+ "registry.listen() application fetch must return a Response",
63
+ );
64
+ }
65
+ return {
66
+ status: response.status,
67
+ headers: Object.fromEntries(response.headers.entries()),
68
+ body: new Uint8Array(await response.arrayBuffer()),
69
+ };
70
+ };
71
+ }
72
+
15
73
  export type FetchHandler = (
16
74
  request: Request,
17
75
  ...args: any
@@ -21,8 +79,36 @@ export interface ServerlessHandler {
21
79
  fetch: FetchHandler;
22
80
  }
23
81
 
82
+ export interface RegistryApplication {
83
+ fetch: FetchHandler;
84
+ }
85
+
86
+ export interface RegistryListenOptions {
87
+ port?: number;
88
+ host?: string;
89
+ publicDir?: string;
90
+ application?: RegistryApplication;
91
+ }
92
+
93
+ export interface RegistryRoutes {
94
+ health(): Promise<Response>;
95
+ metadata(): Promise<Response>;
96
+ prometheusMetrics(request?: Request): Promise<Response>;
97
+ }
98
+
99
+ /**
100
+ * Injectable dependencies for {@link Registry}. Production code uses the
101
+ * defaults. Tests override `buildConfiguredRegistry` to drive lifecycle
102
+ * orchestration against a fake `CoreRuntime` without an engine.
103
+ */
104
+ export interface RegistryDeps {
105
+ buildConfiguredRegistry: typeof buildConfiguredRegistry;
106
+ }
107
+
24
108
  export class Registry<A extends RegistryActors> {
25
109
  #config: RegistryConfigInput<A>;
110
+ #buildConfiguredRegistry: typeof buildConfiguredRegistry;
111
+ public readonly routes: RegistryRoutes;
26
112
 
27
113
  get config(): RegistryConfigInput<A> {
28
114
  return this.#config;
@@ -32,16 +118,55 @@ export class Registry<A extends RegistryActors> {
32
118
  return RegistryConfigSchema.parse(this.#config);
33
119
  }
34
120
 
35
- #nativeServePromise?: Promise<void>;
36
- #nativeServerlessPromise?: ReturnType<typeof buildNativeRegistry>;
121
+ #runtimeServePromise?: Promise<void>;
122
+ #runtimeServeLifecyclePromise?: Promise<void>;
123
+ #runtimeReadyPromise?: Promise<void>;
124
+ #runtimeServeConfiguredPromise?: ReturnType<typeof buildConfiguredRegistry>;
125
+ #runtimeServerlessPromise?: ReturnType<typeof buildConfiguredRegistry>;
126
+ #applicationListenerPromise?: Promise<void>;
37
127
  #configureServerlessPoolPromise?: Promise<void>;
38
128
  #welcomePrinted = false;
39
129
  #shutdownInstalled = false;
40
130
  #shutdownInFlight: Promise<void> | null = null;
41
131
  #signalHandlers: Partial<Record<ShutdownSignal, () => void>> = {};
42
132
 
43
- constructor(config: RegistryConfigInput<A>) {
133
+ constructor(config: RegistryConfigInput<A>, deps?: Partial<RegistryDeps>) {
44
134
  this.#config = config;
135
+ if (config.logging?.baseLogger) {
136
+ configureBaseLogger(config.logging.baseLogger);
137
+ }
138
+ this.#buildConfiguredRegistry =
139
+ deps?.buildConfiguredRegistry ?? buildConfiguredRegistry;
140
+ this.routes = {
141
+ health: () => this.#healthRoute(),
142
+ metadata: () => this.#metadataRoute(),
143
+ prometheusMetrics: (request?: Request) =>
144
+ this.#prometheusMetricsRoute(request),
145
+ };
146
+ }
147
+
148
+ /**
149
+ * Fires `configureServerlessPool` once per process when the registry
150
+ * config opts into it. Cached on the instance so repeated calls (from
151
+ * `handler()` and `listen()`) only run the upsert once. The retry loop
152
+ * inside `configureServerlessPool` tolerates the engine still warming up.
153
+ */
154
+ #ensureServerlessPoolConfigured(
155
+ config: RegistryConfig,
156
+ ): Promise<void> | undefined {
157
+ if (!config.configurePool) return undefined;
158
+
159
+ if (!this.#configureServerlessPoolPromise) {
160
+ this.#configureServerlessPoolPromise = configureServerlessPool(
161
+ config,
162
+ ).catch((error) => {
163
+ this.#configureServerlessPoolPromise = undefined;
164
+ throw error;
165
+ });
166
+ this.#configureServerlessPoolPromise.catch(() => {});
167
+ }
168
+
169
+ return this.#configureServerlessPoolPromise;
45
170
  }
46
171
 
47
172
  /**
@@ -58,19 +183,46 @@ export class Registry<A extends RegistryActors> {
58
183
  const config = this.parseConfig();
59
184
  this.#printWelcome(config, "serverless");
60
185
 
61
- if (config.configurePool && !this.#configureServerlessPoolPromise) {
62
- this.#configureServerlessPoolPromise =
63
- configureServerlessPool(config);
186
+ if (!this.#runtimeServerlessPromise) {
187
+ this.#runtimeServerlessPromise =
188
+ this.#buildConfiguredRegistry(config);
64
189
  }
65
190
 
66
- if (!this.#nativeServerlessPromise) {
67
- this.#nativeServerlessPromise = buildNativeRegistry(config);
191
+ const { runtime, registry, serveConfig } =
192
+ await this.#runtimeServerlessPromise;
193
+ const isStartRequest = isServerlessStartRequest(
194
+ request,
195
+ serveConfig.serverlessBasePath ?? "/api/rivet",
196
+ );
197
+ const isMetadataRequest = isServerlessMetadataRequest(
198
+ request,
199
+ serveConfig.serverlessBasePath ?? "/api/rivet",
200
+ );
201
+ const isEngineMetadataRequest =
202
+ request.headers.get("user-agent")?.startsWith("RivetEngine/") ??
203
+ false;
204
+
205
+ if (isStartRequest) {
206
+ try {
207
+ await this.#ensureServerlessPoolConfigured(config);
208
+ } catch (_error) {
209
+ return new Response(
210
+ JSON.stringify({
211
+ group: "guard",
212
+ code: "service_unavailable",
213
+ message: "Serverless pool is not configured.",
214
+ metadata: null,
215
+ }),
216
+ {
217
+ status: 503,
218
+ headers: { "content-type": "application/json" },
219
+ },
220
+ );
221
+ }
68
222
  }
69
223
 
70
- const { bindings, registry, serveConfig } =
71
- await this.#nativeServerlessPromise;
72
- const cancelToken = new bindings.CancellationToken();
73
- const abort = () => cancelToken.cancel();
224
+ const cancelToken = runtime.createCancellationToken();
225
+ const abort = () => runtime.cancelCancellationToken(cancelToken);
74
226
  if (request.signal.aborted) {
75
227
  abort();
76
228
  } else {
@@ -79,14 +231,11 @@ export class Registry<A extends RegistryActors> {
79
231
 
80
232
  const requestBody = await request.arrayBuffer();
81
233
  if (
82
- isServerlessStartRequest(
83
- request,
84
- serveConfig.serverlessBasePath ?? "/api/rivet",
85
- ) &&
234
+ isStartRequest &&
86
235
  requestBody.byteLength > serveConfig.serverlessMaxStartPayloadBytes
87
236
  ) {
88
237
  request.signal.removeEventListener("abort", abort);
89
- cancelToken.cancel();
238
+ runtime.cancelCancellationToken(cancelToken);
90
239
  return new Response(
91
240
  JSON.stringify({
92
241
  group: "message",
@@ -102,7 +251,9 @@ export class Registry<A extends RegistryActors> {
102
251
  }
103
252
 
104
253
  let settled = false;
105
- let controllerRef: ReadableStreamDefaultController<Uint8Array> | undefined;
254
+ let controllerRef:
255
+ | ReadableStreamDefaultController<Uint8Array>
256
+ | undefined;
106
257
  const backpressureWaiters: Array<() => void> = [];
107
258
  const resolveBackpressure = () => {
108
259
  while (
@@ -129,7 +280,7 @@ export class Registry<A extends RegistryActors> {
129
280
  cancel() {
130
281
  settled = true;
131
282
  resolveBackpressure();
132
- cancelToken.cancel();
283
+ runtime.cancelCancellationToken(cancelToken);
133
284
  },
134
285
  });
135
286
 
@@ -138,20 +289,21 @@ export class Registry<A extends RegistryActors> {
138
289
  headers[key] = value;
139
290
  });
140
291
 
141
- let head;
292
+ let head: RuntimeServerlessResponseHead;
142
293
  try {
143
- head = await registry.handleServerlessRequest(
294
+ head = await runtime.handleServerlessRequest(
295
+ registry,
144
296
  {
145
297
  method: request.method,
146
298
  url: request.url,
147
299
  headers,
148
- body: Buffer.from(requestBody),
300
+ body: new Uint8Array(requestBody),
149
301
  },
150
302
  async (
151
303
  error: unknown,
152
304
  event?: {
153
305
  kind: "chunk" | "end";
154
- chunk?: Buffer;
306
+ chunk?: Uint8Array;
155
307
  error?: {
156
308
  group: string;
157
309
  code: string;
@@ -185,13 +337,32 @@ export class Registry<A extends RegistryActors> {
185
337
  serveConfig,
186
338
  );
187
339
  } catch (err) {
188
- // The NAPI call itself rejected (e.g. `registry_shut_down_error`).
340
+ // The runtime call itself rejected (e.g. `registry_shut_down_error`).
189
341
  // Clean up the abort listener so it doesn't leak, then propagate.
190
342
  request.signal.removeEventListener("abort", abort);
191
- cancelToken.cancel();
343
+ runtime.cancelCancellationToken(cancelToken);
192
344
  throw err;
193
345
  }
194
346
 
347
+ if (isMetadataRequest && !isEngineMetadataRequest) {
348
+ try {
349
+ await this.#ensureServerlessPoolConfigured(config);
350
+ } catch (_error) {
351
+ return new Response(
352
+ JSON.stringify({
353
+ group: "guard",
354
+ code: "service_unavailable",
355
+ message: "Serverless pool is not configured.",
356
+ metadata: null,
357
+ }),
358
+ {
359
+ status: 503,
360
+ headers: { "content-type": "application/json" },
361
+ },
362
+ );
363
+ }
364
+ }
365
+
195
366
  return new Response(stream, {
196
367
  status: head.status,
197
368
  headers: head.headers,
@@ -212,39 +383,242 @@ export class Registry<A extends RegistryActors> {
212
383
  };
213
384
  }
214
385
 
386
+ /**
387
+ * Bind an HTTP listener provided by the native (Rust) runtime and serve
388
+ * the registry's serverless endpoints over it. Resolves only after the
389
+ * registry is shut down (SIGINT/SIGTERM or `nativeRegistry.shutdown()`).
390
+ *
391
+ * @param opts.port Port to listen on. Defaults to `process.env.RIVET_PORT`
392
+ * if set, otherwise 3000.
393
+ * @param opts.host Address to bind. Defaults to `0.0.0.0`.
394
+ * @param opts.publicDir If set, serves static files from this directory
395
+ * as a fallback below the framework routes.
396
+ * @param opts.application If set, handles requests that do not match a
397
+ * framework route.
398
+ *
399
+ * @example
400
+ * ```ts
401
+ * await registry.listen();
402
+ * await registry.listen({ application: app });
403
+ * ```
404
+ */
405
+ public async listen(opts: RegistryListenOptions = {}): Promise<void> {
406
+ const port = opts.port ?? parsePortEnv(process.env.RIVET_PORT) ?? 3000;
407
+ const publicDir = opts.publicDir ?? getRivetkitPublicDir();
408
+ const config = this.parseConfig();
409
+ const application = opts.application
410
+ ? createApplicationFetch(opts.application)
411
+ : undefined;
412
+
413
+ if (application && getRivetkitRuntimeMode() !== "serverless") {
414
+ if (config.runtime === "wasm") {
415
+ throw new Error(
416
+ "registry.listen() requires the native runtime; use an application-owned HTTP server with WebAssembly",
417
+ );
418
+ }
419
+ this.#installSignalHandlers(config);
420
+ this.#printWelcome(config, "serverful", {
421
+ port,
422
+ host: opts.host,
423
+ publicDir,
424
+ });
425
+ this.#startEnvoy(config, true);
426
+ const readyPromise = this.startAndWait();
427
+ const configuredRegistryPromise =
428
+ this.#runtimeServeConfiguredPromise;
429
+ if (!configuredRegistryPromise) {
430
+ throw new Error("registry envoy startup did not initialize");
431
+ }
432
+ const { runtime, registry, serveConfig } =
433
+ await configuredRegistryPromise;
434
+ const listenerPromise = runtime.serveApplicationListener(
435
+ registry,
436
+ {
437
+ port,
438
+ host: opts.host,
439
+ publicDir,
440
+ application,
441
+ },
442
+ serveConfig,
443
+ );
444
+ this.#applicationListenerPromise = listenerPromise;
445
+ const serveLifecyclePromise = this.#runtimeServeLifecyclePromise;
446
+ if (!serveLifecyclePromise) {
447
+ throw new Error(
448
+ "registry envoy serve lifecycle did not initialize",
449
+ );
450
+ }
451
+ await Promise.all([
452
+ readyPromise,
453
+ listenerPromise,
454
+ serveLifecyclePromise,
455
+ ]);
456
+ return;
457
+ }
458
+
459
+ // Cache on both promise fields so the shutdown drain sees Mode A and B.
460
+ const configuredRegistryPromise = buildConfiguredRegistry(config);
461
+ this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
462
+ this.#runtimeServerlessPromise = configuredRegistryPromise;
463
+ this.#installSignalHandlers(config);
464
+
465
+ this.#printWelcome(config, "serverless", {
466
+ port,
467
+ host: opts.host,
468
+ publicDir,
469
+ });
470
+
471
+ // Background fire; the retry loop tolerates engine warm-up.
472
+ this.#ensureServerlessPoolConfigured(config);
473
+
474
+ const { runtime, registry, serveConfig } =
475
+ await configuredRegistryPromise;
476
+ await runtime.serveListener(
477
+ registry,
478
+ {
479
+ port,
480
+ host: opts.host,
481
+ publicDir,
482
+ application,
483
+ },
484
+ serveConfig,
485
+ );
486
+ }
487
+
488
+ /**
489
+ * Returns a health response suitable for mounting in a user-owned router.
490
+ */
491
+ async #healthRoute(): Promise<Response> {
492
+ const configured = await this.#activeConfiguredRegistry();
493
+ if (!configured) {
494
+ return jsonRouteResponse(503, {
495
+ status: "not_started",
496
+ runtime: "rivetkit",
497
+ version: VERSION,
498
+ });
499
+ }
500
+
501
+ const { runtime, registry } = configured;
502
+ if (!runtime.registryHealth) {
503
+ return jsonRouteResponse(501, {
504
+ status: "unsupported",
505
+ runtime: "rivetkit",
506
+ version: VERSION,
507
+ });
508
+ }
509
+
510
+ const response = await runtime.registryHealth(registry);
511
+ return new Response(new Uint8Array(response.body), {
512
+ status: response.status,
513
+ headers: response.headers,
514
+ });
515
+ }
516
+
517
+ /**
518
+ * Returns serverless metadata suitable for mounting in a user-owned router.
519
+ */
520
+ async #metadataRoute(): Promise<Response> {
521
+ const configured = await this.#activeConfiguredRegistry();
522
+ if (!configured) {
523
+ return new Response("registry not started\n", {
524
+ status: 503,
525
+ headers: { "content-type": "text/plain; charset=utf-8" },
526
+ });
527
+ }
528
+
529
+ const { runtime, registry } = configured;
530
+ if (!runtime.registryMetadata) {
531
+ return new Response("metadata is not supported by this runtime\n", {
532
+ status: 501,
533
+ headers: { "content-type": "text/plain; charset=utf-8" },
534
+ });
535
+ }
536
+
537
+ const response = await runtime.registryMetadata(registry);
538
+ return new Response(new Uint8Array(response.body), {
539
+ status: response.status,
540
+ headers: response.headers,
541
+ });
542
+ }
543
+
544
+ /**
545
+ * Returns a Prometheus metrics response suitable for mounting in a user-owned router.
546
+ */
547
+ async #prometheusMetricsRoute(_request?: Request): Promise<Response> {
548
+ const configured = await this.#activeConfiguredRegistry();
549
+ if (!configured) {
550
+ return new Response("registry not started\n", {
551
+ status: 503,
552
+ headers: { "content-type": "text/plain; charset=utf-8" },
553
+ });
554
+ }
555
+
556
+ const { runtime, registry } = configured;
557
+ if (!runtime.registryMetrics) {
558
+ return new Response("metrics are not supported by this runtime\n", {
559
+ status: 501,
560
+ headers: { "content-type": "text/plain; charset=utf-8" },
561
+ });
562
+ }
563
+
564
+ const response = await runtime.registryMetrics(registry);
565
+ return new Response(new Uint8Array(response.body), {
566
+ status: response.status,
567
+ headers: response.headers,
568
+ });
569
+ }
570
+
571
+ async #activeConfiguredRegistry(): Promise<
572
+ Awaited<ReturnType<typeof buildConfiguredRegistry>> | undefined
573
+ > {
574
+ const candidates = [
575
+ this.#runtimeServerlessPromise,
576
+ this.#runtimeServeConfiguredPromise,
577
+ ].filter(
578
+ (
579
+ candidate,
580
+ ): candidate is ReturnType<typeof buildConfiguredRegistry> =>
581
+ candidate !== undefined,
582
+ );
583
+
584
+ if (candidates.length === 0) return undefined;
585
+ return await candidates[0]!;
586
+ }
587
+
215
588
  /**
216
589
  * Starts an actor envoy for standalone server deployments.
217
590
  */
218
591
  #startEnvoy(config: RegistryConfig, printWelcome: boolean) {
219
- if (!this.#nativeServePromise) {
220
- const nativeRegistryPromise = buildNativeRegistry(config);
221
- this.#nativeServePromise = nativeRegistryPromise
222
- .then(async ({ registry, serveConfig }) => {
223
- await registry.serve(serveConfig);
224
- })
225
- .catch((err) => {
592
+ if (!this.#runtimeServePromise) {
593
+ const configuredRegistryPromise =
594
+ this.#buildConfiguredRegistry(config);
595
+ this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
596
+ this.#runtimeServeLifecyclePromise = configuredRegistryPromise.then(
597
+ async ({ runtime, registry, serveConfig }) => {
598
+ await runtime.serveRegistry(registry, serveConfig);
599
+ },
600
+ );
601
+ this.#runtimeServePromise =
602
+ this.#runtimeServeLifecyclePromise.catch((error) => {
226
603
  // Always-attached catch so the stored promise never leaves a
227
604
  // rejection unhandled. Downstream awaits (e.g. #runShutdown's
228
605
  // Promise.race) attach their own catches and still observe
229
606
  // resolution via the race.
230
- logger().warn({ err }, "native registry serve errored");
607
+ logger().warn({ error }, "runtime registry serve errored");
231
608
  });
232
609
  // Install signal handlers once an envoy lifecycle has begun. Only
233
610
  // Mode A ever reaches here. Mode B (handler(request)) intentionally
234
611
  // does not install handlers because it runs on Workers/Vercel/Deno
235
612
  // Deploy where `process.on` is absent or forbidden; those platforms
236
613
  // own their own signal policy.
237
- this.#installSignalHandlers(config, nativeRegistryPromise);
614
+ this.#installSignalHandlers(config);
238
615
  }
239
616
  if (printWelcome) {
240
617
  this.#printWelcome(config, "serverful");
241
618
  }
242
619
  }
243
620
 
244
- #installSignalHandlers(
245
- config: RegistryConfig,
246
- nativeRegistryPromise: ReturnType<typeof buildNativeRegistry>,
247
- ): void {
621
+ #installSignalHandlers(config: RegistryConfig): void {
248
622
  if (this.#shutdownInstalled) return;
249
623
  if (config.shutdown?.disableSignalHandlers) return;
250
624
  // Guard against non-Node runtimes (Workers/Edge) where `process` may
@@ -259,8 +633,7 @@ export class Registry<A extends RegistryActors> {
259
633
  this.#shutdownInstalled = true;
260
634
 
261
635
  const install = (signal: ShutdownSignal) => {
262
- const handler = () =>
263
- this.#onShutdownSignal(signal, config, nativeRegistryPromise);
636
+ const handler = () => this.#onShutdownSignal(signal, config);
264
637
  this.#signalHandlers[signal] = handler;
265
638
  process.on(signal, handler);
266
639
  };
@@ -268,66 +641,102 @@ export class Registry<A extends RegistryActors> {
268
641
  install("SIGTERM");
269
642
  }
270
643
 
271
- #onShutdownSignal(
272
- signal: ShutdownSignal,
273
- config: RegistryConfig,
274
- nativeRegistryPromise: ReturnType<typeof buildNativeRegistry>,
275
- ): void {
644
+ #onShutdownSignal(signal: ShutdownSignal, config: RegistryConfig): void {
276
645
  if (this.#shutdownInFlight !== null) {
277
- // Second delivery of the same (or another) shutdown signal.
278
- // Remove our handler only (preserving any user-installed listeners)
279
- // and re-raise so Node proceeds with its default exit path.
646
+ // Second delivery of the same (or another) shutdown signal, or a
647
+ // drain already started by an explicit `shutdown()` call. Remove
648
+ // our handler only, preserving any user-installed listeners. PID 1
649
+ // must exit directly because re-raised default signals can be
650
+ // swallowed by the container signal path.
280
651
  this.#removeSignalHandlers();
281
- process.kill(process.pid, signal);
652
+ finishShutdownSignal(signal);
282
653
  return;
283
654
  }
284
- this.#shutdownInFlight = this.#runShutdown(
285
- signal,
286
- config,
287
- nativeRegistryPromise,
288
- ).catch((err) => {
655
+ this.#shutdownInFlight = this.#drain(config)
656
+ .catch((err) => {
657
+ logger().warn({ err }, "shutdown error");
658
+ })
659
+ .then(() => {
660
+ this.#removeSignalHandlers();
661
+ finishShutdownSignal(signal);
662
+ });
663
+ }
664
+
665
+ /**
666
+ * Gracefully drains all live registries.
667
+ *
668
+ * Programmatic counterpart to the SIGINT/SIGTERM handlers: tears down
669
+ * every live `CoreRegistry` (both `start()` and `handler()` modes) and
670
+ * waits for the serve promise to resolve, all bounded by the shutdown
671
+ * grace period. Unlike a signal-driven shutdown, this does not re-raise a
672
+ * signal or exit the process. The caller owns process lifetime.
673
+ *
674
+ * Idempotent: concurrent or repeated calls share a single drain. Safe to
675
+ * call even if nothing has been started.
676
+ *
677
+ * @example
678
+ * ```ts
679
+ * const registry = setup({ use: { counter } });
680
+ * registry.start();
681
+ * // ...later, on your own shutdown trigger:
682
+ * await registry.shutdown();
683
+ * ```
684
+ */
685
+ public async shutdown(): Promise<void> {
686
+ if (this.#shutdownInFlight !== null) return this.#shutdownInFlight;
687
+ const config = this.parseConfig();
688
+ // Uninstall our signal handlers so a later SIGINT/SIGTERM does not
689
+ // re-trigger a drain on already-torn-down registries. Subsequent
690
+ // signals fall back to Node's default termination behavior.
691
+ this.#removeSignalHandlers();
692
+ this.#shutdownInFlight = this.#drain(config).catch((err) => {
289
693
  logger().warn({ err }, "shutdown error");
290
694
  });
695
+ return this.#shutdownInFlight;
291
696
  }
292
697
 
293
- async #runShutdown(
294
- signal: ShutdownSignal,
295
- config: RegistryConfig,
296
- nativeRegistryPromise: ReturnType<typeof buildNativeRegistry>,
297
- ): Promise<void> {
298
- const gracePeriodMs = config.shutdown?.gracePeriodMs ?? 30_000;
698
+ async #drain(config: RegistryConfig): Promise<void> {
699
+ const modeAPromise = this.#runtimeServeConfiguredPromise;
700
+ const modeBPromise = this.#runtimeServerlessPromise;
701
+
702
+ const gracePeriodMs =
703
+ config.shutdown?.gracePeriodMs ??
704
+ (await this.#actorStopThresholdMs(modeAPromise ?? modeBPromise)) ??
705
+ 30 * 60 * 1000;
299
706
  // Race the entire drain sequence (both modes + serve promise) against
300
- // a single grace ceiling. Without this, each mode's Rust-side drain
301
- // (20s) could stack sequentially and blow past gracePeriodMs before
302
- // we re-raise the signal.
707
+ // a single grace ceiling. By default, this uses the engine-provided
708
+ // actor stop threshold, matching Pegboard's hard cutoff for actors.
303
709
  const drain = async () => {
304
710
  // Shut down every live `CoreRegistry` we know about. Mode A
305
711
  // (`start()`) and Mode B (`handler()`) each build a separate
306
- // native registry, so one signal handler fans out to both to
307
- // honor the spec invariant "single shutdown tears down both modes".
308
- const registries: Promise<void>[] = [
309
- (async () => {
310
- try {
311
- const { registry } = await nativeRegistryPromise;
312
- await registry.shutdown();
313
- } catch (err) {
314
- logger().warn(
315
- { err },
316
- "native registry shutdown errored (mode A)",
317
- );
318
- }
319
- })(),
320
- ];
321
- if (this.#nativeServerlessPromise) {
712
+ // runtime registry, so one drain fans out to both to honor the
713
+ // spec invariant "single shutdown tears down both modes".
714
+ const registries: Promise<void>[] = [];
715
+ if (modeAPromise !== undefined) {
322
716
  registries.push(
323
717
  (async () => {
324
718
  try {
325
- const { registry } = await this.#nativeServerlessPromise!;
326
- await registry.shutdown();
719
+ const { runtime, registry } = await modeAPromise;
720
+ await runtime.shutdownRegistry(registry);
327
721
  } catch (err) {
328
722
  logger().warn(
329
723
  { err },
330
- "native registry shutdown errored (mode B)",
724
+ "runtime registry shutdown errored (mode A)",
725
+ );
726
+ }
727
+ })(),
728
+ );
729
+ }
730
+ if (modeBPromise !== undefined) {
731
+ registries.push(
732
+ (async () => {
733
+ try {
734
+ const { runtime, registry } = await modeBPromise;
735
+ await runtime.shutdownRegistry(registry);
736
+ } catch (err) {
737
+ logger().warn(
738
+ { error: err },
739
+ "runtime registry shutdown errored (mode B)",
331
740
  );
332
741
  }
333
742
  })(),
@@ -335,11 +744,15 @@ export class Registry<A extends RegistryActors> {
335
744
  }
336
745
  await Promise.all(registries);
337
746
 
338
- if (this.#nativeServePromise) {
747
+ const runtimeServePromise = this.#runtimeServePromise;
748
+ if (runtimeServePromise !== undefined) {
339
749
  // Swallow rejection so the race doesn't itself reject; the
340
750
  // always-attached `.catch` at the promise assignment site has
341
751
  // already logged any serve-side error.
342
- await this.#nativeServePromise.catch(() => undefined);
752
+ await runtimeServePromise.catch(() => undefined);
753
+ }
754
+ if (this.#applicationListenerPromise !== undefined) {
755
+ await this.#applicationListenerPromise.catch(() => undefined);
343
756
  }
344
757
  };
345
758
  await Promise.race([
@@ -348,15 +761,38 @@ export class Registry<A extends RegistryActors> {
348
761
  setTimeout(resolve, gracePeriodMs).unref?.(),
349
762
  ),
350
763
  ]);
351
- this.#removeSignalHandlers();
352
- process.kill(process.pid, signal);
764
+ }
765
+
766
+ async #actorStopThresholdMs(
767
+ configuredRegistryPromise:
768
+ | ReturnType<typeof buildConfiguredRegistry>
769
+ | undefined,
770
+ ): Promise<number | undefined> {
771
+ if (configuredRegistryPromise === undefined) return undefined;
772
+ try {
773
+ const { runtime, registry } = await configuredRegistryPromise;
774
+ const thresholdMs =
775
+ await runtime.registryActorStopThresholdMs?.(registry);
776
+ if (
777
+ thresholdMs !== undefined &&
778
+ Number.isFinite(thresholdMs) &&
779
+ thresholdMs > 0
780
+ ) {
781
+ return thresholdMs;
782
+ }
783
+ } catch (err) {
784
+ logger().warn(
785
+ { err },
786
+ "failed to read actor stop threshold for shutdown grace",
787
+ );
788
+ }
789
+ return undefined;
353
790
  }
354
791
 
355
792
  #removeSignalHandlers(): void {
356
- for (const [signal, handler] of Object.entries(this.#signalHandlers) as [
357
- ShutdownSignal,
358
- () => void,
359
- ][]) {
793
+ for (const [signal, handler] of Object.entries(
794
+ this.#signalHandlers,
795
+ ) as [ShutdownSignal, () => void][]) {
360
796
  if (handler) process.removeListener(signal, handler);
361
797
  }
362
798
  this.#signalHandlers = {};
@@ -367,7 +803,89 @@ export class Registry<A extends RegistryActors> {
367
803
  }
368
804
 
369
805
  /**
370
- * Starts the native actor envoy for standalone server deployments.
806
+ * Starts the serverful registry if needed and waits until its envoy has
807
+ * registered with the Engine. Repeated and concurrent calls share one
808
+ * startup lifecycle and readiness promise.
809
+ *
810
+ * Unlike {@link start}, this reports startup failures and does not resolve
811
+ * merely because an HTTP health endpoint is listening.
812
+ */
813
+ public startAndWait(): Promise<void> {
814
+ if (this.#shutdownInFlight !== null) {
815
+ return Promise.reject(
816
+ new Error(
817
+ "registry.startAndWait() cannot run after shutdown has begun",
818
+ ),
819
+ );
820
+ }
821
+ if (this.#runtimeReadyPromise) return this.#runtimeReadyPromise;
822
+ if (getRivetkitRuntimeMode() === "serverless") {
823
+ return Promise.reject(
824
+ new Error(
825
+ "registry.startAndWait() requires envoy runtime mode; serverless registries become ready per request",
826
+ ),
827
+ );
828
+ }
829
+
830
+ const config = this.parseConfig();
831
+ if (config.runtime === "wasm") {
832
+ return Promise.reject(
833
+ new Error(
834
+ "registry.startAndWait() requires the native runtime; WebAssembly registries do not host an envoy",
835
+ ),
836
+ );
837
+ }
838
+ this.#startEnvoy(config, true);
839
+ const configuredRegistryPromise = this.#runtimeServeConfiguredPromise;
840
+ const serveLifecyclePromise = this.#runtimeServeLifecyclePromise;
841
+ if (!configuredRegistryPromise || !serveLifecyclePromise) {
842
+ throw new Error("registry envoy startup did not initialize");
843
+ }
844
+
845
+ let timeout: ReturnType<typeof setTimeout> | undefined;
846
+ const timeoutPromise = new Promise<never>((_resolve, reject) => {
847
+ timeout = setTimeout(
848
+ () =>
849
+ reject(
850
+ new Error(
851
+ `RivetKit registry did not register with the Engine within ${REGISTRY_READY_TIMEOUT_MS}ms`,
852
+ ),
853
+ ),
854
+ REGISTRY_READY_TIMEOUT_MS,
855
+ );
856
+ timeout.unref?.();
857
+ });
858
+ const readinessPromise = (async () => {
859
+ const { runtime, registry } = await configuredRegistryPromise;
860
+ const stoppedBeforeReady = serveLifecyclePromise.then(() => {
861
+ throw new Error(
862
+ "RivetKit registry stopped before becoming ready",
863
+ );
864
+ });
865
+ await Promise.race([
866
+ runtime.waitRegistryReady(registry),
867
+ stoppedBeforeReady,
868
+ ]);
869
+ })();
870
+ this.#runtimeReadyPromise = Promise.race([
871
+ readinessPromise,
872
+ timeoutPromise,
873
+ ]).finally(() => {
874
+ if (timeout !== undefined) clearTimeout(timeout);
875
+ });
876
+ // The native registry is consumed once serve begins. Retrying the same
877
+ // instance after failure could duplicate partially-created resources, so
878
+ // retain the rejected promise and return the same failure to later calls.
879
+ this.#runtimeReadyPromise.catch(() => {});
880
+ return this.#runtimeReadyPromise;
881
+ }
882
+
883
+ /**
884
+ * Starts the actor envoy for standalone server deployments.
885
+ *
886
+ * Set `RIVETKIT_RUNTIME_MODE=serverless` to instead bind an HTTP listener
887
+ * via `listen()` (Mode B). Mode A (envoy) and Mode B (listener) are
888
+ * mutually exclusive per registry instance.
371
889
  *
372
890
  * @example
373
891
  * ```ts
@@ -376,6 +894,21 @@ export class Registry<A extends RegistryActors> {
376
894
  * ```
377
895
  */
378
896
  public start() {
897
+ if (getRivetkitRuntimeMode() === "serverless") {
898
+ // start() defaults publicDir to "/public" unless overridden by env.
899
+ const publicDir = getRivetkitPublicDir() ?? "/public";
900
+ // Detached listener; bind failures are fatal so exit hard.
901
+ this.listen({ publicDir }).catch((error) => {
902
+ logger().error({ error }, "auto-listen failed; exiting");
903
+ if (
904
+ typeof process !== "undefined" &&
905
+ typeof process.exit === "function"
906
+ ) {
907
+ process.exit(1);
908
+ }
909
+ });
910
+ return;
911
+ }
379
912
  const config = this.parseConfig();
380
913
  this.#startEnvoy(config, true);
381
914
  }
@@ -383,6 +916,7 @@ export class Registry<A extends RegistryActors> {
383
916
  #printWelcome(
384
917
  config: RegistryConfig,
385
918
  kind: "serverless" | "serverful",
919
+ listener?: { port: number; host?: string; publicDir?: string },
386
920
  ): void {
387
921
  if (config.noWelcome || this.#welcomePrinted) return;
388
922
  this.#welcomePrinted = true;
@@ -403,7 +937,9 @@ export class Registry<A extends RegistryActors> {
403
937
 
404
938
  if (config.endpoint) {
405
939
  const endpointType =
406
- config.endpoint === ENGINE_ENDPOINT ? "local native" : "remote";
940
+ config.startEngine || isLocalEngineEndpoint(config.endpoint)
941
+ ? "local native"
942
+ : "remote";
407
943
  logLine("Endpoint", `${config.endpoint} (${endpointType})`);
408
944
  }
409
945
 
@@ -412,6 +948,15 @@ export class Registry<A extends RegistryActors> {
412
948
  }
413
949
 
414
950
  logLine("Actors", Object.keys(config.use).length.toString());
951
+
952
+ if (listener) {
953
+ const host = listener.host ?? "0.0.0.0";
954
+ logLine("Listening", `http://${host}:${listener.port}`);
955
+ if (listener.publicDir) {
956
+ logLine("Public Dir", listener.publicDir);
957
+ }
958
+ }
959
+
415
960
  console.log();
416
961
  }
417
962
  }
@@ -424,6 +969,24 @@ function isServerlessStartRequest(request: Request, basePath: string): boolean {
424
969
  return parsed.pathname === `${normalizedBase}/start`;
425
970
  }
426
971
 
972
+ function isServerlessMetadataRequest(
973
+ request: Request,
974
+ basePath: string,
975
+ ): boolean {
976
+ if (request.method !== "GET") return false;
977
+ const parsed = new URL(request.url);
978
+ const normalizedBase =
979
+ basePath === "/" ? "" : `/${basePath.replace(/^\/+|\/+$/g, "")}`;
980
+ return parsed.pathname === `${normalizedBase}/metadata`;
981
+ }
982
+
983
+ function jsonRouteResponse(status: number, body: unknown): Response {
984
+ return new Response(JSON.stringify(body), {
985
+ status,
986
+ headers: { "content-type": "application/json" },
987
+ });
988
+ }
989
+
427
990
  export function setup<A extends RegistryActors>(
428
991
  input: RegistryConfigInput<A>,
429
992
  ): Registry<A> {