From 6ee9d897b63d25741e174cc1f9e51b2d20f249c3 Mon Sep 17 00:00:00 2001 From: sAchin-680 Date: Wed, 25 Nov 2026 21:44:20 +0530 Subject: [PATCH 1/2] fix(rivetkit): drop a queued ActorConn action when its signal aborts `ActorConnRaw.action()` already took a `signal` option but never actually used it. While a connection is reopening, actions sit in a queue and get sent once it's back, even if the caller has already given up (and maybe retried somewhere else). So the same action could end up running late, or twice. Now the signal is respected: - If it's already aborted, the call rejects with `signal.reason` and nothing gets queued. - If it aborts while the action is still waiting in the queue, the message is pulled out and never sent. - If it aborts after the message went out, only the caller's promise rejects. The action may still run on the actor, so its response is quietly ignored when it comes back. Closes #6010 --- .../rivetkit/src/client/actor-conn.ts | 115 ++++++++++++------ 1 file changed, 81 insertions(+), 34 deletions(-) diff --git a/rivetkit-typescript/packages/rivetkit/src/client/actor-conn.ts b/rivetkit-typescript/packages/rivetkit/src/client/actor-conn.ts index 9921820acc..d67a8f6fce 100644 --- a/rivetkit-typescript/packages/rivetkit/src/client/actor-conn.ts +++ b/rivetkit-typescript/packages/rivetkit/src/client/actor-conn.ts @@ -87,10 +87,26 @@ export type ActorConnStatus = | "connected" | "disconnected"; +interface QueuedMessage { + body: + | { + tag: "ActionRequest"; + val: { id: bigint; name: string; args: unknown }; + } + | { + tag: "SubscriptionRequest"; + val: { eventName: string; subscribe: boolean }; + }; +} + +function abortReason(signal: AbortSignal): unknown { + return signal.reason ?? new Error("Operation aborted"); +} + interface ActionInFlight { name: string; resolve: (response: { id: bigint; output: unknown }) => void; - reject: (error: Error) => void; + reject: (error: unknown) => void; } interface EventSubscriptions> { @@ -167,17 +183,7 @@ export class ActorConnRaw { #actorId?: string; #connId?: string; - #messageQueue: Array<{ - body: - | { - tag: "ActionRequest"; - val: { id: bigint; name: string; args: unknown }; - } - | { - tag: "SubscriptionRequest"; - val: { eventName: string; subscribe: boolean }; - }; - }> = []; + #messageQueue: QueuedMessage[] = []; #actionsInFlight = new Map(); #eventSubscriptions = new Map>>(); @@ -350,6 +356,10 @@ export class ActorConnRaw { * @template Response - The type of the response returned by the action function. * @param {string} name - The name of the action function to call. * @param {...Args} args - The arguments to pass to the action function. + * @param {AbortSignal} [signal] - Gives up on the call. While the connection is reopening the + * action waits in a queue; aborting then removes it, so it is never sent. Once sent, aborting + * only rejects this promise and the action may still run. Use `AbortSignal.timeout(ms)` for + * a deadline. * @returns {Promise} - A promise that resolves to the response of the action function. */ async action< @@ -372,6 +382,8 @@ export class ActorConnRaw { } if (this.#disposed) throw new errors.ActorConnDisposed(); if (this.#connectionOpenError) throw this.#connectionOpenError; + const { signal } = opts; + if (signal?.aborted) throw abortReason(signal); logger().debug({ msg: "action", name: opts.name, args: opts.args }); // If we have an active connection, use the websockactionId @@ -394,7 +406,7 @@ export class ActorConnRaw { inFlightCount: this.#actionsInFlight.size, }); - this.#sendMessage({ + const message: QueuedMessage = { body: { tag: "ActionRequest", val: { @@ -403,17 +415,65 @@ export class ActorConnRaw { args: opts.args, }, }, - }); + }; + this.#sendMessage(message); + + const onAbort = signal + ? () => this.#abortAction(actionId, message, signal) + : undefined; + if (signal && onAbort) { + signal.addEventListener("abort", onAbort, { once: true }); + } // TODO: Throw error if disconnect is called - const { id: responseId, output } = await promise; - if (responseId !== BigInt(actionId)) - throw new Error( - `Request ID ${actionId} does not match response ID ${responseId}`, - ); + try { + const { id: responseId, output } = await promise; + if (responseId !== BigInt(actionId)) + throw new Error( + `Request ID ${actionId} does not match response ID ${responseId}`, + ); + + return output as Response; + } finally { + if (signal && onAbort) { + signal.removeEventListener("abort", onAbort); + } + } + } - return output as Response; + /** + * Gives up on an action whose caller's signal aborted. A message still in the queue is + * removed so it is never sent after a reconnect. A message already sent may still run, + * so its in-flight entry stays to absorb the response; only the caller's promise rejects. + */ + #abortAction( + actionId: number, + message: QueuedMessage, + signal: AbortSignal, + ) { + const inFlight = this.#actionsInFlight.get(actionId); + if (!inFlight) return; + + const reason = abortReason(signal); + const queueIndex = this.#messageQueue.indexOf(message); + if (queueIndex !== -1) { + this.#messageQueue.splice(queueIndex, 1); + this.#actionsInFlight.delete(actionId); + logger().debug({ + msg: "aborted queued action before send", + actionId, + actionName: inFlight.name, + queueLength: this.#messageQueue.length, + }); + } else { + logger().debug({ + msg: "aborted action after send, outcome unknown", + actionId, + actionName: inFlight.name, + }); + } + inFlight.reject(reason); } /** @@ -1391,20 +1451,7 @@ export class ActorConnRaw { }; } - #sendMessage( - message: { - body: - | { - tag: "ActionRequest"; - val: { id: bigint; name: string; args: unknown }; - } - | { - tag: "SubscriptionRequest"; - val: { eventName: string; subscribe: boolean }; - }; - }, - opts?: SendHttpMessageOpts, - ) { + #sendMessage(message: QueuedMessage, opts?: SendHttpMessageOpts) { if (this.#disposed) { if (opts?.ephemeral) { return; From 4a5a9d93d88086ed7b1ad64ae0859d35e0f650ab Mon Sep 17 00:00:00 2001 From: sAchin-680 Date: Wed, 25 Nov 2026 22:02:59 +0530 Subject: [PATCH 2/2] docs(actors): show how to cancel or time out an action call Adds a short "Timeouts and Cancellation" section to the actions page. It shows how to pass a `signal` to `.action()` on handles and connections, what happens when it aborts, and links to the existing section on canceling work inside the actor. --- docs/actors/content/docs/actions.mdx | 12 +++++++ .../actors-actions/calling-with-signal.ts | 35 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 examples/docs/actors-actions/calling-with-signal.ts diff --git a/docs/actors/content/docs/actions.mdx b/docs/actors/content/docs/actions.mdx index f4f44102dd..7d76734a7a 100644 --- a/docs/actors/content/docs/actions.mdx +++ b/docs/actors/content/docs/actions.mdx @@ -63,6 +63,18 @@ The actor client includes type safety out of the box. When you use `createClient +### Timeouts and Cancellation + +Pass a `signal` to stop waiting for an action call, for example with `AbortSignal.timeout()`. Use `.action({ name, args, signal })` for this, since the shorthand `counterActor.increment(1)` doesn't take options. It works the same on handles and connections: + + + +When the signal aborts, the call rejects with the signal's reason. If the action was already sent, it may still run on the actor; only the client stops waiting. On a connection, an action still queued while the connection reconnects is dropped and never sent. + +On a handle, a `signal` passed to `get()` or `getOrCreate()` applies to every action call that doesn't pass its own. + +To cancel work inside the actor itself, see [Canceling Long-Running Actions](#canceling-long-running-actions). + ## Error Handling Actors provide robust error handling out of the box for actions. diff --git a/examples/docs/actors-actions/calling-with-signal.ts b/examples/docs/actors-actions/calling-with-signal.ts new file mode 100644 index 0000000000..84b5aeeb8f --- /dev/null +++ b/examples/docs/actors-actions/calling-with-signal.ts @@ -0,0 +1,35 @@ +import { createClient } from "rivetkit/client"; +import { actor, setup } from "rivetkit"; + +const counter = actor({ + vars: { count: 0 }, + actions: { + increment: (c, amount: number) => { + c.vars.count += amount; + return c.vars.count; + } + } +}); + +const registry = setup({ use: { counter } }); +const client = createClient("http://localhost:6420"); +const counterActor = client.counter.getOrCreate(); + +// Give up if the call takes longer than 5 seconds +const count = await counterActor.action({ + name: "increment", + args: [1], + signal: AbortSignal.timeout(5_000), +}); + +// Connections take a signal the same way +const conn = counterActor.connect(); +const controller = new AbortController(); +const pending = conn.action({ + name: "increment", + args: [1], + signal: controller.signal, +}); + +// Stop waiting, for example when the user leaves the page +controller.abort();