rivetkit 0.0.0-feat-sqlite-sync.a2b9069 → 0.0.0-feat-sqlite-sync-3x.a00b07f

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 (154) hide show
  1. package/dist/browser/client.d.ts +58 -9
  2. package/dist/browser/client.js +193 -23
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.js +1 -5
  5. package/dist/browser/inspector/client.js.map +1 -1
  6. package/dist/tsup/agent-os/index.cjs +3 -2652
  7. package/dist/tsup/agent-os/index.cjs.map +1 -1
  8. package/dist/tsup/agent-os/index.d.cts +1 -2758
  9. package/dist/tsup/agent-os/index.d.ts +1 -2758
  10. package/dist/tsup/agent-os/index.js +3 -2652
  11. package/dist/tsup/agent-os/index.js.map +1 -1
  12. package/dist/tsup/{chunk-PFLHGSS7.cjs → chunk-3JPXBFED.cjs} +4 -4
  13. package/dist/tsup/{chunk-PFLHGSS7.cjs.map → chunk-3JPXBFED.cjs.map} +1 -1
  14. package/dist/tsup/{chunk-VZPQBM4T.js → chunk-5X35FD2T.js} +4 -4
  15. package/dist/tsup/{chunk-62NMENN2.js → chunk-6QNBANXM.js} +3 -3
  16. package/dist/tsup/{chunk-TBVEI4CG.js → chunk-7HILY7QU.js} +185 -25
  17. package/dist/tsup/chunk-7HILY7QU.js.map +1 -0
  18. package/dist/tsup/{chunk-JI6GZ2C2.js → chunk-A2CF6PFH.js} +18 -1
  19. package/dist/tsup/chunk-A2CF6PFH.js.map +1 -0
  20. package/dist/tsup/{chunk-XU5FXL53.cjs → chunk-CT6GQRUN.cjs} +3 -3
  21. package/dist/tsup/{chunk-XU5FXL53.cjs.map → chunk-CT6GQRUN.cjs.map} +1 -1
  22. package/dist/tsup/{chunk-3XABSX7Z.js → chunk-DRZTELHJ.js} +10 -14
  23. package/dist/tsup/chunk-DRZTELHJ.js.map +1 -0
  24. package/dist/tsup/{chunk-S4JJAPRX.js → chunk-DUGEPEJO.js} +2 -2
  25. package/dist/tsup/{chunk-E443NPGV.cjs → chunk-EA6P3N4I.cjs} +3 -3
  26. package/dist/tsup/{chunk-E443NPGV.cjs.map → chunk-EA6P3N4I.cjs.map} +1 -1
  27. package/dist/tsup/{chunk-KNVSGCHJ.cjs → chunk-ERZDCOQ3.cjs} +10 -10
  28. package/dist/tsup/{chunk-KNVSGCHJ.cjs.map → chunk-ERZDCOQ3.cjs.map} +1 -1
  29. package/dist/tsup/{chunk-PFOK45LA.js → chunk-GHTA76HT.js} +2 -2
  30. package/dist/tsup/{chunk-74MPKC4U.js → chunk-ID5VJNZY.js} +2 -2
  31. package/dist/tsup/{chunk-FKJJX36M.cjs → chunk-PXIOH445.cjs} +326 -166
  32. package/dist/tsup/chunk-PXIOH445.cjs.map +1 -0
  33. package/dist/tsup/{chunk-MYWZCDML.cjs → chunk-RTWH3AX3.cjs} +19 -2
  34. package/dist/tsup/chunk-RTWH3AX3.cjs.map +1 -0
  35. package/dist/tsup/{chunk-WMBIR2SY.cjs → chunk-UV4KDO4W.cjs} +3 -3
  36. package/dist/tsup/{chunk-WMBIR2SY.cjs.map → chunk-UV4KDO4W.cjs.map} +1 -1
  37. package/dist/tsup/{chunk-4G6WPUYN.js → chunk-VI2S336K.js} +2 -2
  38. package/dist/tsup/{chunk-4AIU4P2C.cjs → chunk-W7NPIYWC.cjs} +10 -14
  39. package/dist/tsup/chunk-W7NPIYWC.cjs.map +1 -0
  40. package/dist/tsup/{chunk-BO74QMUL.cjs → chunk-ZZQM77UA.cjs} +7 -7
  41. package/dist/tsup/{chunk-BO74QMUL.cjs.map → chunk-ZZQM77UA.cjs.map} +1 -1
  42. package/dist/tsup/client/mod.cjs +6 -6
  43. package/dist/tsup/client/mod.d.cts +15 -3
  44. package/dist/tsup/client/mod.d.ts +15 -3
  45. package/dist/tsup/client/mod.js +5 -5
  46. package/dist/tsup/common/log.cjs +2 -2
  47. package/dist/tsup/common/log.js +1 -1
  48. package/dist/tsup/common/websocket.cjs +3 -3
  49. package/dist/tsup/common/websocket.js +2 -2
  50. package/dist/tsup/{config-DfVrAigH.d.ts → config-B4erdavw.d.ts} +43 -12
  51. package/dist/tsup/{config-BaUctMNL.d.cts → config-BfG1qpYz.d.cts} +7 -1
  52. package/dist/tsup/{config-BaUctMNL.d.ts → config-BfG1qpYz.d.ts} +7 -1
  53. package/dist/tsup/{config-D6T6Ud_V.d.cts → config-DK144OAw.d.cts} +43 -12
  54. package/dist/tsup/{context-CowF_zyQ.d.cts → context-Cvnf3BRe.d.cts} +2 -2
  55. package/dist/tsup/{context-BsFWwi3i.d.ts → context-Oxi6YWcG.d.ts} +2 -2
  56. package/dist/tsup/db/drizzle.cjs +2 -2
  57. package/dist/tsup/db/drizzle.d.cts +1 -1
  58. package/dist/tsup/db/drizzle.d.ts +1 -1
  59. package/dist/tsup/db/drizzle.js +1 -1
  60. package/dist/tsup/db/mod.cjs +3 -3
  61. package/dist/tsup/db/mod.d.cts +2 -2
  62. package/dist/tsup/db/mod.d.ts +2 -2
  63. package/dist/tsup/db/mod.js +2 -2
  64. package/dist/tsup/dynamic/mod.d.cts +2 -2
  65. package/dist/tsup/dynamic/mod.d.ts +2 -2
  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.d.cts +3 -3
  71. package/dist/tsup/inspector-tab/mod.d.ts +3 -3
  72. package/dist/tsup/mod.cjs +256 -174
  73. package/dist/tsup/mod.cjs.map +1 -1
  74. package/dist/tsup/mod.d.cts +4 -4
  75. package/dist/tsup/mod.d.ts +4 -4
  76. package/dist/tsup/mod.js +170 -88
  77. package/dist/tsup/mod.js.map +1 -1
  78. package/dist/tsup/test/mod.cjs +7 -7
  79. package/dist/tsup/test/mod.d.cts +2 -2
  80. package/dist/tsup/test/mod.d.ts +2 -2
  81. package/dist/tsup/test/mod.js +5 -5
  82. package/dist/tsup/unstable/migrations.d.cts +1 -1
  83. package/dist/tsup/unstable/migrations.d.ts +1 -1
  84. package/dist/tsup/utils.cjs +2 -2
  85. package/dist/tsup/utils.js +1 -1
  86. package/dist/tsup/workflow/mod.cjs +17 -17
  87. package/dist/tsup/workflow/mod.d.cts +4 -4
  88. package/dist/tsup/workflow/mod.d.ts +4 -4
  89. package/dist/tsup/workflow/mod.js +5 -5
  90. package/package.json +9 -13
  91. package/src/actor/keys.ts +86 -0
  92. package/src/agent-os/index.ts +5 -65
  93. package/src/client/actor-conn.ts +92 -6
  94. package/src/client/actor-handle.ts +24 -4
  95. package/src/client/client.ts +14 -4
  96. package/src/client/config.ts +12 -1
  97. package/src/client/lifecycle-errors.ts +16 -1
  98. package/src/client/retry-budget.ts +78 -0
  99. package/src/client/utils.ts +13 -2
  100. package/src/common/database/config.ts +7 -1
  101. package/src/common/database/native-database.ts +17 -9
  102. package/src/common/router.ts +1 -1
  103. package/src/engine-api/actors.ts +3 -3
  104. package/src/engine-client/actor-websocket-client.ts +4 -2
  105. package/src/engine-client/api-endpoints.ts +44 -14
  106. package/src/engine-client/mod.ts +2 -2
  107. package/src/registry/config/envoy.ts +1 -1
  108. package/src/registry/config/index.ts +28 -31
  109. package/src/registry/index.ts +51 -19
  110. package/src/registry/napi-runtime.ts +3 -2
  111. package/src/registry/native.ts +129 -40
  112. package/src/registry/runtime.ts +27 -10
  113. package/src/registry/wasm-runtime.ts +6 -3
  114. package/src/utils/env-vars.ts +15 -10
  115. package/dist/tsup/chunk-3XABSX7Z.js.map +0 -1
  116. package/dist/tsup/chunk-4AIU4P2C.cjs.map +0 -1
  117. package/dist/tsup/chunk-FKJJX36M.cjs.map +0 -1
  118. package/dist/tsup/chunk-JI6GZ2C2.js.map +0 -1
  119. package/dist/tsup/chunk-MYWZCDML.cjs.map +0 -1
  120. package/dist/tsup/chunk-TBVEI4CG.js.map +0 -1
  121. package/src/actor/config.test.ts +0 -78
  122. package/src/actor/keys.test.ts +0 -275
  123. package/src/actor/utils.test.ts +0 -48
  124. package/src/agent-os/actor/cron.ts +0 -84
  125. package/src/agent-os/actor/db.ts +0 -54
  126. package/src/agent-os/actor/filesystem.ts +0 -131
  127. package/src/agent-os/actor/index.ts +0 -285
  128. package/src/agent-os/actor/network.ts +0 -58
  129. package/src/agent-os/actor/preview.ts +0 -190
  130. package/src/agent-os/actor/process.ts +0 -177
  131. package/src/agent-os/actor/session.ts +0 -518
  132. package/src/agent-os/actor/shell.ts +0 -60
  133. package/src/agent-os/config.ts +0 -79
  134. package/src/agent-os/fs/database-vfs.ts +0 -624
  135. package/src/agent-os/types.ts +0 -148
  136. package/src/client/test.ts +0 -44
  137. package/src/client/token-provider.test.ts +0 -86
  138. package/src/common/database/mod.test.ts +0 -364
  139. package/src/common/database/native-database.test.ts +0 -241
  140. package/src/common/inline-websocket-adapter.test.ts +0 -51
  141. package/src/db/drizzle.test.ts +0 -164
  142. package/src/registry/config/index.test.ts +0 -25
  143. package/src/registry/run-handler-coordinator.test.ts +0 -252
  144. package/src/registry/runtime.test.ts +0 -124
  145. package/src/unstable/migrations.test.ts +0 -170
  146. package/src/utils/endpoint-parser.test.ts +0 -206
  147. package/src/utils.test.ts +0 -34
  148. package/src/workflow/driver.test.ts +0 -62
  149. /package/dist/tsup/{chunk-VZPQBM4T.js.map → chunk-5X35FD2T.js.map} +0 -0
  150. /package/dist/tsup/{chunk-62NMENN2.js.map → chunk-6QNBANXM.js.map} +0 -0
  151. /package/dist/tsup/{chunk-S4JJAPRX.js.map → chunk-DUGEPEJO.js.map} +0 -0
  152. /package/dist/tsup/{chunk-PFOK45LA.js.map → chunk-GHTA76HT.js.map} +0 -0
  153. /package/dist/tsup/{chunk-74MPKC4U.js.map → chunk-ID5VJNZY.js.map} +0 -0
  154. /package/dist/tsup/{chunk-4G6WPUYN.js.map → chunk-VI2S336K.js.map} +0 -0
@@ -50,6 +50,7 @@ import {
50
50
  import { ACTOR_CONNS_SYMBOL, type ClientRaw } from "./client";
51
51
  import * as errors from "./errors";
52
52
  import { isRetryableLifecycleReconnectSignal } from "./lifecycle-errors";
53
+ import { retryAfterMs } from "./retry-budget";
53
54
  import { logger } from "./log";
54
55
  import { isInvalidToken } from "./token-provider";
55
56
  import { outboundTelemetryHeaders } from "./outbound-telemetry";
@@ -104,6 +105,21 @@ interface EventSubscriptions<Args extends Array<unknown>> {
104
105
  */
105
106
  export type EventUnsubscribe = () => void;
106
107
 
108
+ /**
109
+ * How long a connection attempt may wait for the actor's Init before it is abandoned and
110
+ * retried. Longer than the engine's own WebSocket open deadline (15 s by default), so an engine
111
+ * that answers with a typed close wins, while a socket that never settles is still retried.
112
+ */
113
+ const CONNECT_TIMEOUT_MS = 20_000;
114
+
115
+ function isConnectionOpenTimeout(error: unknown): boolean {
116
+ return (
117
+ error instanceof errors.ActorError &&
118
+ error.group === "client" &&
119
+ error.code === "connection_open_timeout"
120
+ );
121
+ }
122
+
107
123
  /**
108
124
  * A function that handles connection errors.
109
125
  *
@@ -182,6 +198,8 @@ export class ActorConnRaw {
182
198
 
183
199
  /** Promise used to indicate the socket has connected successfully. This will be rejected if the connection fails. */
184
200
  #onOpenPromise?: ReturnType<typeof promiseWithResolvers<undefined>>;
201
+ /** Sockets given up on by the connect timeout. Their late events are ignored. */
202
+ #abandonedSockets = new WeakSet<UniversalWebSocket>();
185
203
 
186
204
  #websocket?: UniversalWebSocket;
187
205
  #authRetryAvailable = true;
@@ -457,12 +475,17 @@ export class ActorConnRaw {
457
475
  minTimeout: 250,
458
476
  maxTimeout: 30_000,
459
477
 
460
- onFailedAttempt: (error) => {
478
+ onFailedAttempt: async (error) => {
461
479
  logger().warn({
462
480
  msg: "failed to reconnect",
463
481
  attempt: error.attemptNumber,
464
482
  error: stringifyError(error),
465
483
  });
484
+ // A close that carried the service's retry hint waits at least that long.
485
+ const hintMs = retryAfterMs(error);
486
+ if (hintMs !== undefined) {
487
+ await new Promise((resolve) => setTimeout(resolve, hintMs));
488
+ }
466
489
  },
467
490
 
468
491
  // Cancel retry if aborted
@@ -498,7 +521,7 @@ export class ActorConnRaw {
498
521
  await this.#connectWebSocket();
499
522
 
500
523
  // Wait for result
501
- await this.#onOpenPromise.promise;
524
+ await this.#waitForOpen(this.#onOpenPromise.promise);
502
525
  } catch (error) {
503
526
  if (this.#shouldRetryConnectionOpenError(error)) {
504
527
  throw error;
@@ -529,10 +552,65 @@ export class ActorConnRaw {
529
552
  }
530
553
  }
531
554
 
555
+ /**
556
+ * Waits for the actor's Init on the current socket, up to {@link CONNECT_TIMEOUT_MS}. A socket
557
+ * can stay connecting with no open, error or close event, as when the engine holds the
558
+ * upgrade or a refused connect reports only an error. On timeout the socket is abandoned
559
+ * and closed, and the retryable `client.connection_open_timeout` starts the next attempt.
560
+ */
561
+ async #waitForOpen(open: Promise<undefined>) {
562
+ let timer: ReturnType<typeof setTimeout> | undefined;
563
+ const timedOut = new Promise<never>((_, reject) => {
564
+ timer = setTimeout(() => {
565
+ reject(
566
+ new errors.ActorError(
567
+ "client",
568
+ "connection_open_timeout",
569
+ `Connection did not open within ${CONNECT_TIMEOUT_MS} ms`,
570
+ ),
571
+ );
572
+ }, CONNECT_TIMEOUT_MS);
573
+ });
574
+ try {
575
+ await Promise.race([open, timedOut]);
576
+ } catch (error) {
577
+ if (isConnectionOpenTimeout(error)) {
578
+ this.#abandonCurrentSocket();
579
+ }
580
+ throw error;
581
+ } finally {
582
+ clearTimeout(timer);
583
+ }
584
+ }
585
+
586
+ #abandonCurrentSocket() {
587
+ const ws = this.#websocket;
588
+ if (!ws) return;
589
+ this.#websocket = undefined;
590
+ this.#abandonedSockets.add(ws);
591
+ logger().warn({
592
+ msg: "connection did not open in time, retrying",
593
+ connId: this.#connId,
594
+ readyState: ws.readyState,
595
+ timeoutMs: CONNECT_TIMEOUT_MS,
596
+ });
597
+ try {
598
+ ws.close(1000, "Connect timeout");
599
+ } catch (err) {
600
+ logger().debug({
601
+ msg: "failed to close abandoned websocket",
602
+ error: stringifyError(err),
603
+ });
604
+ }
605
+ }
606
+
532
607
  #shouldRetryConnectionOpenError(error: unknown): boolean {
533
608
  if (error instanceof errors.ActorConnDisposed) {
534
609
  return false;
535
610
  }
611
+ if (isConnectionOpenTimeout(error)) {
612
+ return true;
613
+ }
536
614
  if (
537
615
  error instanceof errors.ActorError &&
538
616
  isInvalidToken(error.group, error.code) &&
@@ -614,12 +692,14 @@ export class ActorConnRaw {
614
692
  });
615
693
  this.#websocket = ws;
616
694
  ws.addEventListener("open", () => {
695
+ if (this.#abandonedSockets.has(ws)) return;
617
696
  logger().debug({
618
697
  msg: "client websocket open",
619
698
  connId: this.#connId,
620
699
  });
621
700
  });
622
701
  ws.addEventListener("message", async (ev: { data: ConnMessage }) => {
702
+ if (this.#abandonedSockets.has(ws)) return;
623
703
  try {
624
704
  await this.#handleOnMessage(ev.data);
625
705
  } catch (err) {
@@ -630,6 +710,7 @@ export class ActorConnRaw {
630
710
  }
631
711
  });
632
712
  ws.addEventListener("close", async (ev: Event | CloseEventLike) => {
713
+ if (this.#abandonedSockets.has(ws)) return;
633
714
  try {
634
715
  await this.#handleOnClose(ev);
635
716
  } catch (err) {
@@ -640,6 +721,7 @@ export class ActorConnRaw {
640
721
  }
641
722
  });
642
723
  ws.addEventListener("error", () => {
724
+ if (this.#abandonedSockets.has(ws)) return;
643
725
  try {
644
726
  this.#handleOnError();
645
727
  } catch (err) {
@@ -894,7 +976,11 @@ export class ActorConnRaw {
894
976
  const parsed = parseWebSocketCloseReason(reason);
895
977
 
896
978
  if (parsed) {
897
- const { group, code, rayId } = parsed;
979
+ const { group, code, rayId, retryAfterMs } = parsed;
980
+ const closeOptions =
981
+ retryAfterMs === undefined
982
+ ? { rayId }
983
+ : { rayId, metadata: { retry_after_ms: retryAfterMs } };
898
984
  if (
899
985
  isInvalidToken(group, code) &&
900
986
  closeEvent.code === 1008 &&
@@ -923,7 +1009,7 @@ export class ActorConnRaw {
923
1009
  group,
924
1010
  code,
925
1011
  `Connection closed: ${reason}`,
926
- { rayId },
1012
+ closeOptions,
927
1013
  ),
928
1014
  );
929
1015
  return;
@@ -946,7 +1032,7 @@ export class ActorConnRaw {
946
1032
  group,
947
1033
  code,
948
1034
  `Connection closed: ${reason}`,
949
- { rayId },
1035
+ closeOptions,
950
1036
  );
951
1037
  }
952
1038
  } else {
@@ -954,7 +1040,7 @@ export class ActorConnRaw {
954
1040
  group,
955
1041
  code,
956
1042
  `Connection closed: ${reason}`,
957
- { rayId },
1043
+ closeOptions,
958
1044
  );
959
1045
  }
960
1046
 
@@ -61,6 +61,7 @@ import {
61
61
  import { type ClientRaw, CREATE_ACTOR_CONN_PROXY } from "./client";
62
62
  import { ActorError, isSchedulingError } from "./errors";
63
63
  import { retryOnLifecycleBoundary } from "./lifecycle-errors";
64
+ import { RetryBudget, retryAfterMs, retryDelayMs } from "./retry-budget";
64
65
  import { logger } from "./log";
65
66
  import { outboundTelemetryHeaders } from "./outbound-telemetry";
66
67
  import {
@@ -94,6 +95,7 @@ export class ActorHandleRaw {
94
95
  #queueSendMutex = new AsyncMutex();
95
96
  #currentActorInvocation?: CurrentActorInvocation;
96
97
  #startCallSpan?: StartCallSpan;
98
+ #retryBudget: RetryBudget;
97
99
 
98
100
  /**
99
101
  * Do not call this directly.
@@ -113,6 +115,7 @@ export class ActorHandleRaw {
113
115
  signal?: AbortSignal,
114
116
  currentActorInvocation?: CurrentActorInvocation,
115
117
  startCallSpan?: StartCallSpan,
118
+ retryBudget: RetryBudget = new RetryBudget(),
116
119
  ) {
117
120
  this.#client = client;
118
121
  this.#driver = driver;
@@ -124,6 +127,7 @@ export class ActorHandleRaw {
124
127
  this.#signal = signal;
125
128
  this.#currentActorInvocation = currentActorInvocation;
126
129
  this.#startCallSpan = startCallSpan;
130
+ this.#retryBudget = retryBudget;
127
131
  }
128
132
 
129
133
  async #resolveConnectionParams(): Promise<unknown> {
@@ -166,6 +170,7 @@ export class ActorHandleRaw {
166
170
  this.#actorResolutionState,
167
171
  );
168
172
 
173
+ this.#retryBudget.deposit();
169
174
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
170
175
  let actorId: string | undefined;
171
176
  try {
@@ -205,9 +210,19 @@ export class ActorHandleRaw {
205
210
  metadata,
206
211
  attempt,
207
212
  maxAttempts,
208
- )
213
+ ) &&
214
+ this.#retryBudget.tryWithdraw()
209
215
  ) {
210
- await this.#waitForRetryWindow();
216
+ await new Promise((resolve) =>
217
+ setTimeout(
218
+ resolve,
219
+ retryDelayMs(attempt, {
220
+ initialDelayMs: 25,
221
+ maxDelayMs: 1_000,
222
+ hintMs: retryAfterMs(err),
223
+ }),
224
+ ),
225
+ );
211
226
  continue;
212
227
  }
213
228
 
@@ -309,7 +324,10 @@ export class ActorHandleRaw {
309
324
  if (opts.name === "destroy") {
310
325
  return await run();
311
326
  }
312
- return await retryOnLifecycleBoundary(run, { signal });
327
+ return await retryOnLifecycleBoundary(run, {
328
+ signal,
329
+ budget: this.#retryBudget,
330
+ });
313
331
  };
314
332
  if (!call) {
315
333
  return await send();
@@ -1001,7 +1019,9 @@ export class ActorHandleRaw {
1001
1019
  }
1002
1020
 
1003
1021
  /** Issue a token scoped to this actor. Defaults to actor gateway read access. */
1004
- async issueToken(options: ActorIssueTokenOptions = {}): Promise<IssuedToken> {
1022
+ async issueToken(
1023
+ options: ActorIssueTokenOptions = {},
1024
+ ): Promise<IssuedToken> {
1005
1025
  const actorId = await this.resolve();
1006
1026
  const permissions: ActorTokenPermissions = options.permissions ?? {
1007
1027
  actor_gateway: ["read"],
@@ -14,6 +14,7 @@ import {
14
14
  import { type ActorHandle, ActorHandleRaw } from "./actor-handle";
15
15
  import { logger } from "./log";
16
16
  import { resolveGatewayTarget } from "./resolve-gateway-target";
17
+ import { type RetryBudgetOptions, RetryBudget } from "./retry-budget";
17
18
 
18
19
  export type { ClientConfig, ClientConfigInput } from "./config";
19
20
 
@@ -181,6 +182,8 @@ export const CREATE_ACTOR_CONN_PROXY = Symbol("createActorConnProxy");
181
182
  export interface ClientRawOptions {
182
183
  encoding?: Encoding;
183
184
  gateway?: ActorGatewayOptions;
185
+ /** Bounds retries of refused requests across every handle of this client. */
186
+ retryBudget?: RetryBudgetOptions;
184
187
  }
185
188
 
186
189
  /** Runtime-supplied wiring for clients created inside an actor. Set only by the native runtime. */
@@ -211,6 +214,7 @@ export class ClientRaw {
211
214
  #gatewayOptions: ActorGatewayOptions;
212
215
  #currentActorInvocation?: CurrentActorInvocation;
213
216
  #startCallSpan?: StartCallSpan;
217
+ #retryBudget: RetryBudget;
214
218
 
215
219
  /**
216
220
  * Creates an instance of Client.
@@ -228,6 +232,7 @@ export class ClientRaw {
228
232
  this.#gatewayOptions = options.gateway ?? {};
229
233
  this.#currentActorInvocation = options.currentActorInvocation;
230
234
  this.#startCallSpan = options.startCallSpan;
235
+ this.#retryBudget = new RetryBudget(options.retryBudget);
231
236
  }
232
237
 
233
238
  /**
@@ -431,6 +436,7 @@ export class ClientRaw {
431
436
  signal,
432
437
  this.#currentActorInvocation,
433
438
  this.#startCallSpan,
439
+ this.#retryBudget,
434
440
  );
435
441
  }
436
442
 
@@ -477,11 +483,15 @@ export class ClientRaw {
477
483
  *
478
484
  * @template A The actor registry type.
479
485
  */
480
- export type Client<A extends Registry<any>> = ClientRaw & Omit<{
481
- [K in keyof ExtractActorsFromRegistry<A>]: ActorAccessor<
482
- ExtractActorsFromRegistry<A>[K]
486
+ export type Client<A extends Registry<any>> = ClientRaw &
487
+ Omit<
488
+ {
489
+ [K in keyof ExtractActorsFromRegistry<A>]: ActorAccessor<
490
+ ExtractActorsFromRegistry<A>[K]
491
+ >;
492
+ },
493
+ keyof ClientRaw
483
494
  >;
484
- }, keyof ClientRaw>;
485
495
 
486
496
  export type AnyClient = Client<Registry<any>>;
487
497
 
@@ -88,6 +88,17 @@ export const ClientConfigSchemaBase = z.object({
88
88
  // `proxyWebSocket`
89
89
  getUpgradeWebSocket: z.custom<GetUpgradeWebSocket>().optional(),
90
90
 
91
+ /**
92
+ * Bounds retries of refused requests: `percent` retries per 100 requests (default 10), with
93
+ * up to `maxTokens` banked for bursts (default 100). A refusal past the budget is thrown.
94
+ */
95
+ retryBudget: z
96
+ .object({
97
+ percent: z.number().min(0).max(100).optional(),
98
+ maxTokens: z.number().int().min(0).optional(),
99
+ })
100
+ .optional(),
101
+
91
102
  /** Replaces global fetch for actor HTTP gateway requests. */
92
103
  fetch: z.custom<typeof globalThis.fetch>().optional(),
93
104
 
@@ -166,7 +177,7 @@ export function convertRegistryConfigToClientConfig(
166
177
  token: config.token,
167
178
  getToken: undefined,
168
179
  namespace: config.namespace,
169
- poolName: config.envoy.poolName,
180
+ poolName: config.node.poolName,
170
181
  headers: config.headers,
171
182
  gateway: { skipReadyWait: false },
172
183
  encoding: "bare",
@@ -1,4 +1,5 @@
1
1
  import { ActorError, HttpRequestError } from "./errors";
2
+ import { type RetryBudget, retryAfterMs, retryDelayMs } from "./retry-budget";
2
3
 
3
4
  export interface LifecycleBoundaryInfo {
4
5
  kind: "request_retry" | "reconnect_only";
@@ -271,6 +272,11 @@ async function waitWithSignal(ms: number, signal?: AbortSignal) {
271
272
  });
272
273
  }
273
274
 
275
+ /**
276
+ * Runs `run`, retrying retryable lifecycle and refusal errors with jittered exponential backoff
277
+ * that honors the service's `retry_after_ms` hint. With a `budget`, the call credits it once and
278
+ * every retry spends a token; a spent budget returns the error instead of retrying.
279
+ */
274
280
  export async function retryOnLifecycleBoundary<T>(
275
281
  run: () => Promise<T>,
276
282
  opts?: {
@@ -278,11 +284,13 @@ export async function retryOnLifecycleBoundary<T>(
278
284
  initialDelayMs?: number;
279
285
  maxDelayMs?: number;
280
286
  signal?: AbortSignal;
287
+ budget?: RetryBudget;
281
288
  },
282
289
  ): Promise<T> {
283
290
  const maxAttempts = opts?.maxAttempts ?? 5;
284
291
  const initialDelayMs = opts?.initialDelayMs ?? 25;
285
292
  const maxDelayMs = opts?.maxDelayMs ?? 200;
293
+ opts?.budget?.deposit();
286
294
 
287
295
  let lastError: unknown;
288
296
  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
@@ -299,8 +307,15 @@ export async function retryOnLifecycleBoundary<T>(
299
307
  if (attempt === maxAttempts - 1) {
300
308
  break;
301
309
  }
310
+ if (opts?.budget && !opts.budget.tryWithdraw()) {
311
+ break;
312
+ }
302
313
 
303
- const delayMs = Math.min(initialDelayMs * 2 ** attempt, maxDelayMs);
314
+ const delayMs = retryDelayMs(attempt, {
315
+ initialDelayMs,
316
+ maxDelayMs,
317
+ hintMs: retryAfterMs(error),
318
+ });
304
319
  await waitWithSignal(delayMs, opts?.signal);
305
320
  }
306
321
  }
@@ -0,0 +1,78 @@
1
+ import { ActorError } from "./errors";
2
+
3
+ /** How many retries a client may spend, as a share of the requests it sends. */
4
+ export interface RetryBudgetOptions {
5
+ /** Retries allowed per 100 requests (default 10). */
6
+ percent?: number;
7
+ /** Retries the client can bank for a burst of refusals; the budget starts full (default 100). */
8
+ maxTokens?: number;
9
+ }
10
+
11
+ const DEFAULT_PERCENT = 10;
12
+ const DEFAULT_MAX_TOKENS = 100;
13
+
14
+ /**
15
+ * Bounds the client's retries of refused requests. Each request adds a fraction of a token and
16
+ * each retry spends one, so retries stay a fixed share of traffic while the service sheds load
17
+ * instead of multiplying it.
18
+ */
19
+ export class RetryBudget {
20
+ #tokens: number;
21
+ readonly #maxTokens: number;
22
+ readonly #deposit: number;
23
+
24
+ constructor(options: RetryBudgetOptions = {}) {
25
+ const percent = options.percent ?? DEFAULT_PERCENT;
26
+ const maxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;
27
+ if (!(percent >= 0 && percent <= 100)) {
28
+ throw new Error("retryBudget.percent must be in 0..=100");
29
+ }
30
+ if (!(maxTokens >= 0)) {
31
+ throw new Error("retryBudget.maxTokens must be at least 0");
32
+ }
33
+ this.#maxTokens = maxTokens;
34
+ this.#tokens = maxTokens;
35
+ this.#deposit = percent / 100;
36
+ }
37
+
38
+ /** Credits one request sent. */
39
+ deposit(): void {
40
+ this.#tokens = Math.min(this.#maxTokens, this.#tokens + this.#deposit);
41
+ }
42
+
43
+ /** Spends one token. Returns `false` when the budget is spent. */
44
+ tryWithdraw(): boolean {
45
+ // Rounding guards against float drift: ten 0.1 deposits must make one token.
46
+ if (this.#tokens + 1e-9 < 1) {
47
+ return false;
48
+ }
49
+ this.#tokens = Math.max(0, this.#tokens - 1);
50
+ return true;
51
+ }
52
+ }
53
+
54
+ /** The service's retry hint for a refused request, in milliseconds, when it sent one. */
55
+ export function retryAfterMs(error: unknown): number | undefined {
56
+ if (!(error instanceof ActorError)) {
57
+ return undefined;
58
+ }
59
+ const metadata = error.metadata;
60
+ if (metadata === null || typeof metadata !== "object") {
61
+ return undefined;
62
+ }
63
+ const hint = (metadata as { retry_after_ms?: unknown }).retry_after_ms;
64
+ return typeof hint === "number" && hint >= 0 ? hint : undefined;
65
+ }
66
+
67
+ /**
68
+ * The wait before retry `attempt` (0-based): jittered exponential backoff over
69
+ * `[initialDelayMs, maxDelayMs]`, never shorter than the service's hint.
70
+ */
71
+ export function retryDelayMs(
72
+ attempt: number,
73
+ opts: { initialDelayMs: number; maxDelayMs: number; hintMs?: number },
74
+ ): number {
75
+ const backoff = Math.min(opts.initialDelayMs * 2 ** attempt, opts.maxDelayMs);
76
+ const jittered = backoff / 2 + Math.random() * (backoff / 2);
77
+ return Math.max(jittered, opts.hintMs ?? 0);
78
+ }
@@ -19,21 +19,27 @@ export interface ParsedCloseReason {
19
19
  group: string;
20
20
  code: string;
21
21
  rayId?: string;
22
+ /** The service's retry hint, from a `#retry_after_ms=<ms>` suffix. */
23
+ retryAfterMs?: number;
22
24
  }
23
25
 
26
+ const RETRY_AFTER_SUFFIX = /^retry_after_ms=(\d+)$/;
27
+
24
28
  /**
25
29
  * Parses WebSocket close reason string into structured data.
26
30
  *
27
31
  * Expected format examples:
28
32
  * - "guard.actor_runner_failed#t1s80so6h3irenp8ymzltfoittcl00"
29
33
  * - "ws.client_closed"
34
+ * - "guard.service_unavailable#retry_after_ms=1000", a refusal with its retry hint. The hint
35
+ * rides after `#` so older clients still read the retryable `<group>.<code>`.
30
36
  *
31
37
  * Returns undefined if the format is invalid
32
38
  */
33
39
  export function parseWebSocketCloseReason(
34
40
  reason: string,
35
41
  ): ParsedCloseReason | undefined {
36
- const [mainPart, rayId] = reason.split("#");
42
+ const [mainPart, suffix] = reason.split("#");
37
43
  const [group, code] = mainPart.split(".");
38
44
 
39
45
  if (!group || !code) {
@@ -41,10 +47,15 @@ export function parseWebSocketCloseReason(
41
47
  return undefined;
42
48
  }
43
49
 
50
+ const retryAfter = suffix?.match(RETRY_AFTER_SUFFIX);
51
+ if (retryAfter) {
52
+ return { group, code, retryAfterMs: Number(retryAfter[1]) };
53
+ }
54
+
44
55
  return {
45
56
  group,
46
57
  code,
47
- rayId,
58
+ rayId: suffix,
48
59
  };
49
60
  }
50
61
 
@@ -52,7 +52,13 @@ export interface SqliteTransactionOptions {
52
52
  * to change without notice.
53
53
  */
54
54
  export interface SqliteProfilingOptions {
55
- enabled?: boolean;
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[];
56
62
  maxTrackedStatementFingerprints?: number;
57
63
  maxTrackedTransactionFingerprints?: number;
58
64
  maxPrometheusSeries?: number;
@@ -125,6 +125,11 @@ export type StateAwareSqliteDatabase = SqliteDatabase & {
125
125
  ): Promise<SqliteTransactionDatabase>;
126
126
  };
127
127
 
128
+ type NativeSqliteDatabase = StateAwareSqliteDatabase & {
129
+ /** Stop JS calls while leaving the runtime-owned backend open. */
130
+ detachForShutdown(): Promise<void>;
131
+ };
132
+
128
133
  export interface JsNativeTransactionLike {
129
134
  exec(sql: string): Promise<NativeExecResult>;
130
135
  execute(
@@ -360,7 +365,7 @@ class NativeCloseGate {
360
365
  };
361
366
  }
362
367
 
363
- async close(callback: () => Promise<void>): Promise<void> {
368
+ async close(callback?: () => Promise<void>): Promise<void> {
364
369
  if (this.#closed) {
365
370
  return;
366
371
  }
@@ -368,16 +373,17 @@ class NativeCloseGate {
368
373
  if (this.#active > 0) {
369
374
  await new Promise<void>((resolve) => this.#waiters.push(resolve));
370
375
  }
371
- await callback();
376
+ await callback?.();
372
377
  }
373
378
  }
374
379
 
375
380
  export function wrapJsNativeDatabase(
376
381
  database: JsNativeDatabaseLike,
377
- { ownsDatabase = true }: { ownsDatabase?: boolean } = {},
378
- ): StateAwareSqliteDatabase {
382
+ ): NativeSqliteDatabase {
379
383
  const gate = new NativeCloseGate();
380
- let closePromise: Promise<void> | undefined;
384
+ // Detach and explicit close are mutually exclusive terminal operations.
385
+ // Whichever starts first defines whether the backend is physically closed.
386
+ let terminalPromise: Promise<void> | undefined;
381
387
  let lastInsertRowId: number | null = null;
382
388
 
383
389
  const executeNative = async (
@@ -623,10 +629,12 @@ export function wrapJsNativeDatabase(
623
629
  database.abortGeneration(reason);
624
630
  },
625
631
  async close(): Promise<void> {
626
- closePromise ??= gate.close(async () => {
627
- if (ownsDatabase) await database.close();
628
- });
629
- await closePromise;
632
+ terminalPromise ??= gate.close(() => database.close());
633
+ await terminalPromise;
634
+ },
635
+ async detachForShutdown(): Promise<void> {
636
+ terminalPromise ??= gate.close();
637
+ await terminalPromise;
630
638
  },
631
639
  };
632
640
  }
@@ -182,7 +182,7 @@ export function handleMetadataRequest(
182
182
  version: VERSION,
183
183
  envoy: {
184
184
  kind: envoyKind,
185
- version: config.envoy.version,
185
+ version: config.node.version,
186
186
  },
187
187
  envoyProtocolVersion: envoyProtocol.VERSION,
188
188
  actorNames: buildActorNames(config),
@@ -6,7 +6,7 @@ export const ActorSchema = z.object({
6
6
  name: z.string(),
7
7
  key: z.string(),
8
8
  namespace_id: RivetIdSchema,
9
- runner_name_selector: z.string(),
9
+ pool: z.string(),
10
10
  create_ts: z.number(),
11
11
  connectable_ts: z.number().nullable().optional(),
12
12
  destroy_ts: z.number().nullable().optional(),
@@ -31,7 +31,7 @@ export type ActorsListResponse = z.infer<typeof ActorsListResponseSchema>;
31
31
  export const ActorsCreateRequestSchema = z.object({
32
32
  datacenter: z.string().optional(),
33
33
  name: z.string(),
34
- runner_name_selector: z.string(),
34
+ pool: z.string(),
35
35
  crash_policy: z.string(),
36
36
  key: z.string().nullable().optional(),
37
37
  input: z.string().nullable().optional(),
@@ -48,7 +48,7 @@ export const ActorsGetOrCreateRequestSchema = z.object({
48
48
  datacenter: z.string().optional(),
49
49
  name: z.string(),
50
50
  key: z.string(),
51
- runner_name_selector: z.string(),
51
+ pool: z.string(),
52
52
  crash_policy: z.string(),
53
53
  input: z.string().nullable().optional(),
54
54
  });
@@ -1,3 +1,4 @@
1
+ import { actorKeyToGatewayQuery } from "@/actor/keys";
1
2
  import {
2
3
  type ClientConfig,
3
4
  DEFAULT_MAX_QUERY_INPUT_SIZE,
@@ -289,8 +290,9 @@ export function buildActorQueryGatewayUrl(
289
290
  }
290
291
 
291
292
  function pushKeyQueryParams(params: URLSearchParams, key: string[]): void {
292
- if (key.length > 0) {
293
- params.append("rvt-key", key.join(","));
293
+ const rvtKey = actorKeyToGatewayQuery(key);
294
+ if (rvtKey !== undefined) {
295
+ params.append("rvt-key", rvtKey);
294
296
  }
295
297
  }
296
298