saasaloy-queue
Runbook for the queue capability — provider-agnostic background work in packages/queue, with a job table, a schedule table and per-provider modules. Use when enqueueing a job from a route, writing a job handler, scheduling one with cron, choosing or switching QUEUE_PROVIDER, reading a QueueError, or writing a custom queue provider.
- License 许可
- MIT
- 所属仓库
- mimukit/saasaloy
- 最近更新
- 2026-11-13
- Stars
- ★ 4
- Forks
- 0
01 前言 Front Matter
- name
- saasaloy-queue
- description
- Runbook for the queue capability — provider-agnostic background work in packages/queue, with a job table, a schedule table and per-provider modules. Use when enqueueing a job from a route, writing a job handler, scheduling one with cron, choosing or switching QUEUE_PROVIDER, reading a QueueError, or writing a custom queue provider.
03 SKILL.md 正文
queue — provider-agnostic background work from packages/queue
packages/queue (@repo/queue) is the capability core: a job table, a schedule table, a five-field cron matcher, and a provider registry. It has zero runtime dependencies and knows nothing about any particular queue service. Each provider ships as its own module, dropping one file into src/providers/ and registering itself in the providers array in src/index.ts.
Callers import @repo/queue, call createQueue(env), and never learn which provider carries the work. It is the same shape as @repo/email, on purpose (ADR 0033).
Enqueue from a route
import { createQueue } from "@repo/queue";
app.post("/digest", async (c) => {
await createQueue(c.env).enqueue("send-digest", { userId: c.get("userId") });
return c.json({ queued: true });
});
createQueue(env) takes the whole environment. Which key the active provider reads is precisely what the route must not know. It throws a plain Error when QUEUE_PROVIDER is unset or names a provider that is not installed — there is no default in either direction.
enqueue(name, payload?, options?) accepts { delaySeconds }. It throws QueueError("unknown_job") for an unregistered name and QueueError("invalid_job") when the payload fails the job's schema; neither reaches a provider and neither is retryable.
Write a job
A job lives in @queue/jobs/<name>.ts and exports a factory, because the jobs table registers a call and that is what an install patch appends and a remove takes back out. src/jobs/example.ts is the worked example; copy it.
import { defineJob } from "../define";
import type { Job } from "../provider";
export const sendDigestJob = (): Job =>
defineJob<{ userId: string }>({
name: "send-digest",
schema: digestPayload, // optional; any Standard Schema (zod, valibot, arktype)
handler: async ({ userId }, ctx) => {
const user = await ctx.step("load-user", () => loadUser(userId));
await ctx.step("send", () => sendMail(user));
},
});
Then add sendDigestJob() to the jobs array in src/index.ts.
ctx carries attempt, step(name, fn) and sleep(seconds). step and sleep are the durable half of the contract: a provider that can checkpoint replays a recorded step and resumes after a sleep, and one that cannot runs the step inline and returns from the sleep at once. Writing a handler against ctx costs nothing now and is what makes durable: true portable when the Cloudflare Workflows path lands (issue #131).
There is no dedupeKey. A job that must not run twice checks its own table in the handler.
Schedule a job
export const nightlyDigest = () =>
defineSchedule({ name: "nightly-digest", cron: "0 2 * * *", job: "send-digest" });
Add the call to the schedules array in src/index.ts. The expression is five fields, UTC, minute resolution: *, a number, a-b, a,b,c, */n and a-b/n. Named months and weekdays, ?, L, W and # are rejected at defineSchedule, so a malformed expression throws at module load rather than never firing. A schedule finer than one minute is not supported.
A provider's cron tick calls dueSchedules(now) and enqueues one message per hit. The tick never runs a job inline, so a scheduled run gets the same retries and dead-lettering as any other.
QueueError
One error shape, five codes.
| Code | Retryable | Raised by |
|---|---|---|
invalid_job |
no | the core, when a payload fails the job's schema |
unknown_job |
no | the core, when no job is registered under the name |
too_large |
no | a provider, when the payload exceeds the service's limit |
rate_limited |
usually | a provider |
provider_error |
provider's call | a provider, or the core wrapping a raw throw |
A provider maps its vendor code onto one of these and keeps the raw value in providerCode. The core never retries: retryable is the flag a consumer reads to choose between another delivery and the dead-letter queue.
Providers
| Module | QUEUE_PROVIDER |
Carries work with | Use it for |
|---|---|---|---|
queue-cloudflare |
cloudflare |
Cloudflare Queues and one Cron Trigger | staging and production |
queue-memory |
memory |
the same Worker, inline | local dev and tests |
QUEUE_PROVIDER is required in both directions. Install a provider and set the variable; installing one without setting it throws at createQueue, and setting it to a provider that is not installed throws too.
queue-cloudflare
saasaloy add queue-cloudflare
add takes one module per call. The queue core arrives with the provider through dependsOn, so do not name it as a second argument.
The module patches apps/api/wrangler.jsonc with two producer bindings (JOBS → <project>-jobs, JOBS_DLQ → <project>-jobs-dlq, where <project> is the project name saasaloy add read from saasaloy.json), one consumer on <project>-jobs, and one * * * * * Cron Trigger. It registers cloudflare() in the providers array in packages/queue/src/index.ts and cloudflareQueueHandlers() in the handlers array in apps/api/src/worker.ts. Both handlers gate on QUEUE_PROVIDER: when it names anything but cloudflare they write one warn line and return, so switching providers without removing this module does not run every job twice.
A job declared durable: true is refused at enqueue with QueueError("provider_error") rather than run as a plain message. Cloudflare Queues cannot checkpoint, and downgrading in silence would drop the replay the handler asked for. The Workflows path is issue #131.
The first deploy creates the queues
The bindings name queues, and wrangler deploy creates each producer queue the account does not have yet: <project>-jobs and <project>-jobs-dlq, since the dead-letter queue has a producer binding too. A later deploy finds both by name and creates nothing. You run no wrangler queues create. Queues need a Workers paid plan; queue-memory exists so local development needs neither the plan nor the queues.
wrangler dev does not deliver a message to your consumer
wrangler dev binds JOBS and JOBS_DLQ locally and a send() against them succeeds, so the producer half runs offline with no account. It stops there. The local runtime does not hand the message back to the queue export, so a handler you are developing never runs, and no error says so. The cron trigger does not fire on its own either; trigger it by hand:
curl "http://127.0.0.1:8787/cdn-cgi/local/scheduled"
That runs scheduled() and enqueues the due schedules, and there the trail ends locally. Develop a handler against queue-memory, which runs it inline, and use wrangler dev under queue-cloudflare to check the bindings and the tick. The ack, retry and dead-letter split is covered by unit tests against a stubbed batch; proving it live needs a deployed Worker and a real queue.
The two knobs
Everything else in the consumer entry is Cloudflare's default and is fine. These two are worth turning:
max_retries: 3inapps/api/wrangler.jsonc. How many deliveries a message gets before the platform routes it to<project>-jobs-dlqitself. Raise it for work that fails on a flaky upstream; lower it for work whose retry costs money.backoffBaseSeconds, the first retry delay, passed tocloudflareQueueHandlers({ backoffBaseSeconds: 30 }). Each attempt doubles it, so the default gives 30, 60 and 120 seconds undermax_retries: 3. A retryable failure is asked for again with that delay; a non-retryable one is sent toJOBS_DLQand acked at once, without burning the attempts.
What the tick costs
The Cron Trigger fires every minute, which is 1,440 Worker invocations a day whether a schedule is due or not. A tick with nothing due does one dueSchedules(now) call in memory and returns, so the CPU cost is negligible, but the invocation count is real and it is what buys minute resolution for the whole schedule table. If nothing in the project is scheduled, remove the trigger from apps/api/wrangler.jsonc; the producer and consumer keep working without it.
Overlapping runs
Cloudflare gives no lock. A schedule that fires every minute while its job takes 90 seconds has two runs in flight, and a retry can overlap the delivery it is retrying. The tick enqueues rather than running inline, which keeps the tick itself short, but it does not serialize anything. A job that must not overlap takes its own lock — a D1 row, or a KV key with a TTL once the kv capability lands (issue #129) — in the handler. The capability ships no lock of its own.
Write an idempotent handler
Cloudflare Queues is at-least-once. A message can be delivered twice with no failure anywhere, so every handler must be safe to run twice. There is no dedupeKey and there will not be one: the check belongs where the work is, because only the handler knows what "already done" means.
export const chargeInvoiceJob = (): Job =>
defineJob<{ invoiceId: string }>({
name: "charge-invoice",
handler: async ({ invoiceId }, ctx) => {
const invoice = await ctx.step("load", () => db.invoice(invoiceId));
if (invoice.chargedAt) return; // a second delivery, or a retry after a timeout
await ctx.step("charge", () => payments.charge(invoice));
await ctx.step("mark", () => db.markCharged(invoiceId));
},
});
Read state and return early, or write through a unique key and let the constraint reject the duplicate. Do not use ctx.attempt as the test: attempt 0 can arrive twice.
queue-memory
saasaloy add queue-memory
The queue core arrives through dependsOn here too.
The local provider. It runs the job inline, in the same Worker, the moment it is enqueued, so pnpm dev and pnpm test need no Cloudflare account, no paid plan and no network. It patches nothing but the providers array: no binding, no cron trigger, no handler set, no env var of its own. Set QUEUE_PROVIDER=memory in packages/env/.env, run pnpm env:setup, and background work runs.
Install both providers side by side and let the variable choose. QUEUE_PROVIDER=memory locally, cloudflare in staging and production. The Cloudflare handlers stay installed and warn-and-return while memory is selected, so nothing runs twice. One caveat if you switch a deployed Worker from cloudflare to memory: the gated consumer returns without acking or retrying, so any message already in <project>-jobs burns its max_retries redeliveries and then lands in <project>-jobs-dlq. Drain the queue before you switch, or expect to replay the dead-letter queue afterwards.
Three ways it differs from production, each deliberate:
- A handler's failure does not reach the caller.
enqueuerecords the failure and returns, because that is what a real enqueue does: the service accepts the message and the handler fails later, on the consumer. A route that behaved differently here would defeat the point of developing against this provider. Passmemory({ rethrow: true })in a test that wants the throw at the call site. delaySecondsis recorded, not slept. Holding apnpm devrequest for ten minutes is not a useful simulation. The number is on the run so a test can assert on it.durable: truewarns instead of being refused. Nothing here survives the process, so nothing here is durable either, but refusing would mean a handler written for the Workflows path (issue #131) could not be run locally at all. The steps run inline and are recorded. Do not read a passing local run as proof the job resumes.
Assert on what it recorded
The factory returns the provider and its recorder. Keep the value; createQueue(env) gives you the client, not the provider.
import { createQueue, queue } from "@repo/queue";
import { memory } from "@repo/queue/providers/memory";
const jobs = memory();
queue.providers.push(jobs); // in a project, the install patch has already done this
await createQueue({ QUEUE_PROVIDER: "memory" }).enqueue("send-digest", { userId: "u1" });
jobs.ran; // [{ job, payload, delaySeconds?, steps, sleeps }] — every run, in order
jobs.failed; // the subset whose handler threw, each with a normalized `error`
jobs.steps; // every ctx.step name across every run, flattened
jobs.sleeps; // every ctx.sleep duration, in seconds
jobs.scheduled; // every schedule runDue fired
jobs.reset(); // clear all five between tests
runDue(at, env?) stands in for the cron tick with no trigger and no clock:
await jobs.runDue(new Date("2026-09-08T02:00:00Z"));
It matches the schedule table against that UTC minute and enqueues each hit rather than calling the handler itself, exactly as the Cloudflare tick does, so a scheduled run goes through the same path as one a route enqueued. env defaults to selecting this provider.
Write a third provider
One file in src/providers/, exporting a factory that returns a QueueProvider: a name and an enqueue(env, job, payload, options). The core has already looked the job up and validated the payload by the time you are called, so serialize { job: job.name, payload } and send it. Read the binding or secret off env inside that file and nowhere else, map every vendor failure onto QueueError, and set retryable honestly; a wrong true means the job runs twice. Honour delaySeconds, and refuse job.durable unless you can genuinely checkpoint.
A provider whose service pushes work back into the Worker ships a second exported factory returning { queue?, scheduled? } and appends it to the handlers array in apps/api/src/worker.ts with a second plugin-array patch. That handler must gate on QUEUE_PROVIDER and settle every message on every branch. queue-cloudflare is the worked binding example and queue-memory the local one; the authoring rules are in .agents/skills/create-provider/, mode queue.
Removal
Remove the dependents first. queue-cloudflare and queue-memory depend on queue, and so does subscription. remove queue refuses while any of them is installed. --force overrides the refusal, and it leaves the dependents broken.
saasaloy remove queue-<provider> deletes the provider file and reverses its plugin-array registration in the core's providers array. queue-cloudflare also reverses its wrangler-binding patches and its handlers entry in apps/api/src/worker.ts. Messages still in the Cloudflare queue survive. Drain them before you remove, or they are never consumed.
saasaloy remove queue then deletes the packages/queue workspace (index.ts, define.ts, provider.ts, cron.ts, jobs/example.ts, env-preset.ts) and reverses the plugin-array patch that adds the queue preset to apps/api/src/env.ts. A job file you added under src/jobs/ is untracked, so remove leaves it. The @repo/queue line in apps/api/package.json survives, because a package-json-dependency patch has no removal inverse. Drop it by hand and run pnpm install. A file you edited by hand since add counts as drift, and remove asks before it deletes it. remove does not edit packages/env/.env, so delete the QUEUE_PROVIDER lines by hand.
Every route that imports @repo/queue to enqueue stops compiling.
Failure modes
QUEUE_PROVIDER is not set.thrown bycreateQueue(env). The key is required even with one provider installed. Set it inpackages/env/.envand runpnpm env:setup.QUEUE_PROVIDER is "<x>", which is not registered.Fix the value orsaasaloy add queue-<x>.QueueError("unknown_job")withNo job named "<name>" is registered.Add the job to thejobslist in the queueindex.ts.QueueError("invalid_job")withPayload for job "<name>" failed validation. The payload does not match the job schema. Fix the caller. The consumer sends it to the dead-letter queue, because it is never retryable.QueueError("provider_error")withNo `<binding>` Queues binding on this Worker's env.fromqueue-cloudflare. Check the queue producer entry inapps/api/wrangler.jsonc.- Any other
QueueError. Branch oncode(invalid_job,unknown_job,too_large,rate_limited,provider_error). The package never retries. The consumer readsretryableto decide.
Next
Run saasaloy-api to enqueue a job from a route.
04 同仓库更多 Skills
saasaloy-subscription
Runbook for the subscription capability — provider-agnostic subscriptions in packages/subscription, with a plan file, a projection table, a billable-subject file, plan entitlements and per-provider modules. Use when adding a plan, adding a plan feature or a numeric limit, gating an API route with requireFeature or requireWithinLimit, reading the 402 it returns, working out why a subject resolves to the free plan, wiring a checkout or portal route, reading a SubscriptionError, choosing or switching SUBSCRIPTION_PROVIDER, registering a webhook in the vendor's dashboard, writing a third subscription provider, or upgrading a project that still has `billing` installed.
saasaloy-notification
Runbook for the notification module, in-app notifications for apps/app. It owns the notifications and notification_opt_outs tables, notify() in apps/api/src/lib/notify.ts, the /notifications api routes, the bell in the app header, the sidebar badge, the /notifications page with Inbox and Preferences tabs, the notification config section, and the daily prune. Use when sending a notification from an api route, adding or changing a category, changing retention, debugging a badge or bell count that does not move, or removing the module.
saasaloy-cms
Runbook for the cms module, the in-house CMS behind apps/admin. Covers code-defined collections, the Tiptap editor, drafts, revisions and redirects, the publish-time renderer, the public blog on apps/web and its 60-second cache. Use when adding a collection or a field, rendering a stored body, reusing the editor, renderer or media field from another module, moving the blog to another path, re-rendering live posts after a renderer upgrade or a STORAGE_PUBLIC_URL change, or working out why a published post is not live yet.
saasaloy-beta
The beta module's own procedure.
helper
暂无简介
saasaloy-update
Runbook for an AI agent that updates this project to a newer Saasaloy CLI and newer module versions with saasaloy update. Use when the owner says "update saasaloy", "upgrade the CLI", "pull the latest modules", "update the base template", "work the merge plan", "clear the update notes", when saasaloy update or saasaloy outdated --check exits 3 or 2, when a merge plan or .saasaloy/merge-plan.md is handed to you, or when an adopted project takes its first update. Covers the CLI upgrade, the preview, --out, the file merges, the update notes and "Notes that may apply", --resolved and --done, a file deleted locally and --restore, a three-way or two-way base, an update that skips releases, --from, the verify commands, and the exit codes.