rivetkit 3.0.1-preview.2 → 3.0.2

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 (113) hide show
  1. package/dist/browser/client.d.ts +78 -7
  2. package/dist/browser/client.js +67 -7
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.js +4 -1
  5. package/dist/browser/inspector/client.js.map +1 -1
  6. package/dist/tsup/{chunk-4QJQH4T4.cjs → chunk-3C5KLO4V.cjs} +4 -4
  7. package/dist/tsup/{chunk-4QJQH4T4.cjs.map → chunk-3C5KLO4V.cjs.map} +1 -1
  8. package/dist/tsup/{chunk-BSGU45BD.cjs → chunk-3KVVYC5I.cjs} +202 -145
  9. package/dist/tsup/chunk-3KVVYC5I.cjs.map +1 -0
  10. package/dist/tsup/{chunk-JRLVFBMY.js → chunk-3RE23GTB.js} +9 -3
  11. package/dist/tsup/chunk-3RE23GTB.js.map +1 -0
  12. package/dist/tsup/{chunk-SD3PQA7R.js → chunk-47W6FHPJ.js} +2 -2
  13. package/dist/tsup/{chunk-JKTXQQEE.js → chunk-4ASLJWUQ.js} +4 -4
  14. package/dist/tsup/{chunk-G5VHMGDB.js → chunk-ANP7UCAM.js} +66 -9
  15. package/dist/tsup/chunk-ANP7UCAM.js.map +1 -0
  16. package/dist/tsup/{chunk-LNYYP2PY.cjs → chunk-BBEH6RML.cjs} +3 -3
  17. package/dist/tsup/{chunk-LNYYP2PY.cjs.map → chunk-BBEH6RML.cjs.map} +1 -1
  18. package/dist/tsup/{chunk-AGQUQEZM.cjs → chunk-DVXMOEFT.cjs} +7 -7
  19. package/dist/tsup/{chunk-AGQUQEZM.cjs.map → chunk-DVXMOEFT.cjs.map} +1 -1
  20. package/dist/tsup/{chunk-N7UDXIJN.cjs → chunk-FR5QOAYE.cjs} +10 -10
  21. package/dist/tsup/{chunk-N7UDXIJN.cjs.map → chunk-FR5QOAYE.cjs.map} +1 -1
  22. package/dist/tsup/{chunk-OOHHMLQX.js → chunk-HJWK46Z5.js} +3 -3
  23. package/dist/tsup/{chunk-CEUOGGOM.js → chunk-J7T52LN6.js} +2 -2
  24. package/dist/tsup/{chunk-4E76XTEX.cjs → chunk-KF7ETIFK.cjs} +3 -3
  25. package/dist/tsup/{chunk-4E76XTEX.cjs.map → chunk-KF7ETIFK.cjs.map} +1 -1
  26. package/dist/tsup/{chunk-FUSYDRMB.cjs → chunk-M3H37DUQ.cjs} +9 -3
  27. package/dist/tsup/chunk-M3H37DUQ.cjs.map +1 -0
  28. package/dist/tsup/{chunk-BT4SSKF6.cjs → chunk-M7KPJSGO.cjs} +3 -3
  29. package/dist/tsup/{chunk-BT4SSKF6.cjs.map → chunk-M7KPJSGO.cjs.map} +1 -1
  30. package/dist/tsup/{chunk-GPKL6OTF.js → chunk-OF63EVJQ.js} +2 -2
  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-6FEYCVZC.js → chunk-UXDASKP6.js} +1 -1
  34. package/dist/tsup/chunk-UXDASKP6.js.map +1 -0
  35. package/dist/tsup/{chunk-O3HSYSUU.js → chunk-ZAZAKYNQ.js} +2 -2
  36. package/dist/tsup/client/mod.cjs +5 -5
  37. package/dist/tsup/client/mod.d.cts +3 -3
  38. package/dist/tsup/client/mod.d.ts +3 -3
  39. package/dist/tsup/client/mod.js +4 -4
  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-DJ3KW-fe.d.ts → config-BtUHYdoj.d.ts} +23 -1
  45. package/dist/tsup/{config-B2wlj9wx.d.ts → config-CBTr4IhE.d.cts} +50 -8
  46. package/dist/tsup/{config-B2wlj9wx.d.cts → config-CBTr4IhE.d.ts} +50 -8
  47. package/dist/tsup/{config-8NgsxIcT.d.cts → config-H6pJy_J1.d.cts} +23 -1
  48. package/dist/tsup/{context-BL8kUGjq.d.ts → context-DrDoMXSD.d.ts} +2 -2
  49. package/dist/tsup/{context-_RoE_YHL.d.cts → context-TWrKZjqf.d.cts} +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.cjs +2 -2
  59. package/dist/tsup/dynamic/mod.d.cts +2 -2
  60. package/dist/tsup/dynamic/mod.d.ts +2 -2
  61. package/dist/tsup/dynamic/mod.js +1 -1
  62. package/dist/tsup/inspector/mod.cjs +5 -5
  63. package/dist/tsup/inspector/mod.js +4 -4
  64. package/dist/tsup/inspector/workflow.cjs +4 -4
  65. package/dist/tsup/inspector/workflow.js +3 -3
  66. package/dist/tsup/inspector-tab/mod.cjs +2 -2
  67. package/dist/tsup/inspector-tab/mod.d.cts +3 -3
  68. package/dist/tsup/inspector-tab/mod.d.ts +3 -3
  69. package/dist/tsup/inspector-tab/mod.js +1 -1
  70. package/dist/tsup/mod.cjs +258 -125
  71. package/dist/tsup/mod.cjs.map +1 -1
  72. package/dist/tsup/mod.d.cts +4 -4
  73. package/dist/tsup/mod.d.ts +4 -4
  74. package/dist/tsup/mod.js +159 -26
  75. package/dist/tsup/mod.js.map +1 -1
  76. package/dist/tsup/test/mod.cjs +6 -6
  77. package/dist/tsup/test/mod.d.cts +2 -2
  78. package/dist/tsup/test/mod.d.ts +2 -2
  79. package/dist/tsup/test/mod.js +4 -4
  80. package/dist/tsup/unstable/migrations.d.cts +1 -1
  81. package/dist/tsup/unstable/migrations.d.ts +1 -1
  82. package/dist/tsup/utils.cjs +2 -2
  83. package/dist/tsup/utils.js +1 -1
  84. package/dist/tsup/workflow/mod.cjs +10 -10
  85. package/dist/tsup/workflow/mod.cjs.map +1 -1
  86. package/dist/tsup/workflow/mod.d.cts +4 -4
  87. package/dist/tsup/workflow/mod.d.ts +4 -4
  88. package/dist/tsup/workflow/mod.js +5 -5
  89. package/package.json +12 -9
  90. package/src/actor/config.ts +2 -0
  91. package/src/client/actor-handle.ts +43 -7
  92. package/src/client/raw-utils.ts +17 -3
  93. package/src/client/utils.ts +4 -0
  94. package/src/common/database/config.ts +50 -7
  95. package/src/db/mod.ts +1 -0
  96. package/src/registry/config/index.ts +7 -5
  97. package/src/registry/index.ts +142 -1
  98. package/src/registry/napi-runtime.ts +15 -0
  99. package/src/registry/native.ts +24 -17
  100. package/src/registry/runtime.ts +7 -1
  101. package/src/utils/env-vars.ts +4 -2
  102. package/dist/tsup/chunk-6FEYCVZC.js.map +0 -1
  103. package/dist/tsup/chunk-BSGU45BD.cjs.map +0 -1
  104. package/dist/tsup/chunk-FUSYDRMB.cjs.map +0 -1
  105. package/dist/tsup/chunk-G5VHMGDB.js.map +0 -1
  106. package/dist/tsup/chunk-HDVZ6YZG.cjs.map +0 -1
  107. package/dist/tsup/chunk-JRLVFBMY.js.map +0 -1
  108. /package/dist/tsup/{chunk-SD3PQA7R.js.map → chunk-47W6FHPJ.js.map} +0 -0
  109. /package/dist/tsup/{chunk-JKTXQQEE.js.map → chunk-4ASLJWUQ.js.map} +0 -0
  110. /package/dist/tsup/{chunk-OOHHMLQX.js.map → chunk-HJWK46Z5.js.map} +0 -0
  111. /package/dist/tsup/{chunk-CEUOGGOM.js.map → chunk-J7T52LN6.js.map} +0 -0
  112. /package/dist/tsup/{chunk-GPKL6OTF.js.map → chunk-OF63EVJQ.js.map} +0 -0
  113. /package/dist/tsup/{chunk-O3HSYSUU.js.map → chunk-ZAZAKYNQ.js.map} +0 -0
@@ -200,8 +200,16 @@ export class ActorHandleRaw {
200
200
  },
201
201
  }).send(name, body, options as any);
202
202
  } catch (err) {
203
- const { group, code, message, metadata, rayId, actor } =
204
- deconstructError(err, true);
203
+ const {
204
+ group,
205
+ code,
206
+ message,
207
+ metadata,
208
+ rayId,
209
+ actor,
210
+ public: isPublic,
211
+ statusCode,
212
+ } = deconstructError(err, true);
205
213
 
206
214
  if (
207
215
  this.#shouldRetryQueueDispatchOverload(
@@ -272,6 +280,8 @@ export class ActorHandleRaw {
272
280
  }
273
281
 
274
282
  throw new ActorError(group, code, message, {
283
+ public: isPublic,
284
+ statusCode,
275
285
  metadata,
276
286
  rayId,
277
287
  actor,
@@ -434,8 +444,16 @@ export class ActorHandleRaw {
434
444
  }
435
445
  return output;
436
446
  } catch (err) {
437
- const { group, code, message, metadata, rayId, actor } =
438
- deconstructError(err, true);
447
+ const {
448
+ group,
449
+ code,
450
+ message,
451
+ metadata,
452
+ rayId,
453
+ actor,
454
+ public: isPublic,
455
+ statusCode,
456
+ } = deconstructError(err, true);
439
457
 
440
458
  if (
441
459
  await this.#shouldRetrySchedulingError(
@@ -476,7 +494,13 @@ export class ActorHandleRaw {
476
494
  "actor",
477
495
  "not_found",
478
496
  "The actor does not exist or was destroyed.",
479
- { metadata, rayId, actor },
497
+ {
498
+ public: true,
499
+ statusCode: 404,
500
+ metadata,
501
+ rayId,
502
+ actor,
503
+ },
480
504
  );
481
505
  }
482
506
 
@@ -498,6 +522,8 @@ export class ActorHandleRaw {
498
522
  }
499
523
 
500
524
  throw new ActorError(group, code, message, {
525
+ public: isPublic,
526
+ statusCode,
501
527
  metadata,
502
528
  rayId,
503
529
  actor,
@@ -779,8 +805,16 @@ export class ActorHandleRaw {
779
805
  }
780
806
  return response;
781
807
  } catch (err) {
782
- const { group, code, message, metadata, rayId, actor } =
783
- deconstructError(err, true);
808
+ const {
809
+ group,
810
+ code,
811
+ message,
812
+ metadata,
813
+ rayId,
814
+ actor,
815
+ public: isPublic,
816
+ statusCode,
817
+ } = deconstructError(err, true);
784
818
 
785
819
  if (
786
820
  await this.#shouldRetrySchedulingError(
@@ -828,6 +862,8 @@ export class ActorHandleRaw {
828
862
  }
829
863
 
830
864
  throw new ActorError(group, code, message, {
865
+ public: isPublic,
866
+ statusCode,
831
867
  metadata,
832
868
  rayId,
833
869
  actor,
@@ -129,9 +129,23 @@ export async function rawHttpFetch(
129
129
  return driver.sendRequest(target, proxyRequest, options);
130
130
  } catch (err) {
131
131
  // Standardize to ClientActorError instead of the native backend error
132
- const { group, code, message, metadata, rayId, actor } =
133
- deconstructError(err, true);
134
- throw new ActorError(group, code, message, { metadata, rayId, actor });
132
+ const {
133
+ group,
134
+ code,
135
+ message,
136
+ metadata,
137
+ rayId,
138
+ actor,
139
+ public: isPublic,
140
+ statusCode,
141
+ } = deconstructError(err, true);
142
+ throw new ActorError(group, code, message, {
143
+ public: isPublic,
144
+ statusCode,
145
+ metadata,
146
+ rayId,
147
+ actor,
148
+ });
135
149
  }
136
150
  }
137
151
 
@@ -169,6 +169,10 @@ export async function sendHttpRequest<
169
169
  }),
170
170
  );
171
171
  } catch (error) {
172
+ // Credential providers and custom transports can already supply a structured error.
173
+ if (ActorError.isRivetError(error)) {
174
+ throw error;
175
+ }
172
176
  throw new HttpRequestError(`Request failed: ${error}`, {
173
177
  cause: error,
174
178
  });
@@ -52,13 +52,16 @@ export interface SqliteTransactionOptions {
52
52
  * to change without notice.
53
53
  */
54
54
  export interface SqliteProfilingOptions {
55
- /** Exact SQL statements to give fingerprint labels. Profiling defaults to actor
56
- * aggregates without fingerprint labels. Profile logs remain enabled.
57
- * RIVETKIT_SQLITE_PROFILING overrides selection with a JSON object containing
58
- * queries and/or fingerprints arrays. An empty object clears fingerprint selection. */
59
- queries?: string[];
60
- /** Exact query fingerprints to label separately, as reported in profile logs. */
61
- fingerprints?: string[];
55
+ /** Exact SQL filter. Union with filterQueryFingerprints; both empty means all queries. */
56
+ filterQueries?: string[];
57
+ /** Fingerprint filter, including transaction fingerprints. Filters metrics, not diagnostic logs. */
58
+ filterQueryFingerprints?: string[];
59
+ /** Metric defaults apply even when omitted. Disabled metrics allocate no series. */
60
+ metrics?: SqliteProfilingMetricsOptions;
61
+ /** Duration buckets in seconds. Default [0.01, 0.1, 1]. Positive, finite, strictly increasing.
62
+ * All actors in a process enabling the duration histogram must use identical buckets. */
63
+ durationHistogramBucketsSeconds?: number[];
64
+ /** Maximum distinct statement fingerprints per process. Default: 512. */
62
65
  maxTrackedStatementFingerprints?: number;
63
66
  maxTrackedTransactionFingerprints?: number;
64
67
  maxPrometheusSeries?: number;
@@ -71,6 +74,46 @@ export interface SqliteProfilingOptions {
71
74
  diagnosticEventQueueCapacity?: number;
72
75
  }
73
76
 
77
+ /** SQLite profiling metrics. Physical-request metrics and gauges have no query labels. */
78
+ export interface SqliteProfilingMetricsOptions {
79
+ /** Execution count and cumulative seconds. Uses histogram count/sum when enabled, otherwise counters. Default: true. */
80
+ duration?: boolean;
81
+ /** Execution duration histogram. Only applies when duration is enabled. Default: true. */
82
+ durationHistogram?: boolean;
83
+ /** Outcome counters, including success and errors. Default: true. */
84
+ outcomes?: boolean;
85
+ /** Per-query timing phase histograms. Default: false. */
86
+ phaseDurationHistogram?: boolean;
87
+ /** Storage round trips per operation histogram. Default: false. */
88
+ getPagesRoundTripsHistogram?: boolean;
89
+ /** Statements per transaction histogram. Default: false. */
90
+ transactionStatementCountHistogram?: boolean;
91
+ /** Per-query pages returned from storage, including returned prefetch pages. Default: true. */
92
+ pagesFetched?: boolean;
93
+ /** Actor-level page counters by page kind (no query labels). Default: false. */
94
+ localPages?: boolean;
95
+ /** Actor-level byte counters by byte kind (no query labels). Default: false. */
96
+ localBytes?: boolean;
97
+ /** Actor-level physical storage request duration histogram. Default: false. */
98
+ getPagesDurationHistogram?: boolean;
99
+ /** Actor-level pages per storage request histograms, by page kind. Default: false. */
100
+ getPagesPagesHistogram?: boolean;
101
+ /** Actor-level storage response byte histogram. Default: false. */
102
+ getPagesResponseBytesHistogram?: boolean;
103
+ /** Actor-level missing response page counter. Default: false. */
104
+ getPagesMissingPages?: boolean;
105
+ /** Queued SQLite work, aggregated by actor name. Default: true. */
106
+ workerQueueDepth?: boolean;
107
+ /** Executing SQLite work, aggregated by actor name. Default: true. */
108
+ workerInflight?: boolean;
109
+ /** Transaction waiters, aggregated by actor name. Default: true. */
110
+ coordinatorQueueDepth?: boolean;
111
+ /** Counts observations exceeding fingerprint or series limits. Default: true. */
112
+ fingerprintOverflow?: boolean;
113
+ /** Counts diagnostic events dropped by rate limits or backpressure. Default: true. */
114
+ eventDropped?: boolean;
115
+ }
116
+
74
117
  export interface SqliteNativeMetrics {
75
118
  requestBuildNs: number;
76
119
  serializeNs: number;
package/src/db/mod.ts CHANGED
@@ -10,6 +10,7 @@ export type {
10
10
  SqliteDatabase,
11
11
  SqliteNativeMetrics,
12
12
  SqliteProfilingOptions,
13
+ SqliteProfilingMetricsOptions,
13
14
  SqliteQueryResult,
14
15
  SqliteTransactionOptions,
15
16
  } from "@/common/database/config";
@@ -251,8 +251,8 @@ export const RegistryConfigSchema = z
251
251
  .default(() => getRivetRunEngineVersion() ?? VERSION),
252
252
  /**
253
253
  * Starts the first-party Services actor host when RivetKit manages
254
- * a local engine. Disabled by default. Set RIVET_RUN_SERVICES=1
255
- * or startServices: true to enable it.
254
+ * a local engine. Enabled by default for a managed local Engine. Set
255
+ * RIVET_RUN_SERVICES=0 or startServices: false to disable it.
256
256
  */
257
257
  startServices: z.boolean().optional(),
258
258
  /**
@@ -369,7 +369,9 @@ export const RegistryConfigSchema = z
369
369
  ? localEngineEndpoint
370
370
  : (parsedEndpoint?.endpoint ??
371
371
  (isDevEnv ? localEngineEndpoint : undefined));
372
- const startServices = config.startServices ?? getRivetRunServices();
372
+ const engineSpawn = !parsedEndpoint && Boolean(endpoint);
373
+ const startServices =
374
+ config.startServices ?? getRivetRunServices() ?? engineSpawn;
373
375
  const validateServerlessEndpoint = Boolean(
374
376
  config.startEngine || parsedEndpoint,
375
377
  );
@@ -419,7 +421,7 @@ export const RegistryConfigSchema = z
419
421
  ...config,
420
422
  sqlite,
421
423
  endpoint,
422
- engineSpawn: !parsedEndpoint && Boolean(endpoint),
424
+ engineSpawn,
423
425
  startServices,
424
426
  namespace,
425
427
  token,
@@ -656,7 +658,7 @@ export const DocRegistryConfigSchema = z
656
658
  .boolean()
657
659
  .optional()
658
660
  .describe(
659
- "Starts Services when RivetKit manages a local Engine. Disabled by default. Set RIVET_RUN_SERVICES=1 or startServices: true to enable.",
661
+ "Starts Services when RivetKit manages a local Engine. Enabled by default for a managed local Engine. Set RIVET_RUN_SERVICES=0 or startServices: false to disable.",
660
662
  ),
661
663
  configurePool: DocConfigurePoolSchema.describe(
662
664
  "Automatically configure serverless nodes in the engine.",
@@ -20,6 +20,7 @@ import { logger } from "./log";
20
20
  import { buildConfiguredRegistry } from "./native";
21
21
  import { convertNativeHttpResponse } from "./native-http";
22
22
  import type {
23
+ CancellationTokenHandle,
23
24
  CoreRuntime,
24
25
  RuntimeApplicationFetch,
25
26
  RuntimeHttpResponseBodyStream,
@@ -28,6 +29,8 @@ import type {
28
29
 
29
30
  type ShutdownSignal = "SIGINT" | "SIGTERM";
30
31
 
32
+ type ConfiguredRegistry = Awaited<ReturnType<typeof buildConfiguredRegistry>>;
33
+
31
34
  const REGISTRY_READY_TIMEOUT_MS = 30_000;
32
35
  // A managed Engine restart can wait for the old process to release storage and
33
36
  // for its worker lease to expire before the replacement can register.
@@ -36,6 +39,9 @@ const LOCAL_ENGINE_READY_TIMEOUT_MS = 60_000;
36
39
  // reports. Leave time to close the node connection after that, while staying
37
40
  // below the five-second force-kill ceiling used by tsx watch.
38
41
  const LOCAL_DEV_SHUTDOWN_GRACE_PERIOD_MS = 4_000;
42
+ // Matches the engine's default `pegboard.actor_stop_threshold`. Used only when the
43
+ // node has not received the engine's advertised threshold before shutdown begins.
44
+ const DEFAULT_ACTOR_STOP_THRESHOLD_MS = 30_000;
39
45
 
40
46
  // Serverless is disabled for v3; keep the implementation for a later release.
41
47
  function rejectServerless(): void {
@@ -176,6 +182,11 @@ export class Registry<A extends RegistryActors> {
176
182
  #shutdownInstalled = false;
177
183
  #shutdownInFlight: Promise<void> | null = null;
178
184
  #signalHandlers: Partial<Record<ShutdownSignal, () => void>> = {};
185
+ #envoyConfiguredRegistry?: ConfiguredRegistry;
186
+ #activeActorCountListeners = new Set<(count: number) => void>();
187
+ #activeActorCountToken?: CancellationTokenHandle;
188
+ #lastActiveActorCount?: number;
189
+ #activeActorCountSupported?: boolean;
179
190
 
180
191
  constructor(config: RegistryConfigInput<A>, deps?: Partial<RegistryDeps>) {
181
192
  this.#config = config;
@@ -674,6 +685,21 @@ export class Registry<A extends RegistryActors> {
674
685
  const configuredRegistryPromise =
675
686
  this.#buildConfiguredRegistry(config);
676
687
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
688
+ configuredRegistryPromise.then(
689
+ (configured) => {
690
+ this.#envoyConfiguredRegistry = configured;
691
+ try {
692
+ this.#syncActiveActorCountSubscription();
693
+ } catch (error) {
694
+ logger().error(
695
+ { error },
696
+ "failed to subscribe to the active actor count",
697
+ );
698
+ }
699
+ },
700
+ // The serve lifecycle below reports build failures.
701
+ () => undefined,
702
+ );
677
703
  this.#runtimeServeLifecyclePromise = configuredRegistryPromise.then(
678
704
  async ({ runtime, registry, serveConfig }) => {
679
705
  await runtime.serveRegistry(registry, serveConfig);
@@ -799,7 +825,7 @@ export class Registry<A extends RegistryActors> {
799
825
  ? LOCAL_DEV_SHUTDOWN_GRACE_PERIOD_MS
800
826
  : ((await this.#actorStopThresholdMs(
801
827
  modeAPromise ?? modeBPromise,
802
- )) ?? 30 * 60 * 1000);
828
+ )) ?? DEFAULT_ACTOR_STOP_THRESHOLD_MS);
803
829
  }
804
830
  // Race the entire drain sequence (both modes + serve promise) against
805
831
  // a single grace ceiling. Local dev signal shutdowns allow the watcher
@@ -1026,6 +1052,121 @@ export class Registry<A extends RegistryActors> {
1026
1052
  this.#startEnvoy(config, true);
1027
1053
  }
1028
1054
 
1055
+ /**
1056
+ * Returns the number of actors hosted by this process's envoy, which is zero
1057
+ * while it is not serving. Requires the native runtime.
1058
+ */
1059
+ public activeActorCount(): number {
1060
+ this.#assertActiveActorCountSupported("activeActorCount");
1061
+ const configured = this.#envoyConfiguredRegistry;
1062
+ if (!configured) return 0;
1063
+ const { runtime, registry } = configured;
1064
+ if (!runtime.registryActiveActorCount) {
1065
+ throw new Error(
1066
+ "registry.activeActorCount() is not supported by this runtime",
1067
+ );
1068
+ }
1069
+ return runtime.registryActiveActorCount(registry);
1070
+ }
1071
+
1072
+ /**
1073
+ * Calls `callback` with the number of actors hosted by this process's envoy
1074
+ * and again whenever it changes. Rapid changes may coalesce.
1075
+ * Returns a function that unsubscribes. Requires the native runtime.
1076
+ *
1077
+ * @example
1078
+ * ```ts
1079
+ * const unsubscribe = registry.onActiveActorCountChange((count) => {
1080
+ * setTaskProtection(count > 0);
1081
+ * });
1082
+ * ```
1083
+ */
1084
+ public onActiveActorCountChange(
1085
+ callback: (count: number) => void,
1086
+ ): () => void {
1087
+ this.#assertActiveActorCountSupported("onActiveActorCountChange");
1088
+ // Wrap so the same callback can subscribe twice and unsubscribe independently.
1089
+ const listener = (count: number) => callback(count);
1090
+ this.#activeActorCountListeners.add(listener);
1091
+ this.#syncActiveActorCountSubscription();
1092
+
1093
+ // Start late listeners from the stream, not a direct read, which could see a
1094
+ // change the stream coalesced away and never corrects.
1095
+ const lastCount = this.#lastActiveActorCount;
1096
+ if (lastCount !== undefined) {
1097
+ queueMicrotask(() => {
1098
+ if (this.#activeActorCountListeners.has(listener)) {
1099
+ this.#deliverActiveActorCount(listener, lastCount);
1100
+ }
1101
+ });
1102
+ }
1103
+
1104
+ return () => {
1105
+ this.#activeActorCountListeners.delete(listener);
1106
+ this.#syncActiveActorCountSubscription();
1107
+ };
1108
+ }
1109
+
1110
+ #assertActiveActorCountSupported(method: string): void {
1111
+ this.#activeActorCountSupported ??=
1112
+ this.parseConfig().runtime !== "wasm";
1113
+ if (!this.#activeActorCountSupported) {
1114
+ throw new Error(
1115
+ `registry.${method}() requires the native runtime; WebAssembly registries do not host an envoy`,
1116
+ );
1117
+ }
1118
+ }
1119
+
1120
+ /** Holds one native subscription while any listener is registered. */
1121
+ #syncActiveActorCountSubscription(): void {
1122
+ const configured = this.#envoyConfiguredRegistry;
1123
+ if (!configured) return;
1124
+ const { runtime, registry } = configured;
1125
+ const token = this.#activeActorCountToken;
1126
+
1127
+ if (this.#activeActorCountListeners.size === 0) {
1128
+ if (token !== undefined) {
1129
+ this.#activeActorCountToken = undefined;
1130
+ this.#lastActiveActorCount = undefined;
1131
+ runtime.cancelCancellationToken(token);
1132
+ }
1133
+ return;
1134
+ }
1135
+ if (token !== undefined) return;
1136
+
1137
+ if (!runtime.onRegistryActiveActorCountChange) {
1138
+ throw new Error(
1139
+ "active actor count subscriptions are not supported by this runtime",
1140
+ );
1141
+ }
1142
+ const nextToken = runtime.createCancellationToken();
1143
+ this.#activeActorCountToken = nextToken;
1144
+ runtime.onRegistryActiveActorCountChange(
1145
+ registry,
1146
+ (count) => {
1147
+ // Drop calls still queued from a released subscription.
1148
+ if (this.#activeActorCountToken !== nextToken) return;
1149
+ this.#lastActiveActorCount = count;
1150
+ // Iterate a copy so listeners added by a callback are not called twice.
1151
+ for (const listener of [...this.#activeActorCountListeners]) {
1152
+ this.#deliverActiveActorCount(listener, count);
1153
+ }
1154
+ },
1155
+ nextToken,
1156
+ );
1157
+ }
1158
+
1159
+ #deliverActiveActorCount(
1160
+ listener: (count: number) => void,
1161
+ count: number,
1162
+ ): void {
1163
+ try {
1164
+ listener(count);
1165
+ } catch (error) {
1166
+ logger().error({ error }, "active actor count listener threw");
1167
+ }
1168
+ }
1169
+
1029
1170
  #printWelcome(
1030
1171
  config: RegistryConfig,
1031
1172
  kind: "serverless" | "serverful",
@@ -354,6 +354,21 @@ export class NapiCoreRuntime implements CoreRuntime {
354
354
  );
355
355
  }
356
356
 
357
+ registryActiveActorCount(registry: RegistryHandle): number {
358
+ return asNativeRegistry(registry).activeActorCount();
359
+ }
360
+
361
+ onRegistryActiveActorCountChange(
362
+ registry: RegistryHandle,
363
+ callback: (count: number) => void,
364
+ cancelToken: CancellationTokenHandle,
365
+ ): void {
366
+ asNativeRegistry(registry).onActiveActorCountChange(
367
+ callback,
368
+ asNativeCancellationToken(cancelToken),
369
+ );
370
+ }
371
+
357
372
  async registryHealth(
358
373
  registry: RegistryHandle,
359
374
  ): Promise<RuntimeRegistryRouteResponse> {
@@ -5512,6 +5512,11 @@ export function buildNativeFactory(
5512
5512
  conn != null
5513
5513
  ? makeConnCtx(ctx, conn, undefined, cancelToken)
5514
5514
  : makeActorCtx(ctx, undefined, cancelToken);
5515
+ if (scheduledFire) {
5516
+ Object.defineProperty(actorCtx, "scheduledFire", {
5517
+ value: scheduledFire,
5518
+ });
5519
+ }
5515
5520
  const runAction = async () => {
5516
5521
  try {
5517
5522
  return encodeValue(
@@ -5680,7 +5685,7 @@ export function buildNativeFactory(
5680
5685
 
5681
5686
  export async function buildServeConfig(
5682
5687
  config: RegistryConfig,
5683
- resolveServicesBinary = true,
5688
+ resolveNativeBinaries = true,
5684
5689
  ): Promise<RuntimeServeConfig> {
5685
5690
  if (!config.endpoint) {
5686
5691
  throw nativeEndpointNotConfiguredError();
@@ -5693,7 +5698,7 @@ export async function buildServeConfig(
5693
5698
  token: config.token,
5694
5699
  namespace: config.namespace,
5695
5700
  poolName: config.node.poolName,
5696
- startServices: resolveServicesBinary && config.startServices,
5701
+ startServices: resolveNativeBinaries && config.startServices,
5697
5702
  handleInspectorHttpInRuntime: true,
5698
5703
  serverlessBasePath: config.serverless.basePath,
5699
5704
  serverlessPackageVersion: VERSION,
@@ -5704,28 +5709,30 @@ export async function buildServeConfig(
5704
5709
  serverlessMaxStartPayloadBytes: config.serverless.maxStartPayloadBytes,
5705
5710
  };
5706
5711
 
5707
- // Always best-effort resolve the npm-installed engine binary and hand its
5708
- // path to the core. The core alone decides whether to actually spawn a local
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
5709
5714
  // engine using the resolved spawn decision, so
5710
5715
  // JS must not duplicate that decision here. Only JS knows the npm
5711
5716
  // `node_modules` layout, so it resolves the path; if no binary is available
5712
5717
  // (remote-only install, unsupported platform, optional deps skipped), leave
5713
5718
  // it unset and let the core report `engine.binary_unavailable` if it actually
5714
5719
  // needs one.
5715
- try {
5716
- const { getEnginePath } = await loadEngineCli();
5717
- serveConfig.engineBinaryPath = getEnginePath();
5718
- } catch (error) {
5719
- // The npm-installed engine binary could not be resolved. The core still
5720
- // decides whether it needs to spawn a local engine; if it does, it will
5721
- // fail with engine.binary_unavailable (auto-download is off in the napi
5722
- // runtime). Warn so the cause is actionable.
5723
- logger().warn({
5724
- 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",
5725
- error: stringifyError(error),
5726
- });
5720
+ if (resolveNativeBinaries) {
5721
+ try {
5722
+ const { getEnginePath } = await loadEngineCli();
5723
+ serveConfig.engineBinaryPath = getEnginePath();
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.
5729
+ logger().warn({
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",
5731
+ error: stringifyError(error),
5732
+ });
5733
+ }
5727
5734
  }
5728
- if (resolveServicesBinary && config.startServices) {
5735
+ if (resolveNativeBinaries && config.startServices) {
5729
5736
  const servicesBinary = getEnvUniversal("RIVET_SERVICES_BINARY");
5730
5737
  if (servicesBinary) {
5731
5738
  serveConfig.servicesBinaryPath = servicesBinary;
@@ -500,6 +500,12 @@ export interface CoreRuntime {
500
500
  registryActorStopThresholdMs?(
501
501
  registry: RegistryHandle,
502
502
  ): Promise<number | undefined>;
503
+ registryActiveActorCount?(registry: RegistryHandle): number;
504
+ onRegistryActiveActorCountChange?(
505
+ registry: RegistryHandle,
506
+ callback: (count: number) => void,
507
+ cancelToken: CancellationTokenHandle,
508
+ ): void;
503
509
  handleServerlessRequest(
504
510
  registry: RegistryHandle,
505
511
  req: RuntimeServerlessRequest,
@@ -885,7 +891,7 @@ export interface RuntimeBundle {
885
891
 
886
892
  export function servicesBinaryUnavailable(cause: unknown): Error {
887
893
  return new Error(
888
- "services.binary_unavailable: Install @rivet-dev/services yourself to run local Services, or set RIVET_SERVICES_BINARY to its executable path.",
894
+ "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
895
  { cause },
890
896
  );
891
897
  }
@@ -30,8 +30,10 @@ export const getRivetRunEnginePort = (): number | undefined => {
30
30
  };
31
31
  export const getRivetRunEngineVersion = (): string | undefined =>
32
32
  getEnvUniversal("RIVET_RUN_ENGINE_VERSION");
33
- export const getRivetRunServices = (): boolean =>
34
- getEnvUniversal("RIVET_RUN_SERVICES") === "1";
33
+ export const getRivetRunServices = (): boolean | undefined => {
34
+ const value = getEnvUniversal("RIVET_RUN_SERVICES");
35
+ return value === undefined ? undefined : value === "1";
36
+ };
35
37
  export const getRivetEnvoyKind = (): string | undefined =>
36
38
  getEnvUniversal("RIVET_NODE_KIND") ?? getEnvUniversal("RIVET_ENVOY_KIND");
37
39
  export const getRivetEnvoyVersion = (): number | undefined => {