@cslug/queue 0.1.0 → 0.2.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 +9 -2
- package/docs/README.md +117 -3
- package/docs/api.md +28 -0
- package/migrations/00000000_000200_cslug_queue_outbox.sql +11 -0
- package/package.json +11 -4
- package/src/commands.ts +165 -0
- package/src/cron.ts +127 -0
- package/src/discover.ts +28 -0
- package/src/dispatch.ts +124 -0
- package/src/fake.ts +106 -0
- package/src/index.ts +66 -4
- package/src/job.ts +146 -0
- package/src/listener-job.ts +23 -0
- package/src/outbox.ts +66 -0
- package/src/provider.ts +124 -0
- package/src/queue.ts +200 -0
- package/src/redis-queue.ts +234 -0
- package/src/schedule-provider.ts +146 -0
- package/src/schedule.ts +217 -0
- package/src/scheduler.ts +174 -0
- package/src/worker.ts +252 -0
package/src/fake.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { type Application, Clock } from '@cslug/core'
|
|
2
|
+
import { findJob, type JobClass, type PayloadOf } from './job'
|
|
3
|
+
import { type Envelope, type PushOptions, Queue, runJob } from './queue'
|
|
4
|
+
|
|
5
|
+
/** A job the fake recorded. `delay` is in ms (undefined when the job was not delayed). */
|
|
6
|
+
export type PushedJob<P = unknown> = {
|
|
7
|
+
id: string
|
|
8
|
+
job: JobClass
|
|
9
|
+
payload: P
|
|
10
|
+
queue: string
|
|
11
|
+
delay?: number
|
|
12
|
+
runAt?: Date
|
|
13
|
+
priority?: number
|
|
14
|
+
unique?: string
|
|
15
|
+
tries: number
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The queue in tests (`testApp({ fakes: ['queue'] })` → `t.queue`): records jobs instead of sending them.
|
|
20
|
+
* Dispatches inside a transaction are still recorded only at COMMIT, so a rolled-back dispatch is never seen.
|
|
21
|
+
*/
|
|
22
|
+
export class QueueFake extends Queue {
|
|
23
|
+
readonly pushed: PushedJob[] = []
|
|
24
|
+
private waiting: { record: PushedJob; envelope: Envelope }[] = []
|
|
25
|
+
|
|
26
|
+
constructor(private readonly app: Application) {
|
|
27
|
+
super()
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async push(envelope: Envelope, options: PushOptions = {}): Promise<string | null> {
|
|
31
|
+
if (envelope.unique !== undefined && this.waiting.some((w) => w.envelope.unique === envelope.unique)) return null
|
|
32
|
+
const now = this.app.resolve(Clock).now().getTime()
|
|
33
|
+
const job = findJob(envelope.name) as JobClass
|
|
34
|
+
const record: PushedJob = {
|
|
35
|
+
id: envelope.id,
|
|
36
|
+
job,
|
|
37
|
+
payload: envelope.payload,
|
|
38
|
+
queue: envelope.queue,
|
|
39
|
+
tries: envelope.tries,
|
|
40
|
+
...(options.runAt !== undefined && options.runAt > now
|
|
41
|
+
? { delay: options.runAt - now, runAt: new Date(options.runAt) }
|
|
42
|
+
: {}),
|
|
43
|
+
...(envelope.priority !== undefined ? { priority: envelope.priority } : {}),
|
|
44
|
+
...(envelope.unique !== undefined ? { unique: envelope.unique } : {}),
|
|
45
|
+
}
|
|
46
|
+
this.pushed.push(record)
|
|
47
|
+
this.waiting.push({ record, envelope })
|
|
48
|
+
return envelope.id
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Recorded jobs of one class. */
|
|
52
|
+
of<J extends JobClass<never>>(job: J): PushedJob<PayloadOf<J>>[] {
|
|
53
|
+
return this.pushed.filter((p) => p.job === job) as PushedJob<PayloadOf<J>>[]
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
assertPushed<J extends JobClass<never>>(job: J, predicate?: (j: PushedJob<PayloadOf<J>>) => boolean): void {
|
|
57
|
+
const all = this.of(job)
|
|
58
|
+
if (!all.filter((j) => !predicate || predicate(j)).length)
|
|
59
|
+
throw new Error(
|
|
60
|
+
`Expected ${job.name} to be pushed${predicate ? ' matching the predicate' : ''}; pushed: ${describe(all.length ? all : this.pushed)}`,
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
assertNotPushed<J extends JobClass<never>>(job: J, predicate?: (j: PushedJob<PayloadOf<J>>) => boolean): void {
|
|
65
|
+
const matching = this.of(job).filter((j) => !predicate || predicate(j))
|
|
66
|
+
if (matching.length) throw new Error(`Expected ${job.name} not to be pushed; pushed: ${describe(matching)}`)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
assertPushedCount<J extends JobClass<never>>(job: J, count: number): void {
|
|
70
|
+
const n = this.of(job).length
|
|
71
|
+
if (n !== count) throw new Error(`Expected ${job.name} to be pushed ${count} time(s), got ${n}`)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
assertNothingPushed(): void {
|
|
75
|
+
if (this.pushed.length) throw new Error(`Expected no job to be pushed; pushed: ${describe(this.pushed)}`)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Run every waiting job (delays ignored), including jobs those jobs push, once each. A job that throws stops
|
|
80
|
+
* the drain with its error. Returns how many ran.
|
|
81
|
+
*/
|
|
82
|
+
async drain(max = 1000): Promise<number> {
|
|
83
|
+
let ran = 0
|
|
84
|
+
while (this.waiting.length) {
|
|
85
|
+
if (ran >= max) throw new Error(`drain(): more than ${max} jobs; is a job dispatching itself?`)
|
|
86
|
+
const { envelope } = this.waiting.shift() as { envelope: Envelope }
|
|
87
|
+
await runJob(this.app, envelope, 1)
|
|
88
|
+
await this.finished(envelope, true)
|
|
89
|
+
ran++
|
|
90
|
+
}
|
|
91
|
+
return ran
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const describe = (jobs: PushedJob[]) =>
|
|
96
|
+
jobs.length
|
|
97
|
+
? jobs.map((j) => `${j.job?.name ?? '?'}(${JSON.stringify(j.payload, bigintSafe)})`).join(', ')
|
|
98
|
+
: 'nothing'
|
|
99
|
+
const bigintSafe = (_k: string, v: unknown) => (typeof v === 'bigint' ? `${v}n` : v)
|
|
100
|
+
|
|
101
|
+
/** For `@cslug/testing`: swap the queue for a fake and return it. */
|
|
102
|
+
export function installQueueFake(app: Application): QueueFake {
|
|
103
|
+
const fake = new QueueFake(app)
|
|
104
|
+
app.swap(Queue, fake)
|
|
105
|
+
return fake
|
|
106
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,68 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @cslug/queue:
|
|
3
|
-
*
|
|
4
|
-
* Not implemented yet. See docs/packages.md and docs/implementation-plan.md.
|
|
2
|
+
* @cslug/queue: jobs and workers on Redis Streams, retries, delays, unique jobs, after-commit dispatch, queued
|
|
3
|
+
* listeners, the failed store and `queue:*` commands; the scheduler (`defineSchedule`, cron, once-per-tick locks).
|
|
5
4
|
*/
|
|
6
|
-
export {
|
|
5
|
+
export {
|
|
6
|
+
QueueClearCommand,
|
|
7
|
+
QueueFailedCommand,
|
|
8
|
+
QueueForgetCommand,
|
|
9
|
+
QueueHealthCommand,
|
|
10
|
+
QueueRetryCommand,
|
|
11
|
+
QueueStatsCommand,
|
|
12
|
+
QueueWorkCommand,
|
|
13
|
+
} from './commands'
|
|
14
|
+
export { Cron, type LocalTime, localTime } from './cron'
|
|
15
|
+
export { DISCOVERED, discoverJobs } from './discover'
|
|
16
|
+
export { PendingDispatch } from './dispatch'
|
|
17
|
+
export { installQueueFake, type PushedJob, QueueFake } from './fake'
|
|
18
|
+
export {
|
|
19
|
+
type Backoff,
|
|
20
|
+
backoffDelay,
|
|
21
|
+
findJob,
|
|
22
|
+
isJobClass,
|
|
23
|
+
Job,
|
|
24
|
+
type JobClass,
|
|
25
|
+
type JobHooks,
|
|
26
|
+
type JobSettings,
|
|
27
|
+
jobName,
|
|
28
|
+
type PayloadArgs,
|
|
29
|
+
type PayloadOf,
|
|
30
|
+
type PayloadSchema,
|
|
31
|
+
registerJob,
|
|
32
|
+
settingsOf,
|
|
33
|
+
} from './job'
|
|
34
|
+
export { QueuedListenerJob } from './listener-job'
|
|
35
|
+
export { OUTBOX_MIGRATIONS, Outbox } from './outbox'
|
|
36
|
+
export { type QueueConfig, QueueProvider, Workers } from './provider'
|
|
37
|
+
export {
|
|
38
|
+
type Envelope,
|
|
39
|
+
envelopeOf,
|
|
40
|
+
JobNotFoundError,
|
|
41
|
+
type JobSpec,
|
|
42
|
+
JobTimeoutError,
|
|
43
|
+
type PushOptions,
|
|
44
|
+
Queue,
|
|
45
|
+
runFailedHook,
|
|
46
|
+
runJob,
|
|
47
|
+
} from './queue'
|
|
48
|
+
export { BANDS, type Band, bandOf, type FailedJob, GROUP, RedisQueue } from './redis-queue'
|
|
49
|
+
export {
|
|
50
|
+
buildSchedule,
|
|
51
|
+
defineSchedule,
|
|
52
|
+
entryName,
|
|
53
|
+
ScheduleBuilder,
|
|
54
|
+
type ScheduleDefinition,
|
|
55
|
+
ScheduleEntry,
|
|
56
|
+
type TaskContext,
|
|
57
|
+
type Weekday,
|
|
58
|
+
} from './schedule'
|
|
59
|
+
export {
|
|
60
|
+
ScheduleHistoryCommand,
|
|
61
|
+
ScheduleListCommand,
|
|
62
|
+
ScheduleProvider,
|
|
63
|
+
ScheduleRunCommand,
|
|
64
|
+
ScheduleTestCommand,
|
|
65
|
+
ScheduleWorkCommand,
|
|
66
|
+
} from './schedule-provider'
|
|
67
|
+
export { type ScheduleRun, Scheduler } from './scheduler'
|
|
68
|
+
export { parseRead, Worker, type WorkerOptions } from './worker'
|
package/src/job.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { CslugError, type Duration, parseDuration } from '@cslug/core'
|
|
2
|
+
import { PendingDispatch } from './dispatch'
|
|
3
|
+
import type { JobSpec } from './queue'
|
|
4
|
+
|
|
5
|
+
/** How long to wait before retry `n` (1 = after the first failure): a duration, one per retry, or a function. */
|
|
6
|
+
export type Backoff = Duration | readonly Duration[] | ((attempt: number) => number)
|
|
7
|
+
|
|
8
|
+
/** Anything with `parse()`: a `v` schema from `@cslug/validation`, or your own. */
|
|
9
|
+
export type PayloadSchema<T = unknown> = { parse(value: unknown): T }
|
|
10
|
+
|
|
11
|
+
/** The payload type of a job class (from its `handle` parameter; `undefined` when it takes none). */
|
|
12
|
+
export type PayloadOf<J> = J extends abstract new (
|
|
13
|
+
...args: never[]
|
|
14
|
+
) => { handle(...args: infer A): unknown }
|
|
15
|
+
? A[0]
|
|
16
|
+
: never
|
|
17
|
+
|
|
18
|
+
/** `dispatch()` arguments: none for `Job` without a payload, the payload otherwise. */
|
|
19
|
+
export type PayloadArgs<J> = [PayloadOf<J>] extends [undefined] ? [payload?: undefined] : [payload: PayloadOf<J>]
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The static settings a job class may declare. They are deliberately not declared on `Job`, so apps compiled
|
|
23
|
+
* with `noImplicitOverride` write `static tries = 5` without `override` (as for providers).
|
|
24
|
+
*/
|
|
25
|
+
export type JobSettings = {
|
|
26
|
+
/** The name stored with the job (default: the class name). Set it if you rename the class while jobs wait. */
|
|
27
|
+
readonly jobName?: string
|
|
28
|
+
/** Default `'default'`. */
|
|
29
|
+
readonly queue?: string
|
|
30
|
+
/** Attempts in all, the first included. Default 3. */
|
|
31
|
+
readonly tries?: number
|
|
32
|
+
/** Default: exponential from 5 s, capped at 10 min, with jitter. */
|
|
33
|
+
readonly backoff?: Backoff
|
|
34
|
+
/**
|
|
35
|
+
* A run longer than this fails (and is retried). Default `'60s'`. The handler itself cannot be stopped: it keeps
|
|
36
|
+
* running in the background, so keep side effects idempotent.
|
|
37
|
+
*/
|
|
38
|
+
readonly timeout?: Duration
|
|
39
|
+
readonly payloadSchema?: PayloadSchema
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A job class. Its instances may also have `failed(payload, error)`, called once after the last attempt. */
|
|
43
|
+
export type JobClass<P = unknown> = (abstract new (...args: never[]) => Job<P>) & JobSettings
|
|
44
|
+
|
|
45
|
+
/** What a job instance may have besides `handle` (not declared on `Job`, so no `override` is needed). */
|
|
46
|
+
export type JobHooks<P = unknown> = { failed?(payload: P, error: Error): unknown }
|
|
47
|
+
|
|
48
|
+
const DEFAULT_BACKOFF = exponential('5s', { max: '10m', jitter: true })
|
|
49
|
+
|
|
50
|
+
/** A job class's settings with the defaults filled in. */
|
|
51
|
+
export function settingsOf(job: JobSettings) {
|
|
52
|
+
return {
|
|
53
|
+
queue: job.queue ?? 'default',
|
|
54
|
+
tries: job.tries ?? 3,
|
|
55
|
+
backoff: job.backoff ?? DEFAULT_BACKOFF,
|
|
56
|
+
timeoutMs: parseDuration(job.timeout ?? '60s'),
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* A unit of background work: an `@inject()` class with a typed payload and a `handle` method. Optional statics:
|
|
62
|
+
* `queue`, `tries`, `backoff`, `timeout`, `jobName` ({@link JobSettings}); optional `failed(payload, error)`.
|
|
63
|
+
*
|
|
64
|
+
* ```ts
|
|
65
|
+
* @inject(BookingRepository)
|
|
66
|
+
* export class SendCheckinJob extends Job<{ bookingId: string }> {
|
|
67
|
+
* static queue = 'notifications'
|
|
68
|
+
* static tries = 5
|
|
69
|
+
* constructor(private bookings: BookingRepository) { super() }
|
|
70
|
+
* async handle({ bookingId }: { bookingId: string }) { … }
|
|
71
|
+
* }
|
|
72
|
+
* await SendCheckinJob.dispatch({ bookingId }).delay('3d')
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
export abstract class Job<P = void> {
|
|
76
|
+
abstract handle(payload: P): unknown
|
|
77
|
+
|
|
78
|
+
/** Queue this job (after the current transaction commits). Resolves to the job id, or null for a duplicate `unique()`. */
|
|
79
|
+
static dispatch<J extends JobClass<never>>(this: J, ...[payload]: PayloadArgs<J>): PendingDispatch {
|
|
80
|
+
// biome-ignore lint/complexity/noThisInStatic: `this` is the concrete job class (SendCheckinJob), not Job
|
|
81
|
+
return new PendingDispatch(this as JobClass, payload)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** This job with a payload, for `Queue.chain([…])` and `Queue.batch([…])`. */
|
|
85
|
+
static with<J extends JobClass<never>>(this: J, ...[payload]: PayloadArgs<J>): JobSpec {
|
|
86
|
+
// biome-ignore lint/complexity/noThisInStatic: `this` is the concrete job class
|
|
87
|
+
registerJob(this as JobClass)
|
|
88
|
+
// biome-ignore lint/complexity/noThisInStatic: `this` is the concrete job class
|
|
89
|
+
return { name: jobName(this as JobClass), payload }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Exponential backoff: `base`, then ×2 per retry, capped at `max`; `jitter` spreads retries out (±50%). */
|
|
93
|
+
static exponential(base: Duration, options: { max?: Duration; jitter?: boolean } = {}): (attempt: number) => number {
|
|
94
|
+
return exponential(base, options)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* A job base class whose payload is checked against `schema` on dispatch and again before it runs:
|
|
99
|
+
* `class ProcessPaymentEventJob extends Job.schema(v.object({ eventId: v.string() })) { … }`
|
|
100
|
+
*/
|
|
101
|
+
static schema<T>(schema: PayloadSchema<T>) {
|
|
102
|
+
abstract class SchemaJob extends Job<T> {
|
|
103
|
+
static payloadSchema: PayloadSchema = schema
|
|
104
|
+
}
|
|
105
|
+
return SchemaJob
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function exponential(base: Duration, options: { max?: Duration; jitter?: boolean }) {
|
|
110
|
+
const first = parseDuration(base)
|
|
111
|
+
const max = options.max === undefined ? Number.POSITIVE_INFINITY : parseDuration(options.max)
|
|
112
|
+
return (attempt: number) => {
|
|
113
|
+
const ms = Math.min(first * 2 ** Math.max(0, attempt - 1), max)
|
|
114
|
+
return Math.round(options.jitter ? ms * (0.5 + Math.random()) : ms)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Milliseconds to wait before retrying after failed attempt `attempt`. */
|
|
119
|
+
export function backoffDelay(backoff: Backoff, attempt: number): number {
|
|
120
|
+
if (typeof backoff === 'function') return Math.max(0, backoff(attempt))
|
|
121
|
+
if (Array.isArray(backoff)) {
|
|
122
|
+
const list = backoff as readonly Duration[]
|
|
123
|
+
return list.length ? parseDuration(list[Math.min(attempt, list.length) - 1] as Duration) : 0
|
|
124
|
+
}
|
|
125
|
+
return parseDuration(backoff as Duration)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// ── the registry: job name → class, for workers ────────────────────────────────────────────────────
|
|
129
|
+
|
|
130
|
+
const registry = new Map<string, JobClass>()
|
|
131
|
+
|
|
132
|
+
export const jobName = (job: JobClass): string => job.jobName ?? job.name
|
|
133
|
+
|
|
134
|
+
/** Remember a job class by name (dispatch and discovery call this). Two classes with one name is an error. */
|
|
135
|
+
export function registerJob(job: JobClass): void {
|
|
136
|
+
const name = jobName(job)
|
|
137
|
+
const known = registry.get(name)
|
|
138
|
+
if (known && known !== job)
|
|
139
|
+
throw new CslugError('queue.duplicate_job', `Two job classes are named ${name}: set static jobName on one of them`)
|
|
140
|
+
registry.set(name, job)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export const findJob = (name: string): JobClass | undefined => registry.get(name)
|
|
144
|
+
|
|
145
|
+
export const isJobClass = (value: unknown): value is JobClass =>
|
|
146
|
+
typeof value === 'function' && value.prototype instanceof Job && !Object.is(value, Job)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { CslugError, registeredListeners, resolve } from '@cslug/core'
|
|
2
|
+
import { Job } from './job'
|
|
3
|
+
|
|
4
|
+
type Payload = { listener: string; event: string; payload: unknown }
|
|
5
|
+
|
|
6
|
+
/** Runs a `@listener(Event, { queued: true })` class in a worker. */
|
|
7
|
+
export class QueuedListenerJob extends Job<Payload> {
|
|
8
|
+
static jobName = 'cslug.listener'
|
|
9
|
+
|
|
10
|
+
async handle({ listener, event, payload }: Payload) {
|
|
11
|
+
for (const [cls, list] of registeredListeners()) {
|
|
12
|
+
if (cls.eventName !== event) continue
|
|
13
|
+
const found = list.find((l) => l.cls.name === listener)
|
|
14
|
+
if (!found) continue
|
|
15
|
+
const instance = resolve(found.cls) as { handle(payload: unknown, event: unknown): unknown }
|
|
16
|
+
return instance.handle(payload, new cls(payload as never))
|
|
17
|
+
}
|
|
18
|
+
throw new CslugError(
|
|
19
|
+
'queue.listener_not_found',
|
|
20
|
+
`No listener ${listener} for ${event}. Workers load app/listeners/; is the file there?`,
|
|
21
|
+
)
|
|
22
|
+
}
|
|
23
|
+
}
|
package/src/outbox.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
2
|
+
import type { Application, Logger } from '@cslug/core'
|
|
3
|
+
import { decode, encode } from '@cslug/redis'
|
|
4
|
+
import { type Envelope, type PushOptions, Queue } from './queue'
|
|
5
|
+
|
|
6
|
+
type DatabaseModule = typeof import('@cslug/database')
|
|
7
|
+
|
|
8
|
+
/** The outbox table's migration folder (registered with `addMigrations` when `@cslug/database` is present). */
|
|
9
|
+
export const OUTBOX_MIGRATIONS = join(import.meta.dir, '../migrations')
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Durable dispatch (`.durable()`): the job is written to `cslug_queue_outbox` in the current transaction, so it
|
|
13
|
+
* exists if and only if the transaction commits; it is then relayed to the queue (at once after COMMIT, and by
|
|
14
|
+
* workers every second for anything left behind) and deleted. Relaying is at least once.
|
|
15
|
+
*/
|
|
16
|
+
export class Outbox {
|
|
17
|
+
constructor(
|
|
18
|
+
private readonly app: Application,
|
|
19
|
+
private readonly db: DatabaseModule,
|
|
20
|
+
private readonly log: Logger,
|
|
21
|
+
) {}
|
|
22
|
+
|
|
23
|
+
/** The outbox when `@cslug/database` is installed and `Database` is bound (optional integration, rule 3). */
|
|
24
|
+
static async detect(app: Application, log: Logger): Promise<Outbox | undefined> {
|
|
25
|
+
try {
|
|
26
|
+
const db = await import('@cslug/database')
|
|
27
|
+
return app.has(db.Database) ? new Outbox(app, db, log) : undefined
|
|
28
|
+
} catch {
|
|
29
|
+
return undefined
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The `cslug_queue_outbox` table is created by `cslug migrate`. */
|
|
34
|
+
registerMigrations(): void {
|
|
35
|
+
this.db.addMigrations(OUTBOX_MIGRATIONS)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Insert in the ambient transaction. */
|
|
39
|
+
async write(envelope: Envelope, options: PushOptions): Promise<void> {
|
|
40
|
+
const { sql, Database } = this.db
|
|
41
|
+
await this.app
|
|
42
|
+
.resolve(Database)
|
|
43
|
+
.exec(
|
|
44
|
+
sql`insert into cslug_queue_outbox (id, envelope, options) values (${envelope.id}, ${encode(envelope)}, ${encode(options)})`,
|
|
45
|
+
)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Push waiting rows (one, or up to `limit`) to the queue and delete them. Returns how many. */
|
|
49
|
+
async relay(only?: string, limit = 100): Promise<number> {
|
|
50
|
+
const { sql, Database } = this.db
|
|
51
|
+
const db = this.app.resolve(Database)
|
|
52
|
+
const queue = this.app.resolve(Queue)
|
|
53
|
+
return db.transaction(async () => {
|
|
54
|
+
const rows = await db.many<{ id: string; envelope: string; options: string }>(
|
|
55
|
+
sql`select id, envelope, options from cslug_queue_outbox ${only ? sql`where id = ${only}` : sql``}
|
|
56
|
+
order by created_at limit ${limit} for update skip locked`,
|
|
57
|
+
)
|
|
58
|
+
for (const row of rows) {
|
|
59
|
+
await queue.push(decode<Envelope>(row.envelope) as Envelope, decode<PushOptions>(row.options) ?? {})
|
|
60
|
+
await db.exec(sql`delete from cslug_queue_outbox where id = ${row.id}`)
|
|
61
|
+
}
|
|
62
|
+
if (rows.length) this.log.debug('queue.outbox.relayed', { count: rows.length })
|
|
63
|
+
return rows.length
|
|
64
|
+
})
|
|
65
|
+
}
|
|
66
|
+
}
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { Clock, type Duration, EventBus, Logger, parseDuration, type RateLimit, ServiceProvider } from '@cslug/core'
|
|
2
|
+
import { RedisConnections, RedisProvider } from '@cslug/redis'
|
|
3
|
+
import { queueCommands } from './commands'
|
|
4
|
+
import { QueuedListenerJob } from './listener-job'
|
|
5
|
+
import { Outbox } from './outbox'
|
|
6
|
+
import { Queue } from './queue'
|
|
7
|
+
import { RedisQueue } from './redis-queue'
|
|
8
|
+
import { Worker, type WorkerOptions } from './worker'
|
|
9
|
+
|
|
10
|
+
/** `config/queue.ts`. */
|
|
11
|
+
export type QueueConfig = {
|
|
12
|
+
/** Redis connection name (config/redis.ts). Default `'default'`. */
|
|
13
|
+
connection?: string
|
|
14
|
+
/** Queues a plain `cslug queue:work` runs: concurrency (default 1) and an optional rate (`'30/s'`, all workers). */
|
|
15
|
+
queues?: Record<string, { concurrency?: number; rateLimit?: RateLimit }>
|
|
16
|
+
failed?: { keep?: Duration }
|
|
17
|
+
/** How long `SIGTERM` waits for running jobs. Default `'30s'`. */
|
|
18
|
+
shutdownTimeout?: Duration
|
|
19
|
+
/** A job whose worker stopped renewing it for this long is taken over. Default `'30s'`. */
|
|
20
|
+
lease?: Duration
|
|
21
|
+
/** One blocking read; also how soon a due delayed job is noticed. Default `'1s'`. */
|
|
22
|
+
block?: Duration
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The workers running in this process (and the outbox relay), stopped gracefully when the app shuts down. */
|
|
26
|
+
export class Workers {
|
|
27
|
+
private readonly all = new Set<Worker>()
|
|
28
|
+
private relay?: Timer
|
|
29
|
+
|
|
30
|
+
constructor(
|
|
31
|
+
private readonly create: (options: Omit<WorkerOptions, 'leaseMs' | 'blockMs'>) => Worker,
|
|
32
|
+
private readonly shutdownMs: number,
|
|
33
|
+
private readonly outbox: () => Outbox | undefined = () => undefined,
|
|
34
|
+
) {}
|
|
35
|
+
|
|
36
|
+
/** Start a worker for these queues (each `{ name, concurrency, rateLimit? }`). */
|
|
37
|
+
async start(queues: WorkerOptions['queues']): Promise<Worker> {
|
|
38
|
+
const worker = this.create({ queues })
|
|
39
|
+
this.all.add(worker)
|
|
40
|
+
await worker.start()
|
|
41
|
+
const outbox = this.outbox()
|
|
42
|
+
// rows a crashed process left in the outbox (the fast path relays at COMMIT)
|
|
43
|
+
this.relay ??= outbox ? setInterval(() => void outbox.relay().catch(() => {}), 1000) : undefined
|
|
44
|
+
return worker
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async stopAll(timeoutMs = this.shutdownMs): Promise<void> {
|
|
48
|
+
clearInterval(this.relay)
|
|
49
|
+
this.relay = undefined
|
|
50
|
+
await Promise.all([...this.all].map((w) => w.stop(timeoutMs)))
|
|
51
|
+
this.all.clear()
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Binds `Queue` (Redis Streams, on the connection `queue.connection`), runs queued event listeners as jobs,
|
|
57
|
+
* contributes the `queue:*` commands, and stops this process's workers gracefully at shutdown.
|
|
58
|
+
*/
|
|
59
|
+
export class QueueProvider extends ServiceProvider {
|
|
60
|
+
static dependsOn = [RedisProvider]
|
|
61
|
+
|
|
62
|
+
private get config(): QueueConfig {
|
|
63
|
+
return this.app.config<QueueConfig | undefined>('queue') ?? {}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
register() {
|
|
67
|
+
this.commands(queueCommands)
|
|
68
|
+
const config = this.config
|
|
69
|
+
this.app.singleton(
|
|
70
|
+
RedisQueue,
|
|
71
|
+
(c) =>
|
|
72
|
+
new RedisQueue(
|
|
73
|
+
c
|
|
74
|
+
.resolve(RedisConnections)
|
|
75
|
+
.get(config.connection ?? 'default')
|
|
76
|
+
.withPrefix('queue:'),
|
|
77
|
+
() => this.app.resolve(Clock).now().getTime(),
|
|
78
|
+
parseDuration(config.failed?.keep ?? '30d'),
|
|
79
|
+
),
|
|
80
|
+
)
|
|
81
|
+
this.app.singleton(Queue, (c) => c.resolve(RedisQueue))
|
|
82
|
+
this.app.singleton(
|
|
83
|
+
Workers,
|
|
84
|
+
(c) =>
|
|
85
|
+
new Workers(
|
|
86
|
+
(options) =>
|
|
87
|
+
new Worker(
|
|
88
|
+
this.app,
|
|
89
|
+
c.resolve(RedisQueue),
|
|
90
|
+
{
|
|
91
|
+
...options,
|
|
92
|
+
leaseMs: parseDuration(config.lease ?? '30s'),
|
|
93
|
+
blockMs: parseDuration(config.block ?? '1s'),
|
|
94
|
+
},
|
|
95
|
+
c.resolve(Logger),
|
|
96
|
+
),
|
|
97
|
+
parseDuration(config.shutdownTimeout ?? '30s'),
|
|
98
|
+
() => (this.app.has(Outbox) ? this.app.resolve(Outbox) : undefined),
|
|
99
|
+
),
|
|
100
|
+
)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async boot() {
|
|
104
|
+
const outbox = await Outbox.detect(this.app, this.app.resolve(Logger))
|
|
105
|
+
if (outbox) {
|
|
106
|
+
outbox.registerMigrations()
|
|
107
|
+
this.app.instance(Outbox, outbox)
|
|
108
|
+
}
|
|
109
|
+
// queued listeners become jobs (core runs them in-process when no queue is installed)
|
|
110
|
+
this.app.resolve(EventBus).dispatchQueued = async ({ listener, event, payload, options }) => {
|
|
111
|
+
const dispatch = this.app
|
|
112
|
+
.resolve(Queue)
|
|
113
|
+
.dispatch(QueuedListenerJob, { listener: listener.name, event: event.eventName, payload })
|
|
114
|
+
.immediately() // the bus already waited for COMMIT
|
|
115
|
+
if (options.queue) dispatch.onQueue(options.queue)
|
|
116
|
+
if (options.tries) dispatch.tries(options.tries)
|
|
117
|
+
await dispatch
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async shutdown() {
|
|
122
|
+
await this.app.resolve(Workers).stopAll()
|
|
123
|
+
}
|
|
124
|
+
}
|