[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79GM35ETA2869YCNDDAFEBM":3,"skill-same:01M79GM35ETA2869YCNDDAFEBM":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M79GM35ETA2869YCNDDAFEBM","saasaloy-queue",null,"Runbook for the queue capability — provider-agnostic background work in packages\u002Fqueue, 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.","mimukit\u002Fsaasaloy","mimukit","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F11677026?v=4","01M79GFSERAQQ77QPQMC1N0Y6M","Mukitul Islam Mukit","01M79GFSFA4WMGEEBHA68N59WV",4,"MIT","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fqueue\u002Fskills\u002Fsaasaloy-queue\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: saasaloy-queue\ndescription: Runbook for the queue capability — provider-agnostic background work in packages\u002Fqueue, 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.\n---\n\n# queue — provider-agnostic background work from `packages\u002Fqueue`\n\n`packages\u002Fqueue` (`@repo\u002Fqueue`) 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\u002Fproviders\u002F` and registering itself in the `providers` array in `src\u002Findex.ts`.\n\nCallers import `@repo\u002Fqueue`, call `createQueue(env)`, and never learn which provider carries the work. It is the same shape as `@repo\u002Femail`, on purpose (ADR 0033).\n\n## Enqueue from a route\n\n```ts\nimport { createQueue } from \"@repo\u002Fqueue\";\n\napp.post(\"\u002Fdigest\", async (c) => {\n  await createQueue(c.env).enqueue(\"send-digest\", { userId: c.get(\"userId\") });\n  return c.json({ queued: true });\n});\n```\n\n`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.\n\n`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.\n\n## Write a job\n\nA job lives in `@queue\u002Fjobs\u002F\u003Cname>.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\u002Fjobs\u002Fexample.ts` is the worked example; copy it.\n\n```ts\nimport { defineJob } from \"..\u002Fdefine\";\nimport type { Job } from \"..\u002Fprovider\";\n\nexport const sendDigestJob = (): Job =>\n  defineJob\u003C{ userId: string }>({\n    name: \"send-digest\",\n    schema: digestPayload, \u002F\u002F optional; any Standard Schema (zod, valibot, arktype)\n    handler: async ({ userId }, ctx) => {\n      const user = await ctx.step(\"load-user\", () => loadUser(userId));\n      await ctx.step(\"send\", () => sendMail(user));\n    },\n  });\n```\n\nThen add `sendDigestJob()` to the `jobs` array in `src\u002Findex.ts`.\n\n`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).\n\nThere is no `dedupeKey`. A job that must not run twice checks its own table in the handler.\n\n## Schedule a job\n\n```ts\nexport const nightlyDigest = () =>\n  defineSchedule({ name: \"nightly-digest\", cron: \"0 2 * * *\", job: \"send-digest\" });\n```\n\nAdd the call to the `schedules` array in `src\u002Findex.ts`. The expression is five fields, UTC, minute resolution: `*`, a number, `a-b`, `a,b,c`, `*\u002Fn` and `a-b\u002Fn`. 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.\n\nA 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.\n\n## `QueueError`\n\nOne error shape, five codes.\n\n| Code | Retryable | Raised by |\n| --- | --- | --- |\n| `invalid_job` | no | the core, when a payload fails the job's schema |\n| `unknown_job` | no | the core, when no job is registered under the name |\n| `too_large` | no | a provider, when the payload exceeds the service's limit |\n| `rate_limited` | usually | a provider |\n| `provider_error` | provider's call | a provider, or the core wrapping a raw throw |\n\nA 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.\n\n## Providers\n\n| Module | `QUEUE_PROVIDER` | Carries work with | Use it for |\n| --- | --- | --- | --- |\n| `queue-cloudflare` | `cloudflare` | Cloudflare Queues and one Cron Trigger | staging and production |\n| `queue-memory` | `memory` | the same Worker, inline | local dev and tests |\n\n`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.\n\n## `queue-cloudflare`\n\n```sh\nsaasaloy add queue-cloudflare\n```\n\n`add` takes one module per call. The `queue` core arrives with the provider through `dependsOn`, so do not name it as a second argument.\n\nThe module patches `apps\u002Fapi\u002Fwrangler.jsonc` with two producer bindings (`JOBS` → `\u003Cproject>-jobs`, `JOBS_DLQ` → `\u003Cproject>-jobs-dlq`, where `\u003Cproject>` is the project name `saasaloy add` read from `saasaloy.json`), one consumer on `\u003Cproject>-jobs`, and one `* * * * *` Cron Trigger. It registers `cloudflare()` in the `providers` array in `packages\u002Fqueue\u002Fsrc\u002Findex.ts` and `cloudflareQueueHandlers()` in the `handlers` array in `apps\u002Fapi\u002Fsrc\u002Fworker.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.\n\nA 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.\n\n### The first deploy creates the queues\n\nThe bindings name queues, and `wrangler deploy` creates each producer queue the account does not have yet: `\u003Cproject>-jobs` and `\u003Cproject>-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.\n\n### `wrangler dev` does not deliver a message to your consumer\n\n`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:\n\n```sh\ncurl \"http:\u002F\u002F127.0.0.1:8787\u002Fcdn-cgi\u002Flocal\u002Fscheduled\"\n```\n\nThat 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.\n\n### The two knobs\n\nEverything else in the consumer entry is Cloudflare's default and is fine. These two are worth turning:\n\n- **`max_retries: 3`** in `apps\u002Fapi\u002Fwrangler.jsonc`. How many deliveries a message gets before the platform routes it to `\u003Cproject>-jobs-dlq` itself. Raise it for work that fails on a flaky upstream; lower it for work whose retry costs money.\n- **`backoffBaseSeconds`**, the first retry delay, passed to `cloudflareQueueHandlers({ backoffBaseSeconds: 30 })`. Each attempt doubles it, so the default gives 30, 60 and 120 seconds under `max_retries: 3`. A retryable failure is asked for again with that delay; a non-retryable one is sent to `JOBS_DLQ` and acked at once, without burning the attempts.\n\n### What the tick costs\n\nThe 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\u002Fapi\u002Fwrangler.jsonc`; the producer and consumer keep working without it.\n\n### Overlapping runs\n\nCloudflare 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.\n\n### Write an idempotent handler\n\nCloudflare 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.\n\n```ts\nexport const chargeInvoiceJob = (): Job =>\n  defineJob\u003C{ invoiceId: string }>({\n    name: \"charge-invoice\",\n    handler: async ({ invoiceId }, ctx) => {\n      const invoice = await ctx.step(\"load\", () => db.invoice(invoiceId));\n      if (invoice.chargedAt) return; \u002F\u002F a second delivery, or a retry after a timeout\n      await ctx.step(\"charge\", () => payments.charge(invoice));\n      await ctx.step(\"mark\", () => db.markCharged(invoiceId));\n    },\n  });\n```\n\nRead 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.\n\n## `queue-memory`\n\n```sh\nsaasaloy add queue-memory\n```\n\nThe `queue` core arrives through `dependsOn` here too.\n\nThe 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\u002Fenv\u002F.env`, run `pnpm env:setup`, and background work runs.\n\nInstall 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 `\u003Cproject>-jobs` burns its `max_retries` redeliveries and then lands in `\u003Cproject>-jobs-dlq`. Drain the queue before you switch, or expect to replay the dead-letter queue afterwards.\n\nThree ways it differs from production, each deliberate:\n\n- **A handler's failure does not reach the caller.** `enqueue` records 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. Pass `memory({ rethrow: true })` in a test that wants the throw at the call site.\n- **`delaySeconds` is recorded, not slept.** Holding a `pnpm dev` request for ten minutes is not a useful simulation. The number is on the run so a test can assert on it.\n- **`durable: true` warns 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.\n\n### Assert on what it recorded\n\nThe factory returns the provider **and** its recorder. Keep the value; `createQueue(env)` gives you the client, not the provider.\n\n```ts\nimport { createQueue, queue } from \"@repo\u002Fqueue\";\nimport { memory } from \"@repo\u002Fqueue\u002Fproviders\u002Fmemory\";\n\nconst jobs = memory();\nqueue.providers.push(jobs); \u002F\u002F in a project, the install patch has already done this\n\nawait createQueue({ QUEUE_PROVIDER: \"memory\" }).enqueue(\"send-digest\", { userId: \"u1\" });\n\njobs.ran;       \u002F\u002F [{ job, payload, delaySeconds?, steps, sleeps }] — every run, in order\njobs.failed;    \u002F\u002F the subset whose handler threw, each with a normalized `error`\njobs.steps;     \u002F\u002F every ctx.step name across every run, flattened\njobs.sleeps;    \u002F\u002F every ctx.sleep duration, in seconds\njobs.scheduled; \u002F\u002F every schedule runDue fired\njobs.reset();   \u002F\u002F clear all five between tests\n```\n\n`runDue(at, env?)` stands in for the cron tick with no trigger and no clock:\n\n```ts\nawait jobs.runDue(new Date(\"2026-09-08T02:00:00Z\"));\n```\n\nIt 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.\n\n## Write a third provider\n\nOne file in `src\u002Fproviders\u002F`, 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.\n\nA 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\u002Fapi\u002Fsrc\u002Fworker.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\u002Fskills\u002Fcreate-provider\u002F`, mode `queue`.\n\n## Removal\n\nRemove 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.\n\n`saasaloy remove queue-\u003Cprovider>` 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\u002Fapi\u002Fsrc\u002Fworker.ts`. Messages still in the Cloudflare queue survive. Drain them before you remove, or they are never consumed.\n\n`saasaloy remove queue` then deletes the `packages\u002Fqueue` workspace (`index.ts`, `define.ts`, `provider.ts`, `cron.ts`, `jobs\u002Fexample.ts`, `env-preset.ts`) and reverses the `plugin-array` patch that adds the queue preset to `apps\u002Fapi\u002Fsrc\u002Fenv.ts`. A job file you added under `src\u002Fjobs\u002F` is untracked, so `remove` leaves it. The `@repo\u002Fqueue` line in `apps\u002Fapi\u002Fpackage.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\u002Fenv\u002F.env`, so delete the `QUEUE_PROVIDER` lines by hand.\n\nEvery route that imports `@repo\u002Fqueue` to enqueue stops compiling.\n\n## Failure modes\n\n- `QUEUE_PROVIDER is not set.` thrown by `createQueue(env)`. The key is required even with one provider installed. Set it in `packages\u002Fenv\u002F.env` and run `pnpm env:setup`.\n- `QUEUE_PROVIDER is \"\u003Cx>\", which is not registered.` Fix the value or `saasaloy add queue-\u003Cx>`.\n- `QueueError(\"unknown_job\")` with `No job named \"\u003Cname>\" is registered.` Add the job to the `jobs` list in the queue `index.ts`.\n- `QueueError(\"invalid_job\")` with `Payload for job \"\u003Cname>\" 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.\n- `QueueError(\"provider_error\")` with ``No `\u003Cbinding>` Queues binding on this Worker's env.`` from `queue-cloudflare`. Check the queue producer entry in `apps\u002Fapi\u002Fwrangler.jsonc`.\n- Any other `QueueError`. Branch on `code` (`invalid_job`, `unknown_job`, `too_large`, `rate_limited`, `provider_error`). The package never retries. The consumer reads `retryable` to decide.\n\n## Next\n\nRun `saasaloy-api` to enqueue a job from a route.\n","# queue — provider-agnostic background work from `packages\u002Fqueue`\n\n`packages\u002Fqueue` (`@repo\u002Fqueue`) 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\u002Fproviders\u002F` and registering itself in the `providers` array in `src\u002Findex.ts`.\n\nCallers import `@repo\u002Fqueue`, call `createQueue(env)`, and never learn which provider carries the work. It is the same shape as `@repo\u002Femail`, on purpose (ADR 0033).\n\n## Enqueue from a route\n\n```ts\nimport { createQueue } from \"@repo\u002Fqueue\";\n\napp.post(\"\u002Fdigest\", async (c) => {\n  await createQueue(c.env).enqueue(\"send-digest\", { userId: c.get(\"userId\") });\n  return c.json({ queued: true });\n});\n```\n\n`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.\n\n`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.\n\n## Write a job\n\nA job lives in `@queue\u002Fjobs\u002F\u003Cname>.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\u002Fjobs\u002Fexample.ts` is the worked example; copy it.\n\n```ts\nimport { defineJob } from \"..\u002Fdefine\";\nimport type { Job } from \"..\u002Fprovider\";\n\nexport const sendDigestJob = (): Job =>\n  defineJob\u003C{ userId: string }>({\n    name: \"send-digest\",\n    schema: digestPayload, \u002F\u002F optional; any Standard Schema (zod, valibot, arktype)\n    handler: async ({ userId }, ctx) => {\n      const user = await ctx.step(\"load-user\", () => loadUser(userId));\n      await ctx.step(\"send\", () => sendMail(user));\n    },\n  });\n```\n\nThen add `sendDigestJob()` to the `jobs` array in `src\u002Findex.ts`.\n\n`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).\n\nThere is no `dedupeKey`. A job that must not run twice checks its own table in the handler.\n\n## Schedule a job\n\n```ts\nexport const nightlyDigest = () =>\n  defineSchedule({ name: \"nightly-digest\", cron: \"0 2 * * *\", job: \"send-digest\" });\n```\n\nAdd the call to the `schedules` array in `src\u002Findex.ts`. The expression is five fields, UTC, minute resolution: `*`, a number, `a-b`, `a,b,c`, `*\u002Fn` and `a-b\u002Fn`. 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.\n\nA 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.\n\n## `QueueError`\n\nOne error shape, five codes.\n\n| Code | Retryable | Raised by |\n| --- | --- | --- |\n| `invalid_job` | no | the core, when a payload fails the job's schema |\n| `unknown_job` | no | the core, when no job is registered under the name |\n| `too_large` | no | a provider, when the payload exceeds the service's limit |\n| `rate_limited` | usually | a provider |\n| `provider_error` | provider's call | a provider, or the core wrapping a raw throw |\n\nA 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.\n\n## Providers\n\n| Module | `QUEUE_PROVIDER` | Carries work with | Use it for |\n| --- | --- | --- | --- |\n| `queue-cloudflare` | `cloudflare` | Cloudflare Queues and one Cron Trigger | staging and production |\n| `queue-memory` | `memory` | the same Worker, inline | local dev and tests |\n\n`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.\n\n## `queue-cloudflare`\n\n```sh\nsaasaloy add queue-cloudflare\n```\n\n`add` takes one module per call. The `queue` core arrives with the provider through `dependsOn`, so do not name it as a second argument.\n\nThe module patches `apps\u002Fapi\u002Fwrangler.jsonc` with two producer bindings (`JOBS` → `\u003Cproject>-jobs`, `JOBS_DLQ` → `\u003Cproject>-jobs-dlq`, where `\u003Cproject>` is the project name `saasaloy add` read from `saasaloy.json`), one consumer on `\u003Cproject>-jobs`, and one `* * * * *` Cron Trigger. It registers `cloudflare()` in the `providers` array in `packages\u002Fqueue\u002Fsrc\u002Findex.ts` and `cloudflareQueueHandlers()` in the `handlers` array in `apps\u002Fapi\u002Fsrc\u002Fworker.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.\n\nA 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.\n\n### The first deploy creates the queues\n\nThe bindings name queues, and `wrangler deploy` creates each producer queue the account does not have yet: `\u003Cproject>-jobs` and `\u003Cproject>-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.\n\n### `wrangler dev` does not deliver a message to your consumer\n\n`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:\n\n```sh\ncurl \"http:\u002F\u002F127.0.0.1:8787\u002Fcdn-cgi\u002Flocal\u002Fscheduled\"\n```\n\nThat 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.\n\n### The two knobs\n\nEverything else in the consumer entry is Cloudflare's default and is fine. These two are worth turning:\n\n- **`max_retries: 3`** in `apps\u002Fapi\u002Fwrangler.jsonc`. How many deliveries a message gets before the platform routes it to `\u003Cproject>-jobs-dlq` itself. Raise it for work that fails on a flaky upstream; lower it for work whose retry costs money.\n- **`backoffBaseSeconds`**, the first retry delay, passed to `cloudflareQueueHandlers({ backoffBaseSeconds: 30 })`. Each attempt doubles it, so the default gives 30, 60 and 120 seconds under `max_retries: 3`. A retryable failure is asked for again with that delay; a non-retryable one is sent to `JOBS_DLQ` and acked at once, without burning the attempts.\n\n### What the tick costs\n\nThe 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\u002Fapi\u002Fwrangler.jsonc`; the producer and consumer keep working without it.\n\n### Overlapping runs\n\nCloudflare 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.\n\n### Write an idempotent handler\n\nCloudflare 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.\n\n```ts\nexport const chargeInvoiceJob = (): Job =>\n  defineJob\u003C{ invoiceId: string }>({\n    name: \"charge-invoice\",\n    handler: async ({ invoiceId }, ctx) => {\n      const invoice = await ctx.step(\"load\", () => db.invoice(invoiceId));\n      if (invoice.chargedAt) return; \u002F\u002F a second delivery, or a retry after a timeout\n      await ctx.step(\"charge\", () => payments.charge(invoice));\n      await ctx.step(\"mark\", () => db.markCharged(invoiceId));\n    },\n  });\n```\n\nRead 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.\n\n## `queue-memory`\n\n```sh\nsaasaloy add queue-memory\n```\n\nThe `queue` core arrives through `dependsOn` here too.\n\nThe 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\u002Fenv\u002F.env`, run `pnpm env:setup`, and background work runs.\n\nInstall 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 `\u003Cproject>-jobs` burns its `max_retries` redeliveries and then lands in `\u003Cproject>-jobs-dlq`. Drain the queue before you switch, or expect to replay the dead-letter queue afterwards.\n\nThree ways it differs from production, each deliberate:\n\n- **A handler's failure does not reach the caller.** `enqueue` records 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. Pass `memory({ rethrow: true })` in a test that wants the throw at the call site.\n- **`delaySeconds` is recorded, not slept.** Holding a `pnpm dev` request for ten minutes is not a useful simulation. The number is on the run so a test can assert on it.\n- **`durable: true` warns 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.\n\n### Assert on what it recorded\n\nThe factory returns the provider **and** its recorder. Keep the value; `createQueue(env)` gives you the client, not the provider.\n\n```ts\nimport { createQueue, queue } from \"@repo\u002Fqueue\";\nimport { memory } from \"@repo\u002Fqueue\u002Fproviders\u002Fmemory\";\n\nconst jobs = memory();\nqueue.providers.push(jobs); \u002F\u002F in a project, the install patch has already done this\n\nawait createQueue({ QUEUE_PROVIDER: \"memory\" }).enqueue(\"send-digest\", { userId: \"u1\" });\n\njobs.ran;       \u002F\u002F [{ job, payload, delaySeconds?, steps, sleeps }] — every run, in order\njobs.failed;    \u002F\u002F the subset whose handler threw, each with a normalized `error`\njobs.steps;     \u002F\u002F every ctx.step name across every run, flattened\njobs.sleeps;    \u002F\u002F every ctx.sleep duration, in seconds\njobs.scheduled; \u002F\u002F every schedule runDue fired\njobs.reset();   \u002F\u002F clear all five between tests\n```\n\n`runDue(at, env?)` stands in for the cron tick with no trigger and no clock:\n\n```ts\nawait jobs.runDue(new Date(\"2026-09-08T02:00:00Z\"));\n```\n\nIt 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.\n\n## Write a third provider\n\nOne file in `src\u002Fproviders\u002F`, 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.\n\nA 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\u002Fapi\u002Fsrc\u002Fworker.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\u002Fskills\u002Fcreate-provider\u002F`, mode `queue`.\n\n## Removal\n\nRemove 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.\n\n`saasaloy remove queue-\u003Cprovider>` 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\u002Fapi\u002Fsrc\u002Fworker.ts`. Messages still in the Cloudflare queue survive. Drain them before you remove, or they are never consumed.\n\n`saasaloy remove queue` then deletes the `packages\u002Fqueue` workspace (`index.ts`, `define.ts`, `provider.ts`, `cron.ts`, `jobs\u002Fexample.ts`, `env-preset.ts`) and reverses the `plugin-array` patch that adds the queue preset to `apps\u002Fapi\u002Fsrc\u002Fenv.ts`. A job file you added under `src\u002Fjobs\u002F` is untracked, so `remove` leaves it. The `@repo\u002Fqueue` line in `apps\u002Fapi\u002Fpackage.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\u002Fenv\u002F.env`, so delete the `QUEUE_PROVIDER` lines by hand.\n\nEvery route that imports `@repo\u002Fqueue` to enqueue stops compiling.\n\n## Failure modes\n\n- `QUEUE_PROVIDER is not set.` thrown by `createQueue(env)`. The key is required even with one provider installed. Set it in `packages\u002Fenv\u002F.env` and run `pnpm env:setup`.\n- `QUEUE_PROVIDER is \"\u003Cx>\", which is not registered.` Fix the value or `saasaloy add queue-\u003Cx>`.\n- `QueueError(\"unknown_job\")` with `No job named \"\u003Cname>\" is registered.` Add the job to the `jobs` list in the queue `index.ts`.\n- `QueueError(\"invalid_job\")` with `Payload for job \"\u003Cname>\" 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.\n- `QueueError(\"provider_error\")` with ``No `\u003Cbinding>` Queues binding on this Worker's env.`` from `queue-cloudflare`. Check the queue producer entry in `apps\u002Fapi\u002Fwrangler.jsonc`.\n- Any other `QueueError`. Branch on `code` (`invalid_job`, `unknown_job`, `too_large`, `rate_limited`, `provider_error`). The package never retries. The consumer reads `retryable` to decide.\n\n## Next\n\nRun `saasaloy-api` to enqueue a job from a route.\n",{"name":5,"description":7},"main","5ecf3d110b216ef678e06a1630f6b63a8e730bb5","modules\u002Fqueue\u002Fskills\u002Fsaasaloy-queue",0,"https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy","https:\u002F\u002Fsaasaloy.com","https:\u002F\u002Fgithub.com\u002Fmimukit","https:\u002F\u002Fmimukit.com","Senior Software Engineer · 9+ yrs Fullstack (TS\u002FNode\u002FReact) · AI integrations, distributed systems · Building @saasaloy & @codealoy · Bangladesh 🇧🇩 \u002F Remote","2026-11-13 20:39:28",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add mimukit\u002Fsaasaloy --skill saasaloy-queue",{"tool":40,"command":41},"bunx","bunx skills add mimukit\u002Fsaasaloy --skill saasaloy-queue",{"tool":43,"command":44},"pnpm","pnpm dlx skills add mimukit\u002Fsaasaloy --skill saasaloy-queue","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fqueue\u002Fskills\u002Fsaasaloy-queue\u002FSKILL.md",true,[],[49,56,63,70,77,83],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M7BE75C34XHSPVJNQC8FY4Q0","saasaloy-subscription","Runbook for the subscription capability — provider-agnostic subscriptions in packages\u002Fsubscription, 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.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fsubscription\u002Fskills\u002Fsaasaloy-subscription\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M7BE68MJ8H47JZKTBDFYR6JD","saasaloy-notification","Runbook for the notification module, in-app notifications for apps\u002Fapp. It owns the notifications and notification_opt_outs tables, notify() in apps\u002Fapi\u002Fsrc\u002Flib\u002Fnotify.ts, the \u002Fnotifications api routes, the bell in the app header, the sidebar badge, the \u002Fnotifications 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.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fnotification\u002Fskills\u002Fsaasaloy-notification\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M7BE53PDQV0YDPG8RNVGTPEQ","saasaloy-cms","Runbook for the cms module, the in-house CMS behind apps\u002Fadmin. Covers code-defined collections, the Tiptap editor, drafts, revisions and redirects, the publish-time renderer, the public blog on apps\u002Fweb 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.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fcms\u002Fskills\u002Fsaasaloy-cms\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M79GQ03M63V5EKSST92B3S5X","saasaloy-beta","The beta module's own procedure.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fpackages\u002Fcli\u002Ftest\u002Ffixtures\u002Fregistry-clean\u002Fbeta\u002Fsaasaloy-beta\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M79GPXV3K8YF3M4VA0KGVE0B","helper","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fpackages\u002Fcli\u002Ftest\u002Ffixtures\u002Fregistry-broken\u002Fbad-skill\u002Fhelper\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M79GPR8EVS1YX0W8X33Q9YD8","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\u002Fmerge-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.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fpackages\u002Fcli\u002Ftemplates\u002Fbase\u002F_agents\u002Fskills\u002Fsaasaloy-update\u002FSKILL.md",[],[]]