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
@@ -230,7 +230,7 @@ function noopNext() {
230
230
  // package.json
231
231
  var package_default = {
232
232
  name: "rivetkit",
233
- version: "0.0.0-sqlite-query-metrics-v2.f5d3605",
233
+ version: "0.0.0-sqlite-query-metrics-v3.1dff84f",
234
234
  description: "Lightweight libraries for building stateful actors on edge platforms",
235
235
  license: "Apache-2.0",
236
236
  keywords: [
@@ -440,7 +440,6 @@ var package_default = {
440
440
  dependencies: {
441
441
  "@hono/zod-openapi": "^1.1.5",
442
442
  "@opentelemetry/api": "^1.1.0",
443
- "@rivet-dev/services": "^0.2.3",
444
443
  "@rivetkit/bare-ts": "^0.6.2",
445
444
  "@rivetkit/engine-api-full": "workspace:*",
446
445
  "@rivetkit/engine-cli": "workspace:*",
@@ -479,6 +478,9 @@ var package_default = {
479
478
  vitest: "^3.1.1",
480
479
  ws: "^8.18.1"
481
480
  },
481
+ optionalDependencies: {
482
+ "@rivet-dev/services": "^0.2.5"
483
+ },
482
484
  peerDependencies: {
483
485
  "drizzle-kit": "^0.31.2",
484
486
  eventsource: "^4.0.0",
@@ -1152,6 +1154,22 @@ function deserializeActorKey(keyString) {
1152
1154
  }
1153
1155
  return parts;
1154
1156
  }
1157
+ var CANONICAL_SEPARATOR = ",";
1158
+ var CANONICAL_EMPTY_PART = "\\0";
1159
+ function encodeActorKey(key) {
1160
+ return key.map((part) => {
1161
+ if (part === "") {
1162
+ return CANONICAL_EMPTY_PART;
1163
+ }
1164
+ return part.replace(/\\/g, "\\\\").replace(/,/g, "\\,");
1165
+ }).join(CANONICAL_SEPARATOR);
1166
+ }
1167
+ function actorKeyToGatewayQuery(key) {
1168
+ if (key.length === 0) {
1169
+ return void 0;
1170
+ }
1171
+ return encodeActorKey(key);
1172
+ }
1155
1173
 
1156
1174
  // src/client/token-provider.ts
1157
1175
  function isInvalidToken(group, code) {
@@ -1464,6 +1482,14 @@ var ClientConfigSchemaBase = z3.object({
1464
1482
  // This is required in the client config in order to support
1465
1483
  // `proxyWebSocket`
1466
1484
  getUpgradeWebSocket: z3.custom().optional(),
1485
+ /**
1486
+ * Bounds retries of refused requests: `percent` retries per 100 requests (default 10), with
1487
+ * up to `maxTokens` banked for bursts (default 100). A refusal past the budget is thrown.
1488
+ */
1489
+ retryBudget: z3.object({
1490
+ percent: z3.number().min(0).max(100).optional(),
1491
+ maxTokens: z3.number().int().min(0).optional()
1492
+ }).optional(),
1467
1493
  /** Replaces global fetch for actor HTTP gateway requests. */
1468
1494
  fetch: z3.custom().optional(),
1469
1495
  /** Whether to automatically perform health checks when the client is created. */
@@ -1780,8 +1806,9 @@ function buildActorQueryGatewayUrl(endpoint, namespace, query, token, path = "",
1780
1806
  return combineUrlPath(endpoint, gatewayPath);
1781
1807
  }
1782
1808
  function pushKeyQueryParams(params, key) {
1783
- if (key.length > 0) {
1784
- params.append("rvt-key", key.join(","));
1809
+ const rvtKey = actorKeyToGatewayQuery(key);
1810
+ if (rvtKey !== void 0) {
1811
+ params.append("rvt-key", rvtKey);
1785
1812
  }
1786
1813
  }
1787
1814
  function pushInputQueryParam(params, input, maxInputSize) {
@@ -3870,17 +3897,22 @@ function internalClientError(message, opts) {
3870
3897
  }
3871
3898
 
3872
3899
  // src/client/utils.ts
3900
+ var RETRY_AFTER_SUFFIX = /^retry_after_ms=(\d+)$/;
3873
3901
  function parseWebSocketCloseReason(reason) {
3874
- const [mainPart, rayId] = reason.split("#");
3902
+ const [mainPart, suffix] = reason.split("#");
3875
3903
  const [group, code] = mainPart.split(".");
3876
3904
  if (!group || !code) {
3877
3905
  logger2().warn({ msg: "failed to parse close reason", reason });
3878
3906
  return void 0;
3879
3907
  }
3908
+ const retryAfter = suffix?.match(RETRY_AFTER_SUFFIX);
3909
+ if (retryAfter) {
3910
+ return { group, code, retryAfterMs: Number(retryAfter[1]) };
3911
+ }
3880
3912
  return {
3881
3913
  group,
3882
3914
  code,
3883
- rayId
3915
+ rayId: suffix
3884
3916
  };
3885
3917
  }
3886
3918
  function messageLength(message) {
@@ -3937,6 +3969,9 @@ async function sendHttpRequest(opts) {
3937
3969
  })
3938
3970
  );
3939
3971
  } catch (error) {
3972
+ if (RivetError.isRivetError(error)) {
3973
+ throw error;
3974
+ }
3940
3975
  throw new HttpRequestError(`Request failed: ${error}`, {
3941
3976
  cause: error
3942
3977
  });
@@ -4459,7 +4494,7 @@ var RemoteEngineControlClient = class {
4459
4494
  datacenter: region,
4460
4495
  name,
4461
4496
  key: serializeActorKey(key),
4462
- runner_name_selector: poolName ?? this.#config.poolName,
4497
+ pool: poolName ?? this.#config.poolName,
4463
4498
  input: actorInput ? uint8ArrayToBase64(
4464
4499
  encodeCborCompat(actorInput)
4465
4500
  ) : void 0,
@@ -4512,7 +4547,7 @@ var RemoteEngineControlClient = class {
4512
4547
  (config) => createActor(config, {
4513
4548
  datacenter: region,
4514
4549
  name,
4515
- runner_name_selector: poolName ?? this.#config.poolName,
4550
+ pool: poolName ?? this.#config.poolName,
4516
4551
  key: serializeActorKey(key),
4517
4552
  input: input ? uint8ArrayToBase64(
4518
4553
  encodeCborCompat(input)
@@ -4816,6 +4851,56 @@ async function checkForSchedulingError(group, code, actorId, query, driver, rayI
4816
4851
  return null;
4817
4852
  }
4818
4853
 
4854
+ // src/client/retry-budget.ts
4855
+ var DEFAULT_PERCENT = 10;
4856
+ var DEFAULT_MAX_TOKENS = 100;
4857
+ var RetryBudget = class {
4858
+ #tokens;
4859
+ #maxTokens;
4860
+ #deposit;
4861
+ constructor(options = {}) {
4862
+ const percent = options.percent ?? DEFAULT_PERCENT;
4863
+ const maxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;
4864
+ if (!(percent >= 0 && percent <= 100)) {
4865
+ throw new Error("retryBudget.percent must be in 0..=100");
4866
+ }
4867
+ if (!(maxTokens >= 0)) {
4868
+ throw new Error("retryBudget.maxTokens must be at least 0");
4869
+ }
4870
+ this.#maxTokens = maxTokens;
4871
+ this.#tokens = maxTokens;
4872
+ this.#deposit = percent / 100;
4873
+ }
4874
+ /** Credits one request sent. */
4875
+ deposit() {
4876
+ this.#tokens = Math.min(this.#maxTokens, this.#tokens + this.#deposit);
4877
+ }
4878
+ /** Spends one token. Returns `false` when the budget is spent. */
4879
+ tryWithdraw() {
4880
+ if (this.#tokens + 1e-9 < 1) {
4881
+ return false;
4882
+ }
4883
+ this.#tokens = Math.max(0, this.#tokens - 1);
4884
+ return true;
4885
+ }
4886
+ };
4887
+ function retryAfterMs(error) {
4888
+ if (!(error instanceof RivetError)) {
4889
+ return void 0;
4890
+ }
4891
+ const metadata = error.metadata;
4892
+ if (metadata === null || typeof metadata !== "object") {
4893
+ return void 0;
4894
+ }
4895
+ const hint = metadata.retry_after_ms;
4896
+ return typeof hint === "number" && hint >= 0 ? hint : void 0;
4897
+ }
4898
+ function retryDelayMs(attempt, opts) {
4899
+ const backoff = Math.min(opts.initialDelayMs * 2 ** attempt, opts.maxDelayMs);
4900
+ const jittered = backoff / 2 + Math.random() * (backoff / 2);
4901
+ return Math.max(jittered, opts.hintMs ?? 0);
4902
+ }
4903
+
4819
4904
  // src/client/lifecycle-errors.ts
4820
4905
  function* walkErrorChain(error, maxDepth = 8) {
4821
4906
  let current = error;
@@ -4844,7 +4929,7 @@ function classifyActorError(error) {
4844
4929
  if (error.group === "actor" && error.code === "stopping" && error.message.includes("database accessed after actor stopped")) {
4845
4930
  return void 0;
4846
4931
  }
4847
- if (error.group === "actor" && error.code === "restarting") {
4932
+ if (error.group === "actor" && (error.code === "restarting" || error.code === "migrating_from_v2")) {
4848
4933
  return buildLifecycleBoundaryInfo(
4849
4934
  "request_retry",
4850
4935
  "actor_error",
@@ -4855,6 +4940,14 @@ function classifyActorError(error) {
4855
4940
  }
4856
4941
  );
4857
4942
  }
4943
+ if (error.group === "ups" && error.code === "consumer_closed" || error.group === "depot" && error.code === "request_deadline_exceeded") {
4944
+ return buildLifecycleBoundaryInfo(
4945
+ "reconnect_only",
4946
+ "actor_error",
4947
+ error.message,
4948
+ { group: error.group, code: error.code }
4949
+ );
4950
+ }
4858
4951
  if (error.group === "guard" && isRetryableGuardGatewayHttpError(error.code)) {
4859
4952
  return buildLifecycleBoundaryInfo(
4860
4953
  "request_retry",
@@ -4993,6 +5086,7 @@ async function retryOnLifecycleBoundary(run, opts) {
4993
5086
  const maxAttempts = opts?.maxAttempts ?? 5;
4994
5087
  const initialDelayMs = opts?.initialDelayMs ?? 25;
4995
5088
  const maxDelayMs = opts?.maxDelayMs ?? 200;
5089
+ opts?.budget?.deposit();
4996
5090
  let lastError;
4997
5091
  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
4998
5092
  throwIfAborted(opts?.signal);
@@ -5006,7 +5100,14 @@ async function retryOnLifecycleBoundary(run, opts) {
5006
5100
  if (attempt === maxAttempts - 1) {
5007
5101
  break;
5008
5102
  }
5009
- const delayMs = Math.min(initialDelayMs * 2 ** attempt, maxDelayMs);
5103
+ if (opts?.budget && !opts.budget.tryWithdraw()) {
5104
+ break;
5105
+ }
5106
+ const delayMs = retryDelayMs(attempt, {
5107
+ initialDelayMs,
5108
+ maxDelayMs,
5109
+ hintMs: retryAfterMs(error)
5110
+ });
5010
5111
  await waitWithSignal(delayMs, opts?.signal);
5011
5112
  }
5012
5113
  }
@@ -5157,12 +5258,18 @@ function createQueueSender(senderOptions) {
5157
5258
  }
5158
5259
 
5159
5260
  // src/client/actor-conn.ts
5261
+ var CONNECT_TIMEOUT_MS = 2e4;
5262
+ function isConnectionOpenTimeout(error) {
5263
+ return error instanceof RivetError && error.group === "client" && error.code === "connection_open_timeout";
5264
+ }
5160
5265
  var CONNECT_SYMBOL = /* @__PURE__ */ Symbol("connect");
5161
5266
  var ActorConnRaw = class {
5162
5267
  #disposed = false;
5163
5268
  /* Will be aborted on dispose. */
5164
5269
  #abortController = new AbortController();
5165
5270
  #connStatus = "idle";
5271
+ /** The opening failure that stopped retries. Later actions must fail instead of queueing. */
5272
+ #connectionOpenError;
5166
5273
  #actorId;
5167
5274
  #connId;
5168
5275
  #messageQueue = [];
@@ -5184,6 +5291,8 @@ var ActorConnRaw = class {
5184
5291
  #keepNodeAliveInterval;
5185
5292
  /** Promise used to indicate the socket has connected successfully. This will be rejected if the connection fails. */
5186
5293
  #onOpenPromise;
5294
+ /** Sockets given up on by the connect timeout. Their late events are ignored. */
5295
+ #abandonedSockets = /* @__PURE__ */ new WeakSet();
5187
5296
  #websocket;
5188
5297
  #authRetryAvailable = true;
5189
5298
  #client;
@@ -5279,6 +5388,8 @@ var ActorConnRaw = class {
5279
5388
  `Invalid action call: expected an options object { name, args }, got ${typeof opts}. Use conn.actionName(...args) for the shorthand API.`
5280
5389
  );
5281
5390
  }
5391
+ if (this.#disposed) throw new ActorConnDisposed();
5392
+ if (this.#connectionOpenError) throw this.#connectionOpenError;
5282
5393
  logger2().debug({ msg: "action", name: opts.name, args: opts.args });
5283
5394
  const actionId = this.#actionIdCounter;
5284
5395
  this.#actionIdCounter += 1;
@@ -5366,17 +5477,22 @@ var ActorConnRaw = class {
5366
5477
  }
5367
5478
  }
5368
5479
  #connectWithRetry() {
5480
+ this.#connectionOpenError = void 0;
5369
5481
  this.#setConnStatus("connecting");
5370
5482
  pRetry2(this.#connectAndWait.bind(this), {
5371
5483
  forever: true,
5372
5484
  minTimeout: 250,
5373
5485
  maxTimeout: 3e4,
5374
- onFailedAttempt: (error) => {
5486
+ onFailedAttempt: async (error) => {
5375
5487
  logger2().warn({
5376
5488
  msg: "failed to reconnect",
5377
5489
  attempt: error.attemptNumber,
5378
5490
  error: stringifyError(error)
5379
5491
  });
5492
+ const hintMs = retryAfterMs(error);
5493
+ if (hintMs !== void 0) {
5494
+ await new Promise((resolve) => setTimeout(resolve, hintMs));
5495
+ }
5380
5496
  },
5381
5497
  // Cancel retry if aborted
5382
5498
  signal: this.#abortController.signal
@@ -5402,8 +5518,11 @@ var ActorConnRaw = class {
5402
5518
  })
5403
5519
  );
5404
5520
  await this.#connectWebSocket();
5405
- await this.#onOpenPromise.promise;
5521
+ await this.#waitForOpen(this.#onOpenPromise.promise);
5406
5522
  } catch (error) {
5523
+ this.#abandonCurrentSocket(
5524
+ isConnectionOpenTimeout(error) ? "Connect timeout" : "Connection opening failed"
5525
+ );
5407
5526
  if (this.#shouldRetryConnectionOpenError(error)) {
5408
5527
  throw error;
5409
5528
  }
@@ -5413,7 +5532,7 @@ var ActorConnRaw = class {
5413
5532
  `Failed to open connection: ${stringifyError(error)}`,
5414
5533
  { error: stringifyError(error) }
5415
5534
  );
5416
- this.#clearQueuedMessages();
5535
+ this.#connectionOpenError = actorError;
5417
5536
  this.#rejectPendingPromises(actorError, false);
5418
5537
  this.#dispatchActorError(actorError);
5419
5538
  this.#setConnStatus("idle");
@@ -5424,10 +5543,61 @@ var ActorConnRaw = class {
5424
5543
  this.#onOpenPromise = void 0;
5425
5544
  }
5426
5545
  }
5546
+ /**
5547
+ * Waits for the actor's Init on the current socket, up to {@link CONNECT_TIMEOUT_MS}. A socket
5548
+ * can stay connecting with no open, error or close event, as when the engine holds the
5549
+ * upgrade or a refused connect reports only an error. On timeout the socket is abandoned
5550
+ * and closed, and the retryable `client.connection_open_timeout` starts the next attempt.
5551
+ */
5552
+ async #waitForOpen(open) {
5553
+ let timer;
5554
+ const timedOut = new Promise((_, reject) => {
5555
+ timer = setTimeout(() => {
5556
+ reject(
5557
+ new RivetError(
5558
+ "client",
5559
+ "connection_open_timeout",
5560
+ `Connection did not open within ${CONNECT_TIMEOUT_MS} ms`
5561
+ )
5562
+ );
5563
+ }, CONNECT_TIMEOUT_MS);
5564
+ });
5565
+ try {
5566
+ await Promise.race([open, timedOut]);
5567
+ } finally {
5568
+ clearTimeout(timer);
5569
+ }
5570
+ }
5571
+ #abandonCurrentSocket(reason) {
5572
+ const ws = this.#websocket;
5573
+ if (!ws) return;
5574
+ this.#websocket = void 0;
5575
+ this.#abandonedSockets.add(ws);
5576
+ logger2().debug({
5577
+ msg: "closing failed connection attempt",
5578
+ connId: this.#connId,
5579
+ readyState: ws.readyState,
5580
+ reason
5581
+ });
5582
+ try {
5583
+ ws.close(1e3, reason);
5584
+ } catch (err) {
5585
+ logger2().debug({
5586
+ msg: "failed to close abandoned websocket",
5587
+ error: stringifyError(err)
5588
+ });
5589
+ }
5590
+ }
5427
5591
  #shouldRetryConnectionOpenError(error) {
5428
5592
  if (error instanceof ActorConnDisposed) {
5429
5593
  return false;
5430
5594
  }
5595
+ if (isConnectionOpenTimeout(error)) {
5596
+ return true;
5597
+ }
5598
+ if (error instanceof RivetError && error.group === "client" && error.code === "connection_open_interrupted") {
5599
+ return true;
5600
+ }
5431
5601
  if (error instanceof RivetError && isInvalidToken(error.group, error.code) && this.#driver.refreshAuthToken && this.#authRetryAvailable) {
5432
5602
  this.#authRetryAvailable = false;
5433
5603
  return true;
@@ -5487,14 +5657,18 @@ var ActorConnRaw = class {
5487
5657
  });
5488
5658
  this.#websocket = ws;
5489
5659
  ws.addEventListener("open", () => {
5660
+ if (this.#websocket !== ws || this.#abandonedSockets.has(ws))
5661
+ return;
5490
5662
  logger2().debug({
5491
5663
  msg: "client websocket open",
5492
5664
  connId: this.#connId
5493
5665
  });
5494
5666
  });
5495
5667
  ws.addEventListener("message", async (ev) => {
5668
+ if (this.#websocket !== ws || this.#abandonedSockets.has(ws))
5669
+ return;
5496
5670
  try {
5497
- await this.#handleOnMessage(ev.data);
5671
+ await this.#handleOnMessage(ev.data, ws);
5498
5672
  } catch (err) {
5499
5673
  logger2().error({
5500
5674
  msg: "error in websocket message handler",
@@ -5503,6 +5677,8 @@ var ActorConnRaw = class {
5503
5677
  }
5504
5678
  });
5505
5679
  ws.addEventListener("close", async (ev) => {
5680
+ if (this.#websocket !== ws || this.#abandonedSockets.has(ws))
5681
+ return;
5506
5682
  try {
5507
5683
  await this.#handleOnClose(ev);
5508
5684
  } catch (err) {
@@ -5513,6 +5689,8 @@ var ActorConnRaw = class {
5513
5689
  }
5514
5690
  });
5515
5691
  ws.addEventListener("error", () => {
5692
+ if (this.#websocket !== ws || this.#abandonedSockets.has(ws))
5693
+ return;
5516
5694
  try {
5517
5695
  this.#handleOnError();
5518
5696
  } catch (err) {
@@ -5578,7 +5756,7 @@ var ActorConnRaw = class {
5578
5756
  });
5579
5757
  }
5580
5758
  /** Called by the onmessage event from drivers. */
5581
- async #handleOnMessage(data) {
5759
+ async #handleOnMessage(data, socket) {
5582
5760
  logger2().trace({
5583
5761
  msg: "received message",
5584
5762
  dataType: typeof data,
@@ -5586,6 +5764,8 @@ var ActorConnRaw = class {
5586
5764
  isArrayBuffer: data instanceof ArrayBuffer
5587
5765
  });
5588
5766
  const response = await this.#parseMessage(data);
5767
+ if (this.#websocket !== socket || this.#abandonedSockets.has(socket))
5768
+ return;
5589
5769
  logger2().trace(
5590
5770
  getLogMessage() ? {
5591
5771
  msg: "parsed message",
@@ -5657,18 +5837,15 @@ var ActorConnRaw = class {
5657
5837
  this.#actorResolutionState,
5658
5838
  this.#driver
5659
5839
  );
5840
+ if (this.#websocket !== socket || this.#abandonedSockets.has(socket)) {
5841
+ return;
5842
+ }
5660
5843
  if (schedulingError) {
5661
5844
  errorToThrow = schedulingError;
5662
5845
  }
5663
5846
  }
5664
- if (this.#onOpenPromise) {
5665
- this.#onOpenPromise.reject(errorToThrow);
5666
- }
5667
5847
  this.#invalidateActorIfStale(group, code);
5668
- for (const [id, inFlight] of this.#actionsInFlight.entries()) {
5669
- inFlight.reject(errorToThrow);
5670
- this.#actionsInFlight.delete(id);
5671
- }
5848
+ this.#rejectPendingPromises(errorToThrow, false);
5672
5849
  this.#dispatchActorError(errorToThrow);
5673
5850
  }
5674
5851
  } else if (response.body.tag === "ActionResponse") {
@@ -5719,7 +5896,8 @@ var ActorConnRaw = class {
5719
5896
  const reason = closeEvent.reason || "";
5720
5897
  const parsed = parseWebSocketCloseReason(reason);
5721
5898
  if (parsed) {
5722
- const { group, code, rayId } = parsed;
5899
+ const { group, code, rayId, retryAfterMs: retryAfterMs2 } = parsed;
5900
+ const closeOptions = retryAfterMs2 === void 0 ? { rayId } : { rayId, metadata: { retry_after_ms: retryAfterMs2 } };
5723
5901
  if (isInvalidToken(group, code) && closeEvent.code === 1008 && failedSocket) {
5724
5902
  try {
5725
5903
  if (!await this.#driver.refreshAuthToken?.(
@@ -5741,7 +5919,7 @@ var ActorConnRaw = class {
5741
5919
  group,
5742
5920
  code,
5743
5921
  `Connection closed: ${reason}`,
5744
- { rayId }
5922
+ closeOptions
5745
5923
  )
5746
5924
  );
5747
5925
  return;
@@ -5762,7 +5940,7 @@ var ActorConnRaw = class {
5762
5940
  group,
5763
5941
  code,
5764
5942
  `Connection closed: ${reason}`,
5765
- { rayId }
5943
+ closeOptions
5766
5944
  );
5767
5945
  }
5768
5946
  } else {
@@ -5770,14 +5948,17 @@ var ActorConnRaw = class {
5770
5948
  group,
5771
5949
  code,
5772
5950
  `Connection closed: ${reason}`,
5773
- { rayId }
5951
+ closeOptions
5774
5952
  );
5775
5953
  }
5776
5954
  this.#invalidateActorIfStale(group, code);
5777
5955
  } else {
5778
- error = new Error(
5779
- `${wasClean ? "Connection closed" : "Connection lost"} (code: ${closeEvent.code}, reason: ${reason})`
5780
- );
5956
+ const message = `${wasClean ? "Connection closed" : "Connection lost"} (code: ${closeEvent.code}, reason: ${reason})`;
5957
+ error = !wasConnected && closeEvent.code === 1006 ? new RivetError(
5958
+ "client",
5959
+ "connection_open_interrupted",
5960
+ message
5961
+ ) : new Error(message);
5781
5962
  }
5782
5963
  this.#rejectPendingPromises(error, false);
5783
5964
  if (error instanceof RivetError) {
@@ -5793,6 +5974,7 @@ var ActorConnRaw = class {
5793
5974
  }
5794
5975
  }
5795
5976
  #rejectPendingPromises(error, suppressUnhandled) {
5977
+ this.#clearQueuedMessages();
5796
5978
  if (this.#onOpenPromise) {
5797
5979
  if (suppressUnhandled) {
5798
5980
  this.#onOpenPromise.promise.catch(() => {
@@ -6359,8 +6541,23 @@ async function rawHttpFetch(driver, target, params, input, init, options = {}, t
6359
6541
  });
6360
6542
  return driver.sendRequest(target, proxyRequest, options);
6361
6543
  } catch (err) {
6362
- const { group, code, message, metadata, rayId, actor } = deconstructError(err, true);
6363
- throw new RivetError(group, code, message, { metadata, rayId, actor });
6544
+ const {
6545
+ group,
6546
+ code,
6547
+ message,
6548
+ metadata,
6549
+ rayId,
6550
+ actor,
6551
+ public: isPublic,
6552
+ statusCode
6553
+ } = deconstructError(err, true);
6554
+ throw new RivetError(group, code, message, {
6555
+ public: isPublic,
6556
+ statusCode,
6557
+ metadata,
6558
+ rayId,
6559
+ actor
6560
+ });
6364
6561
  }
6365
6562
  }
6366
6563
  async function rawWebSocket(driver, target, params, path, _protocols, options = {}) {
@@ -6454,6 +6651,7 @@ var ActorHandleRaw = class {
6454
6651
  #queueSendMutex = new AsyncMutex();
6455
6652
  #currentActorInvocation;
6456
6653
  #startCallSpan;
6654
+ #retryBudget;
6457
6655
  /**
6458
6656
  * Do not call this directly.
6459
6657
  *
@@ -6461,7 +6659,7 @@ var ActorHandleRaw = class {
6461
6659
  *
6462
6660
  * @protected
6463
6661
  */
6464
- constructor(client, driver, params, getParams, encoding, actorResolutionState, gatewayOptions = {}, signal, currentActorInvocation, startCallSpan) {
6662
+ constructor(client, driver, params, getParams, encoding, actorResolutionState, gatewayOptions = {}, signal, currentActorInvocation, startCallSpan, retryBudget = new RetryBudget()) {
6465
6663
  this.#client = client;
6466
6664
  this.#driver = driver;
6467
6665
  this.#encoding = encoding;
@@ -6472,6 +6670,7 @@ var ActorHandleRaw = class {
6472
6670
  this.#signal = signal;
6473
6671
  this.#currentActorInvocation = currentActorInvocation;
6474
6672
  this.#startCallSpan = startCallSpan;
6673
+ this.#retryBudget = retryBudget;
6475
6674
  }
6476
6675
  async #resolveConnectionParams() {
6477
6676
  if (this.#getParams) {
@@ -6488,6 +6687,7 @@ var ActorHandleRaw = class {
6488
6687
  let useQueryTarget = isDynamicActorQuery(
6489
6688
  this.#actorResolutionState
6490
6689
  );
6690
+ this.#retryBudget.deposit();
6491
6691
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
6492
6692
  let actorId;
6493
6693
  try {
@@ -6514,15 +6714,33 @@ var ActorHandleRaw = class {
6514
6714
  }
6515
6715
  }).send(name, body, options);
6516
6716
  } catch (err) {
6517
- const { group, code, message, metadata, rayId, actor } = deconstructError(err, true);
6717
+ const {
6718
+ group,
6719
+ code,
6720
+ message,
6721
+ metadata,
6722
+ rayId,
6723
+ actor,
6724
+ public: isPublic,
6725
+ statusCode
6726
+ } = deconstructError(err, true);
6518
6727
  if (this.#shouldRetryQueueDispatchOverload(
6519
6728
  group,
6520
6729
  code,
6521
6730
  metadata,
6522
6731
  attempt,
6523
6732
  maxAttempts
6524
- )) {
6525
- await this.#waitForRetryWindow();
6733
+ ) && this.#retryBudget.tryWithdraw()) {
6734
+ await new Promise(
6735
+ (resolve) => setTimeout(
6736
+ resolve,
6737
+ retryDelayMs(attempt, {
6738
+ initialDelayMs: 25,
6739
+ maxDelayMs: 1e3,
6740
+ hintMs: retryAfterMs(err)
6741
+ })
6742
+ )
6743
+ );
6526
6744
  continue;
6527
6745
  }
6528
6746
  if (await this.#shouldRetrySchedulingError(
@@ -6561,6 +6779,8 @@ var ActorHandleRaw = class {
6561
6779
  continue;
6562
6780
  }
6563
6781
  throw new RivetError(group, code, message, {
6782
+ public: isPublic,
6783
+ statusCode,
6564
6784
  metadata,
6565
6785
  rayId,
6566
6786
  actor
@@ -6597,7 +6817,10 @@ var ActorHandleRaw = class {
6597
6817
  if (opts.name === "destroy") {
6598
6818
  return await run();
6599
6819
  }
6600
- return await retryOnLifecycleBoundary(run, { signal });
6820
+ return await retryOnLifecycleBoundary(run, {
6821
+ signal,
6822
+ budget: this.#retryBudget
6823
+ });
6601
6824
  };
6602
6825
  if (!call) {
6603
6826
  return await send();
@@ -6681,7 +6904,16 @@ var ActorHandleRaw = class {
6681
6904
  }
6682
6905
  return output;
6683
6906
  } catch (err) {
6684
- const { group, code, message, metadata, rayId, actor } = deconstructError(err, true);
6907
+ const {
6908
+ group,
6909
+ code,
6910
+ message,
6911
+ metadata,
6912
+ rayId,
6913
+ actor,
6914
+ public: isPublic,
6915
+ statusCode
6916
+ } = deconstructError(err, true);
6685
6917
  if (await this.#shouldRetrySchedulingError(
6686
6918
  group,
6687
6919
  code,
@@ -6710,7 +6942,13 @@ var ActorHandleRaw = class {
6710
6942
  "actor",
6711
6943
  "not_found",
6712
6944
  "The actor does not exist or was destroyed.",
6713
- { metadata, rayId, actor }
6945
+ {
6946
+ public: true,
6947
+ statusCode: 404,
6948
+ metadata,
6949
+ rayId,
6950
+ actor
6951
+ }
6714
6952
  );
6715
6953
  }
6716
6954
  const invalidated = this.#invalidateResolvedActorId(
@@ -6727,6 +6965,8 @@ var ActorHandleRaw = class {
6727
6965
  continue;
6728
6966
  }
6729
6967
  throw new RivetError(group, code, message, {
6968
+ public: isPublic,
6969
+ statusCode,
6730
6970
  metadata,
6731
6971
  rayId,
6732
6972
  actor
@@ -6913,7 +7153,16 @@ var ActorHandleRaw = class {
6913
7153
  }
6914
7154
  return response;
6915
7155
  } catch (err) {
6916
- const { group, code, message, metadata, rayId, actor } = deconstructError(err, true);
7156
+ const {
7157
+ group,
7158
+ code,
7159
+ message,
7160
+ metadata,
7161
+ rayId,
7162
+ actor,
7163
+ public: isPublic,
7164
+ statusCode
7165
+ } = deconstructError(err, true);
6917
7166
  if (await this.#shouldRetrySchedulingError(
6918
7167
  group,
6919
7168
  code,
@@ -6950,6 +7199,8 @@ var ActorHandleRaw = class {
6950
7199
  continue;
6951
7200
  }
6952
7201
  throw new RivetError(group, code, message, {
7202
+ public: isPublic,
7203
+ statusCode,
6953
7204
  metadata,
6954
7205
  rayId,
6955
7206
  actor
@@ -7137,6 +7388,7 @@ var ClientRaw = class {
7137
7388
  #gatewayOptions;
7138
7389
  #currentActorInvocation;
7139
7390
  #startCallSpan;
7391
+ #retryBudget;
7140
7392
  /**
7141
7393
  * Creates an instance of Client.
7142
7394
  */
@@ -7149,6 +7401,7 @@ var ClientRaw = class {
7149
7401
  this.#gatewayOptions = options.gateway ?? {};
7150
7402
  this.#currentActorInvocation = options.currentActorInvocation;
7151
7403
  this.#startCallSpan = options.startCallSpan;
7404
+ this.#retryBudget = new RetryBudget(options.retryBudget);
7152
7405
  }
7153
7406
  /**
7154
7407
  * Gets a stateless handle to a actor by its ID.
@@ -7306,7 +7559,8 @@ var ClientRaw = class {
7306
7559
  this.#gatewayOptions,
7307
7560
  signal,
7308
7561
  this.#currentActorInvocation,
7309
- this.#startCallSpan
7562
+ this.#startCallSpan,
7563
+ this.#retryBudget
7310
7564
  );
7311
7565
  }
7312
7566
  [CREATE_ACTOR_CONN_PROXY](conn) {