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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/dist/browser/client.d.ts +60 -10
  2. package/dist/browser/client.js +294 -40
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.js +4 -2
  5. package/dist/browser/inspector/client.js.map +1 -1
  6. package/dist/tsup/{chunk-HO76AEDH.cjs → chunk-22S5RCCJ.cjs} +3 -3
  7. package/dist/tsup/{chunk-HO76AEDH.cjs.map → chunk-22S5RCCJ.cjs.map} +1 -1
  8. package/dist/tsup/{chunk-EPRA2TCT.js → chunk-2CTZU7GL.js} +2 -2
  9. package/dist/tsup/{chunk-JI6GZ2C2.js → chunk-A2CF6PFH.js} +18 -1
  10. package/dist/tsup/chunk-A2CF6PFH.js.map +1 -0
  11. package/dist/tsup/{chunk-QR6EAWEC.cjs → chunk-CWN7N5AF.cjs} +7 -7
  12. package/dist/tsup/{chunk-QR6EAWEC.cjs.map → chunk-CWN7N5AF.cjs.map} +1 -1
  13. package/dist/tsup/{chunk-3URZ4UV5.js → chunk-D7DWNYEO.js} +2 -2
  14. package/dist/tsup/{chunk-F7IGTKGM.js → chunk-F5PWAGS7.js} +2 -2
  15. package/dist/tsup/{chunk-E2CUROR3.js → chunk-FT6VRK4C.js} +2 -2
  16. package/dist/tsup/{chunk-FYDB45YU.cjs → chunk-HFGXV2CC.cjs} +10 -10
  17. package/dist/tsup/{chunk-FYDB45YU.cjs.map → chunk-HFGXV2CC.cjs.map} +1 -1
  18. package/dist/tsup/{chunk-D4G35VTO.js → chunk-HRKFVQPS.js} +4 -4
  19. package/dist/tsup/{chunk-DHL2M2E2.cjs → chunk-HXJ5U2ZI.cjs} +3 -3
  20. package/dist/tsup/{chunk-DHL2M2E2.cjs.map → chunk-HXJ5U2ZI.cjs.map} +1 -1
  21. package/dist/tsup/{chunk-L3Z3W44Q.cjs → chunk-JJUSO7GJ.cjs} +3 -3
  22. package/dist/tsup/{chunk-L3Z3W44Q.cjs.map → chunk-JJUSO7GJ.cjs.map} +1 -1
  23. package/dist/tsup/{chunk-DDS7OOVF.cjs → chunk-NG5CUXMM.cjs} +420 -182
  24. package/dist/tsup/chunk-NG5CUXMM.cjs.map +1 -0
  25. package/dist/tsup/{chunk-USKGKQZM.js → chunk-NNCL4IBC.js} +12 -7
  26. package/dist/tsup/chunk-NNCL4IBC.js.map +1 -0
  27. package/dist/tsup/{chunk-PJ5EXY6F.js → chunk-QQIFRR3B.js} +283 -45
  28. package/dist/tsup/chunk-QQIFRR3B.js.map +1 -0
  29. package/dist/tsup/{chunk-MYWZCDML.cjs → chunk-RTWH3AX3.cjs} +19 -2
  30. package/dist/tsup/chunk-RTWH3AX3.cjs.map +1 -0
  31. package/dist/tsup/{chunk-HDVZ6YZG.cjs → chunk-SSF2XC33.cjs} +1 -1
  32. package/dist/tsup/chunk-SSF2XC33.cjs.map +1 -0
  33. package/dist/tsup/{chunk-KSP3NXGY.js → chunk-SW33HMM5.js} +3 -3
  34. package/dist/tsup/{chunk-6FEYCVZC.js → chunk-UXDASKP6.js} +1 -1
  35. package/dist/tsup/chunk-UXDASKP6.js.map +1 -0
  36. package/dist/tsup/{chunk-KDT56V3Y.cjs → chunk-Y4QLVCCS.cjs} +12 -7
  37. package/dist/tsup/chunk-Y4QLVCCS.cjs.map +1 -0
  38. package/dist/tsup/{chunk-JW2WPE6Z.cjs → chunk-Y5CFDGPA.cjs} +4 -4
  39. package/dist/tsup/{chunk-JW2WPE6Z.cjs.map → chunk-Y5CFDGPA.cjs.map} +1 -1
  40. package/dist/tsup/client/mod.cjs +6 -6
  41. package/dist/tsup/client/mod.d.cts +15 -3
  42. package/dist/tsup/client/mod.d.ts +15 -3
  43. package/dist/tsup/client/mod.js +5 -5
  44. package/dist/tsup/common/log.cjs +2 -2
  45. package/dist/tsup/common/log.js +1 -1
  46. package/dist/tsup/common/websocket.cjs +3 -3
  47. package/dist/tsup/common/websocket.js +2 -2
  48. package/dist/tsup/{config-Cw_BwH_G.d.ts → config-BiiS5T5M.d.ts} +45 -12
  49. package/dist/tsup/{config-CkmVg2fG.d.cts → config-BnMhcPHl.d.cts} +45 -12
  50. package/dist/tsup/{config-D4clT6mq.d.ts → config-CBTr4IhE.d.cts} +0 -2
  51. package/dist/tsup/{config-D4clT6mq.d.cts → config-CBTr4IhE.d.ts} +0 -2
  52. package/dist/tsup/{context-_xIcgBnE.d.cts → context-DVE8XMm1.d.cts} +2 -2
  53. package/dist/tsup/{context-BYOKTQJi.d.ts → context-iMxXq_Lt.d.ts} +2 -2
  54. package/dist/tsup/db/drizzle.cjs +2 -2
  55. package/dist/tsup/db/drizzle.d.cts +1 -1
  56. package/dist/tsup/db/drizzle.d.ts +1 -1
  57. package/dist/tsup/db/drizzle.js +1 -1
  58. package/dist/tsup/db/mod.cjs +3 -3
  59. package/dist/tsup/db/mod.d.cts +2 -2
  60. package/dist/tsup/db/mod.d.ts +2 -2
  61. package/dist/tsup/db/mod.js +2 -2
  62. package/dist/tsup/dynamic/mod.cjs +2 -2
  63. package/dist/tsup/dynamic/mod.d.cts +2 -2
  64. package/dist/tsup/dynamic/mod.d.ts +2 -2
  65. package/dist/tsup/dynamic/mod.js +1 -1
  66. package/dist/tsup/inspector/mod.cjs +5 -5
  67. package/dist/tsup/inspector/mod.js +4 -4
  68. package/dist/tsup/inspector/workflow.cjs +4 -4
  69. package/dist/tsup/inspector/workflow.js +3 -3
  70. package/dist/tsup/inspector-tab/mod.cjs +2 -2
  71. package/dist/tsup/inspector-tab/mod.d.cts +3 -3
  72. package/dist/tsup/inspector-tab/mod.d.ts +3 -3
  73. package/dist/tsup/inspector-tab/mod.js +1 -1
  74. package/dist/tsup/mod.cjs +298 -198
  75. package/dist/tsup/mod.cjs.map +1 -1
  76. package/dist/tsup/mod.d.cts +4 -4
  77. package/dist/tsup/mod.d.ts +4 -4
  78. package/dist/tsup/mod.js +192 -92
  79. package/dist/tsup/mod.js.map +1 -1
  80. package/dist/tsup/test/mod.cjs +7 -7
  81. package/dist/tsup/test/mod.d.cts +2 -2
  82. package/dist/tsup/test/mod.d.ts +2 -2
  83. package/dist/tsup/test/mod.js +5 -5
  84. package/dist/tsup/unstable/migrations.d.cts +1 -1
  85. package/dist/tsup/unstable/migrations.d.ts +1 -1
  86. package/dist/tsup/utils.cjs +2 -2
  87. package/dist/tsup/utils.js +1 -1
  88. package/dist/tsup/workflow/mod.cjs +25 -22
  89. package/dist/tsup/workflow/mod.cjs.map +1 -1
  90. package/dist/tsup/workflow/mod.d.cts +4 -4
  91. package/dist/tsup/workflow/mod.d.ts +4 -4
  92. package/dist/tsup/workflow/mod.js +11 -8
  93. package/dist/tsup/workflow/mod.js.map +1 -1
  94. package/package.json +12 -10
  95. package/src/actor/config.ts +2 -0
  96. package/src/actor/keys.ts +86 -0
  97. package/src/client/actor-conn.ts +136 -24
  98. package/src/client/actor-handle.ts +64 -10
  99. package/src/client/client.ts +6 -0
  100. package/src/client/config.ts +12 -1
  101. package/src/client/lifecycle-errors.ts +35 -2
  102. package/src/client/raw-utils.ts +17 -3
  103. package/src/client/retry-budget.ts +78 -0
  104. package/src/client/utils.ts +17 -2
  105. package/src/common/database/config.ts +0 -2
  106. package/src/common/database/native-database.ts +17 -6
  107. package/src/common/router.ts +1 -1
  108. package/src/engine-api/actors.ts +3 -3
  109. package/src/engine-client/actor-websocket-client.ts +4 -2
  110. package/src/engine-client/api-endpoints.ts +44 -14
  111. package/src/engine-client/mod.ts +2 -2
  112. package/src/registry/config/envoy.ts +1 -1
  113. package/src/registry/config/index.ts +30 -30
  114. package/src/registry/index.ts +66 -21
  115. package/src/registry/napi-runtime.ts +4 -3
  116. package/src/registry/native.ts +147 -48
  117. package/src/registry/runtime.ts +27 -10
  118. package/src/registry/wasm-runtime.ts +6 -3
  119. package/src/utils/env-vars.ts +13 -6
  120. package/src/workflow/driver.ts +5 -3
  121. package/dist/tsup/chunk-6FEYCVZC.js.map +0 -1
  122. package/dist/tsup/chunk-DDS7OOVF.cjs.map +0 -1
  123. package/dist/tsup/chunk-HDVZ6YZG.cjs.map +0 -1
  124. package/dist/tsup/chunk-JI6GZ2C2.js.map +0 -1
  125. package/dist/tsup/chunk-KDT56V3Y.cjs.map +0 -1
  126. package/dist/tsup/chunk-MYWZCDML.cjs.map +0 -1
  127. package/dist/tsup/chunk-PJ5EXY6F.js.map +0 -1
  128. package/dist/tsup/chunk-USKGKQZM.js.map +0 -1
  129. package/src/actor/config.test.ts +0 -78
  130. package/src/actor/keys.test.ts +0 -275
  131. package/src/actor/utils.test.ts +0 -48
  132. package/src/client/test.ts +0 -44
  133. package/src/client/token-provider.test.ts +0 -86
  134. package/src/common/database/mod.test.ts +0 -364
  135. package/src/common/database/native-database.test.ts +0 -220
  136. package/src/common/inline-websocket-adapter.test.ts +0 -51
  137. package/src/db/drizzle.test.ts +0 -164
  138. package/src/registry/config/index.test.ts +0 -25
  139. package/src/registry/run-handler-coordinator.test.ts +0 -252
  140. package/src/registry/runtime.test.ts +0 -124
  141. package/src/unstable/migrations.test.ts +0 -170
  142. package/src/utils/endpoint-parser.test.ts +0 -206
  143. package/src/utils.test.ts +0 -34
  144. package/src/workflow/driver.test.ts +0 -62
  145. /package/dist/tsup/{chunk-EPRA2TCT.js.map → chunk-2CTZU7GL.js.map} +0 -0
  146. /package/dist/tsup/{chunk-3URZ4UV5.js.map → chunk-D7DWNYEO.js.map} +0 -0
  147. /package/dist/tsup/{chunk-F7IGTKGM.js.map → chunk-F5PWAGS7.js.map} +0 -0
  148. /package/dist/tsup/{chunk-E2CUROR3.js.map → chunk-FT6VRK4C.js.map} +0 -0
  149. /package/dist/tsup/{chunk-D4G35VTO.js.map → chunk-HRKFVQPS.js.map} +0 -0
  150. /package/dist/tsup/{chunk-KSP3NXGY.js.map → chunk-SW33HMM5.js.map} +0 -0
@@ -1,11 +1,12 @@
1
1
  import {
2
+ actorKeyToGatewayQuery,
2
3
  deserializeActorKey,
3
4
  serializeActorKey
4
- } from "./chunk-JI6GZ2C2.js";
5
+ } from "./chunk-A2CF6PFH.js";
5
6
  import {
6
7
  importWebSocket,
7
8
  logger
8
- } from "./chunk-F7IGTKGM.js";
9
+ } from "./chunk-F5PWAGS7.js";
9
10
  import {
10
11
  AsyncMutex
11
12
  } from "./chunk-JTHHCZCZ.js";
@@ -35,7 +36,7 @@ import {
35
36
  serializeWithEncoding,
36
37
  stringifyError,
37
38
  uint8ArrayToBase64
38
- } from "./chunk-USKGKQZM.js";
39
+ } from "./chunk-NNCL4IBC.js";
39
40
  import {
40
41
  INTERNAL_ERROR_CODE,
41
42
  RivetError,
@@ -2176,6 +2177,56 @@ function readRequestBody(request) {
2176
2177
  ).arrayBuffer();
2177
2178
  }
2178
2179
 
2180
+ // src/client/retry-budget.ts
2181
+ var DEFAULT_PERCENT = 10;
2182
+ var DEFAULT_MAX_TOKENS = 100;
2183
+ var RetryBudget = class {
2184
+ #tokens;
2185
+ #maxTokens;
2186
+ #deposit;
2187
+ constructor(options = {}) {
2188
+ const percent = options.percent ?? DEFAULT_PERCENT;
2189
+ const maxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;
2190
+ if (!(percent >= 0 && percent <= 100)) {
2191
+ throw new Error("retryBudget.percent must be in 0..=100");
2192
+ }
2193
+ if (!(maxTokens >= 0)) {
2194
+ throw new Error("retryBudget.maxTokens must be at least 0");
2195
+ }
2196
+ this.#maxTokens = maxTokens;
2197
+ this.#tokens = maxTokens;
2198
+ this.#deposit = percent / 100;
2199
+ }
2200
+ /** Credits one request sent. */
2201
+ deposit() {
2202
+ this.#tokens = Math.min(this.#maxTokens, this.#tokens + this.#deposit);
2203
+ }
2204
+ /** Spends one token. Returns `false` when the budget is spent. */
2205
+ tryWithdraw() {
2206
+ if (this.#tokens + 1e-9 < 1) {
2207
+ return false;
2208
+ }
2209
+ this.#tokens = Math.max(0, this.#tokens - 1);
2210
+ return true;
2211
+ }
2212
+ };
2213
+ function retryAfterMs(error) {
2214
+ if (!(error instanceof RivetError)) {
2215
+ return void 0;
2216
+ }
2217
+ const metadata = error.metadata;
2218
+ if (metadata === null || typeof metadata !== "object") {
2219
+ return void 0;
2220
+ }
2221
+ const hint = metadata.retry_after_ms;
2222
+ return typeof hint === "number" && hint >= 0 ? hint : void 0;
2223
+ }
2224
+ function retryDelayMs(attempt, opts) {
2225
+ const backoff = Math.min(opts.initialDelayMs * 2 ** attempt, opts.maxDelayMs);
2226
+ const jittered = backoff / 2 + Math.random() * (backoff / 2);
2227
+ return Math.max(jittered, opts.hintMs ?? 0);
2228
+ }
2229
+
2179
2230
  // src/client/lifecycle-errors.ts
2180
2231
  function* walkErrorChain(error, maxDepth = 8) {
2181
2232
  let current = error;
@@ -2204,7 +2255,7 @@ function classifyActorError(error) {
2204
2255
  if (error.group === "actor" && error.code === "stopping" && error.message.includes("database accessed after actor stopped")) {
2205
2256
  return void 0;
2206
2257
  }
2207
- if (error.group === "actor" && error.code === "restarting") {
2258
+ if (error.group === "actor" && (error.code === "restarting" || error.code === "migrating_from_v2")) {
2208
2259
  return buildLifecycleBoundaryInfo(
2209
2260
  "request_retry",
2210
2261
  "actor_error",
@@ -2215,6 +2266,14 @@ function classifyActorError(error) {
2215
2266
  }
2216
2267
  );
2217
2268
  }
2269
+ if (error.group === "ups" && error.code === "consumer_closed" || error.group === "depot" && error.code === "request_deadline_exceeded") {
2270
+ return buildLifecycleBoundaryInfo(
2271
+ "reconnect_only",
2272
+ "actor_error",
2273
+ error.message,
2274
+ { group: error.group, code: error.code }
2275
+ );
2276
+ }
2218
2277
  if (error.group === "guard" && isRetryableGuardGatewayHttpError(error.code)) {
2219
2278
  return buildLifecycleBoundaryInfo(
2220
2279
  "request_retry",
@@ -2351,9 +2410,11 @@ async function waitWithSignal(ms, signal) {
2351
2410
  });
2352
2411
  }
2353
2412
  async function retryOnLifecycleBoundary(run, opts) {
2413
+ var _a;
2354
2414
  const maxAttempts = (opts == null ? void 0 : opts.maxAttempts) ?? 5;
2355
2415
  const initialDelayMs = (opts == null ? void 0 : opts.initialDelayMs) ?? 25;
2356
2416
  const maxDelayMs = (opts == null ? void 0 : opts.maxDelayMs) ?? 200;
2417
+ (_a = opts == null ? void 0 : opts.budget) == null ? void 0 : _a.deposit();
2357
2418
  let lastError;
2358
2419
  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
2359
2420
  throwIfAborted(opts == null ? void 0 : opts.signal);
@@ -2367,7 +2428,14 @@ async function retryOnLifecycleBoundary(run, opts) {
2367
2428
  if (attempt === maxAttempts - 1) {
2368
2429
  break;
2369
2430
  }
2370
- const delayMs = Math.min(initialDelayMs * 2 ** attempt, maxDelayMs);
2431
+ if ((opts == null ? void 0 : opts.budget) && !opts.budget.tryWithdraw()) {
2432
+ break;
2433
+ }
2434
+ const delayMs = retryDelayMs(attempt, {
2435
+ initialDelayMs,
2436
+ maxDelayMs,
2437
+ hintMs: retryAfterMs(error)
2438
+ });
2371
2439
  await waitWithSignal(delayMs, opts == null ? void 0 : opts.signal);
2372
2440
  }
2373
2441
  }
@@ -2460,17 +2528,22 @@ function addOutboundTelemetryHeaders(headers, telemetry) {
2460
2528
 
2461
2529
  // src/client/utils.ts
2462
2530
  import invariant from "invariant";
2531
+ var RETRY_AFTER_SUFFIX = /^retry_after_ms=(\d+)$/;
2463
2532
  function parseWebSocketCloseReason(reason) {
2464
- const [mainPart, rayId] = reason.split("#");
2533
+ const [mainPart, suffix] = reason.split("#");
2465
2534
  const [group, code] = mainPart.split(".");
2466
2535
  if (!group || !code) {
2467
2536
  logger().warn({ msg: "failed to parse close reason", reason });
2468
2537
  return void 0;
2469
2538
  }
2539
+ const retryAfter = suffix == null ? void 0 : suffix.match(RETRY_AFTER_SUFFIX);
2540
+ if (retryAfter) {
2541
+ return { group, code, retryAfterMs: Number(retryAfter[1]) };
2542
+ }
2470
2543
  return {
2471
2544
  group,
2472
2545
  code,
2473
- rayId
2546
+ rayId: suffix
2474
2547
  };
2475
2548
  }
2476
2549
  function messageLength(message) {
@@ -2528,6 +2601,9 @@ async function sendHttpRequest(opts) {
2528
2601
  })
2529
2602
  );
2530
2603
  } catch (error) {
2604
+ if (RivetError.isRivetError(error)) {
2605
+ throw error;
2606
+ }
2531
2607
  throw new HttpRequestError(`Request failed: ${error}`, {
2532
2608
  cause: error
2533
2609
  });
@@ -2773,8 +2849,23 @@ async function rawHttpFetch(driver, target, params, input, init, options = {}, t
2773
2849
  });
2774
2850
  return driver.sendRequest(target, proxyRequest, options);
2775
2851
  } catch (err) {
2776
- const { group, code, message, metadata, rayId, actor } = deconstructError(err, true);
2777
- throw new RivetError(group, code, message, { metadata, rayId, actor });
2852
+ const {
2853
+ group,
2854
+ code,
2855
+ message,
2856
+ metadata,
2857
+ rayId,
2858
+ actor,
2859
+ public: isPublic,
2860
+ statusCode
2861
+ } = deconstructError(err, true);
2862
+ throw new RivetError(group, code, message, {
2863
+ public: isPublic,
2864
+ statusCode,
2865
+ metadata,
2866
+ rayId,
2867
+ actor
2868
+ });
2778
2869
  }
2779
2870
  }
2780
2871
  async function rawWebSocket(driver, target, params, path, _protocols, options = {}) {
@@ -2868,6 +2959,7 @@ var ActorHandleRaw = class {
2868
2959
  #queueSendMutex = new AsyncMutex();
2869
2960
  #currentActorInvocation;
2870
2961
  #startCallSpan;
2962
+ #retryBudget;
2871
2963
  /**
2872
2964
  * Do not call this directly.
2873
2965
  *
@@ -2875,7 +2967,7 @@ var ActorHandleRaw = class {
2875
2967
  *
2876
2968
  * @protected
2877
2969
  */
2878
- constructor(client, driver, params, getParams, encoding, actorResolutionState, gatewayOptions = {}, signal, currentActorInvocation, startCallSpan) {
2970
+ constructor(client, driver, params, getParams, encoding, actorResolutionState, gatewayOptions = {}, signal, currentActorInvocation, startCallSpan, retryBudget = new RetryBudget()) {
2879
2971
  this.#client = client;
2880
2972
  this.#driver = driver;
2881
2973
  this.#encoding = encoding;
@@ -2886,6 +2978,7 @@ var ActorHandleRaw = class {
2886
2978
  this.#signal = signal;
2887
2979
  this.#currentActorInvocation = currentActorInvocation;
2888
2980
  this.#startCallSpan = startCallSpan;
2981
+ this.#retryBudget = retryBudget;
2889
2982
  }
2890
2983
  async #resolveConnectionParams() {
2891
2984
  if (this.#getParams) {
@@ -2902,6 +2995,7 @@ var ActorHandleRaw = class {
2902
2995
  let useQueryTarget = isDynamicActorQuery(
2903
2996
  this.#actorResolutionState
2904
2997
  );
2998
+ this.#retryBudget.deposit();
2905
2999
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
2906
3000
  let actorId;
2907
3001
  try {
@@ -2931,15 +3025,33 @@ var ActorHandleRaw = class {
2931
3025
  }
2932
3026
  }).send(name, body, options);
2933
3027
  } catch (err) {
2934
- const { group, code, message, metadata, rayId, actor } = deconstructError(err, true);
3028
+ const {
3029
+ group,
3030
+ code,
3031
+ message,
3032
+ metadata,
3033
+ rayId,
3034
+ actor,
3035
+ public: isPublic,
3036
+ statusCode
3037
+ } = deconstructError(err, true);
2935
3038
  if (this.#shouldRetryQueueDispatchOverload(
2936
3039
  group,
2937
3040
  code,
2938
3041
  metadata,
2939
3042
  attempt,
2940
3043
  maxAttempts
2941
- )) {
2942
- await this.#waitForRetryWindow();
3044
+ ) && this.#retryBudget.tryWithdraw()) {
3045
+ await new Promise(
3046
+ (resolve) => setTimeout(
3047
+ resolve,
3048
+ retryDelayMs(attempt, {
3049
+ initialDelayMs: 25,
3050
+ maxDelayMs: 1e3,
3051
+ hintMs: retryAfterMs(err)
3052
+ })
3053
+ )
3054
+ );
2943
3055
  continue;
2944
3056
  }
2945
3057
  if (await this.#shouldRetrySchedulingError(
@@ -2978,6 +3090,8 @@ var ActorHandleRaw = class {
2978
3090
  continue;
2979
3091
  }
2980
3092
  throw new RivetError(group, code, message, {
3093
+ public: isPublic,
3094
+ statusCode,
2981
3095
  metadata,
2982
3096
  rayId,
2983
3097
  actor
@@ -3016,7 +3130,10 @@ var ActorHandleRaw = class {
3016
3130
  if (opts.name === "destroy") {
3017
3131
  return await run();
3018
3132
  }
3019
- return await retryOnLifecycleBoundary(run, { signal });
3133
+ return await retryOnLifecycleBoundary(run, {
3134
+ signal,
3135
+ budget: this.#retryBudget
3136
+ });
3020
3137
  };
3021
3138
  if (!call) {
3022
3139
  return await send();
@@ -3101,7 +3218,16 @@ var ActorHandleRaw = class {
3101
3218
  }
3102
3219
  return output;
3103
3220
  } catch (err) {
3104
- const { group, code, message, metadata, rayId, actor } = deconstructError(err, true);
3221
+ const {
3222
+ group,
3223
+ code,
3224
+ message,
3225
+ metadata,
3226
+ rayId,
3227
+ actor,
3228
+ public: isPublic,
3229
+ statusCode
3230
+ } = deconstructError(err, true);
3105
3231
  if (await this.#shouldRetrySchedulingError(
3106
3232
  group,
3107
3233
  code,
@@ -3130,7 +3256,13 @@ var ActorHandleRaw = class {
3130
3256
  "actor",
3131
3257
  "not_found",
3132
3258
  "The actor does not exist or was destroyed.",
3133
- { metadata, rayId, actor }
3259
+ {
3260
+ public: true,
3261
+ statusCode: 404,
3262
+ metadata,
3263
+ rayId,
3264
+ actor
3265
+ }
3134
3266
  );
3135
3267
  }
3136
3268
  const invalidated = this.#invalidateResolvedActorId(
@@ -3147,6 +3279,8 @@ var ActorHandleRaw = class {
3147
3279
  continue;
3148
3280
  }
3149
3281
  throw new RivetError(group, code, message, {
3282
+ public: isPublic,
3283
+ statusCode,
3150
3284
  metadata,
3151
3285
  rayId,
3152
3286
  actor
@@ -3334,7 +3468,16 @@ var ActorHandleRaw = class {
3334
3468
  }
3335
3469
  return response;
3336
3470
  } catch (err) {
3337
- const { group, code, message, metadata, rayId, actor } = deconstructError(err, true);
3471
+ const {
3472
+ group,
3473
+ code,
3474
+ message,
3475
+ metadata,
3476
+ rayId,
3477
+ actor,
3478
+ public: isPublic,
3479
+ statusCode
3480
+ } = deconstructError(err, true);
3338
3481
  if (await this.#shouldRetrySchedulingError(
3339
3482
  group,
3340
3483
  code,
@@ -3371,6 +3514,8 @@ var ActorHandleRaw = class {
3371
3514
  continue;
3372
3515
  }
3373
3516
  throw new RivetError(group, code, message, {
3517
+ public: isPublic,
3518
+ statusCode,
3374
3519
  metadata,
3375
3520
  rayId,
3376
3521
  actor
@@ -3558,6 +3703,7 @@ var ClientRaw = class {
3558
3703
  #gatewayOptions;
3559
3704
  #currentActorInvocation;
3560
3705
  #startCallSpan;
3706
+ #retryBudget;
3561
3707
  /**
3562
3708
  * Creates an instance of Client.
3563
3709
  */
@@ -3570,6 +3716,7 @@ var ClientRaw = class {
3570
3716
  this.#gatewayOptions = options.gateway ?? {};
3571
3717
  this.#currentActorInvocation = options.currentActorInvocation;
3572
3718
  this.#startCallSpan = options.startCallSpan;
3719
+ this.#retryBudget = new RetryBudget(options.retryBudget);
3573
3720
  }
3574
3721
  /**
3575
3722
  * Gets a stateless handle to a actor by its ID.
@@ -3727,7 +3874,8 @@ var ClientRaw = class {
3727
3874
  this.#gatewayOptions,
3728
3875
  signal,
3729
3876
  this.#currentActorInvocation,
3730
- this.#startCallSpan
3877
+ this.#startCallSpan,
3878
+ this.#retryBudget
3731
3879
  );
3732
3880
  }
3733
3881
  [CREATE_ACTOR_CONN_PROXY](conn) {
@@ -3927,12 +4075,18 @@ function jwtExpiration(token) {
3927
4075
  }
3928
4076
 
3929
4077
  // src/client/actor-conn.ts
4078
+ var CONNECT_TIMEOUT_MS = 2e4;
4079
+ function isConnectionOpenTimeout(error) {
4080
+ return error instanceof RivetError && error.group === "client" && error.code === "connection_open_timeout";
4081
+ }
3930
4082
  var CONNECT_SYMBOL = /* @__PURE__ */ Symbol("connect");
3931
4083
  var ActorConnRaw = class {
3932
4084
  #disposed = false;
3933
4085
  /* Will be aborted on dispose. */
3934
4086
  #abortController = new AbortController();
3935
4087
  #connStatus = "idle";
4088
+ /** The opening failure that stopped retries. Later actions must fail instead of queueing. */
4089
+ #connectionOpenError;
3936
4090
  #actorId;
3937
4091
  #connId;
3938
4092
  #messageQueue = [];
@@ -3954,6 +4108,8 @@ var ActorConnRaw = class {
3954
4108
  #keepNodeAliveInterval;
3955
4109
  /** Promise used to indicate the socket has connected successfully. This will be rejected if the connection fails. */
3956
4110
  #onOpenPromise;
4111
+ /** Sockets given up on by the connect timeout. Their late events are ignored. */
4112
+ #abandonedSockets = /* @__PURE__ */ new WeakSet();
3957
4113
  #websocket;
3958
4114
  #authRetryAvailable = true;
3959
4115
  #client;
@@ -4052,6 +4208,8 @@ var ActorConnRaw = class {
4052
4208
  `Invalid action call: expected an options object { name, args }, got ${typeof opts}. Use conn.actionName(...args) for the shorthand API.`
4053
4209
  );
4054
4210
  }
4211
+ if (this.#disposed) throw new ActorConnDisposed();
4212
+ if (this.#connectionOpenError) throw this.#connectionOpenError;
4055
4213
  logger().debug({ msg: "action", name: opts.name, args: opts.args });
4056
4214
  const actionId = this.#actionIdCounter;
4057
4215
  this.#actionIdCounter += 1;
@@ -4139,17 +4297,22 @@ var ActorConnRaw = class {
4139
4297
  }
4140
4298
  }
4141
4299
  #connectWithRetry() {
4300
+ this.#connectionOpenError = void 0;
4142
4301
  this.#setConnStatus("connecting");
4143
4302
  pRetry(this.#connectAndWait.bind(this), {
4144
4303
  forever: true,
4145
4304
  minTimeout: 250,
4146
4305
  maxTimeout: 3e4,
4147
- onFailedAttempt: (error) => {
4306
+ onFailedAttempt: async (error) => {
4148
4307
  logger().warn({
4149
4308
  msg: "failed to reconnect",
4150
4309
  attempt: error.attemptNumber,
4151
4310
  error: stringifyError(error)
4152
4311
  });
4312
+ const hintMs = retryAfterMs(error);
4313
+ if (hintMs !== void 0) {
4314
+ await new Promise((resolve) => setTimeout(resolve, hintMs));
4315
+ }
4153
4316
  },
4154
4317
  // Cancel retry if aborted
4155
4318
  signal: this.#abortController.signal
@@ -4175,8 +4338,11 @@ var ActorConnRaw = class {
4175
4338
  })
4176
4339
  );
4177
4340
  await this.#connectWebSocket();
4178
- await this.#onOpenPromise.promise;
4341
+ await this.#waitForOpen(this.#onOpenPromise.promise);
4179
4342
  } catch (error) {
4343
+ this.#abandonCurrentSocket(
4344
+ isConnectionOpenTimeout(error) ? "Connect timeout" : "Connection opening failed"
4345
+ );
4180
4346
  if (this.#shouldRetryConnectionOpenError(error)) {
4181
4347
  throw error;
4182
4348
  }
@@ -4186,7 +4352,7 @@ var ActorConnRaw = class {
4186
4352
  `Failed to open connection: ${stringifyError(error)}`,
4187
4353
  { error: stringifyError(error) }
4188
4354
  );
4189
- this.#clearQueuedMessages();
4355
+ this.#connectionOpenError = actorError;
4190
4356
  this.#rejectPendingPromises(actorError, false);
4191
4357
  this.#dispatchActorError(actorError);
4192
4358
  this.#setConnStatus("idle");
@@ -4197,10 +4363,61 @@ var ActorConnRaw = class {
4197
4363
  this.#onOpenPromise = void 0;
4198
4364
  }
4199
4365
  }
4366
+ /**
4367
+ * Waits for the actor's Init on the current socket, up to {@link CONNECT_TIMEOUT_MS}. A socket
4368
+ * can stay connecting with no open, error or close event, as when the engine holds the
4369
+ * upgrade or a refused connect reports only an error. On timeout the socket is abandoned
4370
+ * and closed, and the retryable `client.connection_open_timeout` starts the next attempt.
4371
+ */
4372
+ async #waitForOpen(open) {
4373
+ let timer;
4374
+ const timedOut = new Promise((_, reject) => {
4375
+ timer = setTimeout(() => {
4376
+ reject(
4377
+ new RivetError(
4378
+ "client",
4379
+ "connection_open_timeout",
4380
+ `Connection did not open within ${CONNECT_TIMEOUT_MS} ms`
4381
+ )
4382
+ );
4383
+ }, CONNECT_TIMEOUT_MS);
4384
+ });
4385
+ try {
4386
+ await Promise.race([open, timedOut]);
4387
+ } finally {
4388
+ clearTimeout(timer);
4389
+ }
4390
+ }
4391
+ #abandonCurrentSocket(reason) {
4392
+ const ws = this.#websocket;
4393
+ if (!ws) return;
4394
+ this.#websocket = void 0;
4395
+ this.#abandonedSockets.add(ws);
4396
+ logger().debug({
4397
+ msg: "closing failed connection attempt",
4398
+ connId: this.#connId,
4399
+ readyState: ws.readyState,
4400
+ reason
4401
+ });
4402
+ try {
4403
+ ws.close(1e3, reason);
4404
+ } catch (err) {
4405
+ logger().debug({
4406
+ msg: "failed to close abandoned websocket",
4407
+ error: stringifyError(err)
4408
+ });
4409
+ }
4410
+ }
4200
4411
  #shouldRetryConnectionOpenError(error) {
4201
4412
  if (error instanceof ActorConnDisposed) {
4202
4413
  return false;
4203
4414
  }
4415
+ if (isConnectionOpenTimeout(error)) {
4416
+ return true;
4417
+ }
4418
+ if (error instanceof RivetError && error.group === "client" && error.code === "connection_open_interrupted") {
4419
+ return true;
4420
+ }
4204
4421
  if (error instanceof RivetError && isInvalidToken(error.group, error.code) && this.#driver.refreshAuthToken && this.#authRetryAvailable) {
4205
4422
  this.#authRetryAvailable = false;
4206
4423
  return true;
@@ -4260,14 +4477,18 @@ var ActorConnRaw = class {
4260
4477
  });
4261
4478
  this.#websocket = ws;
4262
4479
  ws.addEventListener("open", () => {
4480
+ if (this.#websocket !== ws || this.#abandonedSockets.has(ws))
4481
+ return;
4263
4482
  logger().debug({
4264
4483
  msg: "client websocket open",
4265
4484
  connId: this.#connId
4266
4485
  });
4267
4486
  });
4268
4487
  ws.addEventListener("message", async (ev) => {
4488
+ if (this.#websocket !== ws || this.#abandonedSockets.has(ws))
4489
+ return;
4269
4490
  try {
4270
- await this.#handleOnMessage(ev.data);
4491
+ await this.#handleOnMessage(ev.data, ws);
4271
4492
  } catch (err) {
4272
4493
  logger().error({
4273
4494
  msg: "error in websocket message handler",
@@ -4276,6 +4497,8 @@ var ActorConnRaw = class {
4276
4497
  }
4277
4498
  });
4278
4499
  ws.addEventListener("close", async (ev) => {
4500
+ if (this.#websocket !== ws || this.#abandonedSockets.has(ws))
4501
+ return;
4279
4502
  try {
4280
4503
  await this.#handleOnClose(ev);
4281
4504
  } catch (err) {
@@ -4286,6 +4509,8 @@ var ActorConnRaw = class {
4286
4509
  }
4287
4510
  });
4288
4511
  ws.addEventListener("error", () => {
4512
+ if (this.#websocket !== ws || this.#abandonedSockets.has(ws))
4513
+ return;
4289
4514
  try {
4290
4515
  this.#handleOnError();
4291
4516
  } catch (err) {
@@ -4351,7 +4576,7 @@ var ActorConnRaw = class {
4351
4576
  });
4352
4577
  }
4353
4578
  /** Called by the onmessage event from drivers. */
4354
- async #handleOnMessage(data) {
4579
+ async #handleOnMessage(data, socket) {
4355
4580
  var _a;
4356
4581
  logger().trace({
4357
4582
  msg: "received message",
@@ -4360,6 +4585,8 @@ var ActorConnRaw = class {
4360
4585
  isArrayBuffer: data instanceof ArrayBuffer
4361
4586
  });
4362
4587
  const response = await this.#parseMessage(data);
4588
+ if (this.#websocket !== socket || this.#abandonedSockets.has(socket))
4589
+ return;
4363
4590
  logger().trace(
4364
4591
  getLogMessage() ? {
4365
4592
  msg: "parsed message",
@@ -4431,18 +4658,15 @@ var ActorConnRaw = class {
4431
4658
  this.#actorResolutionState,
4432
4659
  this.#driver
4433
4660
  );
4661
+ if (this.#websocket !== socket || this.#abandonedSockets.has(socket)) {
4662
+ return;
4663
+ }
4434
4664
  if (schedulingError) {
4435
4665
  errorToThrow = schedulingError;
4436
4666
  }
4437
4667
  }
4438
- if (this.#onOpenPromise) {
4439
- this.#onOpenPromise.reject(errorToThrow);
4440
- }
4441
4668
  this.#invalidateActorIfStale(group, code);
4442
- for (const [id, inFlight] of this.#actionsInFlight.entries()) {
4443
- inFlight.reject(errorToThrow);
4444
- this.#actionsInFlight.delete(id);
4445
- }
4669
+ this.#rejectPendingPromises(errorToThrow, false);
4446
4670
  this.#dispatchActorError(errorToThrow);
4447
4671
  }
4448
4672
  } else if (response.body.tag === "ActionResponse") {
@@ -4494,7 +4718,8 @@ var ActorConnRaw = class {
4494
4718
  const reason = closeEvent.reason || "";
4495
4719
  const parsed = parseWebSocketCloseReason(reason);
4496
4720
  if (parsed) {
4497
- const { group, code, rayId } = parsed;
4721
+ const { group, code, rayId, retryAfterMs: retryAfterMs2 } = parsed;
4722
+ const closeOptions = retryAfterMs2 === void 0 ? { rayId } : { rayId, metadata: { retry_after_ms: retryAfterMs2 } };
4498
4723
  if (isInvalidToken(group, code) && closeEvent.code === 1008 && failedSocket) {
4499
4724
  try {
4500
4725
  if (!await ((_b = (_a = this.#driver).refreshAuthToken) == null ? void 0 : _b.call(
@@ -4517,7 +4742,7 @@ var ActorConnRaw = class {
4517
4742
  group,
4518
4743
  code,
4519
4744
  `Connection closed: ${reason}`,
4520
- { rayId }
4745
+ closeOptions
4521
4746
  )
4522
4747
  );
4523
4748
  return;
@@ -4538,7 +4763,7 @@ var ActorConnRaw = class {
4538
4763
  group,
4539
4764
  code,
4540
4765
  `Connection closed: ${reason}`,
4541
- { rayId }
4766
+ closeOptions
4542
4767
  );
4543
4768
  }
4544
4769
  } else {
@@ -4546,14 +4771,17 @@ var ActorConnRaw = class {
4546
4771
  group,
4547
4772
  code,
4548
4773
  `Connection closed: ${reason}`,
4549
- { rayId }
4774
+ closeOptions
4550
4775
  );
4551
4776
  }
4552
4777
  this.#invalidateActorIfStale(group, code);
4553
4778
  } else {
4554
- error = new Error(
4555
- `${wasClean ? "Connection closed" : "Connection lost"} (code: ${closeEvent.code}, reason: ${reason})`
4556
- );
4779
+ const message = `${wasClean ? "Connection closed" : "Connection lost"} (code: ${closeEvent.code}, reason: ${reason})`;
4780
+ error = !wasConnected && closeEvent.code === 1006 ? new RivetError(
4781
+ "client",
4782
+ "connection_open_interrupted",
4783
+ message
4784
+ ) : new Error(message);
4557
4785
  }
4558
4786
  this.#rejectPendingPromises(error, false);
4559
4787
  if (error instanceof RivetError) {
@@ -4569,6 +4797,7 @@ var ActorConnRaw = class {
4569
4797
  }
4570
4798
  }
4571
4799
  #rejectPendingPromises(error, suppressUnhandled) {
4800
+ this.#clearQueuedMessages();
4572
4801
  if (this.#onOpenPromise) {
4573
4802
  if (suppressUnhandled) {
4574
4803
  this.#onOpenPromise.promise.catch(() => {
@@ -5164,6 +5393,14 @@ var ClientConfigSchemaBase = z2.object({
5164
5393
  // This is required in the client config in order to support
5165
5394
  // `proxyWebSocket`
5166
5395
  getUpgradeWebSocket: z2.custom().optional(),
5396
+ /**
5397
+ * Bounds retries of refused requests: `percent` retries per 100 requests (default 10), with
5398
+ * up to `maxTokens` banked for bursts (default 100). A refusal past the budget is thrown.
5399
+ */
5400
+ retryBudget: z2.object({
5401
+ percent: z2.number().min(0).max(100).optional(),
5402
+ maxTokens: z2.number().int().min(0).optional()
5403
+ }).optional(),
5167
5404
  /** Replaces global fetch for actor HTTP gateway requests. */
5168
5405
  fetch: z2.custom().optional(),
5169
5406
  /** Whether to automatically perform health checks when the client is created. */
@@ -5206,7 +5443,7 @@ function convertRegistryConfigToClientConfig(config) {
5206
5443
  token: config.token,
5207
5444
  getToken: void 0,
5208
5445
  namespace: config.namespace,
5209
- poolName: config.envoy.poolName,
5446
+ poolName: config.node.poolName,
5210
5447
  headers: config.headers,
5211
5448
  gateway: { skipReadyWait: false },
5212
5449
  encoding: "bare",
@@ -5533,8 +5770,9 @@ function buildActorQueryGatewayUrl(endpoint, namespace, query, token, path = "",
5533
5770
  return combineUrlPath(endpoint, gatewayPath);
5534
5771
  }
5535
5772
  function pushKeyQueryParams(params, key) {
5536
- if (key.length > 0) {
5537
- params.append("rvt-key", key.join(","));
5773
+ const rvtKey = actorKeyToGatewayQuery(key);
5774
+ if (rvtKey !== void 0) {
5775
+ params.append("rvt-key", rvtKey);
5538
5776
  }
5539
5777
  }
5540
5778
  function pushInputQueryParam(params, input, maxInputSize) {
@@ -5716,8 +5954,8 @@ async function updateRunnerConfig(config, runnerName, request) {
5716
5954
  return apiCall(
5717
5955
  config,
5718
5956
  "PUT",
5719
- `/runner-configs/${runnerName}`,
5720
- request
5957
+ `/pools/${encodeURIComponent(runnerName)}`,
5958
+ Object.values(request.datacenters)[0]
5721
5959
  );
5722
5960
  }
5723
5961
 
@@ -6050,7 +6288,7 @@ var RemoteEngineControlClient = class {
6050
6288
  datacenter: region,
6051
6289
  name,
6052
6290
  key: serializeActorKey(key),
6053
- runner_name_selector: poolName ?? this.#config.poolName,
6291
+ pool: poolName ?? this.#config.poolName,
6054
6292
  input: actorInput ? uint8ArrayToBase64(
6055
6293
  encodeCborCompat(actorInput)
6056
6294
  ) : void 0,
@@ -6103,7 +6341,7 @@ var RemoteEngineControlClient = class {
6103
6341
  (config) => createActor(config, {
6104
6342
  datacenter: region,
6105
6343
  name,
6106
- runner_name_selector: poolName ?? this.#config.poolName,
6344
+ pool: poolName ?? this.#config.poolName,
6107
6345
  key: serializeActorKey(key),
6108
6346
  input: input ? uint8ArrayToBase64(
6109
6347
  encodeCborCompat(input)
@@ -6369,4 +6607,4 @@ export {
6369
6607
  updateRunnerConfig,
6370
6608
  RemoteEngineControlClient
6371
6609
  };
6372
- //# sourceMappingURL=chunk-PJ5EXY6F.js.map
6610
+ //# sourceMappingURL=chunk-QQIFRR3B.js.map