rivetkit 0.0.0-sqlite-query-metrics-v2.f5d3605 → 0.0.0-sqlite-sync-3-0-1-release.95f6e2d

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 (139) hide show
  1. package/dist/browser/client.d.ts +99 -59
  2. package/dist/browser/client.js +228 -34
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.js +1 -2
  5. package/dist/browser/inspector/client.js.map +1 -1
  6. package/dist/tsup/{chunk-3URZ4UV5.js → chunk-2HWY7FZU.js} +2 -2
  7. package/dist/tsup/{chunk-PJ5EXY6F.js → chunk-62WFU3BQ.js} +223 -42
  8. package/dist/tsup/chunk-62WFU3BQ.js.map +1 -0
  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-KDT56V3Y.cjs → chunk-AQWZWR2P.cjs} +10 -11
  12. package/dist/tsup/chunk-AQWZWR2P.cjs.map +1 -0
  13. package/dist/tsup/{chunk-L3Z3W44Q.cjs → chunk-E4KDQJCR.cjs} +3 -3
  14. package/dist/tsup/{chunk-L3Z3W44Q.cjs.map → chunk-E4KDQJCR.cjs.map} +1 -1
  15. package/dist/tsup/{chunk-DHL2M2E2.cjs → chunk-E6HKVCPA.cjs} +3 -3
  16. package/dist/tsup/{chunk-DHL2M2E2.cjs.map → chunk-E6HKVCPA.cjs.map} +1 -1
  17. package/dist/tsup/{chunk-DDS7OOVF.cjs → chunk-EQBUH25O.cjs} +362 -181
  18. package/dist/tsup/chunk-EQBUH25O.cjs.map +1 -0
  19. package/dist/tsup/{chunk-USKGKQZM.js → chunk-HQHTTJW5.js} +10 -11
  20. package/dist/tsup/chunk-HQHTTJW5.js.map +1 -0
  21. package/dist/tsup/{chunk-JW2WPE6Z.cjs → chunk-M5SQGPRJ.cjs} +4 -4
  22. package/dist/tsup/{chunk-JW2WPE6Z.cjs.map → chunk-M5SQGPRJ.cjs.map} +1 -1
  23. package/dist/tsup/{chunk-FYDB45YU.cjs → chunk-MYWNJP55.cjs} +10 -10
  24. package/dist/tsup/{chunk-FYDB45YU.cjs.map → chunk-MYWNJP55.cjs.map} +1 -1
  25. package/dist/tsup/{chunk-F7IGTKGM.js → chunk-OWZ76NSH.js} +2 -2
  26. package/dist/tsup/{chunk-KSP3NXGY.js → chunk-QE5MTZHB.js} +3 -3
  27. package/dist/tsup/{chunk-D4G35VTO.js → chunk-QFZY2CK3.js} +4 -4
  28. package/dist/tsup/{chunk-E2CUROR3.js → chunk-QIIIRYN7.js} +2 -2
  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-HO76AEDH.cjs → chunk-UHMB5FFB.cjs} +3 -3
  32. package/dist/tsup/{chunk-HO76AEDH.cjs.map → chunk-UHMB5FFB.cjs.map} +1 -1
  33. package/dist/tsup/{chunk-QR6EAWEC.cjs → chunk-VKXEBB3Z.cjs} +7 -7
  34. package/dist/tsup/{chunk-QR6EAWEC.cjs.map → chunk-VKXEBB3Z.cjs.map} +1 -1
  35. package/dist/tsup/{chunk-EPRA2TCT.js → chunk-ZMVYZ7ZI.js} +2 -2
  36. package/dist/tsup/client/mod.cjs +6 -6
  37. package/dist/tsup/client/mod.d.cts +15 -3
  38. package/dist/tsup/client/mod.d.ts +15 -3
  39. package/dist/tsup/client/mod.js +5 -5
  40. package/dist/tsup/common/log.cjs +2 -2
  41. package/dist/tsup/common/log.js +1 -1
  42. package/dist/tsup/common/websocket.cjs +3 -3
  43. package/dist/tsup/common/websocket.js +2 -2
  44. package/dist/tsup/{config-Cw_BwH_G.d.ts → config-B4erdavw.d.ts} +58 -12
  45. package/dist/tsup/{config-D4clT6mq.d.ts → config-BfG1qpYz.d.cts} +34 -52
  46. package/dist/tsup/{config-D4clT6mq.d.cts → config-BfG1qpYz.d.ts} +34 -52
  47. package/dist/tsup/{config-CkmVg2fG.d.cts → config-DK144OAw.d.cts} +58 -12
  48. package/dist/tsup/{context-_xIcgBnE.d.cts → context-Cvnf3BRe.d.cts} +2 -2
  49. package/dist/tsup/{context-BYOKTQJi.d.ts → context-Oxi6YWcG.d.ts} +2 -2
  50. package/dist/tsup/db/drizzle.cjs +2 -2
  51. package/dist/tsup/db/drizzle.d.cts +1 -1
  52. package/dist/tsup/db/drizzle.d.ts +1 -1
  53. package/dist/tsup/db/drizzle.js +1 -1
  54. package/dist/tsup/db/mod.cjs +3 -3
  55. package/dist/tsup/db/mod.d.cts +2 -2
  56. package/dist/tsup/db/mod.d.ts +2 -2
  57. package/dist/tsup/db/mod.js +2 -2
  58. package/dist/tsup/dynamic/mod.d.cts +2 -2
  59. package/dist/tsup/dynamic/mod.d.ts +2 -2
  60. package/dist/tsup/inspector/mod.cjs +5 -5
  61. package/dist/tsup/inspector/mod.js +4 -4
  62. package/dist/tsup/inspector/workflow.cjs +4 -4
  63. package/dist/tsup/inspector/workflow.js +3 -3
  64. package/dist/tsup/inspector-tab/mod.d.cts +3 -3
  65. package/dist/tsup/inspector-tab/mod.d.ts +3 -3
  66. package/dist/tsup/mod.cjs +553 -202
  67. package/dist/tsup/mod.cjs.map +1 -1
  68. package/dist/tsup/mod.d.cts +4 -4
  69. package/dist/tsup/mod.d.ts +4 -4
  70. package/dist/tsup/mod.js +467 -116
  71. package/dist/tsup/mod.js.map +1 -1
  72. package/dist/tsup/test/mod.cjs +7 -7
  73. package/dist/tsup/test/mod.d.cts +2 -2
  74. package/dist/tsup/test/mod.d.ts +2 -2
  75. package/dist/tsup/test/mod.js +5 -5
  76. package/dist/tsup/unstable/migrations.d.cts +1 -1
  77. package/dist/tsup/unstable/migrations.d.ts +1 -1
  78. package/dist/tsup/utils.cjs +2 -2
  79. package/dist/tsup/utils.js +1 -1
  80. package/dist/tsup/workflow/mod.cjs +22 -19
  81. package/dist/tsup/workflow/mod.cjs.map +1 -1
  82. package/dist/tsup/workflow/mod.d.cts +4 -4
  83. package/dist/tsup/workflow/mod.d.ts +4 -4
  84. package/dist/tsup/workflow/mod.js +10 -7
  85. package/dist/tsup/workflow/mod.js.map +1 -1
  86. package/package.json +9 -10
  87. package/src/actor/keys.ts +86 -0
  88. package/src/client/actor-conn.ts +136 -24
  89. package/src/client/actor-handle.ts +21 -3
  90. package/src/client/client.ts +6 -0
  91. package/src/client/config.ts +12 -1
  92. package/src/client/lifecycle-errors.ts +35 -2
  93. package/src/client/retry-budget.ts +78 -0
  94. package/src/client/utils.ts +13 -2
  95. package/src/common/database/config.ts +46 -52
  96. package/src/common/database/native-database.ts +247 -27
  97. package/src/common/router.ts +1 -1
  98. package/src/db/mod.ts +0 -1
  99. package/src/engine-api/actors.ts +3 -3
  100. package/src/engine-client/actor-websocket-client.ts +4 -2
  101. package/src/engine-client/api-endpoints.ts +44 -14
  102. package/src/engine-client/mod.ts +2 -2
  103. package/src/registry/config/envoy.ts +1 -1
  104. package/src/registry/config/index.ts +29 -31
  105. package/src/registry/index.ts +66 -21
  106. package/src/registry/napi-runtime.ts +82 -3
  107. package/src/registry/native.ts +184 -52
  108. package/src/registry/runtime.ts +79 -10
  109. package/src/registry/wasm-runtime.ts +94 -3
  110. package/src/utils/env-vars.ts +15 -10
  111. package/src/workflow/driver.ts +5 -3
  112. package/dist/tsup/chunk-DDS7OOVF.cjs.map +0 -1
  113. package/dist/tsup/chunk-JI6GZ2C2.js.map +0 -1
  114. package/dist/tsup/chunk-KDT56V3Y.cjs.map +0 -1
  115. package/dist/tsup/chunk-MYWZCDML.cjs.map +0 -1
  116. package/dist/tsup/chunk-PJ5EXY6F.js.map +0 -1
  117. package/dist/tsup/chunk-USKGKQZM.js.map +0 -1
  118. package/src/actor/config.test.ts +0 -78
  119. package/src/actor/keys.test.ts +0 -275
  120. package/src/actor/utils.test.ts +0 -48
  121. package/src/client/test.ts +0 -44
  122. package/src/client/token-provider.test.ts +0 -86
  123. package/src/common/database/mod.test.ts +0 -364
  124. package/src/common/database/native-database.test.ts +0 -220
  125. package/src/common/inline-websocket-adapter.test.ts +0 -51
  126. package/src/db/drizzle.test.ts +0 -164
  127. package/src/registry/config/index.test.ts +0 -25
  128. package/src/registry/run-handler-coordinator.test.ts +0 -252
  129. package/src/registry/runtime.test.ts +0 -124
  130. package/src/unstable/migrations.test.ts +0 -170
  131. package/src/utils/endpoint-parser.test.ts +0 -206
  132. package/src/utils.test.ts +0 -34
  133. package/src/workflow/driver.test.ts +0 -62
  134. /package/dist/tsup/{chunk-3URZ4UV5.js.map → chunk-2HWY7FZU.js.map} +0 -0
  135. /package/dist/tsup/{chunk-F7IGTKGM.js.map → chunk-OWZ76NSH.js.map} +0 -0
  136. /package/dist/tsup/{chunk-KSP3NXGY.js.map → chunk-QE5MTZHB.js.map} +0 -0
  137. /package/dist/tsup/{chunk-D4G35VTO.js.map → chunk-QFZY2CK3.js.map} +0 -0
  138. /package/dist/tsup/{chunk-E2CUROR3.js.map → chunk-QIIIRYN7.js.map} +0 -0
  139. /package/dist/tsup/{chunk-EPRA2TCT.js.map → chunk-ZMVYZ7ZI.js.map} +0 -0
@@ -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,
@@ -60,7 +61,11 @@ import {
60
61
  db as defaultDb,
61
62
  registerNativeStateTransactionOpener,
62
63
  } from "@/common/database/mod";
63
- import { wrapJsNativeDatabase } from "@/common/database/native-database";
64
+ import {
65
+ type JsNativeDatabaseLike,
66
+ type JsNativeSynchronousTransactionLike,
67
+ wrapJsNativeDatabase,
68
+ } from "@/common/database/native-database";
64
69
  import { assertJsonCompatValue, type JsonCompatValue } from "@/common/encoding";
65
70
  import { isResponseLike } from "@/common/fetch-like";
66
71
  import {
@@ -124,8 +129,10 @@ import type {
124
129
  RuntimeScheduledFireInfo,
125
130
  RuntimeServeConfig,
126
131
  RuntimeStateDeltaPayload,
132
+ SqliteTransactionHandle,
127
133
  WebSocketHandle,
128
134
  } from "./runtime";
135
+ import { servicesBinaryUnavailable } from "./runtime";
129
136
  import { loadWasmRuntime } from "./wasm-runtime";
130
137
  import {
131
138
  createWriteThroughProxy,
@@ -347,6 +354,11 @@ type NativeDestroyGate = {
347
354
  type NativeDatabaseClientState = {
348
355
  client: unknown;
349
356
  };
357
+ type NativeActorAbort = {
358
+ signal: AbortSignal;
359
+ listeners: Set<() => void>;
360
+ };
361
+
350
362
  type NativeActorRuntimeState = {
351
363
  sql?: ReturnType<typeof wrapJsNativeDatabase>;
352
364
  databaseClient?: NativeDatabaseClientState;
@@ -354,6 +366,17 @@ type NativeActorRuntimeState = {
354
366
  vars?: unknown;
355
367
  destroyGate?: NativeDestroyGate;
356
368
  persistState?: NativePersistActorState;
369
+ // One native actor abort signal shared by every context of the actor. Each
370
+ // native signal parks a task and a callback handle until the actor stops,
371
+ // so creating one per request or action leaks both. Per-context listeners
372
+ // live in `listeners` so the shared signal never collects one listener per
373
+ // in-flight request.
374
+ actorAbort?: NativeActorAbort;
375
+ // Set once shutdown cleanup has cleared this generation's caches. Work that
376
+ // outlives the generation, such as an untracked timer or a late WebSocket
377
+ // message handler, then fails with `actor.stopping` instead of reading an
378
+ // empty bag as if `vars` or the database were never initialized.
379
+ cleared?: true;
357
380
  };
358
381
 
359
382
  // Keep JS-only actor caches on the NAPI ActorContext runtime-state bag instead
@@ -363,9 +386,10 @@ function getNativeRuntimeState(
363
386
  runtime: CoreRuntime,
364
387
  ctx: ActorContextHandle,
365
388
  ): NativeActorRuntimeState {
366
- const runtimeState = callNativeSync(() =>
367
- runtime.actorRuntimeState(ctx),
368
- ) as NativeActorRuntimeState;
389
+ const runtimeState = readNativeRuntimeStateBag(runtime, ctx);
390
+ if (runtimeState.cleared) {
391
+ throw actorStopping(callNativeSync(() => runtime.actorId(ctx)));
392
+ }
369
393
  if (!runtimeState.destroyGate) {
370
394
  runtimeState.destroyGate = {};
371
395
  }
@@ -379,6 +403,22 @@ function getNativeRuntimeState(
379
403
  return runtimeState;
380
404
  }
381
405
 
406
+ function readNativeRuntimeStateBag(
407
+ runtime: CoreRuntime,
408
+ ctx: ActorContextHandle,
409
+ ): NativeActorRuntimeState {
410
+ return callNativeSync(() =>
411
+ runtime.actorRuntimeState(ctx),
412
+ ) as NativeActorRuntimeState;
413
+ }
414
+
415
+ function isNativeRuntimeStateCleared(
416
+ runtime: CoreRuntime,
417
+ ctx: ActorContextHandle,
418
+ ): boolean {
419
+ return readNativeRuntimeStateBag(runtime, ctx).cleared === true;
420
+ }
421
+
382
422
  function getNativePersistState(
383
423
  runtime: CoreRuntime,
384
424
  ctx: ActorContextHandle,
@@ -521,7 +561,18 @@ function clearNativeRuntimeState(
521
561
  runtime: CoreRuntime,
522
562
  ctx: ActorContextHandle,
523
563
  ) {
564
+ // A coalesced save armed before the clear would otherwise fire against the
565
+ // cleared bag and throw outside any caller.
566
+ const pendingSaveHandle = readNativeRuntimeStateBag(runtime, ctx)
567
+ .persistState?.pendingSaveHandle;
568
+ if (pendingSaveHandle !== undefined) {
569
+ clearImmediate(pendingSaveHandle);
570
+ }
524
571
  callNativeSync(() => runtime.actorClearRuntimeState(ctx));
572
+ // The runtime hands out a fresh bag after a clear. Each generation has its
573
+ // own bag, so marking it makes later access from this generation fail typed
574
+ // without touching any newer generation of the same actor.
575
+ readNativeRuntimeStateBag(runtime, ctx).cleared = true;
525
576
  }
526
577
 
527
578
  async function cleanupNativeSleepRuntimeState(
@@ -536,8 +587,7 @@ async function cleanupNativeSleepRuntimeState(
536
587
  // the tracked work finishes without a deadline.
537
588
  const drained = await runtime.actorWaitForTrackedShutdownWork(ctx);
538
589
  if (!drained) {
539
- await closeNativeDatabaseClient(runtime, ctx);
540
- await closeNativeSqlDatabase(runtime, ctx);
590
+ await detachNativeDatabaseForShutdown(runtime, ctx);
541
591
  void runtime
542
592
  .actorWaitForTrackedShutdownWorkUnbounded(ctx)
543
593
  .then(async () => {
@@ -554,11 +604,26 @@ async function cleanupNativeSleepRuntimeState(
554
604
  }
555
605
 
556
606
  await afterTrackedWorkDrained?.();
557
- await closeNativeDatabaseClient(runtime, ctx);
558
- await closeNativeSqlDatabase(runtime, ctx);
607
+ await detachNativeDatabaseForShutdown(runtime, ctx);
559
608
  clearNativeRuntimeState(runtime, ctx);
560
609
  }
561
610
 
611
+ async function detachNativeDatabaseForShutdown(
612
+ runtime: CoreRuntime,
613
+ ctx: ActorContextHandle,
614
+ ): Promise<void> {
615
+ const runtimeState = getNativeRuntimeState(runtime, ctx);
616
+ // Stop JS access without closing the runtime-owned SQLite backend. Rust still
617
+ // needs it to reconcile scheduled alarms and performs the physical close after
618
+ // this lifecycle callback returns.
619
+ await runtimeState.sql?.detachForShutdown();
620
+ try {
621
+ await closeNativeDatabaseClient(runtime, ctx);
622
+ } finally {
623
+ runtimeState.sql = undefined;
624
+ }
625
+ }
626
+
562
627
  function closeNativeSqlDatabase(
563
628
  runtime: CoreRuntime,
564
629
  ctx: ActorContextHandle,
@@ -595,6 +660,26 @@ async function closeNativeDatabaseClient(
595
660
  }
596
661
  }
597
662
 
663
+ function createNativeSqlTransaction(
664
+ runtime: CoreRuntime,
665
+ transaction: SqliteTransactionHandle,
666
+ ): JsNativeSynchronousTransactionLike {
667
+ return {
668
+ exec: (sql) => runtime.actorSqlTransactionExec(transaction, sql),
669
+ execSync: (sql) =>
670
+ runtime.actorSqlTransactionExecSync(transaction, sql),
671
+ execute: (sql, params) =>
672
+ runtime.actorSqlTransactionExecute(transaction, sql, params),
673
+ executeSync: (sql, params) =>
674
+ runtime.actorSqlTransactionExecuteSync(transaction, sql, params),
675
+ commit: () => runtime.actorSqlTransactionCommit(transaction),
676
+ commitSync: () => runtime.actorSqlTransactionCommitSync(transaction),
677
+ rollback: () => runtime.actorSqlTransactionRollback(transaction),
678
+ rollbackSync: () =>
679
+ runtime.actorSqlTransactionRollbackSync(transaction),
680
+ };
681
+ }
682
+
598
683
  function getOrCreateNativeSqlDatabase(
599
684
  runtime: CoreRuntime,
600
685
  ctx: ActorContextHandle,
@@ -605,9 +690,12 @@ function getOrCreateNativeSqlDatabase(
605
690
  return cachedDatabase;
606
691
  }
607
692
 
608
- const database = wrapJsNativeDatabase({
693
+ const bindings: JsNativeDatabaseLike = {
609
694
  exec: (sql) => runtime.actorSqlExec(ctx, sql),
695
+ execSync: (sql) => runtime.actorSqlExecSync(ctx, sql),
610
696
  execute: (sql, params) => runtime.actorSqlExecute(ctx, sql, params),
697
+ executeSync: (sql, params) =>
698
+ runtime.actorSqlExecuteSync(ctx, sql, params),
611
699
  executeBatch: (statements) =>
612
700
  runtime.actorSqlExecuteBatch(ctx, statements),
613
701
  beginTransaction: async (timeoutMs, name) => {
@@ -616,19 +704,15 @@ function getOrCreateNativeSqlDatabase(
616
704
  timeoutMs,
617
705
  name,
618
706
  );
619
- return {
620
- exec: (sql) =>
621
- runtime.actorSqlTransactionExec(transaction, sql),
622
- execute: (sql, params) =>
623
- runtime.actorSqlTransactionExecute(
624
- transaction,
625
- sql,
626
- params,
627
- ),
628
- commit: () => runtime.actorSqlTransactionCommit(transaction),
629
- rollback: () =>
630
- runtime.actorSqlTransactionRollback(transaction),
631
- };
707
+ return createNativeSqlTransaction(runtime, transaction);
708
+ },
709
+ beginTransactionSync: (timeoutMs, name) => {
710
+ const transaction = runtime.actorSqlBeginTransactionSync(
711
+ ctx,
712
+ timeoutMs,
713
+ name,
714
+ );
715
+ return createNativeSqlTransaction(runtime, transaction);
632
716
  },
633
717
  beginStateTransaction: async (timeoutMs, context) => {
634
718
  const scope = context as NativeStateTransactionScope | undefined;
@@ -668,8 +752,14 @@ function getOrCreateNativeSqlDatabase(
668
752
  run: (sql, params) => runtime.actorSqlRun(ctx, sql, params),
669
753
  metrics: () => runtime.actorSqlMetrics(ctx),
670
754
  takeLastKvError: () => runtime.actorSqlTakeLastKvError(ctx),
755
+ open: () => runtime.actorSqlOpen(ctx),
756
+ commitTicket: () => runtime.actorSqlCommitTicket(ctx),
757
+ whenDurable: (ticket) => runtime.actorSqlWhenDurable(ctx, ticket),
758
+ abortGeneration: (reason) =>
759
+ runtime.actorSqlAbortGeneration(ctx, reason),
671
760
  close: () => runtime.actorSqlClose(ctx),
672
- });
761
+ };
762
+ const database = wrapJsNativeDatabase(bindings);
673
763
  runtimeState.sql = database;
674
764
  return database;
675
765
  }
@@ -776,7 +866,7 @@ function decodeNativeKvValue<T extends NativeKvValueType = "text">(
776
866
  async function loadEngineCli(): Promise<typeof import("@rivetkit/engine-cli")> {
777
867
  // LOAD-BEARING: the specifier is computed (`.join("/")`) on purpose. Do NOT
778
868
  // "simplify" it to a literal `import("@rivetkit/engine-cli")`. Edge adapters
779
- // (e.g. @rivetkit/supabase) pre-bundle this module for Deno; a literal
869
+ // pre-bundle this module for Deno; a literal
780
870
  // dynamic import is statically resolvable, so Deno's eszip bundler would
781
871
  // snapshot the ~117 MB engine-cli binary into the deploy and 413. The
782
872
  // computed specifier keeps it opaque to static analysis so it is never
@@ -784,7 +874,7 @@ async function loadEngineCli(): Promise<typeof import("@rivetkit/engine-cli")> {
784
874
  return import(["@rivetkit", "engine-cli"].join("/"));
785
875
  }
786
876
 
787
- async function loadServices(): Promise<typeof import("@rivet-dev/services")> {
877
+ async function loadServices(): Promise<{ getServicesPath: () => string }> {
788
878
  // Keep the native binary opaque to edge bundlers for the same reason as
789
879
  // engine-cli above.
790
880
  return import(["@rivet-dev", "services"].join("/"));
@@ -3022,22 +3112,28 @@ export class ActorContextHandleAdapter {
3022
3112
 
3023
3113
  get abortSignal(): AbortSignal {
3024
3114
  if (!this.#abortSignal) {
3025
- const actorSignal = this.#createActorAbortSignal();
3115
+ const actorAbort = this.#actorAbort();
3116
+ const actorSignal = actorAbort.signal;
3026
3117
  if (this.#dispatchCancelToken === undefined) {
3027
3118
  this.#abortSignal = actorSignal;
3028
3119
  } else {
3029
3120
  const controller = new AbortController();
3030
3121
  let cleanedUp = false;
3122
+ let releaseDispatchListener: (() => void) | undefined;
3031
3123
  const onActorAbort = () => {
3032
3124
  cleanup();
3033
3125
  controller.abort();
3034
3126
  };
3127
+ // Releasing the native listener on dispose frees it even when the
3128
+ // dispatch token is never cancelled.
3035
3129
  const cleanup = () => {
3036
3130
  if (cleanedUp) {
3037
3131
  return;
3038
3132
  }
3039
3133
  cleanedUp = true;
3040
- actorSignal.removeEventListener("abort", onActorAbort);
3134
+ actorAbort.listeners.delete(onActorAbort);
3135
+ releaseDispatchListener?.();
3136
+ releaseDispatchListener = undefined;
3041
3137
  this.#abortSignalCleanup = undefined;
3042
3138
  };
3043
3139
 
@@ -3051,10 +3147,8 @@ export class ActorContextHandleAdapter {
3051
3147
  } else {
3052
3148
  const dispatchCancelToken = this.#dispatchCancelToken;
3053
3149
  this.#abortSignalCleanup = cleanup;
3054
- actorSignal.addEventListener("abort", onActorAbort, {
3055
- once: true,
3056
- });
3057
- callNativeSync(() =>
3150
+ actorAbort.listeners.add(onActorAbort);
3151
+ releaseDispatchListener = callNativeSync(() =>
3058
3152
  this.#runtime.onCancellationTokenCancelled(
3059
3153
  dispatchCancelToken,
3060
3154
  () => {
@@ -3121,10 +3215,12 @@ export class ActorContextHandleAdapter {
3121
3215
  {
3122
3216
  open: async (requestedActorId) => {
3123
3217
  void requestedActorId;
3124
- return getOrCreateNativeSqlDatabase(
3218
+ const database = getOrCreateNativeSqlDatabase(
3125
3219
  this.#runtime,
3126
3220
  this.#ctx,
3127
3221
  );
3222
+ await database.open();
3223
+ return database;
3128
3224
  },
3129
3225
  },
3130
3226
  async (timeoutMs, context) =>
@@ -3506,24 +3602,49 @@ export class ActorContextHandleAdapter {
3506
3602
 
3507
3603
  async dispose(): Promise<void> {
3508
3604
  // 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();
3605
+ // down so the request-save and onStateChange always run. Shutdown
3606
+ // cleanup may already have cleared the generation, which leaves no
3607
+ // pending save to flush.
3608
+ if (!isNativeRuntimeStateCleared(this.#runtime, this.#ctx)) {
3609
+ this.#flushStateChange();
3610
+ }
3511
3611
  this.#abortSignalCleanup?.();
3512
3612
  }
3513
3613
 
3514
- #createActorAbortSignal(): AbortSignal {
3614
+ #actorAbort(): NativeActorAbort {
3615
+ // An aborted cached signal may belong to a previous generation, so
3616
+ // only a live one is reused.
3617
+ const runtimeState = readNativeRuntimeStateBag(
3618
+ this.#runtime,
3619
+ this.#ctx,
3620
+ );
3621
+ const cached = runtimeState.actorAbort;
3622
+ if (cached && !cached.signal.aborted) {
3623
+ return cached;
3624
+ }
3625
+
3515
3626
  const nativeSignal = callNativeSync(() =>
3516
3627
  this.#runtime.actorAbortSignal(this.#ctx),
3517
3628
  );
3518
3629
  const controller = new AbortController();
3519
- if (nativeSignal.aborted) {
3630
+ const actorAbort: NativeActorAbort = {
3631
+ signal: controller.signal,
3632
+ listeners: new Set(),
3633
+ };
3634
+ const abort = () => {
3520
3635
  controller.abort();
3636
+ for (const listener of actorAbort.listeners) {
3637
+ listener();
3638
+ }
3639
+ actorAbort.listeners.clear();
3640
+ };
3641
+ if (nativeSignal.aborted) {
3642
+ abort();
3521
3643
  } else {
3522
- nativeSignal.addEventListener("abort", () => controller.abort(), {
3523
- once: true,
3524
- });
3644
+ nativeSignal.addEventListener("abort", abort, { once: true });
3525
3645
  }
3526
- return controller.signal;
3646
+ runtimeState.actorAbort = actorAbort;
3647
+ return actorAbort;
3527
3648
  }
3528
3649
 
3529
3650
  #readState(): unknown {
@@ -3896,6 +4017,8 @@ function buildActorTracingConfig(
3896
4017
  };
3897
4018
  }
3898
4019
 
4020
+ const SQLITE_DEFERRED_COMMITS = Symbol.for("rivetkit.sqlite.deferredCommits");
4021
+
3899
4022
  function buildActorConfig(
3900
4023
  definition: AnyActorDefinition,
3901
4024
  registryConfig: RegistryConfig,
@@ -3909,12 +4032,18 @@ function buildActorConfig(
3909
4032
  const sqliteProfiling = (
3910
4033
  config.db as { sqliteProfiling?: SqliteProfilingOptions } | undefined
3911
4034
  )?.sqliteProfiling;
4035
+ // Internal opt-in for embedders, such as Open Orange, that gate outputs on `whenDurable`.
4036
+ const sqliteDeferredCommits =
4037
+ (config.db as Record<symbol, unknown> | undefined)?.[
4038
+ SQLITE_DEFERRED_COMMITS
4039
+ ] === true;
3912
4040
 
3913
4041
  return {
3914
4042
  name: options.name as string | undefined,
3915
4043
  icon: options.icon as string | undefined,
3916
4044
  hasDatabase: true,
3917
4045
  remoteSqlite: usesRemoteSqlite,
4046
+ sqliteDeferredCommits: sqliteDeferredCommits || undefined,
3918
4047
  sqliteProfiling,
3919
4048
  tracing: buildActorTracingConfig(
3920
4049
  definition.config.actions,
@@ -4846,7 +4975,7 @@ export function buildNativeFactory(
4846
4975
  }
4847
4976
  } finally {
4848
4977
  resolveNativeDestroy(runtime, ctx);
4849
- await actorCtx.closeDatabase();
4978
+ await detachNativeDatabaseForShutdown(runtime, ctx);
4850
4979
  clearNativeRuntimeState(runtime, ctx);
4851
4980
  await actorCtx.dispose();
4852
4981
  }
@@ -5598,11 +5727,12 @@ export async function buildServeConfig(
5598
5727
  }
5599
5728
 
5600
5729
  const serveConfig: RuntimeServeConfig = {
5601
- version: config.envoy.version,
5730
+ version: config.node.version,
5602
5731
  endpoint: config.endpoint,
5732
+ engineSpawn: config.engineSpawn,
5603
5733
  token: config.token,
5604
5734
  namespace: config.namespace,
5605
- poolName: config.envoy.poolName,
5735
+ poolName: config.node.poolName,
5606
5736
  startServices: resolveServicesBinary && config.startServices,
5607
5737
  handleInspectorHttpInRuntime: true,
5608
5738
  serverlessBasePath: config.serverless.basePath,
@@ -5616,7 +5746,7 @@ export async function buildServeConfig(
5616
5746
 
5617
5747
  // Always best-effort resolve the npm-installed engine binary and hand its
5618
5748
  // 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
5749
+ // engine using the resolved spawn decision, so
5620
5750
  // JS must not duplicate that decision here. Only JS knows the npm
5621
5751
  // `node_modules` layout, so it resolves the path; if no binary is available
5622
5752
  // (remote-only install, unsupported platform, optional deps skipped), leave
@@ -5636,14 +5766,16 @@ export async function buildServeConfig(
5636
5766
  });
5637
5767
  }
5638
5768
  if (resolveServicesBinary && config.startServices) {
5639
- try {
5640
- const { getServicesPath } = await loadServices();
5641
- serveConfig.servicesBinaryPath = getServicesPath();
5642
- } catch (error) {
5643
- 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",
5645
- error: stringifyError(error),
5646
- });
5769
+ const servicesBinary = getEnvUniversal("RIVET_SERVICES_BINARY");
5770
+ if (servicesBinary) {
5771
+ serveConfig.servicesBinaryPath = servicesBinary;
5772
+ } else {
5773
+ try {
5774
+ const { getServicesPath } = await loadServices();
5775
+ serveConfig.servicesBinaryPath = getServicesPath();
5776
+ } catch (error) {
5777
+ throw servicesBinaryUnavailable(error);
5778
+ }
5647
5779
  }
5648
5780
  }
5649
5781
  serveConfig.engineHost = config.engineHost;
@@ -284,10 +284,15 @@ export interface RuntimeSqlRunResult {
284
284
 
285
285
  export interface RuntimeSqlDatabase {
286
286
  exec(sql: string): Promise<RuntimeSqlExecResult>;
287
+ execSync(sql: string): RuntimeSqlExecResult;
287
288
  execute(
288
289
  sql: string,
289
290
  params?: RuntimeSqlBindParams,
290
291
  ): Promise<RuntimeSqlExecuteResult>;
292
+ executeSync(
293
+ sql: string,
294
+ params?: RuntimeSqlBindParams,
295
+ ): RuntimeSqlExecuteResult;
291
296
  executeBatch(
292
297
  statements: RuntimeSqlBatchStatement[],
293
298
  ): Promise<RuntimeSqlExecuteResult[]>;
@@ -303,19 +308,33 @@ export interface RuntimeSqlDatabase {
303
308
  timeoutMs?: number,
304
309
  name?: string,
305
310
  ): Promise<RuntimeSqlTransactionDatabase>;
311
+ beginTransactionSync(
312
+ timeoutMs?: number,
313
+ name?: string,
314
+ ): RuntimeSqlTransactionDatabase;
306
315
  metrics?(): SqliteNativeMetrics | null;
307
316
  takeLastKvError?(): string | null;
317
+ open(): Promise<void>;
318
+ commitTicket(): number;
319
+ whenDurable(ticket: number): Promise<void>;
308
320
  close(): Promise<void>;
309
321
  }
310
322
 
311
323
  export interface RuntimeSqlTransactionDatabase {
312
324
  exec(sql: string): Promise<RuntimeSqlExecResult>;
325
+ execSync(sql: string): RuntimeSqlExecResult;
313
326
  execute(
314
327
  sql: string,
315
328
  params?: RuntimeSqlBindParams,
316
329
  ): Promise<RuntimeSqlExecuteResult>;
330
+ executeSync(
331
+ sql: string,
332
+ params?: RuntimeSqlBindParams,
333
+ ): RuntimeSqlExecuteResult;
317
334
  commit(): Promise<void>;
335
+ commitSync(): void;
318
336
  rollback(): Promise<void>;
337
+ rollbackSync(): void;
319
338
  }
320
339
 
321
340
  /** Sample rates for the traces an actor starts, in the shape core takes. */
@@ -330,6 +349,7 @@ export interface RuntimeActorConfig {
330
349
  icon?: string;
331
350
  hasDatabase?: boolean;
332
351
  remoteSqlite?: boolean;
352
+ sqliteDeferredCommits?: boolean;
333
353
  sqliteProfiling?: SqliteProfilingOptions;
334
354
  tracing?: RuntimeActorTracingConfig;
335
355
  enableActorRuntimeSocket?: boolean;
@@ -387,6 +407,8 @@ export interface RuntimeServeConfig {
387
407
  engineBinaryPath?: string;
388
408
  startServices?: boolean;
389
409
  servicesBinaryPath?: string;
410
+ /** Whether config resolution selected a managed local development engine. */
411
+ engineSpawn?: boolean;
390
412
  engineHost?: string;
391
413
  enginePort?: number;
392
414
  handleInspectorHttpInRuntime?: boolean;
@@ -532,10 +554,15 @@ export interface CoreRuntime {
532
554
  createCancellationToken(): CancellationTokenHandle;
533
555
  cancellationTokenAborted(token: CancellationTokenHandle): boolean;
534
556
  cancelCancellationToken(token: CancellationTokenHandle): void;
557
+ /**
558
+ * Calls `callback` once when `token` is cancelled. Returns a release
559
+ * function that drops the registration without calling `callback`; call it
560
+ * once cancellation no longer matters so the native listener is freed.
561
+ */
535
562
  onCancellationTokenCancelled(
536
563
  token: CancellationTokenHandle,
537
564
  callback: (...args: unknown[]) => unknown,
538
- ): void;
565
+ ): () => void;
539
566
 
540
567
  actorState(ctx: ActorContextHandle): RuntimeBytes;
541
568
  actorBeginOnStateChange(ctx: ActorContextHandle): void;
@@ -689,11 +716,20 @@ export interface CoreRuntime {
689
716
  ctx: ActorContextHandle,
690
717
  sql: string,
691
718
  ): Promise<RuntimeSqlExecResult>;
719
+ actorSqlExecSync(
720
+ ctx: ActorContextHandle,
721
+ sql: string,
722
+ ): RuntimeSqlExecResult;
692
723
  actorSqlExecute(
693
724
  ctx: ActorContextHandle,
694
725
  sql: string,
695
726
  params?: RuntimeSqlBindParams,
696
727
  ): Promise<RuntimeSqlExecuteResult>;
728
+ actorSqlExecuteSync(
729
+ ctx: ActorContextHandle,
730
+ sql: string,
731
+ params?: RuntimeSqlBindParams,
732
+ ): RuntimeSqlExecuteResult;
697
733
  actorSqlExecuteBatch(
698
734
  ctx: ActorContextHandle,
699
735
  statements: RuntimeSqlBatchStatement[],
@@ -703,21 +739,37 @@ export interface CoreRuntime {
703
739
  timeoutMs?: number,
704
740
  name?: string,
705
741
  ): Promise<SqliteTransactionHandle>;
742
+ actorSqlBeginTransactionSync(
743
+ ctx: ActorContextHandle,
744
+ timeoutMs?: number,
745
+ name?: string,
746
+ ): SqliteTransactionHandle;
706
747
  actorSqlTransactionExec(
707
748
  transaction: SqliteTransactionHandle,
708
749
  sql: string,
709
750
  ): Promise<RuntimeSqlExecResult>;
751
+ actorSqlTransactionExecSync(
752
+ transaction: SqliteTransactionHandle,
753
+ sql: string,
754
+ ): RuntimeSqlExecResult;
710
755
  actorSqlTransactionExecute(
711
756
  transaction: SqliteTransactionHandle,
712
757
  sql: string,
713
758
  params?: RuntimeSqlBindParams,
714
759
  ): Promise<RuntimeSqlExecuteResult>;
760
+ actorSqlTransactionExecuteSync(
761
+ transaction: SqliteTransactionHandle,
762
+ sql: string,
763
+ params?: RuntimeSqlBindParams,
764
+ ): RuntimeSqlExecuteResult;
715
765
  actorSqlTransactionCommit(
716
766
  transaction: SqliteTransactionHandle,
717
767
  ): Promise<void>;
768
+ actorSqlTransactionCommitSync(transaction: SqliteTransactionHandle): void;
718
769
  actorSqlTransactionRollback(
719
770
  transaction: SqliteTransactionHandle,
720
771
  ): Promise<void>;
772
+ actorSqlTransactionRollbackSync(transaction: SqliteTransactionHandle): void;
721
773
  actorBeginStateTransaction(
722
774
  ctx: ActorContextHandle,
723
775
  timeoutMs?: number,
@@ -746,6 +798,13 @@ export interface CoreRuntime {
746
798
  ): Promise<RuntimeSqlRunResult>;
747
799
  actorSqlMetrics(ctx: ActorContextHandle): SqliteNativeMetrics | null;
748
800
  actorSqlTakeLastKvError(ctx: ActorContextHandle): string | null;
801
+ /** Opens the actor database so later synchronous calls never fetch its first pages. */
802
+ actorSqlOpen(ctx: ActorContextHandle): Promise<void>;
803
+ /** Returns the ticket of the latest local commit. */
804
+ actorSqlCommitTicket(ctx: ActorContextHandle): number;
805
+ /** Resolves once the commit `ticket` names and every earlier commit are durable. */
806
+ actorSqlWhenDurable(ctx: ActorContextHandle, ticket: number): Promise<void>;
807
+ actorSqlAbortGeneration(ctx: ActorContextHandle, reason: string): void;
749
808
  actorSqlClose(ctx: ActorContextHandle): Promise<void>;
750
809
  actorRuntimeSocketProvision(
751
810
  ctx: ActorContextHandle,
@@ -876,6 +935,13 @@ export interface RuntimeBundle {
876
935
  runtime: CoreRuntime;
877
936
  }
878
937
 
938
+ export function servicesBinaryUnavailable(cause: unknown): Error {
939
+ return new Error(
940
+ "services.binary_unavailable: Install @rivet-dev/services yourself to run local Services, or set RIVET_SERVICES_BINARY to its executable path.",
941
+ { cause },
942
+ );
943
+ }
944
+
879
945
  export async function buildServeConfig(
880
946
  config: RegistryConfig,
881
947
  loadEnginePath: () => Promise<string>,
@@ -887,11 +953,12 @@ export async function buildServeConfig(
887
953
  }
888
954
 
889
955
  const serveConfig: RuntimeServeConfig = {
890
- version: config.envoy.version,
956
+ version: config.node.version,
891
957
  endpoint: config.endpoint,
958
+ engineSpawn: config.engineSpawn,
892
959
  token: config.token,
893
960
  namespace: config.namespace,
894
- poolName: config.envoy.poolName,
961
+ poolName: config.node.poolName,
895
962
  startServices: config.startServices,
896
963
  handleInspectorHttpInRuntime: true,
897
964
  serverlessBasePath: config.serverless.basePath,
@@ -921,13 +988,15 @@ export async function buildServeConfig(
921
988
  });
922
989
  }
923
990
  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
- });
991
+ const servicesBinary = process.env.RIVET_SERVICES_BINARY;
992
+ if (servicesBinary) {
993
+ serveConfig.servicesBinaryPath = servicesBinary;
994
+ } else {
995
+ try {
996
+ serveConfig.servicesBinaryPath = await loadServicesPath();
997
+ } catch (error) {
998
+ throw servicesBinaryUnavailable(error);
999
+ }
931
1000
  }
932
1001
  }
933
1002
  serveConfig.engineHost = config.engineHost;