rivetkit 0.0.0-sqlite-query-metrics-v2.f5d3605 → 0.0.0-sqlite-query-metrics-v3.1dff84f

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 (150) hide show
  1. package/dist/browser/client.d.ts +60 -10
  2. package/dist/browser/client.js +294 -40
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.js +4 -2
  5. package/dist/browser/inspector/client.js.map +1 -1
  6. package/dist/tsup/{chunk-HO76AEDH.cjs → chunk-22S5RCCJ.cjs} +3 -3
  7. package/dist/tsup/{chunk-HO76AEDH.cjs.map → chunk-22S5RCCJ.cjs.map} +1 -1
  8. package/dist/tsup/{chunk-EPRA2TCT.js → chunk-2CTZU7GL.js} +2 -2
  9. package/dist/tsup/{chunk-JI6GZ2C2.js → chunk-A2CF6PFH.js} +18 -1
  10. package/dist/tsup/chunk-A2CF6PFH.js.map +1 -0
  11. package/dist/tsup/{chunk-QR6EAWEC.cjs → chunk-CWN7N5AF.cjs} +7 -7
  12. package/dist/tsup/{chunk-QR6EAWEC.cjs.map → chunk-CWN7N5AF.cjs.map} +1 -1
  13. package/dist/tsup/{chunk-3URZ4UV5.js → chunk-D7DWNYEO.js} +2 -2
  14. package/dist/tsup/{chunk-F7IGTKGM.js → chunk-F5PWAGS7.js} +2 -2
  15. package/dist/tsup/{chunk-E2CUROR3.js → chunk-FT6VRK4C.js} +2 -2
  16. package/dist/tsup/{chunk-FYDB45YU.cjs → chunk-HFGXV2CC.cjs} +10 -10
  17. package/dist/tsup/{chunk-FYDB45YU.cjs.map → chunk-HFGXV2CC.cjs.map} +1 -1
  18. package/dist/tsup/{chunk-D4G35VTO.js → chunk-HRKFVQPS.js} +4 -4
  19. package/dist/tsup/{chunk-DHL2M2E2.cjs → chunk-HXJ5U2ZI.cjs} +3 -3
  20. package/dist/tsup/{chunk-DHL2M2E2.cjs.map → chunk-HXJ5U2ZI.cjs.map} +1 -1
  21. package/dist/tsup/{chunk-L3Z3W44Q.cjs → chunk-JJUSO7GJ.cjs} +3 -3
  22. package/dist/tsup/{chunk-L3Z3W44Q.cjs.map → chunk-JJUSO7GJ.cjs.map} +1 -1
  23. package/dist/tsup/{chunk-DDS7OOVF.cjs → chunk-NG5CUXMM.cjs} +420 -182
  24. package/dist/tsup/chunk-NG5CUXMM.cjs.map +1 -0
  25. package/dist/tsup/{chunk-USKGKQZM.js → chunk-NNCL4IBC.js} +12 -7
  26. package/dist/tsup/chunk-NNCL4IBC.js.map +1 -0
  27. package/dist/tsup/{chunk-PJ5EXY6F.js → chunk-QQIFRR3B.js} +283 -45
  28. package/dist/tsup/chunk-QQIFRR3B.js.map +1 -0
  29. package/dist/tsup/{chunk-MYWZCDML.cjs → chunk-RTWH3AX3.cjs} +19 -2
  30. package/dist/tsup/chunk-RTWH3AX3.cjs.map +1 -0
  31. package/dist/tsup/{chunk-HDVZ6YZG.cjs → chunk-SSF2XC33.cjs} +1 -1
  32. package/dist/tsup/chunk-SSF2XC33.cjs.map +1 -0
  33. package/dist/tsup/{chunk-KSP3NXGY.js → chunk-SW33HMM5.js} +3 -3
  34. package/dist/tsup/{chunk-6FEYCVZC.js → chunk-UXDASKP6.js} +1 -1
  35. package/dist/tsup/chunk-UXDASKP6.js.map +1 -0
  36. package/dist/tsup/{chunk-KDT56V3Y.cjs → chunk-Y4QLVCCS.cjs} +12 -7
  37. package/dist/tsup/chunk-Y4QLVCCS.cjs.map +1 -0
  38. package/dist/tsup/{chunk-JW2WPE6Z.cjs → chunk-Y5CFDGPA.cjs} +4 -4
  39. package/dist/tsup/{chunk-JW2WPE6Z.cjs.map → chunk-Y5CFDGPA.cjs.map} +1 -1
  40. package/dist/tsup/client/mod.cjs +6 -6
  41. package/dist/tsup/client/mod.d.cts +15 -3
  42. package/dist/tsup/client/mod.d.ts +15 -3
  43. package/dist/tsup/client/mod.js +5 -5
  44. package/dist/tsup/common/log.cjs +2 -2
  45. package/dist/tsup/common/log.js +1 -1
  46. package/dist/tsup/common/websocket.cjs +3 -3
  47. package/dist/tsup/common/websocket.js +2 -2
  48. package/dist/tsup/{config-Cw_BwH_G.d.ts → config-BiiS5T5M.d.ts} +45 -12
  49. package/dist/tsup/{config-CkmVg2fG.d.cts → config-BnMhcPHl.d.cts} +45 -12
  50. package/dist/tsup/{config-D4clT6mq.d.ts → config-CBTr4IhE.d.cts} +0 -2
  51. package/dist/tsup/{config-D4clT6mq.d.cts → config-CBTr4IhE.d.ts} +0 -2
  52. package/dist/tsup/{context-_xIcgBnE.d.cts → context-DVE8XMm1.d.cts} +2 -2
  53. package/dist/tsup/{context-BYOKTQJi.d.ts → context-iMxXq_Lt.d.ts} +2 -2
  54. package/dist/tsup/db/drizzle.cjs +2 -2
  55. package/dist/tsup/db/drizzle.d.cts +1 -1
  56. package/dist/tsup/db/drizzle.d.ts +1 -1
  57. package/dist/tsup/db/drizzle.js +1 -1
  58. package/dist/tsup/db/mod.cjs +3 -3
  59. package/dist/tsup/db/mod.d.cts +2 -2
  60. package/dist/tsup/db/mod.d.ts +2 -2
  61. package/dist/tsup/db/mod.js +2 -2
  62. package/dist/tsup/dynamic/mod.cjs +2 -2
  63. package/dist/tsup/dynamic/mod.d.cts +2 -2
  64. package/dist/tsup/dynamic/mod.d.ts +2 -2
  65. package/dist/tsup/dynamic/mod.js +1 -1
  66. package/dist/tsup/inspector/mod.cjs +5 -5
  67. package/dist/tsup/inspector/mod.js +4 -4
  68. package/dist/tsup/inspector/workflow.cjs +4 -4
  69. package/dist/tsup/inspector/workflow.js +3 -3
  70. package/dist/tsup/inspector-tab/mod.cjs +2 -2
  71. package/dist/tsup/inspector-tab/mod.d.cts +3 -3
  72. package/dist/tsup/inspector-tab/mod.d.ts +3 -3
  73. package/dist/tsup/inspector-tab/mod.js +1 -1
  74. package/dist/tsup/mod.cjs +298 -198
  75. package/dist/tsup/mod.cjs.map +1 -1
  76. package/dist/tsup/mod.d.cts +4 -4
  77. package/dist/tsup/mod.d.ts +4 -4
  78. package/dist/tsup/mod.js +192 -92
  79. package/dist/tsup/mod.js.map +1 -1
  80. package/dist/tsup/test/mod.cjs +7 -7
  81. package/dist/tsup/test/mod.d.cts +2 -2
  82. package/dist/tsup/test/mod.d.ts +2 -2
  83. package/dist/tsup/test/mod.js +5 -5
  84. package/dist/tsup/unstable/migrations.d.cts +1 -1
  85. package/dist/tsup/unstable/migrations.d.ts +1 -1
  86. package/dist/tsup/utils.cjs +2 -2
  87. package/dist/tsup/utils.js +1 -1
  88. package/dist/tsup/workflow/mod.cjs +25 -22
  89. package/dist/tsup/workflow/mod.cjs.map +1 -1
  90. package/dist/tsup/workflow/mod.d.cts +4 -4
  91. package/dist/tsup/workflow/mod.d.ts +4 -4
  92. package/dist/tsup/workflow/mod.js +11 -8
  93. package/dist/tsup/workflow/mod.js.map +1 -1
  94. package/package.json +12 -10
  95. package/src/actor/config.ts +2 -0
  96. package/src/actor/keys.ts +86 -0
  97. package/src/client/actor-conn.ts +136 -24
  98. package/src/client/actor-handle.ts +64 -10
  99. package/src/client/client.ts +6 -0
  100. package/src/client/config.ts +12 -1
  101. package/src/client/lifecycle-errors.ts +35 -2
  102. package/src/client/raw-utils.ts +17 -3
  103. package/src/client/retry-budget.ts +78 -0
  104. package/src/client/utils.ts +17 -2
  105. package/src/common/database/config.ts +0 -2
  106. package/src/common/database/native-database.ts +17 -6
  107. package/src/common/router.ts +1 -1
  108. package/src/engine-api/actors.ts +3 -3
  109. package/src/engine-client/actor-websocket-client.ts +4 -2
  110. package/src/engine-client/api-endpoints.ts +44 -14
  111. package/src/engine-client/mod.ts +2 -2
  112. package/src/registry/config/envoy.ts +1 -1
  113. package/src/registry/config/index.ts +30 -30
  114. package/src/registry/index.ts +66 -21
  115. package/src/registry/napi-runtime.ts +4 -3
  116. package/src/registry/native.ts +147 -48
  117. package/src/registry/runtime.ts +27 -10
  118. package/src/registry/wasm-runtime.ts +6 -3
  119. package/src/utils/env-vars.ts +13 -6
  120. package/src/workflow/driver.ts +5 -3
  121. package/dist/tsup/chunk-6FEYCVZC.js.map +0 -1
  122. package/dist/tsup/chunk-DDS7OOVF.cjs.map +0 -1
  123. package/dist/tsup/chunk-HDVZ6YZG.cjs.map +0 -1
  124. package/dist/tsup/chunk-JI6GZ2C2.js.map +0 -1
  125. package/dist/tsup/chunk-KDT56V3Y.cjs.map +0 -1
  126. package/dist/tsup/chunk-MYWZCDML.cjs.map +0 -1
  127. package/dist/tsup/chunk-PJ5EXY6F.js.map +0 -1
  128. package/dist/tsup/chunk-USKGKQZM.js.map +0 -1
  129. package/src/actor/config.test.ts +0 -78
  130. package/src/actor/keys.test.ts +0 -275
  131. package/src/actor/utils.test.ts +0 -48
  132. package/src/client/test.ts +0 -44
  133. package/src/client/token-provider.test.ts +0 -86
  134. package/src/common/database/mod.test.ts +0 -364
  135. package/src/common/database/native-database.test.ts +0 -220
  136. package/src/common/inline-websocket-adapter.test.ts +0 -51
  137. package/src/db/drizzle.test.ts +0 -164
  138. package/src/registry/config/index.test.ts +0 -25
  139. package/src/registry/run-handler-coordinator.test.ts +0 -252
  140. package/src/registry/runtime.test.ts +0 -124
  141. package/src/unstable/migrations.test.ts +0 -170
  142. package/src/utils/endpoint-parser.test.ts +0 -206
  143. package/src/utils.test.ts +0 -34
  144. package/src/workflow/driver.test.ts +0 -62
  145. /package/dist/tsup/{chunk-EPRA2TCT.js.map → chunk-2CTZU7GL.js.map} +0 -0
  146. /package/dist/tsup/{chunk-3URZ4UV5.js.map → chunk-D7DWNYEO.js.map} +0 -0
  147. /package/dist/tsup/{chunk-F7IGTKGM.js.map → chunk-F5PWAGS7.js.map} +0 -0
  148. /package/dist/tsup/{chunk-E2CUROR3.js.map → chunk-FT6VRK4C.js.map} +0 -0
  149. /package/dist/tsup/{chunk-D4G35VTO.js.map → chunk-HRKFVQPS.js.map} +0 -0
  150. /package/dist/tsup/{chunk-KSP3NXGY.js.map → chunk-SW33HMM5.js.map} +0 -0
@@ -29,6 +29,18 @@ import type {
29
29
  type ShutdownSignal = "SIGINT" | "SIGTERM";
30
30
 
31
31
  const REGISTRY_READY_TIMEOUT_MS = 30_000;
32
+ // A managed Engine restart can wait for the old process to release storage and
33
+ // for its worker lease to expire before the replacement can register.
34
+ const LOCAL_ENGINE_READY_TIMEOUT_MS = 60_000;
35
+ // Core gives local actors three seconds to drain and acknowledge their stopped
36
+ // reports. Leave time to close the node connection after that, while staying
37
+ // below the five-second force-kill ceiling used by tsx watch.
38
+ const LOCAL_DEV_SHUTDOWN_GRACE_PERIOD_MS = 4_000;
39
+
40
+ // Serverless is disabled for v3; keep the implementation for a later release.
41
+ function rejectServerless(): void {
42
+ throw new Error("serverless is disabled in this version");
43
+ }
32
44
 
33
45
  function signalExitCode(signal: ShutdownSignal): number {
34
46
  switch (signal) {
@@ -190,6 +202,7 @@ export class Registry<A extends RegistryActors> {
190
202
  config: RegistryConfig,
191
203
  ): Promise<void> | undefined {
192
204
  if (!config.configurePool) return undefined;
205
+ rejectServerless();
193
206
 
194
207
  if (!this.#configureServerlessPoolPromise) {
195
208
  this.#configureServerlessPoolPromise = configureServerlessPool(
@@ -215,6 +228,7 @@ export class Registry<A extends RegistryActors> {
215
228
  * ```
216
229
  */
217
230
  public async handler(request: Request): Promise<Response> {
231
+ rejectServerless();
218
232
  const config = this.parseConfig();
219
233
  this.#printWelcome(config, "serverless");
220
234
 
@@ -413,6 +427,7 @@ export class Registry<A extends RegistryActors> {
413
427
  * ```
414
428
  */
415
429
  public serve(): ServerlessHandler {
430
+ rejectServerless();
416
431
  return {
417
432
  fetch: (request) => this.handler(request),
418
433
  };
@@ -438,6 +453,9 @@ export class Registry<A extends RegistryActors> {
438
453
  * ```
439
454
  */
440
455
  public async listen(opts: RegistryListenOptions = {}): Promise<void> {
456
+ if (!opts.application) {
457
+ rejectServerless();
458
+ }
441
459
  const port = opts.port ?? parsePortEnv(process.env.RIVET_PORT) ?? 3000;
442
460
  const publicDir = opts.publicDir ?? getRivetkitPublicDir();
443
461
  const config = this.parseConfig();
@@ -554,6 +572,7 @@ export class Registry<A extends RegistryActors> {
554
572
  * Returns serverless metadata suitable for mounting in a user-owned router.
555
573
  */
556
574
  async #metadataRoute(): Promise<Response> {
575
+ rejectServerless();
557
576
  const configured = await this.#activeConfiguredRegistry();
558
577
  if (!configured) {
559
578
  return new Response("registry not started\n", {
@@ -626,7 +645,7 @@ export class Registry<A extends RegistryActors> {
626
645
  */
627
646
  #startEnvoy(config: RegistryConfig, printWelcome: boolean) {
628
647
  if (!this.#runtimeServePromise) {
629
- const configuredEnvoyVersion = this.#config.envoy?.version;
648
+ const configuredEnvoyVersion = this.#config.node?.version;
630
649
  const envoyVersionSource =
631
650
  configuredEnvoyVersion !== undefined
632
651
  ? "config"
@@ -637,7 +656,7 @@ export class Registry<A extends RegistryActors> {
637
656
  logger().info({
638
657
  msg: "starting rivetkit envoy",
639
658
  rivetkitVersion: VERSION,
640
- envoyVersion: config.envoy.version,
659
+ envoyVersion: config.node.version,
641
660
  envoyVersionSource,
642
661
  });
643
662
 
@@ -646,8 +665,8 @@ export class Registry<A extends RegistryActors> {
646
665
  getNodeEnv() === "production"
647
666
  ) {
648
667
  logger().error({
649
- msg: "envoy version defaulted because neither config.envoy.version nor RIVET_ENVOY_VERSION is set; actors will not drain automatically across deploys. See https://rivet.dev/docs/actors/versions",
650
- envoyVersion: config.envoy.version,
668
+ 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",
669
+ envoyVersion: config.node.version,
651
670
  envoyVersionSource,
652
671
  });
653
672
  }
@@ -666,7 +685,13 @@ export class Registry<A extends RegistryActors> {
666
685
  // rejection unhandled. Downstream awaits (e.g. #runShutdown's
667
686
  // Promise.race) attach their own catches and still observe
668
687
  // resolution via the race.
669
- logger().warn({ error }, "runtime registry serve errored");
688
+ logger().error({ error }, "runtime registry serve errored");
689
+ if (
690
+ typeof process !== "undefined" &&
691
+ typeof process.exit === "function"
692
+ ) {
693
+ process.exit(1);
694
+ }
670
695
  });
671
696
  // Install signal handlers once an envoy lifecycle has begun. Only
672
697
  // Mode A ever reaches here. Mode B (handler(request)) intentionally
@@ -714,7 +739,7 @@ export class Registry<A extends RegistryActors> {
714
739
  finishShutdownSignal(signal);
715
740
  return;
716
741
  }
717
- this.#shutdownInFlight = this.#drain(config)
742
+ this.#shutdownInFlight = this.#drain(config, true)
718
743
  .catch((err) => {
719
744
  logger().warn({ err }, "shutdown error");
720
745
  })
@@ -757,18 +782,28 @@ export class Registry<A extends RegistryActors> {
757
782
  return this.#shutdownInFlight;
758
783
  }
759
784
 
760
- async #drain(config: RegistryConfig): Promise<void> {
785
+ async #drain(config: RegistryConfig, signalDriven = false): Promise<void> {
761
786
  const modeAPromise = this.#runtimeServeConfiguredPromise;
762
787
  const modeBPromise = this.#runtimeServerlessPromise;
763
788
  const runtimes = new Set<CoreRuntime>();
764
789
 
765
- const gracePeriodMs =
766
- config.shutdown?.gracePeriodMs ??
767
- (await this.#actorStopThresholdMs(modeAPromise ?? modeBPromise)) ??
768
- 30 * 60 * 1000;
790
+ const localDevSignal =
791
+ signalDriven &&
792
+ getNodeEnv() !== "production" &&
793
+ config.engineSpawn &&
794
+ config.endpoint !== undefined &&
795
+ isLocalEngineEndpoint(config.endpoint);
796
+ let gracePeriodMs = config.shutdown?.gracePeriodMs;
797
+ if (gracePeriodMs === undefined) {
798
+ gracePeriodMs = localDevSignal
799
+ ? LOCAL_DEV_SHUTDOWN_GRACE_PERIOD_MS
800
+ : ((await this.#actorStopThresholdMs(
801
+ modeAPromise ?? modeBPromise,
802
+ )) ?? 30 * 60 * 1000);
803
+ }
769
804
  // Race the entire drain sequence (both modes + serve promise) against
770
- // a single grace ceiling. By default, this uses the engine-provided
771
- // actor stop threshold, matching Pegboard's hard cutoff for actors.
805
+ // a single grace ceiling. Local dev signal shutdowns allow the watcher
806
+ // to restart promptly; other shutdowns use the engine's actor stop threshold.
772
807
  const drain = async () => {
773
808
  // Shut down every live `CoreRegistry` we know about. Mode A
774
809
  // (`start()`) and Mode B (`handler()`) each build a separate
@@ -887,12 +922,16 @@ export class Registry<A extends RegistryActors> {
887
922
  );
888
923
  }
889
924
  if (this.#runtimeReadyPromise) return this.#runtimeReadyPromise;
890
- if (getRivetkitRuntimeMode() === "serverless") {
891
- return Promise.reject(
892
- new Error(
893
- "registry.startAndWait() requires envoy runtime mode; serverless registries become ready per request",
894
- ),
895
- );
925
+ try {
926
+ if (getRivetkitRuntimeMode() === "serverless") {
927
+ return Promise.reject(
928
+ new Error(
929
+ "registry.startAndWait() requires envoy runtime mode; serverless registries become ready per request",
930
+ ),
931
+ );
932
+ }
933
+ } catch (error) {
934
+ return Promise.reject(error);
896
935
  }
897
936
 
898
937
  const config = this.parseConfig();
@@ -910,16 +949,22 @@ export class Registry<A extends RegistryActors> {
910
949
  throw new Error("registry envoy startup did not initialize");
911
950
  }
912
951
 
952
+ const readyTimeoutMs =
953
+ config.engineSpawn &&
954
+ config.endpoint !== undefined &&
955
+ isLocalEngineEndpoint(config.endpoint)
956
+ ? LOCAL_ENGINE_READY_TIMEOUT_MS
957
+ : REGISTRY_READY_TIMEOUT_MS;
913
958
  let timeout: ReturnType<typeof setTimeout> | undefined;
914
959
  const timeoutPromise = new Promise<never>((_resolve, reject) => {
915
960
  timeout = setTimeout(
916
961
  () =>
917
962
  reject(
918
963
  new Error(
919
- `RivetKit registry did not register with the Engine within ${REGISTRY_READY_TIMEOUT_MS}ms`,
964
+ `RivetKit registry did not register with the Engine within ${readyTimeoutMs}ms`,
920
965
  ),
921
966
  ),
922
- REGISTRY_READY_TIMEOUT_MS,
967
+ readyTimeoutMs,
923
968
  );
924
969
  timeout.unref?.();
925
970
  });
@@ -481,8 +481,9 @@ export class NapiCoreRuntime implements CoreRuntime {
481
481
  onCancellationTokenCancelled(
482
482
  token: CancellationTokenHandle,
483
483
  callback: (...args: unknown[]) => unknown,
484
- ): void {
485
- asNativeCancellationToken(token).onCancelled(callback);
484
+ ): () => void {
485
+ const listener = asNativeCancellationToken(token).onCancelled(callback);
486
+ return () => listener.release();
486
487
  }
487
488
 
488
489
  actorState(ctx: ActorContextHandle): Buffer {
@@ -1285,7 +1286,7 @@ export async function loadNapiRuntime(): Promise<{
1285
1286
  }> {
1286
1287
  // LOAD-BEARING: the specifier is computed (`.join("/")`) on purpose. Do NOT
1287
1288
  // "simplify" it to a literal `import("@rivetkit/rivetkit-napi")`. Edge
1288
- // adapters (e.g. @rivetkit/supabase) pre-bundle this module for Deno; a
1289
+ // adapters pre-bundle this module for Deno; a
1289
1290
  // literal dynamic import is statically resolvable, so Deno's eszip bundler
1290
1291
  // would snapshot the native `.node` addon into the deploy and 413. The
1291
1292
  // computed specifier keeps it opaque to static analysis so it is never
@@ -26,6 +26,7 @@ import {
26
26
  } from "@/actor/config";
27
27
  import type { AnyActorDefinition } from "@/actor/definition";
28
28
  import {
29
+ actorStopping,
29
30
  decodeBridgeRivetError,
30
31
  encodeBridgeRivetError,
31
32
  forbiddenError,
@@ -126,6 +127,7 @@ import type {
126
127
  RuntimeStateDeltaPayload,
127
128
  WebSocketHandle,
128
129
  } from "./runtime";
130
+ import { servicesBinaryUnavailable } from "./runtime";
129
131
  import { loadWasmRuntime } from "./wasm-runtime";
130
132
  import {
131
133
  createWriteThroughProxy,
@@ -347,6 +349,11 @@ type NativeDestroyGate = {
347
349
  type NativeDatabaseClientState = {
348
350
  client: unknown;
349
351
  };
352
+ type NativeActorAbort = {
353
+ signal: AbortSignal;
354
+ listeners: Set<() => void>;
355
+ };
356
+
350
357
  type NativeActorRuntimeState = {
351
358
  sql?: ReturnType<typeof wrapJsNativeDatabase>;
352
359
  databaseClient?: NativeDatabaseClientState;
@@ -354,6 +361,17 @@ type NativeActorRuntimeState = {
354
361
  vars?: unknown;
355
362
  destroyGate?: NativeDestroyGate;
356
363
  persistState?: NativePersistActorState;
364
+ // One native actor abort signal shared by every context of the actor. Each
365
+ // native signal parks a task and a callback handle until the actor stops,
366
+ // so creating one per request or action leaks both. Per-context listeners
367
+ // live in `listeners` so the shared signal never collects one listener per
368
+ // in-flight request.
369
+ actorAbort?: NativeActorAbort;
370
+ // Set once shutdown cleanup has cleared this generation's caches. Work that
371
+ // outlives the generation, such as an untracked timer or a late WebSocket
372
+ // message handler, then fails with `actor.stopping` instead of reading an
373
+ // empty bag as if `vars` or the database were never initialized.
374
+ cleared?: true;
357
375
  };
358
376
 
359
377
  // Keep JS-only actor caches on the NAPI ActorContext runtime-state bag instead
@@ -363,9 +381,10 @@ function getNativeRuntimeState(
363
381
  runtime: CoreRuntime,
364
382
  ctx: ActorContextHandle,
365
383
  ): NativeActorRuntimeState {
366
- const runtimeState = callNativeSync(() =>
367
- runtime.actorRuntimeState(ctx),
368
- ) as NativeActorRuntimeState;
384
+ const runtimeState = readNativeRuntimeStateBag(runtime, ctx);
385
+ if (runtimeState.cleared) {
386
+ throw actorStopping(callNativeSync(() => runtime.actorId(ctx)));
387
+ }
369
388
  if (!runtimeState.destroyGate) {
370
389
  runtimeState.destroyGate = {};
371
390
  }
@@ -379,6 +398,22 @@ function getNativeRuntimeState(
379
398
  return runtimeState;
380
399
  }
381
400
 
401
+ function readNativeRuntimeStateBag(
402
+ runtime: CoreRuntime,
403
+ ctx: ActorContextHandle,
404
+ ): NativeActorRuntimeState {
405
+ return callNativeSync(() =>
406
+ runtime.actorRuntimeState(ctx),
407
+ ) as NativeActorRuntimeState;
408
+ }
409
+
410
+ function isNativeRuntimeStateCleared(
411
+ runtime: CoreRuntime,
412
+ ctx: ActorContextHandle,
413
+ ): boolean {
414
+ return readNativeRuntimeStateBag(runtime, ctx).cleared === true;
415
+ }
416
+
382
417
  function getNativePersistState(
383
418
  runtime: CoreRuntime,
384
419
  ctx: ActorContextHandle,
@@ -521,7 +556,18 @@ function clearNativeRuntimeState(
521
556
  runtime: CoreRuntime,
522
557
  ctx: ActorContextHandle,
523
558
  ) {
559
+ // A coalesced save armed before the clear would otherwise fire against the
560
+ // cleared bag and throw outside any caller.
561
+ const pendingSaveHandle = readNativeRuntimeStateBag(runtime, ctx)
562
+ .persistState?.pendingSaveHandle;
563
+ if (pendingSaveHandle !== undefined) {
564
+ clearImmediate(pendingSaveHandle);
565
+ }
524
566
  callNativeSync(() => runtime.actorClearRuntimeState(ctx));
567
+ // The runtime hands out a fresh bag after a clear. Each generation has its
568
+ // own bag, so marking it makes later access from this generation fail typed
569
+ // without touching any newer generation of the same actor.
570
+ readNativeRuntimeStateBag(runtime, ctx).cleared = true;
525
571
  }
526
572
 
527
573
  async function cleanupNativeSleepRuntimeState(
@@ -536,8 +582,7 @@ async function cleanupNativeSleepRuntimeState(
536
582
  // the tracked work finishes without a deadline.
537
583
  const drained = await runtime.actorWaitForTrackedShutdownWork(ctx);
538
584
  if (!drained) {
539
- await closeNativeDatabaseClient(runtime, ctx);
540
- await closeNativeSqlDatabase(runtime, ctx);
585
+ await detachNativeDatabaseForShutdown(runtime, ctx);
541
586
  void runtime
542
587
  .actorWaitForTrackedShutdownWorkUnbounded(ctx)
543
588
  .then(async () => {
@@ -554,11 +599,26 @@ async function cleanupNativeSleepRuntimeState(
554
599
  }
555
600
 
556
601
  await afterTrackedWorkDrained?.();
557
- await closeNativeDatabaseClient(runtime, ctx);
558
- await closeNativeSqlDatabase(runtime, ctx);
602
+ await detachNativeDatabaseForShutdown(runtime, ctx);
559
603
  clearNativeRuntimeState(runtime, ctx);
560
604
  }
561
605
 
606
+ async function detachNativeDatabaseForShutdown(
607
+ runtime: CoreRuntime,
608
+ ctx: ActorContextHandle,
609
+ ): Promise<void> {
610
+ const runtimeState = getNativeRuntimeState(runtime, ctx);
611
+ // Stop JS access without closing the runtime-owned SQLite backend. Rust still
612
+ // needs it to reconcile scheduled alarms and performs the physical close after
613
+ // this lifecycle callback returns.
614
+ await runtimeState.sql?.detachForShutdown();
615
+ try {
616
+ await closeNativeDatabaseClient(runtime, ctx);
617
+ } finally {
618
+ runtimeState.sql = undefined;
619
+ }
620
+ }
621
+
562
622
  function closeNativeSqlDatabase(
563
623
  runtime: CoreRuntime,
564
624
  ctx: ActorContextHandle,
@@ -776,7 +836,7 @@ function decodeNativeKvValue<T extends NativeKvValueType = "text">(
776
836
  async function loadEngineCli(): Promise<typeof import("@rivetkit/engine-cli")> {
777
837
  // LOAD-BEARING: the specifier is computed (`.join("/")`) on purpose. Do NOT
778
838
  // "simplify" it to a literal `import("@rivetkit/engine-cli")`. Edge adapters
779
- // (e.g. @rivetkit/supabase) pre-bundle this module for Deno; a literal
839
+ // pre-bundle this module for Deno; a literal
780
840
  // dynamic import is statically resolvable, so Deno's eszip bundler would
781
841
  // snapshot the ~117 MB engine-cli binary into the deploy and 413. The
782
842
  // computed specifier keeps it opaque to static analysis so it is never
@@ -784,7 +844,7 @@ async function loadEngineCli(): Promise<typeof import("@rivetkit/engine-cli")> {
784
844
  return import(["@rivetkit", "engine-cli"].join("/"));
785
845
  }
786
846
 
787
- async function loadServices(): Promise<typeof import("@rivet-dev/services")> {
847
+ async function loadServices(): Promise<{ getServicesPath: () => string }> {
788
848
  // Keep the native binary opaque to edge bundlers for the same reason as
789
849
  // engine-cli above.
790
850
  return import(["@rivet-dev", "services"].join("/"));
@@ -3022,22 +3082,28 @@ export class ActorContextHandleAdapter {
3022
3082
 
3023
3083
  get abortSignal(): AbortSignal {
3024
3084
  if (!this.#abortSignal) {
3025
- const actorSignal = this.#createActorAbortSignal();
3085
+ const actorAbort = this.#actorAbort();
3086
+ const actorSignal = actorAbort.signal;
3026
3087
  if (this.#dispatchCancelToken === undefined) {
3027
3088
  this.#abortSignal = actorSignal;
3028
3089
  } else {
3029
3090
  const controller = new AbortController();
3030
3091
  let cleanedUp = false;
3092
+ let releaseDispatchListener: (() => void) | undefined;
3031
3093
  const onActorAbort = () => {
3032
3094
  cleanup();
3033
3095
  controller.abort();
3034
3096
  };
3097
+ // Releasing the native listener on dispose frees it even when the
3098
+ // dispatch token is never cancelled.
3035
3099
  const cleanup = () => {
3036
3100
  if (cleanedUp) {
3037
3101
  return;
3038
3102
  }
3039
3103
  cleanedUp = true;
3040
- actorSignal.removeEventListener("abort", onActorAbort);
3104
+ actorAbort.listeners.delete(onActorAbort);
3105
+ releaseDispatchListener?.();
3106
+ releaseDispatchListener = undefined;
3041
3107
  this.#abortSignalCleanup = undefined;
3042
3108
  };
3043
3109
 
@@ -3051,10 +3117,8 @@ export class ActorContextHandleAdapter {
3051
3117
  } else {
3052
3118
  const dispatchCancelToken = this.#dispatchCancelToken;
3053
3119
  this.#abortSignalCleanup = cleanup;
3054
- actorSignal.addEventListener("abort", onActorAbort, {
3055
- once: true,
3056
- });
3057
- callNativeSync(() =>
3120
+ actorAbort.listeners.add(onActorAbort);
3121
+ releaseDispatchListener = callNativeSync(() =>
3058
3122
  this.#runtime.onCancellationTokenCancelled(
3059
3123
  dispatchCancelToken,
3060
3124
  () => {
@@ -3506,24 +3570,49 @@ export class ActorContextHandleAdapter {
3506
3570
 
3507
3571
  async dispose(): Promise<void> {
3508
3572
  // Flush any save coalesced for this tick before the context is torn
3509
- // down so the request-save and onStateChange always run.
3510
- this.#flushStateChange();
3573
+ // down so the request-save and onStateChange always run. Shutdown
3574
+ // cleanup may already have cleared the generation, which leaves no
3575
+ // pending save to flush.
3576
+ if (!isNativeRuntimeStateCleared(this.#runtime, this.#ctx)) {
3577
+ this.#flushStateChange();
3578
+ }
3511
3579
  this.#abortSignalCleanup?.();
3512
3580
  }
3513
3581
 
3514
- #createActorAbortSignal(): AbortSignal {
3582
+ #actorAbort(): NativeActorAbort {
3583
+ // An aborted cached signal may belong to a previous generation, so
3584
+ // only a live one is reused.
3585
+ const runtimeState = readNativeRuntimeStateBag(
3586
+ this.#runtime,
3587
+ this.#ctx,
3588
+ );
3589
+ const cached = runtimeState.actorAbort;
3590
+ if (cached && !cached.signal.aborted) {
3591
+ return cached;
3592
+ }
3593
+
3515
3594
  const nativeSignal = callNativeSync(() =>
3516
3595
  this.#runtime.actorAbortSignal(this.#ctx),
3517
3596
  );
3518
3597
  const controller = new AbortController();
3519
- if (nativeSignal.aborted) {
3598
+ const actorAbort: NativeActorAbort = {
3599
+ signal: controller.signal,
3600
+ listeners: new Set(),
3601
+ };
3602
+ const abort = () => {
3520
3603
  controller.abort();
3604
+ for (const listener of actorAbort.listeners) {
3605
+ listener();
3606
+ }
3607
+ actorAbort.listeners.clear();
3608
+ };
3609
+ if (nativeSignal.aborted) {
3610
+ abort();
3521
3611
  } else {
3522
- nativeSignal.addEventListener("abort", () => controller.abort(), {
3523
- once: true,
3524
- });
3612
+ nativeSignal.addEventListener("abort", abort, { once: true });
3525
3613
  }
3526
- return controller.signal;
3614
+ runtimeState.actorAbort = actorAbort;
3615
+ return actorAbort;
3527
3616
  }
3528
3617
 
3529
3618
  #readState(): unknown {
@@ -4846,7 +4935,7 @@ export function buildNativeFactory(
4846
4935
  }
4847
4936
  } finally {
4848
4937
  resolveNativeDestroy(runtime, ctx);
4849
- await actorCtx.closeDatabase();
4938
+ await detachNativeDatabaseForShutdown(runtime, ctx);
4850
4939
  clearNativeRuntimeState(runtime, ctx);
4851
4940
  await actorCtx.dispose();
4852
4941
  }
@@ -5423,6 +5512,11 @@ export function buildNativeFactory(
5423
5512
  conn != null
5424
5513
  ? makeConnCtx(ctx, conn, undefined, cancelToken)
5425
5514
  : makeActorCtx(ctx, undefined, cancelToken);
5515
+ if (scheduledFire) {
5516
+ Object.defineProperty(actorCtx, "scheduledFire", {
5517
+ value: scheduledFire,
5518
+ });
5519
+ }
5426
5520
  const runAction = async () => {
5427
5521
  try {
5428
5522
  return encodeValue(
@@ -5591,19 +5685,20 @@ export function buildNativeFactory(
5591
5685
 
5592
5686
  export async function buildServeConfig(
5593
5687
  config: RegistryConfig,
5594
- resolveServicesBinary = true,
5688
+ resolveNativeBinaries = true,
5595
5689
  ): Promise<RuntimeServeConfig> {
5596
5690
  if (!config.endpoint) {
5597
5691
  throw nativeEndpointNotConfiguredError();
5598
5692
  }
5599
5693
 
5600
5694
  const serveConfig: RuntimeServeConfig = {
5601
- version: config.envoy.version,
5695
+ version: config.node.version,
5602
5696
  endpoint: config.endpoint,
5697
+ engineSpawn: config.engineSpawn,
5603
5698
  token: config.token,
5604
5699
  namespace: config.namespace,
5605
- poolName: config.envoy.poolName,
5606
- startServices: resolveServicesBinary && config.startServices,
5700
+ poolName: config.node.poolName,
5701
+ startServices: resolveNativeBinaries && config.startServices,
5607
5702
  handleInspectorHttpInRuntime: true,
5608
5703
  serverlessBasePath: config.serverless.basePath,
5609
5704
  serverlessPackageVersion: VERSION,
@@ -5614,38 +5709,42 @@ export async function buildServeConfig(
5614
5709
  serverlessMaxStartPayloadBytes: config.serverless.maxStartPayloadBytes,
5615
5710
  };
5616
5711
 
5617
- // Always best-effort resolve the npm-installed engine binary and hand its
5618
- // path to the core. The core alone decides whether to actually spawn a local
5619
- // engine (its `should_manage_engine`, based on the endpoint + spawn mode), so
5712
+ // For native runtimes, best-effort resolve the npm-installed engine binary
5713
+ // and hand its path to the core. The core decides whether to spawn a local
5714
+ // engine using the resolved spawn decision, so
5620
5715
  // JS must not duplicate that decision here. Only JS knows the npm
5621
5716
  // `node_modules` layout, so it resolves the path; if no binary is available
5622
5717
  // (remote-only install, unsupported platform, optional deps skipped), leave
5623
5718
  // it unset and let the core report `engine.binary_unavailable` if it actually
5624
5719
  // needs one.
5625
- try {
5626
- const { getEnginePath } = await loadEngineCli();
5627
- serveConfig.engineBinaryPath = getEnginePath();
5628
- } catch (error) {
5629
- // The npm-installed engine binary could not be resolved. The core still
5630
- // decides whether it needs to spawn a local engine; if it does, it will
5631
- // fail with engine.binary_unavailable (auto-download is off in the napi
5632
- // runtime). Warn so the cause is actionable.
5633
- logger().warn({
5634
- msg: "could not resolve a local engine binary; if a local engine must be spawned it will fail with engine.binary_unavailable — set RIVET_ENGINE_BINARY_PATH or install the @rivetkit/engine-cli platform package",
5635
- error: stringifyError(error),
5636
- });
5637
- }
5638
- if (resolveServicesBinary && config.startServices) {
5720
+ if (resolveNativeBinaries) {
5639
5721
  try {
5640
- const { getServicesPath } = await loadServices();
5641
- serveConfig.servicesBinaryPath = getServicesPath();
5722
+ const { getEnginePath } = await loadEngineCli();
5723
+ serveConfig.engineBinaryPath = getEnginePath();
5642
5724
  } catch (error) {
5725
+ // The npm-installed engine binary could not be resolved. The core still
5726
+ // decides whether it needs to spawn a local engine; if it does, it will
5727
+ // fail with engine.binary_unavailable (auto-download is off in the napi
5728
+ // runtime). Warn so the cause is actionable.
5643
5729
  logger().warn({
5644
- msg: "could not resolve the Services binary; a local engine will fail with services.binary_unavailable — set RIVET_RUN_SERVICES=0 to disable Services or RIVET_SERVICES_BINARY to a local rivet-services binary",
5730
+ msg: "could not resolve a local engine binary; if a local engine must be spawned it will fail with engine.binary_unavailable — set RIVET_ENGINE_BINARY_PATH or install the @rivetkit/engine-cli platform package",
5645
5731
  error: stringifyError(error),
5646
5732
  });
5647
5733
  }
5648
5734
  }
5735
+ if (resolveNativeBinaries && config.startServices) {
5736
+ const servicesBinary = getEnvUniversal("RIVET_SERVICES_BINARY");
5737
+ if (servicesBinary) {
5738
+ serveConfig.servicesBinaryPath = servicesBinary;
5739
+ } else {
5740
+ try {
5741
+ const { getServicesPath } = await loadServices();
5742
+ serveConfig.servicesBinaryPath = getServicesPath();
5743
+ } catch (error) {
5744
+ throw servicesBinaryUnavailable(error);
5745
+ }
5746
+ }
5747
+ }
5649
5748
  serveConfig.engineHost = config.engineHost;
5650
5749
  serveConfig.enginePort = config.enginePort;
5651
5750
  if (config.test?.enabled) {
@@ -387,6 +387,8 @@ export interface RuntimeServeConfig {
387
387
  engineBinaryPath?: string;
388
388
  startServices?: boolean;
389
389
  servicesBinaryPath?: string;
390
+ /** Whether config resolution selected a managed local development engine. */
391
+ engineSpawn?: boolean;
390
392
  engineHost?: string;
391
393
  enginePort?: number;
392
394
  handleInspectorHttpInRuntime?: boolean;
@@ -532,10 +534,15 @@ export interface CoreRuntime {
532
534
  createCancellationToken(): CancellationTokenHandle;
533
535
  cancellationTokenAborted(token: CancellationTokenHandle): boolean;
534
536
  cancelCancellationToken(token: CancellationTokenHandle): void;
537
+ /**
538
+ * Calls `callback` once when `token` is cancelled. Returns a release
539
+ * function that drops the registration without calling `callback`; call it
540
+ * once cancellation no longer matters so the native listener is freed.
541
+ */
535
542
  onCancellationTokenCancelled(
536
543
  token: CancellationTokenHandle,
537
544
  callback: (...args: unknown[]) => unknown,
538
- ): void;
545
+ ): () => void;
539
546
 
540
547
  actorState(ctx: ActorContextHandle): RuntimeBytes;
541
548
  actorBeginOnStateChange(ctx: ActorContextHandle): void;
@@ -876,6 +883,13 @@ export interface RuntimeBundle {
876
883
  runtime: CoreRuntime;
877
884
  }
878
885
 
886
+ export function servicesBinaryUnavailable(cause: unknown): Error {
887
+ return new Error(
888
+ "services.binary_unavailable: Install @rivet-dev/services to run local Services, set RIVET_SERVICES_BINARY to its executable path, or set RIVET_RUN_SERVICES=0 to disable Services.",
889
+ { cause },
890
+ );
891
+ }
892
+
879
893
  export async function buildServeConfig(
880
894
  config: RegistryConfig,
881
895
  loadEnginePath: () => Promise<string>,
@@ -887,11 +901,12 @@ export async function buildServeConfig(
887
901
  }
888
902
 
889
903
  const serveConfig: RuntimeServeConfig = {
890
- version: config.envoy.version,
904
+ version: config.node.version,
891
905
  endpoint: config.endpoint,
906
+ engineSpawn: config.engineSpawn,
892
907
  token: config.token,
893
908
  namespace: config.namespace,
894
- poolName: config.envoy.poolName,
909
+ poolName: config.node.poolName,
895
910
  startServices: config.startServices,
896
911
  handleInspectorHttpInRuntime: true,
897
912
  serverlessBasePath: config.serverless.basePath,
@@ -921,13 +936,15 @@ export async function buildServeConfig(
921
936
  });
922
937
  }
923
938
  if (config.startServices) {
924
- try {
925
- serveConfig.servicesBinaryPath = await loadServicesPath();
926
- } catch (error) {
927
- logger().warn({
928
- msg: "could not resolve the Services binary; a local Engine will fail with services.binary_unavailable — set RIVET_RUN_SERVICES=0 to disable Services or RIVET_SERVICES_BINARY to a local rivet-services binary",
929
- error: stringifyError(error),
930
- });
939
+ const servicesBinary = process.env.RIVET_SERVICES_BINARY;
940
+ if (servicesBinary) {
941
+ serveConfig.servicesBinaryPath = servicesBinary;
942
+ } else {
943
+ try {
944
+ serveConfig.servicesBinaryPath = await loadServicesPath();
945
+ } catch (error) {
946
+ throw servicesBinaryUnavailable(error);
947
+ }
931
948
  }
932
949
  }
933
950
  serveConfig.engineHost = config.engineHost;
@@ -66,7 +66,9 @@ type WasmWebSocketHandle = object;
66
66
  interface WasmCancellationToken {
67
67
  aborted(): boolean;
68
68
  cancel(): void;
69
- onCancelled(callback: (...args: unknown[]) => unknown): void;
69
+ onCancelled(callback: (...args: unknown[]) => unknown): {
70
+ release(): void;
71
+ };
70
72
  }
71
73
 
72
74
  interface WasmCoreRegistry {
@@ -390,10 +392,11 @@ export class WasmCoreRuntime implements CoreRuntime {
390
392
  onCancellationTokenCancelled(
391
393
  token: CancellationTokenHandle,
392
394
  callback: (...args: unknown[]) => unknown,
393
- ): void {
394
- callWasmSync(() =>
395
+ ): () => void {
396
+ const listener = callWasmSync(() =>
395
397
  asWasmCancellationToken(token).onCancelled(callback),
396
398
  );
399
+ return () => callWasmSync(() => listener.release());
397
400
  }
398
401
 
399
402
  actorState(ctx: ActorContextHandle): RuntimeBytes {