rivetkit 0.0.0-feat-sqlite-sync.32022a9 → 0.0.0-feat-sqlite-sync-3x.a00b07f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/dist/browser/client.d.ts +58 -9
  2. package/dist/browser/client.js +193 -23
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.js +1 -5
  5. package/dist/browser/inspector/client.js.map +1 -1
  6. package/dist/tsup/agent-os/index.cjs +3 -2652
  7. package/dist/tsup/agent-os/index.cjs.map +1 -1
  8. package/dist/tsup/agent-os/index.d.cts +1 -2758
  9. package/dist/tsup/agent-os/index.d.ts +1 -2758
  10. package/dist/tsup/agent-os/index.js +3 -2652
  11. package/dist/tsup/agent-os/index.js.map +1 -1
  12. package/dist/tsup/{chunk-6ZHUGY2E.cjs → chunk-3JPXBFED.cjs} +4 -4
  13. package/dist/tsup/{chunk-6ZHUGY2E.cjs.map → chunk-3JPXBFED.cjs.map} +1 -1
  14. package/dist/tsup/{chunk-6VNQCLKF.js → chunk-5X35FD2T.js} +4 -4
  15. package/dist/tsup/{chunk-BJGWUWNE.js → chunk-6QNBANXM.js} +3 -3
  16. package/dist/tsup/{chunk-Z6IVW2Y5.js → chunk-7HILY7QU.js} +188 -28
  17. package/dist/tsup/chunk-7HILY7QU.js.map +1 -0
  18. package/dist/tsup/{chunk-JI6GZ2C2.js → chunk-A2CF6PFH.js} +18 -1
  19. package/dist/tsup/chunk-A2CF6PFH.js.map +1 -0
  20. package/dist/tsup/{chunk-7XBDAFGQ.cjs → chunk-CT6GQRUN.cjs} +3 -3
  21. package/dist/tsup/{chunk-7XBDAFGQ.cjs.map → chunk-CT6GQRUN.cjs.map} +1 -1
  22. package/dist/tsup/{chunk-M27XAZNI.js → chunk-DRZTELHJ.js} +10 -14
  23. package/dist/tsup/chunk-DRZTELHJ.js.map +1 -0
  24. package/dist/tsup/{chunk-EDJKDOI2.js → chunk-DUGEPEJO.js} +2 -2
  25. package/dist/tsup/{chunk-PMU5EDGT.cjs → chunk-EA6P3N4I.cjs} +3 -3
  26. package/dist/tsup/{chunk-PMU5EDGT.cjs.map → chunk-EA6P3N4I.cjs.map} +1 -1
  27. package/dist/tsup/{chunk-WE7D64FW.cjs → chunk-ERZDCOQ3.cjs} +10 -10
  28. package/dist/tsup/{chunk-WE7D64FW.cjs.map → chunk-ERZDCOQ3.cjs.map} +1 -1
  29. package/dist/tsup/{chunk-UZ5O42HF.js → chunk-GHTA76HT.js} +2 -2
  30. package/dist/tsup/{chunk-IAVZH6HH.js → chunk-ID5VJNZY.js} +2 -2
  31. package/dist/tsup/{chunk-2LRKNNQJ.cjs → chunk-PXIOH445.cjs} +327 -167
  32. package/dist/tsup/chunk-PXIOH445.cjs.map +1 -0
  33. package/dist/tsup/{chunk-MYWZCDML.cjs → chunk-RTWH3AX3.cjs} +19 -2
  34. package/dist/tsup/chunk-RTWH3AX3.cjs.map +1 -0
  35. package/dist/tsup/{chunk-5LBUG2IK.cjs → chunk-UV4KDO4W.cjs} +3 -3
  36. package/dist/tsup/{chunk-5LBUG2IK.cjs.map → chunk-UV4KDO4W.cjs.map} +1 -1
  37. package/dist/tsup/{chunk-HHALUH4L.js → chunk-VI2S336K.js} +2 -2
  38. package/dist/tsup/{chunk-6BRDJRCZ.cjs → chunk-W7NPIYWC.cjs} +10 -14
  39. package/dist/tsup/chunk-W7NPIYWC.cjs.map +1 -0
  40. package/dist/tsup/{chunk-4SIQMCXI.cjs → chunk-ZZQM77UA.cjs} +7 -7
  41. package/dist/tsup/{chunk-4SIQMCXI.cjs.map → chunk-ZZQM77UA.cjs.map} +1 -1
  42. package/dist/tsup/client/mod.cjs +6 -6
  43. package/dist/tsup/client/mod.d.cts +15 -3
  44. package/dist/tsup/client/mod.d.ts +15 -3
  45. package/dist/tsup/client/mod.js +5 -5
  46. package/dist/tsup/common/log.cjs +2 -2
  47. package/dist/tsup/common/log.js +1 -1
  48. package/dist/tsup/common/websocket.cjs +3 -3
  49. package/dist/tsup/common/websocket.js +2 -2
  50. package/dist/tsup/{config-DfVrAigH.d.ts → config-B4erdavw.d.ts} +43 -12
  51. package/dist/tsup/{config-BaUctMNL.d.cts → config-BfG1qpYz.d.cts} +7 -1
  52. package/dist/tsup/{config-BaUctMNL.d.ts → config-BfG1qpYz.d.ts} +7 -1
  53. package/dist/tsup/{config-D6T6Ud_V.d.cts → config-DK144OAw.d.cts} +43 -12
  54. package/dist/tsup/{context-CowF_zyQ.d.cts → context-Cvnf3BRe.d.cts} +2 -2
  55. package/dist/tsup/{context-BsFWwi3i.d.ts → context-Oxi6YWcG.d.ts} +2 -2
  56. package/dist/tsup/db/drizzle.cjs +2 -2
  57. package/dist/tsup/db/drizzle.d.cts +1 -1
  58. package/dist/tsup/db/drizzle.d.ts +1 -1
  59. package/dist/tsup/db/drizzle.js +1 -1
  60. package/dist/tsup/db/mod.cjs +3 -3
  61. package/dist/tsup/db/mod.d.cts +2 -2
  62. package/dist/tsup/db/mod.d.ts +2 -2
  63. package/dist/tsup/db/mod.js +2 -2
  64. package/dist/tsup/dynamic/mod.d.cts +2 -2
  65. package/dist/tsup/dynamic/mod.d.ts +2 -2
  66. package/dist/tsup/inspector/mod.cjs +5 -5
  67. package/dist/tsup/inspector/mod.js +4 -4
  68. package/dist/tsup/inspector/workflow.cjs +4 -4
  69. package/dist/tsup/inspector/workflow.js +3 -3
  70. package/dist/tsup/inspector-tab/mod.d.cts +3 -3
  71. package/dist/tsup/inspector-tab/mod.d.ts +3 -3
  72. package/dist/tsup/mod.cjs +256 -174
  73. package/dist/tsup/mod.cjs.map +1 -1
  74. package/dist/tsup/mod.d.cts +4 -4
  75. package/dist/tsup/mod.d.ts +4 -4
  76. package/dist/tsup/mod.js +170 -88
  77. package/dist/tsup/mod.js.map +1 -1
  78. package/dist/tsup/test/mod.cjs +7 -7
  79. package/dist/tsup/test/mod.d.cts +2 -2
  80. package/dist/tsup/test/mod.d.ts +2 -2
  81. package/dist/tsup/test/mod.js +5 -5
  82. package/dist/tsup/unstable/migrations.d.cts +1 -1
  83. package/dist/tsup/unstable/migrations.d.ts +1 -1
  84. package/dist/tsup/utils.cjs +2 -2
  85. package/dist/tsup/utils.js +1 -1
  86. package/dist/tsup/workflow/mod.cjs +17 -17
  87. package/dist/tsup/workflow/mod.d.cts +4 -4
  88. package/dist/tsup/workflow/mod.d.ts +4 -4
  89. package/dist/tsup/workflow/mod.js +5 -5
  90. package/package.json +9 -13
  91. package/src/actor/keys.ts +86 -0
  92. package/src/agent-os/index.ts +5 -65
  93. package/src/client/actor-conn.ts +92 -6
  94. package/src/client/actor-handle.ts +24 -4
  95. package/src/client/client.ts +14 -4
  96. package/src/client/config.ts +12 -1
  97. package/src/client/lifecycle-errors.ts +16 -1
  98. package/src/client/retry-budget.ts +78 -0
  99. package/src/client/utils.ts +13 -2
  100. package/src/common/database/config.ts +7 -1
  101. package/src/common/database/native-database.ts +17 -9
  102. package/src/common/router.ts +1 -1
  103. package/src/engine-api/actors.ts +3 -3
  104. package/src/engine-client/actor-websocket-client.ts +4 -2
  105. package/src/engine-client/api-endpoints.ts +44 -14
  106. package/src/engine-client/mod.ts +2 -2
  107. package/src/registry/config/envoy.ts +1 -1
  108. package/src/registry/config/index.ts +28 -31
  109. package/src/registry/index.ts +51 -19
  110. package/src/registry/napi-runtime.ts +3 -2
  111. package/src/registry/native.ts +129 -40
  112. package/src/registry/runtime.ts +27 -10
  113. package/src/registry/wasm-runtime.ts +6 -3
  114. package/src/utils/env-vars.ts +15 -10
  115. package/dist/tsup/chunk-2LRKNNQJ.cjs.map +0 -1
  116. package/dist/tsup/chunk-6BRDJRCZ.cjs.map +0 -1
  117. package/dist/tsup/chunk-JI6GZ2C2.js.map +0 -1
  118. package/dist/tsup/chunk-M27XAZNI.js.map +0 -1
  119. package/dist/tsup/chunk-MYWZCDML.cjs.map +0 -1
  120. package/dist/tsup/chunk-Z6IVW2Y5.js.map +0 -1
  121. package/src/actor/config.test.ts +0 -78
  122. package/src/actor/keys.test.ts +0 -275
  123. package/src/actor/utils.test.ts +0 -48
  124. package/src/agent-os/actor/cron.ts +0 -84
  125. package/src/agent-os/actor/db.ts +0 -54
  126. package/src/agent-os/actor/filesystem.ts +0 -131
  127. package/src/agent-os/actor/index.ts +0 -285
  128. package/src/agent-os/actor/network.ts +0 -58
  129. package/src/agent-os/actor/preview.ts +0 -190
  130. package/src/agent-os/actor/process.ts +0 -177
  131. package/src/agent-os/actor/session.ts +0 -518
  132. package/src/agent-os/actor/shell.ts +0 -60
  133. package/src/agent-os/config.ts +0 -79
  134. package/src/agent-os/fs/database-vfs.ts +0 -624
  135. package/src/agent-os/types.ts +0 -148
  136. package/src/client/test.ts +0 -44
  137. package/src/client/token-provider.test.ts +0 -86
  138. package/src/common/database/mod.test.ts +0 -364
  139. package/src/common/database/native-database.test.ts +0 -241
  140. package/src/common/inline-websocket-adapter.test.ts +0 -51
  141. package/src/db/drizzle.test.ts +0 -164
  142. package/src/registry/config/index.test.ts +0 -25
  143. package/src/registry/run-handler-coordinator.test.ts +0 -252
  144. package/src/registry/runtime.test.ts +0 -124
  145. package/src/unstable/migrations.test.ts +0 -170
  146. package/src/utils/endpoint-parser.test.ts +0 -206
  147. package/src/utils.test.ts +0 -34
  148. package/src/workflow/driver.test.ts +0 -62
  149. /package/dist/tsup/{chunk-6VNQCLKF.js.map → chunk-5X35FD2T.js.map} +0 -0
  150. /package/dist/tsup/{chunk-BJGWUWNE.js.map → chunk-6QNBANXM.js.map} +0 -0
  151. /package/dist/tsup/{chunk-EDJKDOI2.js.map → chunk-DUGEPEJO.js.map} +0 -0
  152. /package/dist/tsup/{chunk-UZ5O42HF.js.map → chunk-GHTA76HT.js.map} +0 -0
  153. /package/dist/tsup/{chunk-IAVZH6HH.js.map → chunk-ID5VJNZY.js.map} +0 -0
  154. /package/dist/tsup/{chunk-HHALUH4L.js.map → chunk-VI2S336K.js.map} +0 -0
@@ -51,7 +51,13 @@ interface SqliteTransactionOptions {
51
51
  * to change without notice.
52
52
  */
53
53
  interface SqliteProfilingOptions {
54
- enabled?: boolean;
54
+ /** Exact SQL statements to give fingerprint labels. Profiling defaults to actor
55
+ * aggregates without fingerprint labels. Profile logs remain enabled.
56
+ * RIVETKIT_SQLITE_PROFILING overrides selection with a JSON object containing
57
+ * queries and/or fingerprints arrays. An empty object clears fingerprint selection. */
58
+ queries?: string[];
59
+ /** Exact query fingerprints to label separately, as reported in profile logs. */
60
+ fingerprints?: string[];
55
61
  maxTrackedStatementFingerprints?: number;
56
62
  maxTrackedTransactionFingerprints?: number;
57
63
  maxPrometheusSeries?: number;
@@ -780,6 +786,8 @@ interface RuntimeServeConfig {
780
786
  engineBinaryPath?: string;
781
787
  startServices?: boolean;
782
788
  servicesBinaryPath?: string;
789
+ /** Whether config resolution selected a managed local development engine. */
790
+ engineSpawn?: boolean;
783
791
  engineHost?: string;
784
792
  enginePort?: number;
785
793
  handleInspectorHttpInRuntime?: boolean;
@@ -868,7 +876,12 @@ interface CoreRuntime {
868
876
  createCancellationToken(): CancellationTokenHandle;
869
877
  cancellationTokenAborted(token: CancellationTokenHandle): boolean;
870
878
  cancelCancellationToken(token: CancellationTokenHandle): void;
871
- onCancellationTokenCancelled(token: CancellationTokenHandle, callback: (...args: unknown[]) => unknown): void;
879
+ /**
880
+ * Calls `callback` once when `token` is cancelled. Returns a release
881
+ * function that drops the registration without calling `callback`; call it
882
+ * once cancellation no longer matters so the native listener is freed.
883
+ */
884
+ onCancellationTokenCancelled(token: CancellationTokenHandle, callback: (...args: unknown[]) => unknown): () => void;
872
885
  actorState(ctx: ActorContextHandle): RuntimeBytes;
873
886
  actorBeginOnStateChange(ctx: ActorContextHandle): void;
874
887
  actorEndOnStateChange(ctx: ActorContextHandle): void;
@@ -1272,6 +1285,27 @@ declare class ActorConnRaw {
1272
1285
  */
1273
1286
  type ActorConn<AD extends AnyActorDefinition> = Omit<ActorConnRaw, "send" | "on" | "once"> & ActorDefinitionQueueSend<AD> & ActorDefinitionEventSubscriptions<AD> & ActorDefinitionActions<AD>;
1274
1287
 
1288
+ /** How many retries a client may spend, as a share of the requests it sends. */
1289
+ interface RetryBudgetOptions {
1290
+ /** Retries allowed per 100 requests (default 10). */
1291
+ percent?: number;
1292
+ /** Retries the client can bank for a burst of refusals; the budget starts full (default 100). */
1293
+ maxTokens?: number;
1294
+ }
1295
+ /**
1296
+ * Bounds the client's retries of refused requests. Each request adds a fraction of a token and
1297
+ * each retry spends one, so retries stay a fixed share of traffic while the service sheds load
1298
+ * instead of multiplying it.
1299
+ */
1300
+ declare class RetryBudget {
1301
+ #private;
1302
+ constructor(options?: RetryBudgetOptions);
1303
+ /** Credits one request sent. */
1304
+ deposit(): void;
1305
+ /** Spends one token. Returns `false` when the budget is spent. */
1306
+ tryWithdraw(): boolean;
1307
+ }
1308
+
1275
1309
  /**
1276
1310
  * Provides underlying functions for stateless {@link ActorHandle} for action calls.
1277
1311
  * Similar to ActorConnRaw but doesn't maintain a connection.
@@ -1287,7 +1321,7 @@ declare class ActorHandleRaw {
1287
1321
  *
1288
1322
  * @protected
1289
1323
  */
1290
- constructor(client: any, driver: EngineControlClient, params: unknown, getParams: (() => Promise<unknown>) | undefined, encoding: Encoding, actorResolutionState: ActorResolutionState, gatewayOptions?: ActorGatewayOptions, signal?: AbortSignal, currentActorInvocation?: CurrentActorInvocation, startCallSpan?: StartCallSpan);
1324
+ constructor(client: any, driver: EngineControlClient, params: unknown, getParams: (() => Promise<unknown>) | undefined, encoding: Encoding, actorResolutionState: ActorResolutionState, gatewayOptions?: ActorGatewayOptions, signal?: AbortSignal, currentActorInvocation?: CurrentActorInvocation, startCallSpan?: StartCallSpan, retryBudget?: RetryBudget);
1291
1325
  send(name: string, body: unknown, options: QueueSendWaitOptions): Promise<QueueSendResult>;
1292
1326
  send(name: string, body: unknown, options?: QueueSendNoWaitOptions): Promise<void>;
1293
1327
  /**
@@ -1371,6 +1405,10 @@ declare const ClientConfigSchema: z$1.ZodPipe<z$1.ZodObject<{
1371
1405
  skipReadyWait: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
1372
1406
  }, z$1.core.$strip>>>;
1373
1407
  getUpgradeWebSocket: z$1.ZodOptional<z$1.ZodCustom<GetUpgradeWebSocket, GetUpgradeWebSocket>>;
1408
+ retryBudget: z$1.ZodOptional<z$1.ZodObject<{
1409
+ percent: z$1.ZodOptional<z$1.ZodNumber>;
1410
+ maxTokens: z$1.ZodOptional<z$1.ZodNumber>;
1411
+ }, z$1.core.$strip>>;
1374
1412
  fetch: z$1.ZodOptional<z$1.ZodCustom<typeof fetch, typeof fetch>>;
1375
1413
  disableMetadataLookup: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
1376
1414
  maxInputSize: z$1.ZodDefault<z$1.ZodNumber>;
@@ -1390,6 +1428,10 @@ declare const ClientConfigSchema: z$1.ZodPipe<z$1.ZodObject<{
1390
1428
  devtools: boolean;
1391
1429
  getToken?: GetToken | undefined;
1392
1430
  getUpgradeWebSocket?: GetUpgradeWebSocket | undefined;
1431
+ retryBudget?: {
1432
+ percent?: number | undefined;
1433
+ maxTokens?: number | undefined;
1434
+ } | undefined;
1393
1435
  fetch?: typeof fetch | undefined;
1394
1436
  }, {
1395
1437
  endpoint: string;
@@ -1406,6 +1448,10 @@ declare const ClientConfigSchema: z$1.ZodPipe<z$1.ZodObject<{
1406
1448
  devtools: boolean;
1407
1449
  getToken?: GetToken | undefined;
1408
1450
  getUpgradeWebSocket?: GetUpgradeWebSocket | undefined;
1451
+ retryBudget?: {
1452
+ percent?: number | undefined;
1453
+ maxTokens?: number | undefined;
1454
+ } | undefined;
1409
1455
  fetch?: typeof fetch | undefined;
1410
1456
  }>>;
1411
1457
  type ClientConfigInput = z$1.input<typeof ClientConfigSchema>;
@@ -1554,6 +1600,8 @@ declare const CREATE_ACTOR_CONN_PROXY: unique symbol;
1554
1600
  interface ClientRawOptions {
1555
1601
  encoding?: Encoding;
1556
1602
  gateway?: ActorGatewayOptions;
1603
+ /** Bounds retries of refused requests across every handle of this client. */
1604
+ retryBudget?: RetryBudgetOptions;
1557
1605
  }
1558
1606
  /** Runtime-supplied wiring for clients created inside an actor. Set only by the native runtime. */
1559
1607
  interface ActorClientRuntimeOptions {
@@ -2349,11 +2397,11 @@ declare const RegistryConfigSchema: z$2.ZodPipe<z$2.ZodObject<{
2349
2397
  publicEndpoint: z$2.ZodPipe<z$2.ZodOptional<z$2.ZodString>, z$2.ZodTransform<string | undefined, string | undefined>>;
2350
2398
  publicToken: z$2.ZodPipe<z$2.ZodOptional<z$2.ZodString>, z$2.ZodTransform<string | undefined, string | undefined>>;
2351
2399
  }, z$2.core.$strip>>>;
2352
- envoy: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodObject<{
2400
+ node: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodObject<{
2353
2401
  poolName: z$2.ZodDefault<z$2.ZodString>;
2354
2402
  version: z$2.ZodDefault<z$2.ZodNumber>;
2355
2403
  totalSlots: z$2.ZodDefault<z$2.ZodNumber>;
2356
- envoyKey: z$2.ZodOptional<z$2.ZodString>;
2404
+ nodeKey: z$2.ZodOptional<z$2.ZodString>;
2357
2405
  }, z$2.core.$strip>>>;
2358
2406
  shutdown: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodObject<{
2359
2407
  gracePeriodMs: z$2.ZodOptional<z$2.ZodNumber>;
@@ -2364,6 +2412,7 @@ declare const RegistryConfigSchema: z$2.ZodPipe<z$2.ZodObject<{
2364
2412
  backend: "local" | "remote";
2365
2413
  } | undefined;
2366
2414
  endpoint: string | undefined;
2415
+ engineSpawn: boolean;
2367
2416
  startServices: boolean;
2368
2417
  namespace: string;
2369
2418
  token: string | undefined;
@@ -2403,11 +2452,11 @@ declare const RegistryConfigSchema: z$2.ZodPipe<z$2.ZodObject<{
2403
2452
  engineHost: string;
2404
2453
  enginePort: number;
2405
2454
  engineVersion: string;
2406
- envoy: {
2455
+ node: {
2407
2456
  poolName: string;
2408
2457
  version: number;
2409
2458
  totalSlots: number;
2410
- envoyKey?: string | undefined;
2459
+ nodeKey?: string | undefined;
2411
2460
  };
2412
2461
  shutdown: {
2413
2462
  disableSignalHandlers: boolean;
@@ -2464,11 +2513,11 @@ declare const RegistryConfigSchema: z$2.ZodPipe<z$2.ZodObject<{
2464
2513
  publicEndpoint: string | undefined;
2465
2514
  publicToken: string | undefined;
2466
2515
  };
2467
- envoy: {
2516
+ node: {
2468
2517
  poolName: string;
2469
2518
  version: number;
2470
2519
  totalSlots: number;
2471
- envoyKey?: string | undefined;
2520
+ nodeKey?: string | undefined;
2472
2521
  };
2473
2522
  shutdown: {
2474
2523
  disableSignalHandlers: boolean;
@@ -230,7 +230,7 @@ function noopNext() {
230
230
  // package.json
231
231
  var package_default = {
232
232
  name: "rivetkit",
233
- version: "0.0.0-feat-sqlite-sync.32022a9",
233
+ version: "0.0.0-feat-sqlite-sync-3x.a00b07f",
234
234
  description: "Lightweight libraries for building stateful actors on edge platforms",
235
235
  license: "Apache-2.0",
236
236
  keywords: [
@@ -440,8 +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/agent-os-core": "^0.1.1",
444
- "@rivet-dev/services": "^0.2.0",
445
443
  "@rivetkit/bare-ts": "^0.6.2",
446
444
  "@rivetkit/engine-api-full": "workspace:*",
447
445
  "@rivetkit/engine-cli": "workspace:*",
@@ -468,8 +466,6 @@ var package_default = {
468
466
  "@hono/node-server": "^1.18.2",
469
467
  "@hono/node-ws": "^1.1.1",
470
468
  "@opentelemetry/sdk-trace-node": "2.11.0",
471
- "@rivet-dev/agent-os-common": "*",
472
- "@rivet-dev/agent-os-pi": "^0.1.1",
473
469
  "@standard-schema/spec": "^1.0.0",
474
470
  "@types/invariant": "^2",
475
471
  "@types/node": "^22.13.1",
@@ -1155,6 +1151,22 @@ function deserializeActorKey(keyString) {
1155
1151
  }
1156
1152
  return parts;
1157
1153
  }
1154
+ var CANONICAL_SEPARATOR = ",";
1155
+ var CANONICAL_EMPTY_PART = "\\0";
1156
+ function encodeActorKey(key) {
1157
+ return key.map((part) => {
1158
+ if (part === "") {
1159
+ return CANONICAL_EMPTY_PART;
1160
+ }
1161
+ return part.replace(/\\/g, "\\\\").replace(/,/g, "\\,");
1162
+ }).join(CANONICAL_SEPARATOR);
1163
+ }
1164
+ function actorKeyToGatewayQuery(key) {
1165
+ if (key.length === 0) {
1166
+ return void 0;
1167
+ }
1168
+ return encodeActorKey(key);
1169
+ }
1158
1170
 
1159
1171
  // src/client/token-provider.ts
1160
1172
  function isInvalidToken(group, code) {
@@ -1467,6 +1479,14 @@ var ClientConfigSchemaBase = z3.object({
1467
1479
  // This is required in the client config in order to support
1468
1480
  // `proxyWebSocket`
1469
1481
  getUpgradeWebSocket: z3.custom().optional(),
1482
+ /**
1483
+ * Bounds retries of refused requests: `percent` retries per 100 requests (default 10), with
1484
+ * up to `maxTokens` banked for bursts (default 100). A refusal past the budget is thrown.
1485
+ */
1486
+ retryBudget: z3.object({
1487
+ percent: z3.number().min(0).max(100).optional(),
1488
+ maxTokens: z3.number().int().min(0).optional()
1489
+ }).optional(),
1470
1490
  /** Replaces global fetch for actor HTTP gateway requests. */
1471
1491
  fetch: z3.custom().optional(),
1472
1492
  /** Whether to automatically perform health checks when the client is created. */
@@ -1783,8 +1803,9 @@ function buildActorQueryGatewayUrl(endpoint, namespace, query, token, path = "",
1783
1803
  return combineUrlPath(endpoint, gatewayPath);
1784
1804
  }
1785
1805
  function pushKeyQueryParams(params, key) {
1786
- if (key.length > 0) {
1787
- params.append("rvt-key", key.join(","));
1806
+ const rvtKey = actorKeyToGatewayQuery(key);
1807
+ if (rvtKey !== void 0) {
1808
+ params.append("rvt-key", rvtKey);
1788
1809
  }
1789
1810
  }
1790
1811
  function pushInputQueryParam(params, input, maxInputSize) {
@@ -3873,17 +3894,22 @@ function internalClientError(message, opts) {
3873
3894
  }
3874
3895
 
3875
3896
  // src/client/utils.ts
3897
+ var RETRY_AFTER_SUFFIX = /^retry_after_ms=(\d+)$/;
3876
3898
  function parseWebSocketCloseReason(reason) {
3877
- const [mainPart, rayId] = reason.split("#");
3899
+ const [mainPart, suffix] = reason.split("#");
3878
3900
  const [group, code] = mainPart.split(".");
3879
3901
  if (!group || !code) {
3880
3902
  logger2().warn({ msg: "failed to parse close reason", reason });
3881
3903
  return void 0;
3882
3904
  }
3905
+ const retryAfter = suffix?.match(RETRY_AFTER_SUFFIX);
3906
+ if (retryAfter) {
3907
+ return { group, code, retryAfterMs: Number(retryAfter[1]) };
3908
+ }
3883
3909
  return {
3884
3910
  group,
3885
3911
  code,
3886
- rayId
3912
+ rayId: suffix
3887
3913
  };
3888
3914
  }
3889
3915
  function messageLength(message) {
@@ -4462,7 +4488,7 @@ var RemoteEngineControlClient = class {
4462
4488
  datacenter: region,
4463
4489
  name,
4464
4490
  key: serializeActorKey(key),
4465
- runner_name_selector: poolName ?? this.#config.poolName,
4491
+ pool: poolName ?? this.#config.poolName,
4466
4492
  input: actorInput ? uint8ArrayToBase64(
4467
4493
  encodeCborCompat(actorInput)
4468
4494
  ) : void 0,
@@ -4515,7 +4541,7 @@ var RemoteEngineControlClient = class {
4515
4541
  (config) => createActor(config, {
4516
4542
  datacenter: region,
4517
4543
  name,
4518
- runner_name_selector: poolName ?? this.#config.poolName,
4544
+ pool: poolName ?? this.#config.poolName,
4519
4545
  key: serializeActorKey(key),
4520
4546
  input: input ? uint8ArrayToBase64(
4521
4547
  encodeCborCompat(input)
@@ -4819,6 +4845,56 @@ async function checkForSchedulingError(group, code, actorId, query, driver, rayI
4819
4845
  return null;
4820
4846
  }
4821
4847
 
4848
+ // src/client/retry-budget.ts
4849
+ var DEFAULT_PERCENT = 10;
4850
+ var DEFAULT_MAX_TOKENS = 100;
4851
+ var RetryBudget = class {
4852
+ #tokens;
4853
+ #maxTokens;
4854
+ #deposit;
4855
+ constructor(options = {}) {
4856
+ const percent = options.percent ?? DEFAULT_PERCENT;
4857
+ const maxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;
4858
+ if (!(percent >= 0 && percent <= 100)) {
4859
+ throw new Error("retryBudget.percent must be in 0..=100");
4860
+ }
4861
+ if (!(maxTokens >= 0)) {
4862
+ throw new Error("retryBudget.maxTokens must be at least 0");
4863
+ }
4864
+ this.#maxTokens = maxTokens;
4865
+ this.#tokens = maxTokens;
4866
+ this.#deposit = percent / 100;
4867
+ }
4868
+ /** Credits one request sent. */
4869
+ deposit() {
4870
+ this.#tokens = Math.min(this.#maxTokens, this.#tokens + this.#deposit);
4871
+ }
4872
+ /** Spends one token. Returns `false` when the budget is spent. */
4873
+ tryWithdraw() {
4874
+ if (this.#tokens + 1e-9 < 1) {
4875
+ return false;
4876
+ }
4877
+ this.#tokens = Math.max(0, this.#tokens - 1);
4878
+ return true;
4879
+ }
4880
+ };
4881
+ function retryAfterMs(error) {
4882
+ if (!(error instanceof RivetError)) {
4883
+ return void 0;
4884
+ }
4885
+ const metadata = error.metadata;
4886
+ if (metadata === null || typeof metadata !== "object") {
4887
+ return void 0;
4888
+ }
4889
+ const hint = metadata.retry_after_ms;
4890
+ return typeof hint === "number" && hint >= 0 ? hint : void 0;
4891
+ }
4892
+ function retryDelayMs(attempt, opts) {
4893
+ const backoff = Math.min(opts.initialDelayMs * 2 ** attempt, opts.maxDelayMs);
4894
+ const jittered = backoff / 2 + Math.random() * (backoff / 2);
4895
+ return Math.max(jittered, opts.hintMs ?? 0);
4896
+ }
4897
+
4822
4898
  // src/client/lifecycle-errors.ts
4823
4899
  function* walkErrorChain(error, maxDepth = 8) {
4824
4900
  let current = error;
@@ -4996,6 +5072,7 @@ async function retryOnLifecycleBoundary(run, opts) {
4996
5072
  const maxAttempts = opts?.maxAttempts ?? 5;
4997
5073
  const initialDelayMs = opts?.initialDelayMs ?? 25;
4998
5074
  const maxDelayMs = opts?.maxDelayMs ?? 200;
5075
+ opts?.budget?.deposit();
4999
5076
  let lastError;
5000
5077
  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
5001
5078
  throwIfAborted(opts?.signal);
@@ -5009,7 +5086,14 @@ async function retryOnLifecycleBoundary(run, opts) {
5009
5086
  if (attempt === maxAttempts - 1) {
5010
5087
  break;
5011
5088
  }
5012
- const delayMs = Math.min(initialDelayMs * 2 ** attempt, maxDelayMs);
5089
+ if (opts?.budget && !opts.budget.tryWithdraw()) {
5090
+ break;
5091
+ }
5092
+ const delayMs = retryDelayMs(attempt, {
5093
+ initialDelayMs,
5094
+ maxDelayMs,
5095
+ hintMs: retryAfterMs(error)
5096
+ });
5013
5097
  await waitWithSignal(delayMs, opts?.signal);
5014
5098
  }
5015
5099
  }
@@ -5160,6 +5244,10 @@ function createQueueSender(senderOptions) {
5160
5244
  }
5161
5245
 
5162
5246
  // src/client/actor-conn.ts
5247
+ var CONNECT_TIMEOUT_MS = 2e4;
5248
+ function isConnectionOpenTimeout(error) {
5249
+ return error instanceof RivetError && error.group === "client" && error.code === "connection_open_timeout";
5250
+ }
5163
5251
  var CONNECT_SYMBOL = /* @__PURE__ */ Symbol("connect");
5164
5252
  var ActorConnRaw = class {
5165
5253
  #disposed = false;
@@ -5187,6 +5275,8 @@ var ActorConnRaw = class {
5187
5275
  #keepNodeAliveInterval;
5188
5276
  /** Promise used to indicate the socket has connected successfully. This will be rejected if the connection fails. */
5189
5277
  #onOpenPromise;
5278
+ /** Sockets given up on by the connect timeout. Their late events are ignored. */
5279
+ #abandonedSockets = /* @__PURE__ */ new WeakSet();
5190
5280
  #websocket;
5191
5281
  #authRetryAvailable = true;
5192
5282
  #client;
@@ -5374,12 +5464,16 @@ var ActorConnRaw = class {
5374
5464
  forever: true,
5375
5465
  minTimeout: 250,
5376
5466
  maxTimeout: 3e4,
5377
- onFailedAttempt: (error) => {
5467
+ onFailedAttempt: async (error) => {
5378
5468
  logger2().warn({
5379
5469
  msg: "failed to reconnect",
5380
5470
  attempt: error.attemptNumber,
5381
5471
  error: stringifyError(error)
5382
5472
  });
5473
+ const hintMs = retryAfterMs(error);
5474
+ if (hintMs !== void 0) {
5475
+ await new Promise((resolve) => setTimeout(resolve, hintMs));
5476
+ }
5383
5477
  },
5384
5478
  // Cancel retry if aborted
5385
5479
  signal: this.#abortController.signal
@@ -5405,7 +5499,7 @@ var ActorConnRaw = class {
5405
5499
  })
5406
5500
  );
5407
5501
  await this.#connectWebSocket();
5408
- await this.#onOpenPromise.promise;
5502
+ await this.#waitForOpen(this.#onOpenPromise.promise);
5409
5503
  } catch (error) {
5410
5504
  if (this.#shouldRetryConnectionOpenError(error)) {
5411
5505
  throw error;
@@ -5427,10 +5521,63 @@ var ActorConnRaw = class {
5427
5521
  this.#onOpenPromise = void 0;
5428
5522
  }
5429
5523
  }
5524
+ /**
5525
+ * Waits for the actor's Init on the current socket, up to {@link CONNECT_TIMEOUT_MS}. A socket
5526
+ * can stay connecting with no open, error or close event, as when the engine holds the
5527
+ * upgrade or a refused connect reports only an error. On timeout the socket is abandoned
5528
+ * and closed, and the retryable `client.connection_open_timeout` starts the next attempt.
5529
+ */
5530
+ async #waitForOpen(open) {
5531
+ let timer;
5532
+ const timedOut = new Promise((_, reject) => {
5533
+ timer = setTimeout(() => {
5534
+ reject(
5535
+ new RivetError(
5536
+ "client",
5537
+ "connection_open_timeout",
5538
+ `Connection did not open within ${CONNECT_TIMEOUT_MS} ms`
5539
+ )
5540
+ );
5541
+ }, CONNECT_TIMEOUT_MS);
5542
+ });
5543
+ try {
5544
+ await Promise.race([open, timedOut]);
5545
+ } catch (error) {
5546
+ if (isConnectionOpenTimeout(error)) {
5547
+ this.#abandonCurrentSocket();
5548
+ }
5549
+ throw error;
5550
+ } finally {
5551
+ clearTimeout(timer);
5552
+ }
5553
+ }
5554
+ #abandonCurrentSocket() {
5555
+ const ws = this.#websocket;
5556
+ if (!ws) return;
5557
+ this.#websocket = void 0;
5558
+ this.#abandonedSockets.add(ws);
5559
+ logger2().warn({
5560
+ msg: "connection did not open in time, retrying",
5561
+ connId: this.#connId,
5562
+ readyState: ws.readyState,
5563
+ timeoutMs: CONNECT_TIMEOUT_MS
5564
+ });
5565
+ try {
5566
+ ws.close(1e3, "Connect timeout");
5567
+ } catch (err) {
5568
+ logger2().debug({
5569
+ msg: "failed to close abandoned websocket",
5570
+ error: stringifyError(err)
5571
+ });
5572
+ }
5573
+ }
5430
5574
  #shouldRetryConnectionOpenError(error) {
5431
5575
  if (error instanceof ActorConnDisposed) {
5432
5576
  return false;
5433
5577
  }
5578
+ if (isConnectionOpenTimeout(error)) {
5579
+ return true;
5580
+ }
5434
5581
  if (error instanceof RivetError && isInvalidToken(error.group, error.code) && this.#driver.refreshAuthToken && this.#authRetryAvailable) {
5435
5582
  this.#authRetryAvailable = false;
5436
5583
  return true;
@@ -5490,12 +5637,14 @@ var ActorConnRaw = class {
5490
5637
  });
5491
5638
  this.#websocket = ws;
5492
5639
  ws.addEventListener("open", () => {
5640
+ if (this.#abandonedSockets.has(ws)) return;
5493
5641
  logger2().debug({
5494
5642
  msg: "client websocket open",
5495
5643
  connId: this.#connId
5496
5644
  });
5497
5645
  });
5498
5646
  ws.addEventListener("message", async (ev) => {
5647
+ if (this.#abandonedSockets.has(ws)) return;
5499
5648
  try {
5500
5649
  await this.#handleOnMessage(ev.data);
5501
5650
  } catch (err) {
@@ -5506,6 +5655,7 @@ var ActorConnRaw = class {
5506
5655
  }
5507
5656
  });
5508
5657
  ws.addEventListener("close", async (ev) => {
5658
+ if (this.#abandonedSockets.has(ws)) return;
5509
5659
  try {
5510
5660
  await this.#handleOnClose(ev);
5511
5661
  } catch (err) {
@@ -5516,6 +5666,7 @@ var ActorConnRaw = class {
5516
5666
  }
5517
5667
  });
5518
5668
  ws.addEventListener("error", () => {
5669
+ if (this.#abandonedSockets.has(ws)) return;
5519
5670
  try {
5520
5671
  this.#handleOnError();
5521
5672
  } catch (err) {
@@ -5722,7 +5873,8 @@ var ActorConnRaw = class {
5722
5873
  const reason = closeEvent.reason || "";
5723
5874
  const parsed = parseWebSocketCloseReason(reason);
5724
5875
  if (parsed) {
5725
- const { group, code, rayId } = parsed;
5876
+ const { group, code, rayId, retryAfterMs: retryAfterMs2 } = parsed;
5877
+ const closeOptions = retryAfterMs2 === void 0 ? { rayId } : { rayId, metadata: { retry_after_ms: retryAfterMs2 } };
5726
5878
  if (isInvalidToken(group, code) && closeEvent.code === 1008 && failedSocket) {
5727
5879
  try {
5728
5880
  if (!await this.#driver.refreshAuthToken?.(
@@ -5744,7 +5896,7 @@ var ActorConnRaw = class {
5744
5896
  group,
5745
5897
  code,
5746
5898
  `Connection closed: ${reason}`,
5747
- { rayId }
5899
+ closeOptions
5748
5900
  )
5749
5901
  );
5750
5902
  return;
@@ -5765,7 +5917,7 @@ var ActorConnRaw = class {
5765
5917
  group,
5766
5918
  code,
5767
5919
  `Connection closed: ${reason}`,
5768
- { rayId }
5920
+ closeOptions
5769
5921
  );
5770
5922
  }
5771
5923
  } else {
@@ -5773,7 +5925,7 @@ var ActorConnRaw = class {
5773
5925
  group,
5774
5926
  code,
5775
5927
  `Connection closed: ${reason}`,
5776
- { rayId }
5928
+ closeOptions
5777
5929
  );
5778
5930
  }
5779
5931
  this.#invalidateActorIfStale(group, code);
@@ -6457,6 +6609,7 @@ var ActorHandleRaw = class {
6457
6609
  #queueSendMutex = new AsyncMutex();
6458
6610
  #currentActorInvocation;
6459
6611
  #startCallSpan;
6612
+ #retryBudget;
6460
6613
  /**
6461
6614
  * Do not call this directly.
6462
6615
  *
@@ -6464,7 +6617,7 @@ var ActorHandleRaw = class {
6464
6617
  *
6465
6618
  * @protected
6466
6619
  */
6467
- constructor(client, driver, params, getParams, encoding, actorResolutionState, gatewayOptions = {}, signal, currentActorInvocation, startCallSpan) {
6620
+ constructor(client, driver, params, getParams, encoding, actorResolutionState, gatewayOptions = {}, signal, currentActorInvocation, startCallSpan, retryBudget = new RetryBudget()) {
6468
6621
  this.#client = client;
6469
6622
  this.#driver = driver;
6470
6623
  this.#encoding = encoding;
@@ -6475,6 +6628,7 @@ var ActorHandleRaw = class {
6475
6628
  this.#signal = signal;
6476
6629
  this.#currentActorInvocation = currentActorInvocation;
6477
6630
  this.#startCallSpan = startCallSpan;
6631
+ this.#retryBudget = retryBudget;
6478
6632
  }
6479
6633
  async #resolveConnectionParams() {
6480
6634
  if (this.#getParams) {
@@ -6491,6 +6645,7 @@ var ActorHandleRaw = class {
6491
6645
  let useQueryTarget = isDynamicActorQuery(
6492
6646
  this.#actorResolutionState
6493
6647
  );
6648
+ this.#retryBudget.deposit();
6494
6649
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
6495
6650
  let actorId;
6496
6651
  try {
@@ -6524,8 +6679,17 @@ var ActorHandleRaw = class {
6524
6679
  metadata,
6525
6680
  attempt,
6526
6681
  maxAttempts
6527
- )) {
6528
- await this.#waitForRetryWindow();
6682
+ ) && this.#retryBudget.tryWithdraw()) {
6683
+ await new Promise(
6684
+ (resolve) => setTimeout(
6685
+ resolve,
6686
+ retryDelayMs(attempt, {
6687
+ initialDelayMs: 25,
6688
+ maxDelayMs: 1e3,
6689
+ hintMs: retryAfterMs(err)
6690
+ })
6691
+ )
6692
+ );
6529
6693
  continue;
6530
6694
  }
6531
6695
  if (await this.#shouldRetrySchedulingError(
@@ -6600,7 +6764,10 @@ var ActorHandleRaw = class {
6600
6764
  if (opts.name === "destroy") {
6601
6765
  return await run();
6602
6766
  }
6603
- return await retryOnLifecycleBoundary(run, { signal });
6767
+ return await retryOnLifecycleBoundary(run, {
6768
+ signal,
6769
+ budget: this.#retryBudget
6770
+ });
6604
6771
  };
6605
6772
  if (!call) {
6606
6773
  return await send();
@@ -7140,6 +7307,7 @@ var ClientRaw = class {
7140
7307
  #gatewayOptions;
7141
7308
  #currentActorInvocation;
7142
7309
  #startCallSpan;
7310
+ #retryBudget;
7143
7311
  /**
7144
7312
  * Creates an instance of Client.
7145
7313
  */
@@ -7152,6 +7320,7 @@ var ClientRaw = class {
7152
7320
  this.#gatewayOptions = options.gateway ?? {};
7153
7321
  this.#currentActorInvocation = options.currentActorInvocation;
7154
7322
  this.#startCallSpan = options.startCallSpan;
7323
+ this.#retryBudget = new RetryBudget(options.retryBudget);
7155
7324
  }
7156
7325
  /**
7157
7326
  * Gets a stateless handle to a actor by its ID.
@@ -7309,7 +7478,8 @@ var ClientRaw = class {
7309
7478
  this.#gatewayOptions,
7310
7479
  signal,
7311
7480
  this.#currentActorInvocation,
7312
- this.#startCallSpan
7481
+ this.#startCallSpan,
7482
+ this.#retryBudget
7313
7483
  );
7314
7484
  }
7315
7485
  [CREATE_ACTOR_CONN_PROXY](conn) {