Skip to content

Typed client

@cairnflow/sdk/client calls your handlers from an application, a script or an edge function. It imports nothing from node:*, follows the cluster’s redirects, retries safely, and takes its types from your service definitions.

app.ts
import { connect, InvocationFailed } from "@cairnflow/sdk/client";
import type { orders, signup } from "./services.ts";
const c = connect({ url: process.env.CAIRN_URL!, apiKey: process.env.CAIRN_KEY! });
// Call and wait for the result.
const receipt = await c.service<typeof orders>("OrderService").submit({ amount: 5 });
// Send and get a handle back at once.
const h = await c.service<typeof orders>("OrderService").send.submit({ amount: 5 });
const result = await h.attach({ timeoutMs: 60_000 });

Export the definitions from the module that declares them and import them with import type. Only types cross over, so the client bundle does not pull in your service code or node:http:

services.ts
import { service, type ServiceContext } from "@cairnflow/sdk";
export const orders = service("OrderService", {
async submit(ctx: ServiceContext, input: { amount: number }) {
return { receipt: await ctx.run("charge", () => charge(input.amount)) };
},
});

c.service<typeof orders>("OrderService") then exposes submit(input, opts?), typed with the handler’s input and returning a promise of its output. The name string must match the service name; the type parameter only describes it.

Call For
c.service<D>(name, opts?) A plain service
c.object<D>(name, key, opts?) A virtual object, by key
c.workflow<D>(name, workflowId, opts?) A workflow, by ID
c.invocation<O>(id) Any invocation, by ID

opts is { scope } to address the target inside a scope.

Each target exposes one function per handler, which calls and waits, plus send.<handler>, which returns an InvocationHandle as soon as the invocation is durable.

const wf = c.workflow<typeof signup>("UserSignup", "u-1");
await wf.send.run({ email: "[email protected]" }); // start without waiting
await wf.click({ secret }); // a shared handler
const verified = await wf.attach(); // wait for run's result
const now = await wf.output(); // { ready: false } or { ready: true, value }

Calling run a second time for the same ID throws AlreadyInvoked, with the ID of the existing run.

Method Meaning
id The invocation ID
attach({ timeoutMs?, signal? }) Wait until it finishes; returns the output
output() { ready: false } or { ready: true, value }, without waiting
status() Status, timestamps, and failure details
signal(name, value?) Deliver a signal
cancel({ mode? }) Cooperative cancel by default; { mode: "hard" } needs an admin key — see Cancellation

Waiting uses long polls of 25 seconds each (attachWaitMs), below the idle timeout of common load balancers. A 503, or a 429 that names no invocation, is retried after a backoff (honouring Retry-After). If timeoutMs runs out first, attach throws AttachTimeout; the invocation keeps running and you can attach again by ID.

Option Meaning
idempotencyKey Idempotency key for this call. Absent: generated once and reused across the client’s retries. null: send none
timeoutMs Give up waiting after this long (calls only)
signal AbortSignal to stop waiting
limitKey Limit key, for calls in a scope
logLevel Minimum ctx.log level for this invocation: "debug", "info", "warn" or "error"
headers Extra request headers

Every call carries an Idempotency-Key. When you do not pass one, the client generates a random key and keeps it across its own retries, so a lost response or a network error never creates a second invocation. Pass your own key to deduplicate across processes or restarts:

await c.service<typeof orders>("OrderService").submit(order, {
idempotencyKey: `order-${order.id}`,
});

The same key returns the same invocation: its result if it has finished, or a handle to wait on. send.<handler> returns a handle to that invocation even when it has already failed or is paused. Deduplication lasts as long as the finished invocation is retained. A workflow’s run needs no key: the workflow ID already makes it run once.

Error When
InvocationFailed The invocation ended failed. It is a TerminalError, with code, message and invocationId
InvocationPaused The invocation is paused (for example, retries exhausted). Has code and invocationId
AlreadyInvoked A workflow run was called again for the same ID
AttachTimeout timeoutMs ran out; the invocation is still running
CairnHttpError Any other HTTP error (400, 401, 403, 404, …), with status and code
try {
await c.object<typeof cart>("Cart", userId).checkout();
} catch (e) {
if (e instanceof InvocationFailed && e.code === 409) {
// business failure reported by the handler
} else {
throw e;
}
}
Option Default Meaning
url — Your environment’s endpoint
apiKey — Sent as Authorization: Bearer
headers — Extra headers on every request
maxAttempts 8 Attempts per request
maxElapsedMs 30000 Time budget per request, including waits between attempts
attachWaitMs 25000 Length of each long poll while waiting for a result
followLeader true Follow the cluster’s redirect to the node that owns the invocation
fetch global fetch Custom fetch implementation

The client also exposes c.promise(...) and c.awakeable(id) for promises and awakeables, and c.schedules for schedules.

The client has no delayed send; to run something later, use ctx.send(..., { delay }) inside a handler.