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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/dist/browser/client.d.ts +99 -59
  2. package/dist/browser/client.js +228 -34
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.js +1 -2
  5. package/dist/browser/inspector/client.js.map +1 -1
  6. package/dist/tsup/{chunk-3URZ4UV5.js → chunk-2HWY7FZU.js} +2 -2
  7. package/dist/tsup/{chunk-PJ5EXY6F.js → chunk-62WFU3BQ.js} +223 -42
  8. package/dist/tsup/chunk-62WFU3BQ.js.map +1 -0
  9. package/dist/tsup/{chunk-JI6GZ2C2.js → chunk-A2CF6PFH.js} +18 -1
  10. package/dist/tsup/chunk-A2CF6PFH.js.map +1 -0
  11. package/dist/tsup/{chunk-KDT56V3Y.cjs → chunk-AQWZWR2P.cjs} +10 -11
  12. package/dist/tsup/chunk-AQWZWR2P.cjs.map +1 -0
  13. package/dist/tsup/{chunk-L3Z3W44Q.cjs → chunk-E4KDQJCR.cjs} +3 -3
  14. package/dist/tsup/{chunk-L3Z3W44Q.cjs.map → chunk-E4KDQJCR.cjs.map} +1 -1
  15. package/dist/tsup/{chunk-DHL2M2E2.cjs → chunk-E6HKVCPA.cjs} +3 -3
  16. package/dist/tsup/{chunk-DHL2M2E2.cjs.map → chunk-E6HKVCPA.cjs.map} +1 -1
  17. package/dist/tsup/{chunk-DDS7OOVF.cjs → chunk-EQBUH25O.cjs} +362 -181
  18. package/dist/tsup/chunk-EQBUH25O.cjs.map +1 -0
  19. package/dist/tsup/{chunk-USKGKQZM.js → chunk-HQHTTJW5.js} +10 -11
  20. package/dist/tsup/chunk-HQHTTJW5.js.map +1 -0
  21. package/dist/tsup/{chunk-JW2WPE6Z.cjs → chunk-M5SQGPRJ.cjs} +4 -4
  22. package/dist/tsup/{chunk-JW2WPE6Z.cjs.map → chunk-M5SQGPRJ.cjs.map} +1 -1
  23. package/dist/tsup/{chunk-FYDB45YU.cjs → chunk-MYWNJP55.cjs} +10 -10
  24. package/dist/tsup/{chunk-FYDB45YU.cjs.map → chunk-MYWNJP55.cjs.map} +1 -1
  25. package/dist/tsup/{chunk-F7IGTKGM.js → chunk-OWZ76NSH.js} +2 -2
  26. package/dist/tsup/{chunk-KSP3NXGY.js → chunk-QE5MTZHB.js} +3 -3
  27. package/dist/tsup/{chunk-D4G35VTO.js → chunk-QFZY2CK3.js} +4 -4
  28. package/dist/tsup/{chunk-E2CUROR3.js → chunk-QIIIRYN7.js} +2 -2
  29. package/dist/tsup/{chunk-MYWZCDML.cjs → chunk-RTWH3AX3.cjs} +19 -2
  30. package/dist/tsup/chunk-RTWH3AX3.cjs.map +1 -0
  31. package/dist/tsup/{chunk-HO76AEDH.cjs → chunk-UHMB5FFB.cjs} +3 -3
  32. package/dist/tsup/{chunk-HO76AEDH.cjs.map → chunk-UHMB5FFB.cjs.map} +1 -1
  33. package/dist/tsup/{chunk-QR6EAWEC.cjs → chunk-VKXEBB3Z.cjs} +7 -7
  34. package/dist/tsup/{chunk-QR6EAWEC.cjs.map → chunk-VKXEBB3Z.cjs.map} +1 -1
  35. package/dist/tsup/{chunk-EPRA2TCT.js → chunk-ZMVYZ7ZI.js} +2 -2
  36. package/dist/tsup/client/mod.cjs +6 -6
  37. package/dist/tsup/client/mod.d.cts +15 -3
  38. package/dist/tsup/client/mod.d.ts +15 -3
  39. package/dist/tsup/client/mod.js +5 -5
  40. package/dist/tsup/common/log.cjs +2 -2
  41. package/dist/tsup/common/log.js +1 -1
  42. package/dist/tsup/common/websocket.cjs +3 -3
  43. package/dist/tsup/common/websocket.js +2 -2
  44. package/dist/tsup/{config-Cw_BwH_G.d.ts → config-B4erdavw.d.ts} +58 -12
  45. package/dist/tsup/{config-D4clT6mq.d.ts → config-BfG1qpYz.d.cts} +34 -52
  46. package/dist/tsup/{config-D4clT6mq.d.cts → config-BfG1qpYz.d.ts} +34 -52
  47. package/dist/tsup/{config-CkmVg2fG.d.cts → config-DK144OAw.d.cts} +58 -12
  48. package/dist/tsup/{context-_xIcgBnE.d.cts → context-Cvnf3BRe.d.cts} +2 -2
  49. package/dist/tsup/{context-BYOKTQJi.d.ts → context-Oxi6YWcG.d.ts} +2 -2
  50. package/dist/tsup/db/drizzle.cjs +2 -2
  51. package/dist/tsup/db/drizzle.d.cts +1 -1
  52. package/dist/tsup/db/drizzle.d.ts +1 -1
  53. package/dist/tsup/db/drizzle.js +1 -1
  54. package/dist/tsup/db/mod.cjs +3 -3
  55. package/dist/tsup/db/mod.d.cts +2 -2
  56. package/dist/tsup/db/mod.d.ts +2 -2
  57. package/dist/tsup/db/mod.js +2 -2
  58. package/dist/tsup/dynamic/mod.d.cts +2 -2
  59. package/dist/tsup/dynamic/mod.d.ts +2 -2
  60. package/dist/tsup/inspector/mod.cjs +5 -5
  61. package/dist/tsup/inspector/mod.js +4 -4
  62. package/dist/tsup/inspector/workflow.cjs +4 -4
  63. package/dist/tsup/inspector/workflow.js +3 -3
  64. package/dist/tsup/inspector-tab/mod.d.cts +3 -3
  65. package/dist/tsup/inspector-tab/mod.d.ts +3 -3
  66. package/dist/tsup/mod.cjs +553 -202
  67. package/dist/tsup/mod.cjs.map +1 -1
  68. package/dist/tsup/mod.d.cts +4 -4
  69. package/dist/tsup/mod.d.ts +4 -4
  70. package/dist/tsup/mod.js +467 -116
  71. package/dist/tsup/mod.js.map +1 -1
  72. package/dist/tsup/test/mod.cjs +7 -7
  73. package/dist/tsup/test/mod.d.cts +2 -2
  74. package/dist/tsup/test/mod.d.ts +2 -2
  75. package/dist/tsup/test/mod.js +5 -5
  76. package/dist/tsup/unstable/migrations.d.cts +1 -1
  77. package/dist/tsup/unstable/migrations.d.ts +1 -1
  78. package/dist/tsup/utils.cjs +2 -2
  79. package/dist/tsup/utils.js +1 -1
  80. package/dist/tsup/workflow/mod.cjs +22 -19
  81. package/dist/tsup/workflow/mod.cjs.map +1 -1
  82. package/dist/tsup/workflow/mod.d.cts +4 -4
  83. package/dist/tsup/workflow/mod.d.ts +4 -4
  84. package/dist/tsup/workflow/mod.js +10 -7
  85. package/dist/tsup/workflow/mod.js.map +1 -1
  86. package/package.json +9 -10
  87. package/src/actor/keys.ts +86 -0
  88. package/src/client/actor-conn.ts +136 -24
  89. package/src/client/actor-handle.ts +21 -3
  90. package/src/client/client.ts +6 -0
  91. package/src/client/config.ts +12 -1
  92. package/src/client/lifecycle-errors.ts +35 -2
  93. package/src/client/retry-budget.ts +78 -0
  94. package/src/client/utils.ts +13 -2
  95. package/src/common/database/config.ts +46 -52
  96. package/src/common/database/native-database.ts +247 -27
  97. package/src/common/router.ts +1 -1
  98. package/src/db/mod.ts +0 -1
  99. package/src/engine-api/actors.ts +3 -3
  100. package/src/engine-client/actor-websocket-client.ts +4 -2
  101. package/src/engine-client/api-endpoints.ts +44 -14
  102. package/src/engine-client/mod.ts +2 -2
  103. package/src/registry/config/envoy.ts +1 -1
  104. package/src/registry/config/index.ts +29 -31
  105. package/src/registry/index.ts +66 -21
  106. package/src/registry/napi-runtime.ts +82 -3
  107. package/src/registry/native.ts +184 -52
  108. package/src/registry/runtime.ts +79 -10
  109. package/src/registry/wasm-runtime.ts +94 -3
  110. package/src/utils/env-vars.ts +15 -10
  111. package/src/workflow/driver.ts +5 -3
  112. package/dist/tsup/chunk-DDS7OOVF.cjs.map +0 -1
  113. package/dist/tsup/chunk-JI6GZ2C2.js.map +0 -1
  114. package/dist/tsup/chunk-KDT56V3Y.cjs.map +0 -1
  115. package/dist/tsup/chunk-MYWZCDML.cjs.map +0 -1
  116. package/dist/tsup/chunk-PJ5EXY6F.js.map +0 -1
  117. package/dist/tsup/chunk-USKGKQZM.js.map +0 -1
  118. package/src/actor/config.test.ts +0 -78
  119. package/src/actor/keys.test.ts +0 -275
  120. package/src/actor/utils.test.ts +0 -48
  121. package/src/client/test.ts +0 -44
  122. package/src/client/token-provider.test.ts +0 -86
  123. package/src/common/database/mod.test.ts +0 -364
  124. package/src/common/database/native-database.test.ts +0 -220
  125. package/src/common/inline-websocket-adapter.test.ts +0 -51
  126. package/src/db/drizzle.test.ts +0 -164
  127. package/src/registry/config/index.test.ts +0 -25
  128. package/src/registry/run-handler-coordinator.test.ts +0 -252
  129. package/src/registry/runtime.test.ts +0 -124
  130. package/src/unstable/migrations.test.ts +0 -170
  131. package/src/utils/endpoint-parser.test.ts +0 -206
  132. package/src/utils.test.ts +0 -34
  133. package/src/workflow/driver.test.ts +0 -62
  134. /package/dist/tsup/{chunk-3URZ4UV5.js.map → chunk-2HWY7FZU.js.map} +0 -0
  135. /package/dist/tsup/{chunk-F7IGTKGM.js.map → chunk-OWZ76NSH.js.map} +0 -0
  136. /package/dist/tsup/{chunk-KSP3NXGY.js.map → chunk-QE5MTZHB.js.map} +0 -0
  137. /package/dist/tsup/{chunk-D4G35VTO.js.map → chunk-QFZY2CK3.js.map} +0 -0
  138. /package/dist/tsup/{chunk-E2CUROR3.js.map → chunk-QIIIRYN7.js.map} +0 -0
  139. /package/dist/tsup/{chunk-EPRA2TCT.js.map → chunk-ZMVYZ7ZI.js.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  bufferToArrayBuffer,
3
3
  toUint8Array
4
- } from "./chunk-USKGKQZM.js";
4
+ } from "./chunk-HQHTTJW5.js";
5
5
 
6
6
  // src/common/bare/transport/v1.ts
7
7
  import * as bare from "@rivetkit/bare-ts";
@@ -593,4 +593,4 @@ export {
593
593
  encodeWorkflowHistoryTransport,
594
594
  decodeWorkflowHistoryTransport
595
595
  };
596
- //# sourceMappingURL=chunk-3URZ4UV5.js.map
596
+ //# sourceMappingURL=chunk-2HWY7FZU.js.map
@@ -1,14 +1,15 @@
1
1
  import {
2
+ actorKeyToGatewayQuery,
2
3
  deserializeActorKey,
3
4
  serializeActorKey
4
- } from "./chunk-JI6GZ2C2.js";
5
- import {
6
- importWebSocket,
7
- logger
8
- } from "./chunk-F7IGTKGM.js";
5
+ } from "./chunk-A2CF6PFH.js";
9
6
  import {
10
7
  AsyncMutex
11
8
  } from "./chunk-JTHHCZCZ.js";
9
+ import {
10
+ importWebSocket,
11
+ logger
12
+ } from "./chunk-OWZ76NSH.js";
12
13
  import {
13
14
  EncodingSchema,
14
15
  assertUnreachable,
@@ -35,7 +36,7 @@ import {
35
36
  serializeWithEncoding,
36
37
  stringifyError,
37
38
  uint8ArrayToBase64
38
- } from "./chunk-USKGKQZM.js";
39
+ } from "./chunk-HQHTTJW5.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) {
@@ -2868,6 +2941,7 @@ var ActorHandleRaw = class {
2868
2941
  #queueSendMutex = new AsyncMutex();
2869
2942
  #currentActorInvocation;
2870
2943
  #startCallSpan;
2944
+ #retryBudget;
2871
2945
  /**
2872
2946
  * Do not call this directly.
2873
2947
  *
@@ -2875,7 +2949,7 @@ var ActorHandleRaw = class {
2875
2949
  *
2876
2950
  * @protected
2877
2951
  */
2878
- constructor(client, driver, params, getParams, encoding, actorResolutionState, gatewayOptions = {}, signal, currentActorInvocation, startCallSpan) {
2952
+ constructor(client, driver, params, getParams, encoding, actorResolutionState, gatewayOptions = {}, signal, currentActorInvocation, startCallSpan, retryBudget = new RetryBudget()) {
2879
2953
  this.#client = client;
2880
2954
  this.#driver = driver;
2881
2955
  this.#encoding = encoding;
@@ -2886,6 +2960,7 @@ var ActorHandleRaw = class {
2886
2960
  this.#signal = signal;
2887
2961
  this.#currentActorInvocation = currentActorInvocation;
2888
2962
  this.#startCallSpan = startCallSpan;
2963
+ this.#retryBudget = retryBudget;
2889
2964
  }
2890
2965
  async #resolveConnectionParams() {
2891
2966
  if (this.#getParams) {
@@ -2902,6 +2977,7 @@ var ActorHandleRaw = class {
2902
2977
  let useQueryTarget = isDynamicActorQuery(
2903
2978
  this.#actorResolutionState
2904
2979
  );
2980
+ this.#retryBudget.deposit();
2905
2981
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
2906
2982
  let actorId;
2907
2983
  try {
@@ -2938,8 +3014,17 @@ var ActorHandleRaw = class {
2938
3014
  metadata,
2939
3015
  attempt,
2940
3016
  maxAttempts
2941
- )) {
2942
- await this.#waitForRetryWindow();
3017
+ ) && this.#retryBudget.tryWithdraw()) {
3018
+ await new Promise(
3019
+ (resolve) => setTimeout(
3020
+ resolve,
3021
+ retryDelayMs(attempt, {
3022
+ initialDelayMs: 25,
3023
+ maxDelayMs: 1e3,
3024
+ hintMs: retryAfterMs(err)
3025
+ })
3026
+ )
3027
+ );
2943
3028
  continue;
2944
3029
  }
2945
3030
  if (await this.#shouldRetrySchedulingError(
@@ -3016,7 +3101,10 @@ var ActorHandleRaw = class {
3016
3101
  if (opts.name === "destroy") {
3017
3102
  return await run();
3018
3103
  }
3019
- return await retryOnLifecycleBoundary(run, { signal });
3104
+ return await retryOnLifecycleBoundary(run, {
3105
+ signal,
3106
+ budget: this.#retryBudget
3107
+ });
3020
3108
  };
3021
3109
  if (!call) {
3022
3110
  return await send();
@@ -3558,6 +3646,7 @@ var ClientRaw = class {
3558
3646
  #gatewayOptions;
3559
3647
  #currentActorInvocation;
3560
3648
  #startCallSpan;
3649
+ #retryBudget;
3561
3650
  /**
3562
3651
  * Creates an instance of Client.
3563
3652
  */
@@ -3570,6 +3659,7 @@ var ClientRaw = class {
3570
3659
  this.#gatewayOptions = options.gateway ?? {};
3571
3660
  this.#currentActorInvocation = options.currentActorInvocation;
3572
3661
  this.#startCallSpan = options.startCallSpan;
3662
+ this.#retryBudget = new RetryBudget(options.retryBudget);
3573
3663
  }
3574
3664
  /**
3575
3665
  * Gets a stateless handle to a actor by its ID.
@@ -3727,7 +3817,8 @@ var ClientRaw = class {
3727
3817
  this.#gatewayOptions,
3728
3818
  signal,
3729
3819
  this.#currentActorInvocation,
3730
- this.#startCallSpan
3820
+ this.#startCallSpan,
3821
+ this.#retryBudget
3731
3822
  );
3732
3823
  }
3733
3824
  [CREATE_ACTOR_CONN_PROXY](conn) {
@@ -3927,12 +4018,18 @@ function jwtExpiration(token) {
3927
4018
  }
3928
4019
 
3929
4020
  // src/client/actor-conn.ts
4021
+ var CONNECT_TIMEOUT_MS = 2e4;
4022
+ function isConnectionOpenTimeout(error) {
4023
+ return error instanceof RivetError && error.group === "client" && error.code === "connection_open_timeout";
4024
+ }
3930
4025
  var CONNECT_SYMBOL = /* @__PURE__ */ Symbol("connect");
3931
4026
  var ActorConnRaw = class {
3932
4027
  #disposed = false;
3933
4028
  /* Will be aborted on dispose. */
3934
4029
  #abortController = new AbortController();
3935
4030
  #connStatus = "idle";
4031
+ /** The opening failure that stopped retries. Later actions must fail instead of queueing. */
4032
+ #connectionOpenError;
3936
4033
  #actorId;
3937
4034
  #connId;
3938
4035
  #messageQueue = [];
@@ -3954,6 +4051,8 @@ var ActorConnRaw = class {
3954
4051
  #keepNodeAliveInterval;
3955
4052
  /** Promise used to indicate the socket has connected successfully. This will be rejected if the connection fails. */
3956
4053
  #onOpenPromise;
4054
+ /** Sockets given up on by the connect timeout. Their late events are ignored. */
4055
+ #abandonedSockets = /* @__PURE__ */ new WeakSet();
3957
4056
  #websocket;
3958
4057
  #authRetryAvailable = true;
3959
4058
  #client;
@@ -4052,6 +4151,8 @@ var ActorConnRaw = class {
4052
4151
  `Invalid action call: expected an options object { name, args }, got ${typeof opts}. Use conn.actionName(...args) for the shorthand API.`
4053
4152
  );
4054
4153
  }
4154
+ if (this.#disposed) throw new ActorConnDisposed();
4155
+ if (this.#connectionOpenError) throw this.#connectionOpenError;
4055
4156
  logger().debug({ msg: "action", name: opts.name, args: opts.args });
4056
4157
  const actionId = this.#actionIdCounter;
4057
4158
  this.#actionIdCounter += 1;
@@ -4139,17 +4240,22 @@ var ActorConnRaw = class {
4139
4240
  }
4140
4241
  }
4141
4242
  #connectWithRetry() {
4243
+ this.#connectionOpenError = void 0;
4142
4244
  this.#setConnStatus("connecting");
4143
4245
  pRetry(this.#connectAndWait.bind(this), {
4144
4246
  forever: true,
4145
4247
  minTimeout: 250,
4146
4248
  maxTimeout: 3e4,
4147
- onFailedAttempt: (error) => {
4249
+ onFailedAttempt: async (error) => {
4148
4250
  logger().warn({
4149
4251
  msg: "failed to reconnect",
4150
4252
  attempt: error.attemptNumber,
4151
4253
  error: stringifyError(error)
4152
4254
  });
4255
+ const hintMs = retryAfterMs(error);
4256
+ if (hintMs !== void 0) {
4257
+ await new Promise((resolve) => setTimeout(resolve, hintMs));
4258
+ }
4153
4259
  },
4154
4260
  // Cancel retry if aborted
4155
4261
  signal: this.#abortController.signal
@@ -4175,8 +4281,11 @@ var ActorConnRaw = class {
4175
4281
  })
4176
4282
  );
4177
4283
  await this.#connectWebSocket();
4178
- await this.#onOpenPromise.promise;
4284
+ await this.#waitForOpen(this.#onOpenPromise.promise);
4179
4285
  } catch (error) {
4286
+ this.#abandonCurrentSocket(
4287
+ isConnectionOpenTimeout(error) ? "Connect timeout" : "Connection opening failed"
4288
+ );
4180
4289
  if (this.#shouldRetryConnectionOpenError(error)) {
4181
4290
  throw error;
4182
4291
  }
@@ -4186,7 +4295,7 @@ var ActorConnRaw = class {
4186
4295
  `Failed to open connection: ${stringifyError(error)}`,
4187
4296
  { error: stringifyError(error) }
4188
4297
  );
4189
- this.#clearQueuedMessages();
4298
+ this.#connectionOpenError = actorError;
4190
4299
  this.#rejectPendingPromises(actorError, false);
4191
4300
  this.#dispatchActorError(actorError);
4192
4301
  this.#setConnStatus("idle");
@@ -4197,10 +4306,61 @@ var ActorConnRaw = class {
4197
4306
  this.#onOpenPromise = void 0;
4198
4307
  }
4199
4308
  }
4309
+ /**
4310
+ * Waits for the actor's Init on the current socket, up to {@link CONNECT_TIMEOUT_MS}. A socket
4311
+ * can stay connecting with no open, error or close event, as when the engine holds the
4312
+ * upgrade or a refused connect reports only an error. On timeout the socket is abandoned
4313
+ * and closed, and the retryable `client.connection_open_timeout` starts the next attempt.
4314
+ */
4315
+ async #waitForOpen(open) {
4316
+ let timer;
4317
+ const timedOut = new Promise((_, reject) => {
4318
+ timer = setTimeout(() => {
4319
+ reject(
4320
+ new RivetError(
4321
+ "client",
4322
+ "connection_open_timeout",
4323
+ `Connection did not open within ${CONNECT_TIMEOUT_MS} ms`
4324
+ )
4325
+ );
4326
+ }, CONNECT_TIMEOUT_MS);
4327
+ });
4328
+ try {
4329
+ await Promise.race([open, timedOut]);
4330
+ } finally {
4331
+ clearTimeout(timer);
4332
+ }
4333
+ }
4334
+ #abandonCurrentSocket(reason) {
4335
+ const ws = this.#websocket;
4336
+ if (!ws) return;
4337
+ this.#websocket = void 0;
4338
+ this.#abandonedSockets.add(ws);
4339
+ logger().debug({
4340
+ msg: "closing failed connection attempt",
4341
+ connId: this.#connId,
4342
+ readyState: ws.readyState,
4343
+ reason
4344
+ });
4345
+ try {
4346
+ ws.close(1e3, reason);
4347
+ } catch (err) {
4348
+ logger().debug({
4349
+ msg: "failed to close abandoned websocket",
4350
+ error: stringifyError(err)
4351
+ });
4352
+ }
4353
+ }
4200
4354
  #shouldRetryConnectionOpenError(error) {
4201
4355
  if (error instanceof ActorConnDisposed) {
4202
4356
  return false;
4203
4357
  }
4358
+ if (isConnectionOpenTimeout(error)) {
4359
+ return true;
4360
+ }
4361
+ if (error instanceof RivetError && error.group === "client" && error.code === "connection_open_interrupted") {
4362
+ return true;
4363
+ }
4204
4364
  if (error instanceof RivetError && isInvalidToken(error.group, error.code) && this.#driver.refreshAuthToken && this.#authRetryAvailable) {
4205
4365
  this.#authRetryAvailable = false;
4206
4366
  return true;
@@ -4260,14 +4420,18 @@ var ActorConnRaw = class {
4260
4420
  });
4261
4421
  this.#websocket = ws;
4262
4422
  ws.addEventListener("open", () => {
4423
+ if (this.#websocket !== ws || this.#abandonedSockets.has(ws))
4424
+ return;
4263
4425
  logger().debug({
4264
4426
  msg: "client websocket open",
4265
4427
  connId: this.#connId
4266
4428
  });
4267
4429
  });
4268
4430
  ws.addEventListener("message", async (ev) => {
4431
+ if (this.#websocket !== ws || this.#abandonedSockets.has(ws))
4432
+ return;
4269
4433
  try {
4270
- await this.#handleOnMessage(ev.data);
4434
+ await this.#handleOnMessage(ev.data, ws);
4271
4435
  } catch (err) {
4272
4436
  logger().error({
4273
4437
  msg: "error in websocket message handler",
@@ -4276,6 +4440,8 @@ var ActorConnRaw = class {
4276
4440
  }
4277
4441
  });
4278
4442
  ws.addEventListener("close", async (ev) => {
4443
+ if (this.#websocket !== ws || this.#abandonedSockets.has(ws))
4444
+ return;
4279
4445
  try {
4280
4446
  await this.#handleOnClose(ev);
4281
4447
  } catch (err) {
@@ -4286,6 +4452,8 @@ var ActorConnRaw = class {
4286
4452
  }
4287
4453
  });
4288
4454
  ws.addEventListener("error", () => {
4455
+ if (this.#websocket !== ws || this.#abandonedSockets.has(ws))
4456
+ return;
4289
4457
  try {
4290
4458
  this.#handleOnError();
4291
4459
  } catch (err) {
@@ -4351,7 +4519,7 @@ var ActorConnRaw = class {
4351
4519
  });
4352
4520
  }
4353
4521
  /** Called by the onmessage event from drivers. */
4354
- async #handleOnMessage(data) {
4522
+ async #handleOnMessage(data, socket) {
4355
4523
  var _a;
4356
4524
  logger().trace({
4357
4525
  msg: "received message",
@@ -4360,6 +4528,8 @@ var ActorConnRaw = class {
4360
4528
  isArrayBuffer: data instanceof ArrayBuffer
4361
4529
  });
4362
4530
  const response = await this.#parseMessage(data);
4531
+ if (this.#websocket !== socket || this.#abandonedSockets.has(socket))
4532
+ return;
4363
4533
  logger().trace(
4364
4534
  getLogMessage() ? {
4365
4535
  msg: "parsed message",
@@ -4431,18 +4601,15 @@ var ActorConnRaw = class {
4431
4601
  this.#actorResolutionState,
4432
4602
  this.#driver
4433
4603
  );
4604
+ if (this.#websocket !== socket || this.#abandonedSockets.has(socket)) {
4605
+ return;
4606
+ }
4434
4607
  if (schedulingError) {
4435
4608
  errorToThrow = schedulingError;
4436
4609
  }
4437
4610
  }
4438
- if (this.#onOpenPromise) {
4439
- this.#onOpenPromise.reject(errorToThrow);
4440
- }
4441
4611
  this.#invalidateActorIfStale(group, code);
4442
- for (const [id, inFlight] of this.#actionsInFlight.entries()) {
4443
- inFlight.reject(errorToThrow);
4444
- this.#actionsInFlight.delete(id);
4445
- }
4612
+ this.#rejectPendingPromises(errorToThrow, false);
4446
4613
  this.#dispatchActorError(errorToThrow);
4447
4614
  }
4448
4615
  } else if (response.body.tag === "ActionResponse") {
@@ -4494,7 +4661,8 @@ var ActorConnRaw = class {
4494
4661
  const reason = closeEvent.reason || "";
4495
4662
  const parsed = parseWebSocketCloseReason(reason);
4496
4663
  if (parsed) {
4497
- const { group, code, rayId } = parsed;
4664
+ const { group, code, rayId, retryAfterMs: retryAfterMs2 } = parsed;
4665
+ const closeOptions = retryAfterMs2 === void 0 ? { rayId } : { rayId, metadata: { retry_after_ms: retryAfterMs2 } };
4498
4666
  if (isInvalidToken(group, code) && closeEvent.code === 1008 && failedSocket) {
4499
4667
  try {
4500
4668
  if (!await ((_b = (_a = this.#driver).refreshAuthToken) == null ? void 0 : _b.call(
@@ -4517,7 +4685,7 @@ var ActorConnRaw = class {
4517
4685
  group,
4518
4686
  code,
4519
4687
  `Connection closed: ${reason}`,
4520
- { rayId }
4688
+ closeOptions
4521
4689
  )
4522
4690
  );
4523
4691
  return;
@@ -4538,7 +4706,7 @@ var ActorConnRaw = class {
4538
4706
  group,
4539
4707
  code,
4540
4708
  `Connection closed: ${reason}`,
4541
- { rayId }
4709
+ closeOptions
4542
4710
  );
4543
4711
  }
4544
4712
  } else {
@@ -4546,14 +4714,17 @@ var ActorConnRaw = class {
4546
4714
  group,
4547
4715
  code,
4548
4716
  `Connection closed: ${reason}`,
4549
- { rayId }
4717
+ closeOptions
4550
4718
  );
4551
4719
  }
4552
4720
  this.#invalidateActorIfStale(group, code);
4553
4721
  } else {
4554
- error = new Error(
4555
- `${wasClean ? "Connection closed" : "Connection lost"} (code: ${closeEvent.code}, reason: ${reason})`
4556
- );
4722
+ const message = `${wasClean ? "Connection closed" : "Connection lost"} (code: ${closeEvent.code}, reason: ${reason})`;
4723
+ error = !wasConnected && closeEvent.code === 1006 ? new RivetError(
4724
+ "client",
4725
+ "connection_open_interrupted",
4726
+ message
4727
+ ) : new Error(message);
4557
4728
  }
4558
4729
  this.#rejectPendingPromises(error, false);
4559
4730
  if (error instanceof RivetError) {
@@ -4569,6 +4740,7 @@ var ActorConnRaw = class {
4569
4740
  }
4570
4741
  }
4571
4742
  #rejectPendingPromises(error, suppressUnhandled) {
4743
+ this.#clearQueuedMessages();
4572
4744
  if (this.#onOpenPromise) {
4573
4745
  if (suppressUnhandled) {
4574
4746
  this.#onOpenPromise.promise.catch(() => {
@@ -5164,6 +5336,14 @@ var ClientConfigSchemaBase = z2.object({
5164
5336
  // This is required in the client config in order to support
5165
5337
  // `proxyWebSocket`
5166
5338
  getUpgradeWebSocket: z2.custom().optional(),
5339
+ /**
5340
+ * Bounds retries of refused requests: `percent` retries per 100 requests (default 10), with
5341
+ * up to `maxTokens` banked for bursts (default 100). A refusal past the budget is thrown.
5342
+ */
5343
+ retryBudget: z2.object({
5344
+ percent: z2.number().min(0).max(100).optional(),
5345
+ maxTokens: z2.number().int().min(0).optional()
5346
+ }).optional(),
5167
5347
  /** Replaces global fetch for actor HTTP gateway requests. */
5168
5348
  fetch: z2.custom().optional(),
5169
5349
  /** Whether to automatically perform health checks when the client is created. */
@@ -5206,7 +5386,7 @@ function convertRegistryConfigToClientConfig(config) {
5206
5386
  token: config.token,
5207
5387
  getToken: void 0,
5208
5388
  namespace: config.namespace,
5209
- poolName: config.envoy.poolName,
5389
+ poolName: config.node.poolName,
5210
5390
  headers: config.headers,
5211
5391
  gateway: { skipReadyWait: false },
5212
5392
  encoding: "bare",
@@ -5533,8 +5713,9 @@ function buildActorQueryGatewayUrl(endpoint, namespace, query, token, path = "",
5533
5713
  return combineUrlPath(endpoint, gatewayPath);
5534
5714
  }
5535
5715
  function pushKeyQueryParams(params, key) {
5536
- if (key.length > 0) {
5537
- params.append("rvt-key", key.join(","));
5716
+ const rvtKey = actorKeyToGatewayQuery(key);
5717
+ if (rvtKey !== void 0) {
5718
+ params.append("rvt-key", rvtKey);
5538
5719
  }
5539
5720
  }
5540
5721
  function pushInputQueryParam(params, input, maxInputSize) {
@@ -5716,8 +5897,8 @@ async function updateRunnerConfig(config, runnerName, request) {
5716
5897
  return apiCall(
5717
5898
  config,
5718
5899
  "PUT",
5719
- `/runner-configs/${runnerName}`,
5720
- request
5900
+ `/pools/${encodeURIComponent(runnerName)}`,
5901
+ Object.values(request.datacenters)[0]
5721
5902
  );
5722
5903
  }
5723
5904
 
@@ -6050,7 +6231,7 @@ var RemoteEngineControlClient = class {
6050
6231
  datacenter: region,
6051
6232
  name,
6052
6233
  key: serializeActorKey(key),
6053
- runner_name_selector: poolName ?? this.#config.poolName,
6234
+ pool: poolName ?? this.#config.poolName,
6054
6235
  input: actorInput ? uint8ArrayToBase64(
6055
6236
  encodeCborCompat(actorInput)
6056
6237
  ) : void 0,
@@ -6103,7 +6284,7 @@ var RemoteEngineControlClient = class {
6103
6284
  (config) => createActor(config, {
6104
6285
  datacenter: region,
6105
6286
  name,
6106
- runner_name_selector: poolName ?? this.#config.poolName,
6287
+ pool: poolName ?? this.#config.poolName,
6107
6288
  key: serializeActorKey(key),
6108
6289
  input: input ? uint8ArrayToBase64(
6109
6290
  encodeCborCompat(input)
@@ -6369,4 +6550,4 @@ export {
6369
6550
  updateRunnerConfig,
6370
6551
  RemoteEngineControlClient
6371
6552
  };
6372
- //# sourceMappingURL=chunk-PJ5EXY6F.js.map
6553
+ //# sourceMappingURL=chunk-62WFU3BQ.js.map