@cslug/queue 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # @cslug/queue
2
2
 
3
- Jobs and workers on Redis Streams, after-commit and durable dispatch, and the scheduler.
3
+ Jobs and workers on Redis Streams: retries with backoff, delays, priorities, unique jobs, after-commit dispatch,
4
+ queued listeners, the failed store and the `queue:*` commands; the scheduler (`routes/schedule.ts`). List
5
+ `QueueProvider` and `ScheduleProvider` in `bootstrap/providers.ts`.
4
6
 
5
- > Not implemented yet. Part of [cslug](https://github.com/cslugts/cslug).
7
+ ```ts
8
+ await SendCheckinJob.dispatch({ bookingId }).delay('3d')
9
+ ```
10
+
11
+ Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
12
+ [guide 11](../../guides/11-queues-and-jobs.md), [guide 12](../../guides/12-scheduler.md).
package/docs/README.md CHANGED
@@ -1,6 +1,120 @@
1
1
  # @cslug/queue
2
2
 
3
- Jobs and workers on Redis Streams, after-commit and durable dispatch, and the scheduler.
3
+ Jobs on cslug's own queue on Redis Streams ([D8](../../../docs/decisions.md)), with no dependency. List
4
+ `QueueProvider` after `RedisProvider` in `bootstrap/providers.ts`; the guide is
5
+ [guide 11](../../../guides/11-queues-and-jobs.md).
4
6
 
5
- > **Not implemented yet.** This version is an empty placeholder kept for the lockstep release; the package is
6
- > planned for 0.2.0.
7
+ ```ts
8
+ @inject(BookingRepository)
9
+ export class SendCheckinJob extends Job<{ bookingId: string }> {
10
+ static queue = 'notifications'
11
+ static tries = 5
12
+ static backoff = Job.exponential('30s', { max: '30m', jitter: true })
13
+ constructor(private bookings: BookingRepository) { super() }
14
+ async handle({ bookingId }: { bookingId: string }) { … }
15
+ async failed({ bookingId }: { bookingId: string }, error: Error) { … } // after the last attempt
16
+ }
17
+
18
+ await SendCheckinJob.dispatch({ bookingId }).delay('3d').unique(`checkin:${bookingId}`)
19
+ ```
20
+
21
+ The statics (`queue`, `tries`, `backoff`, `timeout`, `jobName`) and `failed` are not declared on `Job`, so
22
+ apps with `noImplicitOverride` need no `override`. Defaults: queue `default`, 3 tries, exponential backoff from
23
+ 5 s (capped at 10 min, with jitter), timeout 60 s. A job without constructor arguments needs no `@inject`.
24
+
25
+ ## How it works
26
+
27
+ | | Redis (under the connection prefix + `queue:`) |
28
+ |---|---|
29
+ | Waiting jobs | A stream per queue and priority band: `q:<queue>:high`, `q:<queue>`, `q:<queue>:low` (priorities 1–3, 4–7, 8–10), consumer group `workers` |
30
+ | Delayed jobs and retries | A sorted set `delayed:<queue>` scored by due time; workers move due jobs to the streams (Lua) |
31
+ | `unique(key)` | `SET unique:<key> <job id> NX PX` (default hold 1 day + delay); released when the job finishes or fails for good |
32
+ | Failed jobs | A hash `failed` + a sorted set `failed:index`; older than `queue.failed.keep` (default 30 d) are pruned |
33
+ | Ack, retry, fail | One Lua script each (`XACK` + `XDEL` + the next step), so a job is never lost between two commands |
34
+
35
+ **Dispatch.** Inside `db.transaction()` the push is held until COMMIT and dropped on rollback (core's
36
+ `afterCommit`, which `@cslug/database` drives); `.immediately()` opts out. Outside a transaction it is sent
37
+ before `await` returns. `await` gives the job id, or `null` when a `unique` key is already held (inside a
38
+ transaction the id, since the check happens at COMMIT). Payloads are JSON that keeps `bigint` and `Date`.
39
+
40
+ **Workers.** `cslug queue:work` loads `app/jobs/` and `app/listeners/` (subfolders included, not `*.test.ts`),
41
+ then runs a read loop per queue on its own connection (`autoReconnect: false`, a client-side deadline on each
42
+ blocking read; spike c). Each job runs in a fresh scope and context (`jobId`, `attempt`), its payload checked
43
+ against `Job.schema(…)` if declared, under `timeout`. A failure retries after `backoff(attempt)`; after `tries`
44
+ attempts, `failed(payload, error)` runs once and the job goes to the failed store.
45
+
46
+ **Crashes.** A running job renews its lease every `lease / 3`. A job whose worker died is taken over by another
47
+ worker once it has been idle for `queue.lease` (default 30 s; `XAUTOCLAIM`), and counts as an attempt. Delivery is
48
+ **at least once**: make side effects idempotent (`db.idempotent`). A job that runs past its `timeout` fails, but
49
+ its handler cannot be stopped and finishes in the background.
50
+
51
+ **Shutdown.** On `SIGTERM` the provider stops the workers: no new reads, running jobs finish (up to
52
+ `queue.shutdownTimeout`, default 30 s); what is left is taken over after its lease.
53
+
54
+ **Queued listeners.** `@listener(Event, { queued: true, queue, tries })` runs as the job `cslug.listener` on that
55
+ queue, after COMMIT.
56
+
57
+ ## Commands
58
+
59
+ `queue:work [--queues=a,b] [--concurrency=n]` (`--queue` works too; default: every queue in config, concurrency
60
+ from config, else 1) · `queue:failed [--json]` · `queue:retry <id|all>` · `queue:forget <id>` ·
61
+ `queue:clear [queue] [--force]` · `queue:stats [--json]`.
62
+
63
+ ## Tests
64
+
65
+ `testApp({ fakes: ['queue'] })` swaps in `QueueFake` (`t.queue`): `assertPushed(Job, (j) => …)`,
66
+ `assertNotPushed`, `assertPushedCount`, `assertNothingPushed`, `of(Job)`, `pushed`, and `drain()`, which runs
67
+ every recorded job (delays ignored), including those they push. A rolled-back dispatch is never recorded.
68
+
69
+ ## Scheduler
70
+
71
+ List `ScheduleProvider` after `QueueProvider`. It loads `routes/schedule.ts` at boot
72
+ ([guide 12](../../../guides/12-scheduler.md)):
73
+
74
+ ```ts
75
+ export default defineSchedule((s) => {
76
+ s.job(DispatchDailyCheckinsJob).dailyAt('08:00').timezone('Indian/Antananarivo')
77
+ s.call('cache:prune-fx', async ({ resolve }) => resolve(Cache).tags(['fx']).flush()).hourly()
78
+ s.cron('0 */6 * * *', 'db:vacuum-webhook-inbox', VacuumWebhookInboxJob)
79
+ })
80
+ ```
81
+
82
+ - **Cron:** cslug's own 5-field parser (lists, ranges, steps, month and day names, 0 or 7 for Sunday; day of month
83
+ OR day of week when both are set). Times are wall-clock in the entry's zone (`.timezone()`, else
84
+ `schedule.timezone`, else UTC), DST included.
85
+ - **Once per tick:** before running, an instance takes the lock `schedule:<name>:<tick>` (core's `Lock`, Redis with
86
+ `RedisProvider`) and keeps it 10 min, so any number of schedulers run an entry once per minute.
87
+ - **No overlap:** a job entry is dispatched with `unique('schedule:<name>')` (skipped while the last one waits or
88
+ runs); an inline task holds `schedule:<name>:running`. `.allowOverlap()` turns both off.
89
+ - **Names:** from the job class (`DispatchDailyCheckinsJob` → `dispatch-daily-checkins`), the first argument of
90
+ `s.call` / `s.cron`, or `.as(name)`. Two entries with one name are refused.
91
+ - **History:** the last 100 runs per entry in Redis (`schedule:history:<name>` under the queue prefix): `name`,
92
+ `scheduledFor`, `startedAt`, `finishedAt`, `status` (`dispatched`, `ok`, `failed`, `skipped`), `error`.
93
+ - **`catchUp('once')`:** when the loop starts, an entry whose next tick after its last recorded run is already past
94
+ runs once for that tick. Other missed ticks are skipped.
95
+ - **The loop** (`schedule:work`) ticks at the start of every minute, writes a heartbeat, and stops after the current
96
+ tick at shutdown.
97
+
98
+ Commands: `schedule:work`, `schedule:run` (one tick, for an external cron), `schedule:list [--json]`,
99
+ `schedule:history <name> [--last=10]`, `schedule:test <name>` (run now, ignoring the schedule and the tick lock).
100
+
101
+ In tests: `t.schedule.runDue()` runs what is due at `t.clock`'s time, without the tick lock, so a test can replay a
102
+ tick.
103
+
104
+ ## Durable dispatch, chains, batches, rate limits
105
+
106
+ - **`.durable()`** (needs `@cslug/database`; the provider detects it, binds `Outbox` and registers the
107
+ `cslug_queue_outbox` migration): inside a transaction the job is inserted in that transaction and relayed right
108
+ after COMMIT; workers relay leftovers every second (`SELECT … FOR UPDATE SKIP LOCKED`, push, delete). Outside a
109
+ transaction it is sent at once.
110
+ - **`Queue.chain([A.with(p), B.with(q)])`**: the remaining jobs travel in the envelope; the next one is dispatched
111
+ when the previous succeeds; a job that fails for good ends the chain.
112
+ - **`Queue.batch([...]).then(C.with(r)).allowFailures()`**: a Redis hash counts finished jobs (an atomic Lua
113
+ countdown); the last one dispatches `then()` (not if a job failed, without `allowFailures()`). Batch state
114
+ expires after 7 days. With the fake, `drain()` runs chains and batches too.
115
+ - **`rateLimit`** per queue (`queues.notifications.rateLimit: '30/s'`): every job takes a hit on core's
116
+ `RateLimiter` (Redis with `RedisProvider`, so shared by all workers) and waits for its turn.
117
+ - **`queue:health`**: exit 1 if no worker loop wrote its heartbeat within `--stale` (default 2 m) or a queue's
118
+ oldest waiting job is older than `--max-wait` (default 10 m). For worker-only services.
119
+ - **One process** (guide 21, model 1): `cslug serve --with-worker --with-scheduler` runs `queue:work` and
120
+ `schedule:work` in the web process; `@cslug/http` finds them by signature (it does not import the queue).
package/docs/api.md ADDED
@@ -0,0 +1,28 @@
1
+ # @cslug/queue: API
2
+
3
+ | | |
4
+ |---|---|
5
+ | `Job<P>` | Base class: `handle(payload)`; optional `failed(payload, error)`. Statics: `dispatch(payload)`, `with(payload)` (a `JobSpec` for chains and batches), `exponential(base, { max, jitter })`, `schema(schema)` (a base class whose payload is validated on dispatch and before each run) |
6
+ | `JobSettings` | Optional statics of a job class: `jobName`, `queue`, `tries`, `backoff`, `timeout`, `payloadSchema` |
7
+ | `PendingDispatch` | `delay(duration)`, `at(date)`, `onQueue(name)`, `priority(1…10)`, `unique(key, holdFor = '1d')`, `tries(n)`, `durable()`, `immediately()`; sent when awaited → job id, or `null` for a held unique key |
8
+ | `Queue` | Abstract: `dispatch(Job, payload)`, `push(envelope, { runAt, uniqueFor })`, `finished(envelope, ok)`. Static: `chain(specs).dispatch()`, `batch(specs).then(spec).allowFailures().dispatch()` → batch id. Bound to `RedisQueue` |
9
+ | `RedisQueue` | `push`, `promote(queue)`, `ensureGroups(queue)`, `complete` / `retry` / `fail`, `failed()`, `retryFailed(id)`, `forget(id)`, `queues()`, `stats(queue)` → `{ queue, waiting, active, delayed, failed, oldestAgeMs }`, `clear(queue)` |
10
+ | `Worker` | `start()`, `stop(timeoutMs)`, `consumer`; options `{ queues: [{ name, concurrency }], leaseMs, blockMs }` |
11
+ | `Workers` | The workers of this process: `start(queues)`, `stopAll(timeoutMs)` (called by the provider at shutdown) |
12
+ | `QueueFake` | `pushed`, `of(Job)`, `assertPushed(Job, predicate?)`, `assertNotPushed`, `assertPushedCount(Job, n)`, `assertNothingPushed()`, `drain(max = 1000)`. `PushedJob`: `{ id, job, payload, queue, delay?, runAt?, priority?, unique?, tries }` |
13
+ | `installQueueFake(app)` | Used by `@cslug/testing` for `fakes: ['queue']` |
14
+ | `QueuedListenerJob` | The job (`cslug.listener`) that runs queued `@listener` classes |
15
+ | `discoverJobs(app)` | Imports `app/jobs/` and `app/listeners/`, registers job classes; returns how many |
16
+ | `registerJob`, `findJob`, `jobName`, `isJobClass`, `settingsOf`, `backoffDelay` | The job registry and settings with defaults |
17
+ | `runJob(app, envelope, attempt)`, `runFailedHook` | Run one delivery in a fresh scope and context |
18
+ | `JobNotFoundError`, `JobTimeoutError` | Typed errors (`queue.job_not_found`, `queue.job_timeout`) |
19
+ | `Outbox`, `OUTBOX_MIGRATIONS` | `write(envelope, options)` (ambient transaction), `relay(id?, limit = 100)`, `registerMigrations()`, `Outbox.detect(app, log)` |
20
+ | `QueueProvider` | Config `queue.{connection, queues.<name>.{concurrency, rateLimit}, failed.keep, shutdownTimeout, lease, block}` |
21
+ | Commands | `QueueHealthCommand`, `QueueWorkCommand`, `QueueFailedCommand`, `QueueRetryCommand`, `QueueForgetCommand`, `QueueClearCommand`, `QueueStatsCommand` |
22
+ | `defineSchedule(fn)`, `ScheduleBuilder` | `s.job(Job, payload?)`, `s.call(name, ({ app, resolve }) => …)`, `s.cron(expr, name, Job, payload?)` |
23
+ | `ScheduleEntry` | Frequencies: `cron`, `everyMinute`, `everyFiveMinutes`, `everyTenMinutes`, `everyFifteenMinutes`, `everyThirtyMinutes`, `hourly`, `hourlyAt(m)`, `daily`, `dailyAt('HH:MM')`, `twiceDaily(a, b)`, `weekly`, `weeklyOn(day, time)`, `monthly`, `monthlyOn(day, time)`. Modifiers: `weekdays`, `between(from, to)`, `when(fn)`, `environments(list)`, `timezone(tz)`, `allowOverlap`, `catchUp('once')`, `as(name)` |
24
+ | `Scheduler` | `entries`, `runDue(now?, { exclusive })`, `run(entry, tick, exclusive)`, `catchUp(now?)`, `next(entry, after?)`, `history(name, last)`, `heartbeat()`, `start()`, `stop()`, `find(name)`, `tzOf(entry)` |
25
+ | `ScheduleRun` | `{ name, scheduledFor, startedAt, finishedAt?, status: 'dispatched' \| 'ok' \| 'failed' \| 'skipped', error? }` |
26
+ | `Cron`, `localTime(date, tz)` | `new Cron(expr).matches(local)`, `.next(after, tz)` |
27
+ | `ScheduleProvider` | Loads `routes/schedule.ts`; config `schedule.timezone` |
28
+ | Schedule commands | `ScheduleWorkCommand`, `ScheduleRunCommand`, `ScheduleListCommand`, `ScheduleHistoryCommand`, `ScheduleTestCommand` |
@@ -0,0 +1,11 @@
1
+ -- up
2
+ create table cslug_queue_outbox (
3
+ id uuid primary key,
4
+ envelope text not null,
5
+ options text not null,
6
+ created_at timestamptz not null default now()
7
+ );
8
+ create index cslug_queue_outbox_created_at_idx on cslug_queue_outbox (created_at);
9
+
10
+ -- down
11
+ drop table cslug_queue_outbox;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cslug/queue",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Jobs and workers on Redis Streams, after-commit and durable dispatch, and the scheduler.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -20,6 +20,7 @@
20
20
  },
21
21
  "files": [
22
22
  "src",
23
+ "migrations",
23
24
  "docs",
24
25
  "stubs",
25
26
  "README.md"
@@ -28,13 +29,19 @@
28
29
  "bun": ">=1.3.14"
29
30
  },
30
31
  "peerDependencies": {
31
- "@cslug/core": "0.1.0",
32
- "@cslug/redis": "0.1.0",
33
- "@cslug/database": "0.1.0"
32
+ "@cslug/core": "0.3.0",
33
+ "@cslug/redis": "0.3.0",
34
+ "@cslug/database": "0.3.0"
34
35
  },
35
36
  "peerDependenciesMeta": {
36
37
  "@cslug/database": {
37
38
  "optional": true
38
39
  }
40
+ },
41
+ "devDependencies": {
42
+ "@cslug/testing": "workspace:*",
43
+ "@cslug/validation": "workspace:*",
44
+ "@cslug/database": "workspace:*",
45
+ "@cslug/http": "workspace:*"
39
46
  }
40
47
  }
@@ -0,0 +1,165 @@
1
+ import { arg, Command, flag, parseDuration } from '@cslug/core'
2
+ import { discoverJobs } from './discover'
3
+ import type { QueueConfig } from './provider'
4
+ import { Workers } from './provider'
5
+ import { RedisQueue } from './redis-queue'
6
+
7
+ abstract class QueueCommand extends Command {
8
+ protected get queue(): RedisQueue {
9
+ return this.app.resolve(RedisQueue)
10
+ }
11
+ protected get config(): QueueConfig {
12
+ return this.app.config<QueueConfig | undefined>('queue') ?? {}
13
+ }
14
+ }
15
+
16
+ /** `cslug queue:work`: run jobs until SIGTERM (running jobs finish, up to `queue.shutdownTimeout`). */
17
+ export class QueueWorkCommand extends QueueCommand {
18
+ static signature = 'queue:work'
19
+ static description = 'Run queued jobs'
20
+ static longRunning = true
21
+ static args = {
22
+ queues: flag.list().describe('Queues to run (default: every queue in config/queue.ts)'),
23
+ queue: flag.list().describe('Same as --queues'),
24
+ concurrency: flag.number().optional().describe('Jobs at a time per queue (default: config, else 1)'),
25
+ }
26
+
27
+ async handle({ queues, queue, concurrency }: Command.Args<typeof QueueWorkCommand>) {
28
+ const configured = this.config.queues ?? {}
29
+ const names = [...queues, ...queue].length ? [...new Set([...queues, ...queue])] : Object.keys(configured)
30
+ if (!names.length) names.push('default')
31
+ const jobs = await discoverJobs(this.app)
32
+ const list = names.map((name) => ({
33
+ name,
34
+ concurrency: concurrency ?? configured[name]?.concurrency ?? 1,
35
+ rateLimit: configured[name]?.rateLimit,
36
+ }))
37
+ await this.app.resolve(Workers).start(list)
38
+ if (process.stdout.isTTY)
39
+ this.info(`Working ${list.map((q) => `${q.name} (×${q.concurrency})`).join(', ')}; ${jobs} job classes`)
40
+ }
41
+ }
42
+
43
+ /** `cslug queue:failed`: jobs that failed their last attempt. */
44
+ export class QueueFailedCommand extends QueueCommand {
45
+ static signature = 'queue:failed'
46
+ static description = 'List failed jobs'
47
+ static args = { json: flag.boolean() }
48
+
49
+ async handle({ json }: Command.Args<typeof QueueFailedCommand>) {
50
+ const rows = (await this.queue.failed()).map((f) => ({
51
+ id: f.envelope.id,
52
+ job: f.envelope.name,
53
+ queue: f.envelope.queue,
54
+ attempts: f.envelope.tries,
55
+ failedAt: new Date(f.failedAt),
56
+ error: f.error,
57
+ }))
58
+ if (json) this.line(JSON.stringify(rows))
59
+ else this.table(rows)
60
+ }
61
+ }
62
+
63
+ /** `cslug queue:retry <id|all>`: queue failed jobs again, from their first attempt. */
64
+ export class QueueRetryCommand extends QueueCommand {
65
+ static signature = 'queue:retry'
66
+ static description = 'Retry a failed job (or all)'
67
+ static args = { id: arg.string().describe('Job id, or "all"') }
68
+
69
+ async handle({ id }: Command.Args<typeof QueueRetryCommand>) {
70
+ const ids = id === 'all' ? (await this.queue.failed()).map((f) => f.envelope.id) : [id]
71
+ let n = 0
72
+ for (const one of ids) if (await this.queue.retryFailed(one)) n++
73
+ if (!n && id !== 'all') {
74
+ this.error(`No failed job ${id}`)
75
+ return 1
76
+ }
77
+ this.success(`${n} job(s) queued again`)
78
+ return 0
79
+ }
80
+ }
81
+
82
+ /** `cslug queue:forget <id>`: delete a failed job. */
83
+ export class QueueForgetCommand extends QueueCommand {
84
+ static signature = 'queue:forget'
85
+ static description = 'Delete a failed job'
86
+ static args = { id: arg.string() }
87
+
88
+ async handle({ id }: Command.Args<typeof QueueForgetCommand>) {
89
+ if (!(await this.queue.forget(id))) {
90
+ this.error(`No failed job ${id}`)
91
+ return 1
92
+ }
93
+ this.success(`Forgot ${id}`)
94
+ return 0
95
+ }
96
+ }
97
+
98
+ /** `cslug queue:clear [queue]`: delete waiting and delayed jobs. */
99
+ export class QueueClearCommand extends QueueCommand {
100
+ static signature = 'queue:clear'
101
+ static description = 'Delete the waiting and delayed jobs of a queue'
102
+ static args = { name: arg.string().default('default'), force: flag.boolean() }
103
+
104
+ async handle({ name, force }: Command.Args<typeof QueueClearCommand>) {
105
+ if (this.app.config('app.env') === 'production' && !force) {
106
+ this.error('queue:clear in production: add --force if you really mean it')
107
+ return 1
108
+ }
109
+ await this.queue.clear(name)
110
+ this.success(`Cleared ${name}`)
111
+ return 0
112
+ }
113
+ }
114
+
115
+ /** `cslug queue:stats`: waiting / active / delayed / failed per queue, and the oldest waiting job's age. */
116
+ export class QueueStatsCommand extends QueueCommand {
117
+ static signature = 'queue:stats'
118
+ static description = 'Jobs per queue and state'
119
+ static args = { json: flag.boolean() }
120
+
121
+ async handle({ json }: Command.Args<typeof QueueStatsCommand>) {
122
+ const names = [...new Set([...Object.keys(this.config.queues ?? {}), ...(await this.queue.queues())])].sort()
123
+ const rows = []
124
+ for (const name of names) rows.push(await this.queue.stats(name))
125
+ if (json) this.line(JSON.stringify(rows))
126
+ else
127
+ this.table(rows.map((r) => ({ ...r, oldestAge: `${Math.round(r.oldestAgeMs / 1000)}s`, oldestAgeMs: undefined })))
128
+ }
129
+ }
130
+
131
+ /** `cslug queue:health`: exit 1 if no worker ran its loop lately or a queue's oldest job waits too long. */
132
+ export class QueueHealthCommand extends QueueCommand {
133
+ static signature = 'queue:health'
134
+ static description = 'Check the workers (for services without HTTP)'
135
+ static args = {
136
+ stale: flag.string().default('2m').describe('A worker heartbeat older than this is a problem'),
137
+ maxWait: flag.string().default('10m').describe('A job waiting longer than this is a problem'),
138
+ }
139
+
140
+ async handle({ stale, maxWait }: Command.Args<typeof QueueHealthCommand>) {
141
+ const problems: string[] = []
142
+ const redis = this.queue.redis
143
+ const beat = Number(await redis.send('GET', [redis.key('heartbeat')]))
144
+ if (!beat || Date.now() - beat > parseDuration(stale)) problems.push(`no worker heartbeat within ${stale}`)
145
+ const names = [...new Set([...Object.keys(this.config.queues ?? {}), ...(await this.queue.queues())])]
146
+ for (const name of names) {
147
+ const s = await this.queue.stats(name)
148
+ if (s.waiting > 0 && s.oldestAgeMs > parseDuration(maxWait))
149
+ problems.push(`${name}: oldest job waiting ${Math.round(s.oldestAgeMs / 1000)}s`)
150
+ }
151
+ for (const p of problems) this.error(p)
152
+ if (!problems.length) this.success('queue healthy')
153
+ return problems.length ? 1 : 0
154
+ }
155
+ }
156
+
157
+ export const queueCommands = [
158
+ QueueHealthCommand,
159
+ QueueWorkCommand,
160
+ QueueFailedCommand,
161
+ QueueRetryCommand,
162
+ QueueForgetCommand,
163
+ QueueClearCommand,
164
+ QueueStatsCommand,
165
+ ]
package/src/cron.ts ADDED
@@ -0,0 +1,127 @@
1
+ import { CslugError } from '@cslug/core'
2
+
3
+ const NAMES: Record<string, number> = Object.fromEntries([
4
+ ...'sun mon tue wed thu fri sat'.split(' ').map((d, i) => [d, i]),
5
+ ...'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ').map((m, i) => [m, i + 1]),
6
+ ])
7
+ const FIELDS = [
8
+ ['minute', 0, 59],
9
+ ['hour', 0, 23],
10
+ ['day of month', 1, 31],
11
+ ['month', 1, 12],
12
+ ['day of week', 0, 7],
13
+ ] as const
14
+
15
+ /** Wall-clock parts of an instant in a time zone. */
16
+ export type LocalTime = { year: number; month: number; day: number; hour: number; minute: number; weekday: number }
17
+
18
+ /**
19
+ * A 5-field cron expression (`minute hour day-of-month month day-of-week`): `*`, lists, ranges, steps, month and
20
+ * day names, 0 or 7 for Sunday. When both day fields are restricted, either matching is enough (as in cron).
21
+ */
22
+ export class Cron {
23
+ private readonly sets: Set<number>[]
24
+ private readonly anyDay: boolean
25
+ private readonly anyWeekday: boolean
26
+
27
+ constructor(readonly expression: string) {
28
+ const parts = expression.trim().split(/\s+/)
29
+ if (parts.length !== 5) throw cronError(expression, 'needs 5 fields: minute hour day-of-month month day-of-week')
30
+ this.sets = parts.map((p, i) => parseField(p, FIELDS[i] as (typeof FIELDS)[number], expression))
31
+ const weekdays = this.sets[4] as Set<number>
32
+ if (weekdays.has(7)) weekdays.add(0)
33
+ this.anyDay = parts[2] === '*'
34
+ this.anyWeekday = parts[4] === '*'
35
+ }
36
+
37
+ matches(t: LocalTime): boolean {
38
+ const [m, h, dom, mon, dow] = this.sets as [Set<number>, Set<number>, Set<number>, Set<number>, Set<number>]
39
+ return m.has(t.minute) && h.has(t.hour) && mon.has(t.month) && this.dayMatches(dom, dow, t)
40
+ }
41
+
42
+ private dayMatches(dom: Set<number>, dow: Set<number>, t: LocalTime): boolean {
43
+ if (this.anyDay && this.anyWeekday) return true
44
+ if (this.anyDay) return dow.has(t.weekday)
45
+ if (this.anyWeekday) return dom.has(t.day)
46
+ return dom.has(t.day) || dow.has(t.weekday)
47
+ }
48
+
49
+ /** The first matching minute strictly after `after`, in time zone `tz` (within ~5 years, else undefined). */
50
+ next(after: Date, tz = 'UTC'): Date | undefined {
51
+ let t = Math.floor(after.getTime() / 60_000) * 60_000 + 60_000
52
+ const end = t + 5 * 366 * 86_400_000
53
+ const [m, h, , mon] = this.sets as [Set<number>, Set<number>, Set<number>, Set<number>]
54
+ while (t < end) {
55
+ const local = localTime(new Date(t), tz)
56
+ if (!mon.has(local.month) || !this.dayMatches(this.sets[2] as Set<number>, this.sets[4] as Set<number>, local)) {
57
+ // towards the next local midnight, stopping an hour short so a DST change cannot make us overshoot it
58
+ const toMidnight = (23 - local.hour) * 60 + (60 - local.minute)
59
+ t += Math.max(60 - local.minute, toMidnight - 60) * 60_000
60
+ } else if (!h.has(local.hour)) {
61
+ t += (60 - local.minute) * 60_000
62
+ } else if (!m.has(local.minute)) {
63
+ t += 60_000
64
+ } else {
65
+ return new Date(t)
66
+ }
67
+ }
68
+ return undefined
69
+ }
70
+ }
71
+
72
+ function parseField(field: string, [label, min, max]: (typeof FIELDS)[number], expression: string): Set<number> {
73
+ const out = new Set<number>()
74
+ const value = (s: string) => {
75
+ const n = NAMES[s.toLowerCase()] ?? (/^\d+$/.test(s) ? Number(s) : Number.NaN)
76
+ if (!Number.isInteger(n) || n < min || n > max)
77
+ throw cronError(expression, `${label} "${s}" is not in ${min}–${max}`)
78
+ return n
79
+ }
80
+ for (const part of field.split(',')) {
81
+ const [range, stepText] = part.split('/')
82
+ const step = stepText === undefined ? 1 : Number(stepText)
83
+ if (!Number.isInteger(step) || step < 1) throw cronError(expression, `bad step in "${part}"`)
84
+ let [from, to] = [min as number, max as number]
85
+ if (range !== '*') {
86
+ const [a, b] = (range ?? '').split('-')
87
+ from = value(a ?? '')
88
+ to = b === undefined ? (stepText === undefined ? from : max) : value(b)
89
+ }
90
+ if (from > to) throw cronError(expression, `${label} range "${range}" goes backwards`)
91
+ for (let n = from; n <= to; n += step) out.add(n)
92
+ }
93
+ return out
94
+ }
95
+
96
+ const cronError = (expression: string, why: string) =>
97
+ new CslugError('schedule.bad_cron', `Invalid cron "${expression}": ${why}`)
98
+
99
+ const formatters = new Map<string, Intl.DateTimeFormat>()
100
+ const WEEKDAYS: Record<string, number> = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 }
101
+
102
+ /** Wall-clock parts of `date` in `tz` (an IANA zone). */
103
+ export function localTime(date: Date, tz = 'UTC'): LocalTime {
104
+ let f = formatters.get(tz)
105
+ if (!f) {
106
+ f = new Intl.DateTimeFormat('en-US', {
107
+ timeZone: tz,
108
+ hourCycle: 'h23',
109
+ year: 'numeric',
110
+ month: 'numeric',
111
+ day: 'numeric',
112
+ hour: 'numeric',
113
+ minute: 'numeric',
114
+ weekday: 'short',
115
+ })
116
+ formatters.set(tz, f)
117
+ }
118
+ const p = Object.fromEntries(f.formatToParts(date).map((x) => [x.type, x.value]))
119
+ return {
120
+ year: Number(p.year),
121
+ month: Number(p.month),
122
+ day: Number(p.day),
123
+ hour: Number(p.hour),
124
+ minute: Number(p.minute),
125
+ weekday: WEEKDAYS[p.weekday as string] ?? 0,
126
+ }
127
+ }
@@ -0,0 +1,28 @@
1
+ import { existsSync, readdirSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import type { Application } from '@cslug/core'
4
+ import { isJobClass, registerJob } from './job'
5
+
6
+ /** Folders a worker loads so it can run any job or queued listener (docs/directory-structure.md § Rules). */
7
+ export const DISCOVERED = ['app/jobs', 'app/listeners']
8
+
9
+ /** Import every module under `app/jobs/` and `app/listeners/` (subfolders included); register the job classes. */
10
+ export async function discoverJobs(app: Application): Promise<number> {
11
+ let found = 0
12
+ for (const folder of DISCOVERED) {
13
+ const dir = join(app.rootDir, folder)
14
+ if (!existsSync(dir)) continue
15
+ const files = (readdirSync(dir, { recursive: true }) as string[])
16
+ .filter((f) => f.endsWith('.ts') && !f.endsWith('.test.ts') && !f.endsWith('.d.ts'))
17
+ .sort()
18
+ for (const file of files) {
19
+ const mod = (await import(join(dir, file))) as Record<string, unknown>
20
+ for (const value of Object.values(mod)) {
21
+ if (!isJobClass(value)) continue
22
+ registerJob(value)
23
+ found++
24
+ }
25
+ }
26
+ }
27
+ return found
28
+ }
@@ -0,0 +1,124 @@
1
+ import {
2
+ Clock,
3
+ CslugError,
4
+ currentApp,
5
+ currentContext,
6
+ type Duration,
7
+ parseDuration,
8
+ resolve,
9
+ type TransactionHooks,
10
+ } from '@cslug/core'
11
+ import type { JobClass } from './job'
12
+ import { Outbox } from './outbox'
13
+ import { type Envelope, envelopeOf, type PushOptions, Queue } from './queue'
14
+
15
+ /**
16
+ * A dispatch being configured; it is sent when awaited. Inside a database transaction it is held until COMMIT
17
+ * and dropped on rollback, unless `.immediately()`.
18
+ *
19
+ * ```ts
20
+ * await SendCheckinJob.dispatch({ bookingId }).delay('3d').onQueue('urgent').unique(`checkin:${bookingId}`)
21
+ * ```
22
+ */
23
+ export class PendingDispatch implements PromiseLike<string | null> {
24
+ private queueName?: string
25
+ private runAt?: Date
26
+ private delayMs?: number
27
+ private uniqueKey?: string
28
+ private uniqueFor?: number
29
+ private priorityLevel?: number
30
+ private triesOverride?: number
31
+ private now = false
32
+ private isDurable = false
33
+ private sent?: Promise<string | null>
34
+
35
+ constructor(
36
+ private readonly job: JobClass,
37
+ private readonly payload: unknown,
38
+ private readonly queue?: Queue,
39
+ ) {}
40
+
41
+ delay(duration: Duration): this {
42
+ this.delayMs = parseDuration(duration)
43
+ return this
44
+ }
45
+ at(when: Date): this {
46
+ this.runAt = when
47
+ return this
48
+ }
49
+ onQueue(name: string): this {
50
+ this.queueName = name
51
+ return this
52
+ }
53
+ /** 1 (first) … 10 (last); default 5. Jobs are taken in three bands: 1–3, 4–7, 8–10. */
54
+ priority(level: number): this {
55
+ if (!Number.isInteger(level) || level < 1 || level > 10) throw new RangeError('priority() takes 1 … 10')
56
+ this.priorityLevel = level
57
+ return this
58
+ }
59
+ /** Ignored while a job with the same key is waiting or running (the key is held at most `holdFor`, default 1 day). */
60
+ unique(key: string, holdFor: Duration = '1d'): this {
61
+ this.uniqueKey = key
62
+ this.uniqueFor = parseDuration(holdFor)
63
+ return this
64
+ }
65
+ /** Attempts in all (overrides the job's `static tries`). */
66
+ tries(n: number): this {
67
+ this.triesOverride = n
68
+ return this
69
+ }
70
+ /**
71
+ * Write the job to the outbox table in the current transaction: it exists if and only if the transaction
72
+ * commits (for jobs that move money). Needs `@cslug/database`. Outside a transaction it is sent at once.
73
+ */
74
+ durable(): this {
75
+ this.isDurable = true
76
+ return this
77
+ }
78
+ /** Send now even inside a transaction (rarely right: the job may run before the data it needs is committed). */
79
+ immediately(): this {
80
+ this.now = true
81
+ return this
82
+ }
83
+
84
+ // biome-ignore lint/suspicious/noThenProperty: a dispatch is sent by awaiting it
85
+ then<A = string | null, B = never>(
86
+ onFulfilled?: ((id: string | null) => A | PromiseLike<A>) | null,
87
+ onRejected?: ((reason: unknown) => B | PromiseLike<B>) | null,
88
+ ): Promise<A | B> {
89
+ this.sent ??= this.send()
90
+ return this.sent.then(onFulfilled, onRejected)
91
+ }
92
+
93
+ private async send(): Promise<string | null> {
94
+ const queue = this.queue ?? resolve(Queue)
95
+ const payload = this.job.payloadSchema ? this.job.payloadSchema.parse(this.payload) : this.payload
96
+ const envelope: Envelope = envelopeOf(this.job, payload, this.queueName)
97
+ if (this.priorityLevel !== undefined) envelope.priority = this.priorityLevel
98
+ if (this.uniqueKey !== undefined) envelope.unique = this.uniqueKey
99
+ if (this.triesOverride !== undefined) envelope.tries = this.triesOverride
100
+ const options: PushOptions = { uniqueFor: this.uniqueFor }
101
+ if (this.runAt) options.runAt = this.runAt.getTime()
102
+ else if (this.delayMs) options.runAt = resolve(Clock).now().getTime() + this.delayMs
103
+ if (options.runAt !== undefined && this.uniqueFor !== undefined)
104
+ options.uniqueFor = this.uniqueFor + Math.max(0, options.runAt - resolve(Clock).now().getTime())
105
+
106
+ const tx = currentContext()?.tx as TransactionHooks | undefined
107
+ if (this.isDurable && tx && typeof tx.afterCommit === 'function') {
108
+ if (!currentApp().has(Outbox))
109
+ throw new CslugError(
110
+ 'queue.no_outbox',
111
+ '.durable() needs @cslug/database (DatabaseProvider before QueueProvider)',
112
+ )
113
+ const outbox = resolve(Outbox)
114
+ await outbox.write(envelope, options)
115
+ tx.afterCommit(() => outbox.relay(envelope.id))
116
+ return envelope.id
117
+ }
118
+ if (!this.now && tx && typeof tx.afterCommit === 'function') {
119
+ tx.afterCommit(() => queue.push(envelope, options))
120
+ return envelope.id
121
+ }
122
+ return queue.push(envelope, options)
123
+ }
124
+ }