rivetkit 3.0.7 → 3.1.0

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 (111) hide show
  1. package/dist/browser/client.d.ts +115 -2
  2. package/dist/browser/client.js +145 -7
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.js +1 -1
  5. package/dist/browser/inspector/client.js.map +1 -1
  6. package/dist/tsup/{chunk-RFJ4NNO3.js → chunk-AOBZYPOQ.js} +4 -4
  7. package/dist/tsup/{chunk-YWWDUC6D.cjs → chunk-AQJFKHBK.cjs} +5 -1
  8. package/dist/tsup/chunk-AQJFKHBK.cjs.map +1 -0
  9. package/dist/tsup/{chunk-U3CMQVMS.cjs → chunk-BADLJ4CM.cjs} +3 -3
  10. package/dist/tsup/{chunk-U3CMQVMS.cjs.map → chunk-BADLJ4CM.cjs.map} +1 -1
  11. package/dist/tsup/{chunk-5A2KUC5L.cjs → chunk-CUM3GALQ.cjs} +10 -10
  12. package/dist/tsup/{chunk-5A2KUC5L.cjs.map → chunk-CUM3GALQ.cjs.map} +1 -1
  13. package/dist/tsup/{chunk-S6ZMUE7Q.js → chunk-CVTQX3MI.js} +2 -2
  14. package/dist/tsup/{chunk-QTCX5KN3.js → chunk-F5FZ6NI4.js} +2 -2
  15. package/dist/tsup/{chunk-AY25XAXA.js → chunk-G3KFGH3I.js} +3 -3
  16. package/dist/tsup/{chunk-AY25XAXA.js.map → chunk-G3KFGH3I.js.map} +1 -1
  17. package/dist/tsup/{chunk-WBUHPDDM.cjs → chunk-HFE4VBQU.cjs} +2 -2
  18. package/dist/tsup/{chunk-WBUHPDDM.cjs.map → chunk-HFE4VBQU.cjs.map} +1 -1
  19. package/dist/tsup/{chunk-YO4TJ56P.js → chunk-IDJSGBVA.js} +2 -2
  20. package/dist/tsup/{chunk-PBIQPYE5.js → chunk-IHEO5OT3.js} +5 -1
  21. package/dist/tsup/chunk-IHEO5OT3.js.map +1 -0
  22. package/dist/tsup/{chunk-K6WETGBW.cjs → chunk-QM5MJLVC.cjs} +3 -3
  23. package/dist/tsup/{chunk-K6WETGBW.cjs.map → chunk-QM5MJLVC.cjs.map} +1 -1
  24. package/dist/tsup/{chunk-NMLZDHH2.js → chunk-RYGXJQWL.js} +2 -2
  25. package/dist/tsup/{chunk-HKD7AH4Z.cjs → chunk-T5YMCOWY.cjs} +286 -149
  26. package/dist/tsup/chunk-T5YMCOWY.cjs.map +1 -0
  27. package/dist/tsup/{chunk-7OXC5BQF.js → chunk-TY25ZHJV.js} +2 -2
  28. package/dist/tsup/{chunk-7OXC5BQF.js.map → chunk-TY25ZHJV.js.map} +1 -1
  29. package/dist/tsup/{chunk-YTELGNB3.cjs → chunk-UJNHLIIG.cjs} +7 -7
  30. package/dist/tsup/{chunk-YTELGNB3.cjs.map → chunk-UJNHLIIG.cjs.map} +1 -1
  31. package/dist/tsup/{chunk-YMCG4FCB.js → chunk-VCORVUP2.js} +146 -9
  32. package/dist/tsup/chunk-VCORVUP2.js.map +1 -0
  33. package/dist/tsup/{chunk-OEOODXVI.cjs → chunk-VGJXSQMF.cjs} +4 -4
  34. package/dist/tsup/{chunk-OEOODXVI.cjs.map → chunk-VGJXSQMF.cjs.map} +1 -1
  35. package/dist/tsup/{chunk-VM4SXQOC.cjs → chunk-YWWIVWBR.cjs} +3 -3
  36. package/dist/tsup/{chunk-VM4SXQOC.cjs.map → chunk-YWWIVWBR.cjs.map} +1 -1
  37. package/dist/tsup/client/mod.cjs +5 -5
  38. package/dist/tsup/client/mod.d.cts +2 -2
  39. package/dist/tsup/client/mod.d.ts +2 -2
  40. package/dist/tsup/client/mod.js +4 -4
  41. package/dist/tsup/common/log.cjs +2 -2
  42. package/dist/tsup/common/log.js +1 -1
  43. package/dist/tsup/common/websocket.cjs +3 -3
  44. package/dist/tsup/common/websocket.js +2 -2
  45. package/dist/tsup/{config-BDJltifk.d.cts → config-BDdeBoxX.d.cts} +117 -3
  46. package/dist/tsup/{config-DXC7qzme.d.ts → config-Ch-SMJ-n.d.ts} +117 -3
  47. package/dist/tsup/{context-DgPsVbw6.d.ts → context-B-wRuYrf.d.ts} +5 -1
  48. package/dist/tsup/{context-osC4Q1ax.d.cts → context-NzsxAAoN.d.cts} +5 -1
  49. package/dist/tsup/db/drizzle.cjs +2 -2
  50. package/dist/tsup/db/drizzle.js +1 -1
  51. package/dist/tsup/db/mod.cjs +3 -3
  52. package/dist/tsup/db/mod.js +2 -2
  53. package/dist/tsup/dynamic/mod.cjs +2 -2
  54. package/dist/tsup/dynamic/mod.d.cts +1 -1
  55. package/dist/tsup/dynamic/mod.d.ts +1 -1
  56. package/dist/tsup/dynamic/mod.js +1 -1
  57. package/dist/tsup/inspector/mod.cjs +5 -5
  58. package/dist/tsup/inspector/mod.js +4 -4
  59. package/dist/tsup/inspector/workflow.cjs +4 -4
  60. package/dist/tsup/inspector/workflow.js +3 -3
  61. package/dist/tsup/inspector-tab/mod.cjs +2 -2
  62. package/dist/tsup/inspector-tab/mod.d.cts +2 -2
  63. package/dist/tsup/inspector-tab/mod.d.ts +2 -2
  64. package/dist/tsup/inspector-tab/mod.js +1 -1
  65. package/dist/tsup/mod.cjs +153 -110
  66. package/dist/tsup/mod.cjs.map +1 -1
  67. package/dist/tsup/mod.d.cts +3 -3
  68. package/dist/tsup/mod.d.ts +3 -3
  69. package/dist/tsup/mod.js +49 -6
  70. package/dist/tsup/mod.js.map +1 -1
  71. package/dist/tsup/test/mod.cjs +6 -6
  72. package/dist/tsup/test/mod.d.cts +1 -1
  73. package/dist/tsup/test/mod.d.ts +1 -1
  74. package/dist/tsup/test/mod.js +4 -4
  75. package/dist/tsup/utils.cjs +2 -2
  76. package/dist/tsup/utils.js +1 -1
  77. package/dist/tsup/workflow/mod.cjs +22 -10
  78. package/dist/tsup/workflow/mod.cjs.map +1 -1
  79. package/dist/tsup/workflow/mod.d.cts +3 -3
  80. package/dist/tsup/workflow/mod.d.ts +3 -3
  81. package/dist/tsup/workflow/mod.js +17 -5
  82. package/dist/tsup/workflow/mod.js.map +1 -1
  83. package/package.json +9 -9
  84. package/src/actor/config.ts +82 -0
  85. package/src/client/actor-conn.ts +43 -7
  86. package/src/client/client.ts +93 -0
  87. package/src/client/errors.ts +12 -0
  88. package/src/client/lifecycle-errors.ts +28 -1
  89. package/src/client/mod.ts +1 -0
  90. package/src/client/retry-budget.ts +4 -1
  91. package/src/common/actor-router-consts.ts +1 -0
  92. package/src/engine-api/actors.ts +12 -0
  93. package/src/engine-client/actor-http-client.ts +6 -0
  94. package/src/engine-client/actor-websocket-client.ts +25 -1
  95. package/src/engine-client/api-endpoints.ts +16 -0
  96. package/src/engine-client/driver.ts +12 -0
  97. package/src/engine-client/mod.ts +30 -0
  98. package/src/registry/napi-runtime.ts +8 -0
  99. package/src/registry/native.ts +49 -0
  100. package/src/registry/runtime.ts +11 -0
  101. package/src/registry/wasm-runtime.ts +9 -0
  102. package/src/workflow/context.ts +17 -0
  103. package/dist/tsup/chunk-HKD7AH4Z.cjs.map +0 -1
  104. package/dist/tsup/chunk-PBIQPYE5.js.map +0 -1
  105. package/dist/tsup/chunk-YMCG4FCB.js.map +0 -1
  106. package/dist/tsup/chunk-YWWDUC6D.cjs.map +0 -1
  107. /package/dist/tsup/{chunk-RFJ4NNO3.js.map → chunk-AOBZYPOQ.js.map} +0 -0
  108. /package/dist/tsup/{chunk-S6ZMUE7Q.js.map → chunk-CVTQX3MI.js.map} +0 -0
  109. /package/dist/tsup/{chunk-QTCX5KN3.js.map → chunk-F5FZ6NI4.js.map} +0 -0
  110. /package/dist/tsup/{chunk-YO4TJ56P.js.map → chunk-IDJSGBVA.js.map} +0 -0
  111. /package/dist/tsup/{chunk-NMLZDHH2.js.map → chunk-RYGXJQWL.js.map} +0 -0
@@ -12,6 +12,10 @@ import {
12
12
  CONNECT_SYMBOL,
13
13
  } from "./actor-conn";
14
14
  import { type ActorHandle, ActorHandleRaw } from "./actor-handle";
15
+ import {
16
+ isRetryableForkRefusal,
17
+ retryOnLifecycleBoundary,
18
+ } from "./lifecycle-errors";
15
19
  import { logger } from "./log";
16
20
  import { resolveGatewayTarget } from "./resolve-gateway-target";
17
21
  import { type RetryBudgetOptions, RetryBudget } from "./retry-budget";
@@ -90,6 +94,21 @@ export interface ActorAccessor<AD extends AnyActorDefinition> {
90
94
  key?: string | string[],
91
95
  opts?: CreateOptions,
92
96
  ): Promise<ActorHandle<AD>>;
97
+
98
+ /**
99
+ * Forks the actor `actorId` into a new actor of this name, and returns a
100
+ * stateless handle to the new actor with its ID resolved.
101
+ *
102
+ * The new actor starts at once on a copy of the source's database as of
103
+ * its last committed write, runs `onFork` once with `opts.input`, and
104
+ * keeps running independently of the source. A fork is not idempotent:
105
+ * a `key` already held answers `actor.duplicate_key`.
106
+ *
107
+ * @param {string} actorId - The ID of the source actor.
108
+ * @param {ForkOptions} [opts] - The new actor's key and the fork input.
109
+ * @returns {Promise<ActorHandle<AD>>} - A promise that resolves to a handle to the new actor.
110
+ */
111
+ fork(actorId: string, opts?: ForkOptions): Promise<ActorHandle<AD>>;
93
112
  }
94
113
 
95
114
  /**
@@ -155,6 +174,16 @@ export interface CreateOptions extends QueryOptions {
155
174
  poolName?: string;
156
175
  }
157
176
 
177
+ /**
178
+ * Options for forking an actor.
179
+ */
180
+ export interface ForkOptions extends QueryOptions {
181
+ /** The new actor's key. Omit for a keyless actor. */
182
+ key?: string | string[];
183
+ /** The fork input, passed to the new actor's `onFork` hook. */
184
+ input?: unknown;
185
+ }
186
+
158
187
  /**
159
188
  * Represents a region to connect to.
160
189
  * @typedef {Object} Region
@@ -419,6 +448,60 @@ export class ClientRaw {
419
448
  return proxy;
420
449
  }
421
450
 
451
+ /**
452
+ * Forks the actor `actorId` into a new actor and returns a handle to it.
453
+ *
454
+ * @template AD The actor class that this handle is for.
455
+ * @param {string} name - The name of the actor; the source has the same name.
456
+ * @param {string} actorId - The ID of the source actor.
457
+ * @param {ForkOptions} [opts] - The new actor's key and the fork input.
458
+ * @returns {Promise<ActorHandle<AD>>} - A promise that resolves to a handle to the new actor.
459
+ */
460
+ async fork<AD extends AnyActorDefinition>(
461
+ name: string,
462
+ actorId: string,
463
+ opts?: ForkOptions,
464
+ ): Promise<ActorHandle<AD>> {
465
+ const key = typeof opts?.key === "string" ? [opts.key] : opts?.key;
466
+
467
+ logger().debug({
468
+ msg: "fork actor",
469
+ name,
470
+ sourceActorId: actorId,
471
+ key,
472
+ });
473
+
474
+ // The client is the retry owner: a fork refused before it did anything is sent again
475
+ // after the service's hint, within the client's retry budget.
476
+ const forked = await retryOnLifecycleBoundary(
477
+ () =>
478
+ this.#driver.forkActor({
479
+ actorId,
480
+ key,
481
+ input: opts?.input,
482
+ }),
483
+ {
484
+ signal: opts?.signal,
485
+ budget: this.#retryBudget,
486
+ isRetryable: isRetryableForkRefusal,
487
+ },
488
+ );
489
+
490
+ const getForIdQuery = {
491
+ getForId: {
492
+ name,
493
+ actorId: forked.actorId,
494
+ },
495
+ } satisfies ActorQuery;
496
+ const handle = this.#createHandle(
497
+ opts?.params,
498
+ opts?.getParams,
499
+ getForIdQuery,
500
+ opts?.signal,
501
+ );
502
+ return createActorProxy(handle) as ActorHandle<AD>;
503
+ }
504
+
422
505
  #createHandle(
423
506
  params: unknown,
424
507
  getParams: (() => Promise<unknown>) | undefined,
@@ -559,6 +642,16 @@ export function createClientWithDriver<A extends Registry<any>>(
559
642
  ExtractActorsFromRegistry<A>[typeof prop]
560
643
  >(prop, key, opts);
561
644
  },
645
+ fork: async (
646
+ actorId: string,
647
+ opts: ForkOptions = {},
648
+ ): Promise<
649
+ ActorHandle<ExtractActorsFromRegistry<A>[typeof prop]>
650
+ > => {
651
+ return await target.fork<
652
+ ExtractActorsFromRegistry<A>[typeof prop]
653
+ >(prop, actorId, opts);
654
+ },
562
655
  } as ActorAccessor<ExtractActorsFromRegistry<A>[typeof prop]>;
563
656
  }
564
657
 
@@ -46,6 +46,18 @@ export function isSchedulingError(group: string, code: string): boolean {
46
46
  );
47
47
  }
48
48
 
49
+ /**
50
+ * Checks if a connection closed because its actor was destroyed. The actor is gone, so
51
+ * reconnecting through `getOrCreate` would create it again.
52
+ */
53
+ export function isActorDestroyed(group: string, code: string): boolean {
54
+ return group === "actor" && code === "destroyed";
55
+ }
56
+
57
+ export function isActorNotFound(group: string, code: string): boolean {
58
+ return group === "actor" && code === "not_found";
59
+ }
60
+
49
61
  export function actorSchedulingError(
50
62
  group: string,
51
63
  code: string,
@@ -290,10 +290,35 @@ async function waitWithSignal(ms: number, signal?: AbortSignal) {
290
290
  });
291
291
  }
292
292
 
293
+ /**
294
+ * Whether a fork was refused before it did anything, so sending it again cannot make a second
295
+ * copy: `actor.fork_unavailable` while an engine upgrade rolls out, and
296
+ * `guard.service_unavailable` with the reason `actor_moving` while a keyed source waits for its
297
+ * namespace's backfill. Every other fork error, including the timeouts after which a copy may
298
+ * exist, goes to the caller.
299
+ */
300
+ export function isRetryableForkRefusal(error: unknown): boolean {
301
+ if (!(error instanceof ActorError)) {
302
+ return false;
303
+ }
304
+ if (error.group === "actor" && error.code === "fork_unavailable") {
305
+ return true;
306
+ }
307
+ if (error.group === "guard" && error.code === "service_unavailable") {
308
+ const metadata = error.metadata as
309
+ | { reason?: unknown }
310
+ | null
311
+ | undefined;
312
+ return metadata?.reason === "actor_moving";
313
+ }
314
+ return false;
315
+ }
316
+
293
317
  /**
294
318
  * Runs `run`, retrying retryable lifecycle and refusal errors with jittered exponential backoff
295
319
  * that honors the service's `retry_after_ms` hint. With a `budget`, the call credits it once and
296
320
  * every retry spends a token; a spent budget returns the error instead of retrying.
321
+ * `isRetryable` replaces the lifecycle classification for calls that retry other errors.
297
322
  */
298
323
  export async function retryOnLifecycleBoundary<T>(
299
324
  run: () => Promise<T>,
@@ -303,11 +328,13 @@ export async function retryOnLifecycleBoundary<T>(
303
328
  maxDelayMs?: number;
304
329
  signal?: AbortSignal;
305
330
  budget?: RetryBudget;
331
+ isRetryable?: (error: unknown) => boolean;
306
332
  },
307
333
  ): Promise<T> {
308
334
  const maxAttempts = opts?.maxAttempts ?? 5;
309
335
  const initialDelayMs = opts?.initialDelayMs ?? 25;
310
336
  const maxDelayMs = opts?.maxDelayMs ?? 200;
337
+ const isRetryable = opts?.isRetryable ?? isRetryableLifecycleRequestError;
311
338
  opts?.budget?.deposit();
312
339
 
313
340
  let lastError: unknown;
@@ -317,7 +344,7 @@ export async function retryOnLifecycleBoundary<T>(
317
344
  try {
318
345
  return await run();
319
346
  } catch (error) {
320
- if (!isRetryableLifecycleRequestError(error)) {
347
+ if (!isRetryable(error)) {
321
348
  throw error;
322
349
  }
323
350
 
package/src/client/mod.ts CHANGED
@@ -52,6 +52,7 @@ export type {
52
52
  CreateOptions,
53
53
  ExtractActorsFromRegistry,
54
54
  ExtractRegistryFromClient,
55
+ ForkOptions,
55
56
  GetOptions,
56
57
  GetWithIdOptions,
57
58
  QueryOptions,
@@ -72,7 +72,10 @@ export function retryDelayMs(
72
72
  attempt: number,
73
73
  opts: { initialDelayMs: number; maxDelayMs: number; hintMs?: number },
74
74
  ): number {
75
- const backoff = Math.min(opts.initialDelayMs * 2 ** attempt, opts.maxDelayMs);
75
+ const backoff = Math.min(
76
+ opts.initialDelayMs * 2 ** attempt,
77
+ opts.maxDelayMs,
78
+ );
76
79
  const jittered = backoff / 2 + Math.random() * (backoff / 2);
77
80
  return Math.max(jittered, opts.hintMs ?? 0);
78
81
  }
@@ -35,6 +35,7 @@ export const HEADER_RIVET_SKIP_READY_WAIT = "x-rivet-skip-ready-wait";
35
35
  export const WS_PROTOCOL_STANDARD = "rivet";
36
36
  export const WS_PROTOCOL_TARGET = "rivet_target.";
37
37
  export const WS_PROTOCOL_ACTOR = "rivet_actor.";
38
+ export const WS_PROTOCOL_NAMESPACE = "rivet_namespace.";
38
39
  export const WS_PROTOCOL_ENCODING = "rivet_encoding.";
39
40
  export const WS_PROTOCOL_CONN_PARAMS = "rivet_conn_params.";
40
41
  export const WS_PROTOCOL_TOKEN = "rivet_token.";
@@ -43,6 +43,18 @@ export const ActorsCreateResponseSchema = z.object({
43
43
  });
44
44
  export type ActorsCreateResponse = z.infer<typeof ActorsCreateResponseSchema>;
45
45
 
46
+ // MARK: POST /actors/{actor_id}/fork
47
+ export const ActorsForkRequestSchema = z.object({
48
+ key: z.string().nullable().optional(),
49
+ input: z.string().nullable().optional(),
50
+ });
51
+ export type ActorsForkRequest = z.infer<typeof ActorsForkRequestSchema>;
52
+
53
+ export const ActorsForkResponseSchema = z.object({
54
+ actor: ActorSchema,
55
+ });
56
+ export type ActorsForkResponse = z.infer<typeof ActorsForkResponseSchema>;
57
+
46
58
  // MARK: PUT /actors
47
59
  export const ActorsGetOrCreateRequestSchema = z.object({
48
60
  datacenter: z.string().optional(),
@@ -1,6 +1,7 @@
1
1
  import type { ClientConfig } from "@/client/config";
2
2
  import {
3
3
  HEADER_RIVET_ACTOR,
4
+ HEADER_RIVET_NAMESPACE,
4
5
  HEADER_RIVET_RAY_ID,
5
6
  HEADER_RIVET_SKIP_READY_WAIT,
6
7
  HEADER_RIVET_TARGET,
@@ -87,6 +88,11 @@ function buildGuardHeaders(
87
88
  if (options.directActorId !== undefined) {
88
89
  headers.set(HEADER_RIVET_TARGET, "actor");
89
90
  headers.set(HEADER_RIVET_ACTOR, options.directActorId);
91
+ // An actor ID resolves within its namespace. Without one the gateway falls back
92
+ // to the token's namespace, or to `default` for the admin token.
93
+ if (runConfig.namespace) {
94
+ headers.set(HEADER_RIVET_NAMESPACE, runConfig.namespace);
95
+ }
90
96
  }
91
97
  if (shouldSkipReadyWait(options)) {
92
98
  headers.set(HEADER_RIVET_SKIP_READY_WAIT, "1");
@@ -8,6 +8,7 @@ import {
8
8
  WS_PROTOCOL_ACTOR,
9
9
  WS_PROTOCOL_CONN_PARAMS,
10
10
  WS_PROTOCOL_ENCODING,
11
+ WS_PROTOCOL_NAMESPACE,
11
12
  WS_PROTOCOL_STANDARD as WS_PROTOCOL_RIVETKIT,
12
13
  WS_PROTOCOL_SKIP_READY_WAIT,
13
14
  WS_PROTOCOL_TARGET,
@@ -194,15 +195,34 @@ class BufferedRemoteWebSocket implements UniversalWebSocket {
194
195
  }
195
196
  }
196
197
 
198
+ /**
199
+ * Builds the gateway URL of an actor addressed by ID. The actor's namespace rides as
200
+ * `rvt-namespace`: an actor ID is resolved within its namespace, so without it the gateway
201
+ * falls back to the token's namespace, or to `default` for the admin token.
202
+ */
197
203
  export function buildActorGatewayUrl(
198
204
  endpoint: string,
205
+ namespace: string,
199
206
  actorId: string,
200
207
  token: string | undefined,
201
208
  path = "",
202
209
  ): string {
210
+ if (namespace.length === 0) {
211
+ throw new Error("actor gateway namespace must not be empty");
212
+ }
203
213
  const tokenSegment =
204
214
  token !== undefined ? `@${encodeURIComponent(token)}` : "";
205
- const gatewayPath = `/gateway/${encodeURIComponent(actorId)}${tokenSegment}${path}`;
215
+ const params = new URLSearchParams();
216
+ params.append("rvt-namespace", namespace);
217
+ let separator: string;
218
+ if (path.endsWith("?") || path.endsWith("&")) {
219
+ separator = "";
220
+ } else if (path.includes("?")) {
221
+ separator = "&";
222
+ } else {
223
+ separator = "?";
224
+ }
225
+ const gatewayPath = `/gateway/${encodeURIComponent(actorId)}${tokenSegment}${path}${separator}${params.toString()}`;
206
226
  return combineUrlPath(endpoint, gatewayPath);
207
227
  }
208
228
 
@@ -395,6 +415,10 @@ export function buildWebSocketProtocols(
395
415
  if (target) {
396
416
  protocols.push(`${WS_PROTOCOL_TARGET}${target.target}`);
397
417
  protocols.push(`${WS_PROTOCOL_ACTOR}${target.actorId}`);
418
+ // An actor ID resolves within its namespace; see `buildActorGatewayUrl`.
419
+ if (runConfig.namespace) {
420
+ protocols.push(`${WS_PROTOCOL_NAMESPACE}${runConfig.namespace}`);
421
+ }
398
422
  if (runConfig.token) {
399
423
  protocols.push(`${WS_PROTOCOL_TOKEN}${runConfig.token}`);
400
424
  }
@@ -6,6 +6,8 @@ import type {
6
6
  ActorsCreateRequest,
7
7
  ActorsCreateResponse,
8
8
  ActorsDeleteResponse,
9
+ ActorsForkRequest,
10
+ ActorsForkResponse,
9
11
  ActorsGetOrCreateRequest,
10
12
  ActorsGetOrCreateResponse,
11
13
  ActorsListResponse,
@@ -105,6 +107,20 @@ export async function createActor(
105
107
  );
106
108
  }
107
109
 
110
+ // MARK: Fork actor
111
+ export async function forkActor(
112
+ config: ClientConfig,
113
+ actorId: RivetId,
114
+ request: ActorsForkRequest,
115
+ ): Promise<ActorsForkResponse> {
116
+ return apiCall<ActorsForkRequest, ActorsForkResponse>(
117
+ config,
118
+ "POST",
119
+ `/actors/${encodeURIComponent(actorId)}/fork`,
120
+ request,
121
+ );
122
+ }
123
+
108
124
  // MARK: Destroy actor
109
125
  export async function destroyActor(
110
126
  config: ClientConfig,
@@ -23,6 +23,8 @@ export interface EngineControlClient {
23
23
  getWithKey(input: GetWithKeyInput): Promise<ActorOutput | undefined>;
24
24
  getOrCreateWithKey(input: GetOrCreateWithKeyInput): Promise<ActorOutput>;
25
25
  createActor(input: CreateInput): Promise<ActorOutput>;
26
+ /** Forks the actor `actorId` into a new actor of the same name, started on a copy of its database. */
27
+ forkActor(input: ForkInput): Promise<ActorOutput>;
26
28
  listActors(input: ListActorsInput): Promise<ActorOutput[]>;
27
29
 
28
30
  sendRequest(
@@ -105,6 +107,16 @@ export interface CreateInput {
105
107
  poolName?: string;
106
108
  }
107
109
 
110
+ export interface ForkInput {
111
+ c?: HonoContext | undefined;
112
+ /** The source actor. */
113
+ actorId: string;
114
+ /** The new actor's key; omitted for a keyless actor. */
115
+ key?: ActorKey;
116
+ /** The fork input, given to the new actor's `onFork` hook. */
117
+ input?: unknown;
118
+ }
119
+
108
120
  export interface ListActorsInput {
109
121
  c?: HonoContext | undefined;
110
122
  name: string;
@@ -20,6 +20,7 @@ import type {
20
20
  ActorOutput,
21
21
  CreateInput,
22
22
  EngineControlClient,
23
+ ForkInput,
23
24
  GatewayRequestOptions,
24
25
  GatewayTarget,
25
26
  GetForIdInput,
@@ -43,6 +44,7 @@ import {
43
44
  import {
44
45
  createActor,
45
46
  destroyActor,
47
+ forkActor,
46
48
  getActor,
47
49
  getActorByKey,
48
50
  getOrCreateActor,
@@ -346,6 +348,32 @@ export class RemoteEngineControlClient implements EngineControlClient {
346
348
  return apiActorToOutput(result.actor);
347
349
  }
348
350
 
351
+ async forkActor({ actorId, key, input }: ForkInput): Promise<ActorOutput> {
352
+ await this.#metadataPromise;
353
+
354
+ logger().info({ msg: "forking actor via engine api", actorId, key });
355
+
356
+ const result = await this.#withCredential((config) =>
357
+ forkActor(config, actorId, {
358
+ key: key ? serializeActorKey(key) : undefined,
359
+ input:
360
+ input !== undefined
361
+ ? uint8ArrayToBase64(
362
+ encodeCborCompat(input as JsonCompatValue),
363
+ )
364
+ : undefined,
365
+ }),
366
+ );
367
+
368
+ logger().info({
369
+ msg: "actor forked",
370
+ actorId: result.actor.actor_id,
371
+ sourceActorId: actorId,
372
+ });
373
+
374
+ return apiActorToOutput(result.actor);
375
+ }
376
+
349
377
  async listActors({ name }: ListActorsInput): Promise<ActorOutput[]> {
350
378
  await this.#metadataPromise;
351
379
 
@@ -574,6 +602,7 @@ export class RemoteEngineControlClient implements EngineControlClient {
574
602
  if ("directId" in target) {
575
603
  return buildActorGatewayUrl(
576
604
  endpoint,
605
+ config.namespace,
577
606
  target.directId,
578
607
  config.token,
579
608
  path,
@@ -583,6 +612,7 @@ export class RemoteEngineControlClient implements EngineControlClient {
583
612
  if ("getForId" in target) {
584
613
  return buildActorGatewayUrl(
585
614
  endpoint,
615
+ config.namespace,
586
616
  target.getForId.actorId,
587
617
  config.token,
588
618
  path,
@@ -692,10 +692,18 @@ export class NapiCoreRuntime implements CoreRuntime {
692
692
  return asNativeActorContext(ctx).key();
693
693
  }
694
694
 
695
+ actorForkChain(ctx: ActorContextHandle) {
696
+ return asNativeActorContext(ctx).forkChain();
697
+ }
698
+
695
699
  actorRegion(ctx: ActorContextHandle): string {
696
700
  return asNativeActorContext(ctx).region();
697
701
  }
698
702
 
703
+ actorNamespace(ctx: ActorContextHandle): string {
704
+ return asNativeActorContext(ctx).namespace();
705
+ }
706
+
699
707
  actorSleep(ctx: ActorContextHandle): void {
700
708
  asNativeActorContext(ctx).sleep();
701
709
  }
@@ -9,6 +9,7 @@ import {
9
9
  type ActorCron,
10
10
  type ActorCronEveryOptions,
11
11
  type ActorCronSetOptions,
12
+ type ActorForkLink,
12
13
  type ActorLogger,
13
14
  type ActorRun,
14
15
  type ActorSchedule,
@@ -115,6 +116,7 @@ import type {
115
116
  CoreRuntime,
116
117
  RegistryHandle,
117
118
  RuntimeActorConfig,
119
+ RuntimeActorKeySegment,
118
120
  RuntimeActorTracingConfig,
119
121
  RuntimeBytes,
120
122
  RuntimeCronFire,
@@ -3027,10 +3029,24 @@ export class ActorContextHandleAdapter {
3027
3029
  );
3028
3030
  }
3029
3031
 
3032
+ get forkChain(): ActorForkLink[] {
3033
+ return callNativeSync(() =>
3034
+ this.#runtime.actorForkChain(this.#ctx),
3035
+ ).map((link) => ({
3036
+ actorId: link.actorId,
3037
+ key: toActorKey(link.key),
3038
+ forkedAt: link.forkedAt,
3039
+ }));
3040
+ }
3041
+
3030
3042
  get region(): string {
3031
3043
  return callNativeSync(() => this.#runtime.actorRegion(this.#ctx));
3032
3044
  }
3033
3045
 
3046
+ get namespace(): string {
3047
+ return callNativeSync(() => this.#runtime.actorNamespace(this.#ctx));
3048
+ }
3049
+
3034
3050
  get conns(): ReadonlyMap<string, NativeConnAdapter> {
3035
3051
  if (!this.#connMap) {
3036
3052
  this.#connMap = new NativeConnectionMap(
@@ -4832,6 +4848,39 @@ export function buildNativeFactory(
4832
4848
  },
4833
4849
  )
4834
4850
  : undefined,
4851
+ onFork:
4852
+ typeof config.onFork === "function"
4853
+ ? wrapNativeCallback(
4854
+ async (
4855
+ error: unknown,
4856
+ payload: {
4857
+ ctx: ActorContextHandle;
4858
+ fork: {
4859
+ actorId: string;
4860
+ key: RuntimeActorKeySegment[];
4861
+ forkedAt: number;
4862
+ input?: RuntimeBytes;
4863
+ };
4864
+ },
4865
+ ) => {
4866
+ const { ctx, fork } = unwrapTsfnPayload(
4867
+ error,
4868
+ payload,
4869
+ );
4870
+ const actorCtx = makeActorCtx(ctx);
4871
+ try {
4872
+ await config.onFork(actorCtx, {
4873
+ actorId: fork.actorId,
4874
+ key: toActorKey(fork.key),
4875
+ forkedAt: fork.forkedAt,
4876
+ input: decodeValue(fork.input),
4877
+ });
4878
+ } finally {
4879
+ await actorCtx.dispose();
4880
+ }
4881
+ },
4882
+ )
4883
+ : undefined,
4835
4884
  onWake:
4836
4885
  typeof config.onWake === "function"
4837
4886
  ? wrapNativeCallback(
@@ -34,6 +34,13 @@ export interface RuntimeActorKeySegment {
34
34
  numberValue?: number;
35
35
  }
36
36
 
37
+ /** One individual actor fork behind an actor, as the runtime reports it. */
38
+ export interface RuntimeForkLink {
39
+ actorId: string;
40
+ key: RuntimeActorKeySegment[];
41
+ forkedAt: number;
42
+ }
43
+
37
44
  /** Resolves correlation at operation time so retained clients cannot freeze stale context. */
38
45
  export type CurrentActorInvocation = () =>
39
46
  | ActorInvocationTraceContext
@@ -624,7 +631,11 @@ export interface CoreRuntime {
624
631
  currentInvocationScope(): object | undefined;
625
632
  actorName(ctx: ActorContextHandle): string;
626
633
  actorKey(ctx: ActorContextHandle): RuntimeActorKeySegment[];
634
+ /** The individual actor forks behind the actor, oldest first. */
635
+ actorForkChain(ctx: ActorContextHandle): RuntimeForkLink[];
627
636
  actorRegion(ctx: ActorContextHandle): string;
637
+ /** The name of the namespace the actor runs in. */
638
+ actorNamespace(ctx: ActorContextHandle): string;
628
639
  actorSleep(ctx: ActorContextHandle): void;
629
640
  actorDestroy(ctx: ActorContextHandle): void;
630
641
  actorAbortSignal(ctx: ActorContextHandle): AbortSignal;
@@ -20,6 +20,7 @@ import type {
20
20
  RuntimeBytes,
21
21
  RuntimeCronFire,
22
22
  RuntimeCronJobInfo,
23
+ RuntimeForkLink,
23
24
  RuntimeHttpRequest,
24
25
  RuntimeInspectorSnapshot,
25
26
  RuntimeKvEntry,
@@ -586,10 +587,18 @@ export class WasmCoreRuntime implements CoreRuntime {
586
587
  return callHandle(asWasmActorContext(ctx), "key");
587
588
  }
588
589
 
590
+ actorForkChain(ctx: ActorContextHandle): RuntimeForkLink[] {
591
+ return callHandle(asWasmActorContext(ctx), "forkChain");
592
+ }
593
+
589
594
  actorRegion(ctx: ActorContextHandle): string {
590
595
  return callHandle(asWasmActorContext(ctx), "region");
591
596
  }
592
597
 
598
+ actorNamespace(ctx: ActorContextHandle): string {
599
+ return callHandle(asWasmActorContext(ctx), "namespace");
600
+ }
601
+
593
602
  actorSleep(ctx: ActorContextHandle): void {
594
603
  callHandle(asWasmActorContext(ctx), "sleep");
595
604
  }
@@ -13,6 +13,7 @@ import type {
13
13
  WorkflowQueueMessage,
14
14
  } from "@rivetkit/workflow-engine";
15
15
  import type {
16
+ ActorForkLink,
16
17
  QueueFilterName,
17
18
  QueueNextBatchOptions,
18
19
  QueueNextOptions,
@@ -353,6 +354,14 @@ export class WorkflowStepContext<
353
354
  return this.#runCtx.key;
354
355
  }
355
356
 
357
+ get forkChain(): ActorForkLink[] {
358
+ return this.#runCtx.forkChain;
359
+ }
360
+
361
+ get namespace(): string {
362
+ return this.#runCtx.namespace;
363
+ }
364
+
356
365
  get log() {
357
366
  return this.#runCtx.log;
358
367
  }
@@ -508,6 +517,14 @@ export class WorkflowContext<
508
517
  return this.#runCtx.key;
509
518
  }
510
519
 
520
+ get forkChain(): ActorForkLink[] {
521
+ return this.#runCtx.forkChain;
522
+ }
523
+
524
+ get namespace(): string {
525
+ return this.#runCtx.namespace;
526
+ }
527
+
511
528
  get log() {
512
529
  return this.#runCtx.log;
513
530
  }