Jobs
The registry runs jobs and rebuilds saved scopes.
A job is one listener delivery, scheduled call, or cron run.
Job
Waits in the queue
Lease
Runner renews its claim
Done
Runner removes the job
Retry
Backoff then claim again
Failed
Adapter keeps the job
- Runs
failed, if the listener has one
export const const prepareStay: Listener<{
bookingId: string;
}, {
scope: {
actor: string | null;
};
}>
prepareStay = const listener: <{
bookingId: string;
}>(def: {
id?: string;
event: () => EventDef<unknown, {
bookingId: string;
}, string | undefined, Schema<any, any>>;
attempts?: number;
delay?: number;
when?: ((payload: {
bookingId: string;
}) => boolean) | undefined;
key?: ((payload: {
bookingId: string;
}) => string) | undefined;
unique?: ((payload: {
bookingId: string;
}) => string) | undefined;
scope?: ((payload: {
bookingId: string;
}) => {
actor: string | null;
}) | undefined;
timeout?: number;
queue?: string;
meta?: undefined;
handler: (ctx: ListenerCtx<{
scope: {
actor: string | null;
};
}, {
bookingId: string;
}>, payload: {
bookingId: string;
}) => Promise<unknown>;
retry?: (error: AppError) => boolean;
failed?: ((ctx: ListenerCtx<...>, payload: {
bookingId: string;
}, error: unknown) => Promise<unknown>) | undefined;
}) => Listener<...>
React to an event after commit, like an action. Must be idempotent.
`listener({ event: () => bookings.confirmed, async handler(ctx, payload) {…} })`listener({
event: () => EventDef<unknown, {
bookingId: string;
}, string | undefined, Schema<any, any>>
The event it reacts to, as a thunk so modules can import each other's barrels without cycles.event: () => const confirmed: EventDef<{
bookingId: string;
}, {
bookingId: string;
}, undefined, z.ZodObject<{
bookingId: z.ZodString;
}, z.core.$strip>>
confirmed,
attempts?: number | undefinedTries in total, the first included, like Laravel's `$tries`. Default 1: a retry repeats side effects, so opt in.
Once they're used, the job is `failed` (kept by `databaseQueue` and `outbox`, retried with `registry.jobs.retry(id)`).attempts: 3,
async handler: (ctx: ListenerCtx<{
scope: {
actor: string | null;
};
}, {
bookingId: string;
}>, payload: {
bookingId: string;
}) => Promise<unknown>
handler(ctx: ListenerCtx<{
scope: {
actor: string | null;
};
}, {
bookingId: string;
}>
ctx, { bookingId: stringbookingId }) {
await ctx: ListenerCtx<{
scope: {
actor: string | null;
};
}, {
bookingId: string;
}>
ctx.ActionCtx<{ scope: { actor: string | null; }; }, { actor: string | null; }>.run: <Fn<"mutation", {
title: string;
bookingId: string;
}, void, false, {
scope: {
actor: string | null;
};
}, z.ZodObject<{
title: z.ZodString;
bookingId: z.ZodString;
}, z.core.$strip>, undefined>>(fn: Fn<"mutation", {
title: string;
bookingId: string;
}, void, false, {
scope: {
actor: string | null;
};
}, z.ZodObject<{
title: z.ZodString;
bookingId: z.ZodString;
}, z.core.$strip>, undefined>, input: {
title: string;
bookingId: string;
}, options?: RunOptions<{
actor: string | null;
}> | undefined) => Promise<void>
Call any function: `await ctx.run(bookings.confirmPaid, { bookingId })`. Each mutation you run commits on its own.run(const tasks: {
create: Fn<"mutation", {
title: string;
bookingId: string;
}, void, false, {
scope: {
actor: string | null;
};
}, z.ZodObject<{
title: z.ZodString;
bookingId: z.ZodString;
}, z.core.$strip>, undefined>;
}
tasks.create: Fn<"mutation", {
title: string;
bookingId: string;
}, void, false, {
scope: {
actor: string | null;
};
}, z.ZodObject<{
title: z.ZodString;
bookingId: z.ZodString;
}, z.core.$strip>, undefined>
create, { title: stringtitle: "Prepare keys", bookingId: stringbookingId });
},
});
- Commit. Deliveries and scheduled calls commit with the mutation in the jobs table.
- Claim (1). A claim spends one attempt. The receipt controls renewal and settlement.
- Done. The runner removes the row before delivering follow-up jobs.
- Retry. The runner renews every third of the lease for up to 15 minutes. An expired lease makes the job available again. Default backoff is
exp(min(attempt, 10))seconds. - Failed. An expired final claim fails the job without running its handler again.
- Idempotency. Work can repeat after a crash. Use a unique constraint or idempotency key. For deliveries, pair
ctx.event.idwith the listener’s identity.
Compare adapter guarantees.
Listener options
| Option | Rule |
|---|---|
attempts, delay, queue |
The job keeps its attempts and due time. See defaults. |
when |
Tests parsed payload at commit. False skips delivery. A throw rolls back. Check current state in the handler. |
key |
Runs jobs in enqueue order, one at a time per listener and key. Concurrent commits have no defined order. Waiting spends no attempt. Backoff holds the key. Terminal failure releases it. Use ctx.run for follow-up jobs with that key. |
unique |
Keeps the first waiting job per value. Group bursts with delay. Read current state. |
timeout |
Aborts ctx.signal and blocks new ctx.run calls. Pass the signal to external operations. A running mutation can still commit. |
retry |
Overrides the default of retrying only conflict among app errors. Unexpected exceptions retry while attempts remain. Stale payloads fail immediately. |
failed |
Runs after terminal failure outside a transaction, with current payload and scope. A crash or discard can skip it. Throws reach onError as "<listener> (failed)". |
Use either key or unique. Both read parsed payload at commit. Empty values or throws roll back the mutation.
Scope
store saves IDs from the scope with the job. load rebuilds the scope when the job runs, and reads today’s role through ctx.db.
const createRegistry: <{}, {
accountId: string;
actorId: string | null;
}>(options: TypedOptions<{
scope: Scope;
db: Db;
}, {}, {
accountId: string;
actorId: string | null;
}>) => Registry<Scope, {}, Record<string, never>, {}, AppError<never, undefined> | AppError<never, {
issues: {
message: string;
path?: PropertyKey[];
}[];
}>>
Create the registry once at startup: `createRegistry({ modules, database, services })`.createRegistry({
modules: OwnModules<{
scope: Scope;
db: Db;
}, {}>
One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`.modules: {},
database: DatabaseOptions<DatabaseAdapter<unknown, unknown>> & DatabaseOptions<DatabaseAdapter<unknown, Db>>`database: { adapter: drizzleAdapter(db) }`, with `transactionAttempts` when 3 isn't right.database: { DatabaseOptions<A extends DatabaseAdapter<any, any> = DatabaseAdapter<unknown, unknown>>.adapter: DatabaseAdapter<unknown, unknown> & DatabaseAdapter<unknown, Db>adapter: const database: DatabaseAdapter<Db, Db>database },
jobs?: JobsOptions<Scope, {
accountId: string;
actorId: string | null;
}, Db, {
readonly [x: string]: never;
}> | undefined
Background work: `jobs: { adapter: databaseQueue(), scope: { store, load } }`. Default: in-process, scope as-is (nothing waits).jobs: {
adapter?: JobsAdapter | undefined`inProcess()` (default), or a durable one like `databaseQueue()`. Its own options go in its factory.adapter: function databaseQueue(options?: DatabaseQueueOptions): StoredJobsYour database as the queue, like Laravel's `database` driver: jobs are rows written in the mutation's transaction, so
a committed one is never lost. After commit the request runs them (through `waitUntil` on serverless), so no worker
is needed, or `work(registry)` in the same process takes them; `sweep` picks up what a crash, a retry or a delay left
behind. With `runIn: "worker"`, requests only write rows and workers in other processes run them. At least once: a crash between a job finishing and its row being deleted runs it again.
```ts
const registry = createRegistry({ modules, database, jobs: { adapter: databaseQueue(), scope: { store, load } } });
work(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
```databaseQueue(),
scope?: JobScope<Scope, {
accountId: string;
actorId: string | null;
}, Db, {
readonly [x: string]: never;
}> | undefined
How a job gets its scope, applied in every adapter, `inProcess()` and tests included. Required with an adapter that
keeps jobs to run later (`createRegistry` refuses one without `load`): such a job runs as the scope `load` rebuilds,
with today's roles.scope: {
JobScope<Scope, { accountId: string; actorId: string | null; }, Db, { readonly [x: string]: never; }>.store?: ((scope: Scope) => {
accountId: string;
actorId: string | null;
}) | undefined
What a job keeps of the scope it was queued as: ids, as plain JSON. Sync, from the scope only.store: (scope: Scopescope) => ({ accountId: stringaccountId: scope: Scopescope.accountId: stringaccountId, actorId: string | nullactorId: scope: Scopescope.actor: {
id: string;
role: string;
} | null
actor?.id: string | undefinedid ?? null }),
async JobScope<Scope, { accountId: string; actorId: string | null; }, Db, { readonly [x: string]: never; }>.load?: ((ctx: LoadCtx<Db, {
readonly [x: string]: never;
}>, stored: {
accountId: string;
actorId: string | null;
}) => Scope | Promise<Scope | null> | null) | undefined
The scope a job runs as, rebuilt from what `store` saved with today's roles: `null` discards the job. Read through
`ctx.db`, as a query does, so a test's rows are visible. Write `store` first so TypeScript infers `stored`.load(ctx: LoadCtx<Db, {
readonly [x: string]: never;
}>
ctx, saved: {
accountId: string;
actorId: string | null;
}
saved) {
const { const accountId: stringaccountId, const actorId: string | nullactorId } = saved: {
accountId: string;
actorId: string | null;
}
saved;
if (!const actorId: string | nullactorId) return { accountId: stringaccountId, actor: {
id: string;
role: string;
} | null
actor: null };
const const role: string | nullrole = await ctx: LoadCtx<Db, {
readonly [x: string]: never;
}>
ctx.LoadCtx<Db, { readonly [x: string]: never; }>.db: DbThe registry's database, as your queries read it: in `createTestRegistry`, the test's transaction.db.function roleOf(accountId: string, userId: string): Promise<string | null>roleOf(const accountId: stringaccountId, const actorId: stringactorId);
return const role: string | nullrole ? { accountId: stringaccountId, actor: {
id: string;
role: string;
} | null
actor: { id: stringid: const actorId: stringactorId, role: stringrole } } : null;
},
},
},
});
- Default. Deliveries and scheduled calls inherit the mutation’s scope. Each
ctx.runchecks policy. - Override. A listener’s
scope(payload)picks a whole scope at commit. Take account IDs from the emitter’sctx.scope. - Store. Save plain JSON with
jobs.scope.store. Keep enough to rebuild system scopes. Omitstoreto save the whole scope. - Load. Set
jobs.scope.load(ctx, saved)when you setstore, or when the jobs adapter keeps jobs to run later. Every adapter exceptinProcess()keeps them, andcreateRegistryrefuses a registry withoutload. Rebuild membership and roles throughctx.db. Returnnullto discard. A throw orundefinedfails the attempt. - Order. Put
storefirst for type inference. The loader runs before handlers and again for a listener’sfailed, even in tests. Crons use their declared scope.
Scheduled calls
ctx.schedule(tasks.create, { title: "Collect keys", bookingId }, { at: checkOut, replace: true });
- Target. In a mutation, schedule a registered mutation or action. The registry checks input at commit and input and policy at run time.
- Time. Use a
Dateforator seconds fordelay. Past dates and zero delay run after commit. Future calls need an adapter that holds jobs. - Input. Use plain JSON.
- Options. Set
attempts,queue, or a wholescope. See loop limits. - Replacement. With
replace: true, the newest waiting call with the same function and input wins. Use IDs in the input. - Cancellation. Update the app row and check it before acting. Check and write in the same mutation when possible. Scheduling returns no handle.
Queues
Declare extra names in jobs.queues. Workers and sweeps take the first listed queue with a due job. Without a list, they take the earliest available job. With default runIn, the request handles due-now jobs if local workers cannot take all of them.
Operations
Method on registry.jobs |
Result |
|---|---|
sweep({ queues }) |
Runs due jobs and counts outcomes. Returns zeros without a sweeper. |
run(job, { attempt }) |
Consumer acknowledges "done", "failed", or "discarded" and retries on a throw. |
failed({ source, scope, limit, cursor }) |
Lists failures newest first. Matches nested fields in stored scope. Default limit 100. Reuse the returned cursor. |
retry(id) |
Gives a failed job fresh attempts. |
forget(id) |
Removes a failed job. |
invoke(cron, { at }) |
Hands off one cron and returns a new job ID. |
- Reports.
onErrorgets source, job, attempt, and outcome when available. - Access. Guard operator routes with a policy. For user retries, check the app row in a mutation and emit again.
- Deploys. Keep definition IDs stable. An unknown ID spends an attempt. Deploy a new listener before its emitter.