@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/schedule.ts
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { type Application, CslugError, kebab, type resolve } from '@cslug/core'
|
|
2
|
+
import { Cron, type LocalTime } from './cron'
|
|
3
|
+
import type { JobClass, PayloadOf } from './job'
|
|
4
|
+
|
|
5
|
+
/** What an inline `s.call()` task receives. */
|
|
6
|
+
export type TaskContext = { app: Application; resolve: typeof resolve }
|
|
7
|
+
type Task = (ctx: TaskContext) => unknown
|
|
8
|
+
|
|
9
|
+
const DAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] as const
|
|
10
|
+
export type Weekday = (typeof DAYS)[number]
|
|
11
|
+
|
|
12
|
+
const hm = (time: string): [number, number] => {
|
|
13
|
+
const m = /^(\d{1,2}):(\d{2})$/.exec(time)
|
|
14
|
+
const [h, min] = [Number(m?.[1]), Number(m?.[2])]
|
|
15
|
+
if (!m || h > 23 || min > 59) throw new CslugError('schedule.bad_time', `Use "HH:MM" (24 h), not "${time}"`)
|
|
16
|
+
return [h, min]
|
|
17
|
+
}
|
|
18
|
+
const ordinal = (n: number) =>
|
|
19
|
+
`${n}${n % 10 === 1 && n !== 11 ? 'st' : n % 10 === 2 && n !== 12 ? 'nd' : n % 10 === 3 && n !== 13 ? 'rd' : 'th'}`
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* One scheduled entry: when it runs (cron, by default every minute) and what it does (dispatch a job, or an
|
|
23
|
+
* inline task). Frequency helpers replace the cron; modifiers narrow it.
|
|
24
|
+
*/
|
|
25
|
+
export class ScheduleEntry {
|
|
26
|
+
crons: Cron[] = [new Cron('* * * * *')]
|
|
27
|
+
description = 'every minute'
|
|
28
|
+
tz?: string
|
|
29
|
+
overlap = false
|
|
30
|
+
catchUpMode?: 'once'
|
|
31
|
+
private filters: ((t: LocalTime, app: Application) => boolean)[] = []
|
|
32
|
+
|
|
33
|
+
constructor(
|
|
34
|
+
public name: string,
|
|
35
|
+
readonly job?: JobClass,
|
|
36
|
+
readonly payload?: unknown,
|
|
37
|
+
readonly task?: Task,
|
|
38
|
+
) {}
|
|
39
|
+
|
|
40
|
+
/** Raw cron (5 fields). */
|
|
41
|
+
cron(expression: string): this {
|
|
42
|
+
return this.at([expression], expression)
|
|
43
|
+
}
|
|
44
|
+
everyMinute(): this {
|
|
45
|
+
return this.at(['* * * * *'], 'every minute')
|
|
46
|
+
}
|
|
47
|
+
everyFiveMinutes(): this {
|
|
48
|
+
return this.at(['*/5 * * * *'], 'every 5 minutes')
|
|
49
|
+
}
|
|
50
|
+
everyTenMinutes(): this {
|
|
51
|
+
return this.at(['*/10 * * * *'], 'every 10 minutes')
|
|
52
|
+
}
|
|
53
|
+
everyFifteenMinutes(): this {
|
|
54
|
+
return this.at(['*/15 * * * *'], 'every 15 minutes')
|
|
55
|
+
}
|
|
56
|
+
everyThirtyMinutes(): this {
|
|
57
|
+
return this.at(['*/30 * * * *'], 'every 30 minutes')
|
|
58
|
+
}
|
|
59
|
+
hourly(): this {
|
|
60
|
+
return this.at(['0 * * * *'], 'hourly')
|
|
61
|
+
}
|
|
62
|
+
hourlyAt(minute: number): this {
|
|
63
|
+
return this.at([`${minute} * * * *`], `hourly at :${String(minute).padStart(2, '0')}`)
|
|
64
|
+
}
|
|
65
|
+
daily(): this {
|
|
66
|
+
return this.dailyAt('00:00')
|
|
67
|
+
}
|
|
68
|
+
dailyAt(time: string): this {
|
|
69
|
+
const [h, m] = hm(time)
|
|
70
|
+
return this.at([`${m} ${h} * * *`], `daily ${time}`)
|
|
71
|
+
}
|
|
72
|
+
twiceDaily(first: string, second: string): this {
|
|
73
|
+
const [[h1, m1], [h2, m2]] = [hm(first), hm(second)]
|
|
74
|
+
return this.at([`${m1} ${h1} * * *`, `${m2} ${h2} * * *`], `daily ${first} and ${second}`)
|
|
75
|
+
}
|
|
76
|
+
weekly(): this {
|
|
77
|
+
return this.weeklyOn('sunday', '00:00')
|
|
78
|
+
}
|
|
79
|
+
weeklyOn(day: Weekday, time = '00:00'): this {
|
|
80
|
+
const [h, m] = hm(time)
|
|
81
|
+
const n = DAYS.indexOf(day)
|
|
82
|
+
if (n < 0) throw new CslugError('schedule.bad_day', `weeklyOn(): "${day}" is not a weekday name`)
|
|
83
|
+
return this.at([`${m} ${h} * * ${n}`], `${day}s ${time}`)
|
|
84
|
+
}
|
|
85
|
+
monthly(): this {
|
|
86
|
+
return this.monthlyOn(1, '00:00')
|
|
87
|
+
}
|
|
88
|
+
monthlyOn(day: number, time = '00:00'): this {
|
|
89
|
+
const [h, m] = hm(time)
|
|
90
|
+
return this.at([`${m} ${h} ${day} * *`], `monthly ${ordinal(day)} ${time}`)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Only Monday to Friday. */
|
|
94
|
+
weekdays(): this {
|
|
95
|
+
this.description += ', weekdays'
|
|
96
|
+
return this.filter((t) => t.weekday >= 1 && t.weekday <= 5)
|
|
97
|
+
}
|
|
98
|
+
/** Only between two local times (inclusive). */
|
|
99
|
+
between(from: string, to: string): this {
|
|
100
|
+
const [a, b] = [hm(from), hm(to)].map(([h, m]) => h * 60 + m) as [number, number]
|
|
101
|
+
this.description += `, ${from}–${to}`
|
|
102
|
+
return this.filter((t) => t.hour * 60 + t.minute >= a && t.hour * 60 + t.minute <= b)
|
|
103
|
+
}
|
|
104
|
+
/** Only when `fn` returns true at the tick. */
|
|
105
|
+
when(fn: () => boolean): this {
|
|
106
|
+
return this.filter(() => fn())
|
|
107
|
+
}
|
|
108
|
+
/** Only in these `app.env` values. */
|
|
109
|
+
environments(envs: readonly string[]): this {
|
|
110
|
+
return this.filter((_, app) => envs.includes(String(app.config('app.env') ?? 'development')))
|
|
111
|
+
}
|
|
112
|
+
/** Interpret times in this IANA zone (default: `schedule.timezone`, else UTC). */
|
|
113
|
+
timezone(tz: string): this {
|
|
114
|
+
this.tz = tz
|
|
115
|
+
return this
|
|
116
|
+
}
|
|
117
|
+
/** Start even if the previous run is still going. */
|
|
118
|
+
allowOverlap(): this {
|
|
119
|
+
this.overlap = true
|
|
120
|
+
return this
|
|
121
|
+
}
|
|
122
|
+
/** After downtime, run one missed tick on recovery (default: missed ticks are skipped). */
|
|
123
|
+
catchUp(mode: 'once'): this {
|
|
124
|
+
this.catchUpMode = mode
|
|
125
|
+
return this
|
|
126
|
+
}
|
|
127
|
+
/** Rename the entry (history, locks, `schedule:test`). */
|
|
128
|
+
as(name: string): this {
|
|
129
|
+
this.name = name
|
|
130
|
+
return this
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Due at this local minute? */
|
|
134
|
+
isDue(t: LocalTime, app: Application): boolean {
|
|
135
|
+
return this.crons.some((c) => c.matches(t)) && this.filters.every((f) => f(t, app))
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** The next due minute after `after` (filters included), in `tz`. */
|
|
139
|
+
nextAfter(after: Date, tz: string, app: Application, localOf: (d: Date) => LocalTime): Date | undefined {
|
|
140
|
+
let from = after
|
|
141
|
+
for (let i = 0; i < 10_000; i++) {
|
|
142
|
+
const candidates = this.crons.map((c) => c.next(from, tz)).filter((d): d is Date => !!d)
|
|
143
|
+
if (!candidates.length) return undefined
|
|
144
|
+
const next = new Date(Math.min(...candidates.map((d) => d.getTime())))
|
|
145
|
+
if (this.filters.every((f) => f(localOf(next), app))) return next
|
|
146
|
+
from = next
|
|
147
|
+
}
|
|
148
|
+
return undefined
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
private at(expressions: string[], description: string): this {
|
|
152
|
+
this.crons = expressions.map((e) => new Cron(e))
|
|
153
|
+
this.description = description
|
|
154
|
+
return this
|
|
155
|
+
}
|
|
156
|
+
private filter(fn: (t: LocalTime, app: Application) => boolean): this {
|
|
157
|
+
this.filters.push(fn)
|
|
158
|
+
return this
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** The builder `routes/schedule.ts` receives. */
|
|
163
|
+
export class ScheduleBuilder {
|
|
164
|
+
readonly entries: ScheduleEntry[] = []
|
|
165
|
+
|
|
166
|
+
/** Dispatch this job (to the queue; the scheduler stays light). */
|
|
167
|
+
job<J extends JobClass<never>>(
|
|
168
|
+
job: J,
|
|
169
|
+
...payload: PayloadOf<J> extends undefined ? [] : [PayloadOf<J>]
|
|
170
|
+
): ScheduleEntry {
|
|
171
|
+
return this.add(new ScheduleEntry(entryName(job.name), job as JobClass, payload[0]))
|
|
172
|
+
}
|
|
173
|
+
/** Run a small task inline, in the scheduler process (keep it fast). */
|
|
174
|
+
call(name: string, task: Task): ScheduleEntry {
|
|
175
|
+
return this.add(new ScheduleEntry(name, undefined, undefined, task))
|
|
176
|
+
}
|
|
177
|
+
/** `s.cron('0 *\/6 * * *', 'db:vacuum', VacuumJob)`: a job on a raw cron with a name. */
|
|
178
|
+
cron<J extends JobClass<never>>(
|
|
179
|
+
expression: string,
|
|
180
|
+
name: string,
|
|
181
|
+
job: J,
|
|
182
|
+
...payload: PayloadOf<J> extends undefined ? [] : [PayloadOf<J>]
|
|
183
|
+
): ScheduleEntry {
|
|
184
|
+
return this.add(new ScheduleEntry(name, job as JobClass, payload[0]).cron(expression))
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
private add(entry: ScheduleEntry): ScheduleEntry {
|
|
188
|
+
this.entries.push(entry)
|
|
189
|
+
return entry
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** `SendDueRemindersJob` → `send-due-reminders`. */
|
|
194
|
+
export const entryName = (className: string) => kebab(className.replace(/Job$/, '')).replace(/^-/, '')
|
|
195
|
+
|
|
196
|
+
export type ScheduleDefinition = { readonly __schedule: true; define(s: ScheduleBuilder): void }
|
|
197
|
+
|
|
198
|
+
/** `routes/schedule.ts`: `export default defineSchedule((s) => { s.job(ReportJob).dailyAt('07:00') })`. */
|
|
199
|
+
export function defineSchedule(define: (s: ScheduleBuilder) => void): ScheduleDefinition {
|
|
200
|
+
return { __schedule: true, define }
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Build the entries of a definition; names must be unique. */
|
|
204
|
+
export function buildSchedule(definition: ScheduleDefinition): ScheduleEntry[] {
|
|
205
|
+
const builder = new ScheduleBuilder()
|
|
206
|
+
definition.define(builder)
|
|
207
|
+
const seen = new Set<string>()
|
|
208
|
+
for (const e of builder.entries) {
|
|
209
|
+
if (seen.has(e.name))
|
|
210
|
+
throw new CslugError(
|
|
211
|
+
'schedule.duplicate_name',
|
|
212
|
+
`Two schedule entries are named "${e.name}": rename one with .as(name)`,
|
|
213
|
+
)
|
|
214
|
+
seen.add(e.name)
|
|
215
|
+
}
|
|
216
|
+
return builder.entries
|
|
217
|
+
}
|
package/src/scheduler.ts
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { type Application, Clock, Lock, type Logger, resolve, runInContext } from '@cslug/core'
|
|
2
|
+
import type { Redis } from '@cslug/redis'
|
|
3
|
+
import { decode, encode } from '@cslug/redis'
|
|
4
|
+
import { localTime } from './cron'
|
|
5
|
+
import { Queue } from './queue'
|
|
6
|
+
import type { ScheduleEntry } from './schedule'
|
|
7
|
+
|
|
8
|
+
/** One recorded run (`cslug schedule:history`). */
|
|
9
|
+
export type ScheduleRun = {
|
|
10
|
+
name: string
|
|
11
|
+
scheduledFor: Date
|
|
12
|
+
startedAt: Date
|
|
13
|
+
finishedAt?: Date
|
|
14
|
+
/** `dispatched` (job sent to the queue), `ok` / `failed` (inline task), `skipped` (previous run still going). */
|
|
15
|
+
status: 'dispatched' | 'ok' | 'failed' | 'skipped'
|
|
16
|
+
error?: string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const KEEP = 100
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Runs `routes/schedule.ts`: each minute, every due entry runs once across all scheduler instances (a lock per
|
|
23
|
+
* entry and tick), not while its previous run is still going (unless `allowOverlap()`), and is recorded.
|
|
24
|
+
*/
|
|
25
|
+
export class Scheduler {
|
|
26
|
+
entries: ScheduleEntry[] = []
|
|
27
|
+
private running = false
|
|
28
|
+
private wake?: () => void
|
|
29
|
+
private loop?: Promise<void>
|
|
30
|
+
|
|
31
|
+
constructor(
|
|
32
|
+
private readonly app: Application,
|
|
33
|
+
private readonly store: Redis | undefined,
|
|
34
|
+
private readonly timezone: string,
|
|
35
|
+
private readonly log: Logger,
|
|
36
|
+
) {}
|
|
37
|
+
|
|
38
|
+
tzOf(entry: ScheduleEntry): string {
|
|
39
|
+
return entry.tz ?? this.timezone
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
find(name: string): ScheduleEntry | undefined {
|
|
43
|
+
return this.entries.find((e) => e.name === name)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
next(entry: ScheduleEntry, after: Date = this.now()): Date | undefined {
|
|
47
|
+
const tz = this.tzOf(entry)
|
|
48
|
+
return entry.nextAfter(after, tz, this.app, (d) => localTime(d, tz))
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Run every entry due at `now`'s minute. `exclusive: false` skips the once-per-tick lock (tests, where the
|
|
53
|
+
* same tick is replayed). Returns the runs this instance made.
|
|
54
|
+
*/
|
|
55
|
+
async runDue(now: Date = this.now(), options: { exclusive?: boolean } = {}): Promise<ScheduleRun[]> {
|
|
56
|
+
const tick = new Date(Math.floor(now.getTime() / 60_000) * 60_000)
|
|
57
|
+
const runs: ScheduleRun[] = []
|
|
58
|
+
for (const entry of this.entries) {
|
|
59
|
+
if (!entry.isDue(localTime(tick, this.tzOf(entry)), this.app)) continue
|
|
60
|
+
const run = await this.run(entry, tick, options.exclusive ?? true)
|
|
61
|
+
if (run) runs.push(run)
|
|
62
|
+
}
|
|
63
|
+
return runs
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Run one entry for `tick` (no schedule check). `exclusive`: take the once-per-tick lock first. */
|
|
67
|
+
async run(entry: ScheduleEntry, tick: Date, exclusive = true): Promise<ScheduleRun | undefined> {
|
|
68
|
+
const lock = this.app.resolve(Lock)
|
|
69
|
+
if (exclusive && !(await lock.acquire(`schedule:${entry.name}:${tick.toISOString()}`, '10m'))) return undefined
|
|
70
|
+
const run: ScheduleRun = { name: entry.name, scheduledFor: tick, startedAt: this.now(), status: 'ok' }
|
|
71
|
+
const scope = this.app.createScope()
|
|
72
|
+
try {
|
|
73
|
+
await runInContext({ app: this.app, scope, requestId: `schedule:${entry.name}` }, async () => {
|
|
74
|
+
if (entry.job) {
|
|
75
|
+
let dispatch = this.app.resolve(Queue).dispatch(entry.job as never, entry.payload as never)
|
|
76
|
+
if (!entry.overlap) dispatch = dispatch.unique(`schedule:${entry.name}`)
|
|
77
|
+
run.status = (await dispatch) === null ? 'skipped' : 'dispatched'
|
|
78
|
+
return
|
|
79
|
+
}
|
|
80
|
+
const held = entry.overlap ? undefined : await lock.acquire(`schedule:${entry.name}:running`, '1h')
|
|
81
|
+
if (!entry.overlap && !held) {
|
|
82
|
+
run.status = 'skipped'
|
|
83
|
+
return
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
await entry.task?.({ app: this.app, resolve })
|
|
87
|
+
} finally {
|
|
88
|
+
await held?.release()
|
|
89
|
+
}
|
|
90
|
+
})
|
|
91
|
+
} catch (error) {
|
|
92
|
+
run.status = 'failed'
|
|
93
|
+
run.error = error instanceof Error ? error.message : String(error)
|
|
94
|
+
this.log.error('schedule.failed', { entry: entry.name, error })
|
|
95
|
+
} finally {
|
|
96
|
+
await scope.dispose()
|
|
97
|
+
}
|
|
98
|
+
run.finishedAt = this.now()
|
|
99
|
+
if (run.status !== 'failed')
|
|
100
|
+
this.log.info(`schedule.${run.status}`, { entry: entry.name, tick: tick.toISOString() })
|
|
101
|
+
await this.record(run)
|
|
102
|
+
return run
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** For entries with `catchUp('once')`: if a tick was missed since the last recorded run, run it once now. */
|
|
106
|
+
async catchUp(now: Date = this.now()): Promise<ScheduleRun[]> {
|
|
107
|
+
const tick = Math.floor(now.getTime() / 60_000) * 60_000
|
|
108
|
+
const runs: ScheduleRun[] = []
|
|
109
|
+
for (const entry of this.entries.filter((e) => e.catchUpMode === 'once')) {
|
|
110
|
+
const [last] = await this.history(entry.name, 1)
|
|
111
|
+
const missed = last && this.next(entry, last.scheduledFor)
|
|
112
|
+
if (!missed || missed.getTime() >= tick) continue
|
|
113
|
+
const run = await this.run(entry, missed)
|
|
114
|
+
if (run) runs.push(run)
|
|
115
|
+
}
|
|
116
|
+
return runs
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async history(name: string, last = 10): Promise<ScheduleRun[]> {
|
|
120
|
+
if (!this.store) return []
|
|
121
|
+
const rows = (await this.store.send('LRANGE', [
|
|
122
|
+
this.store.key(`schedule:history:${name}`),
|
|
123
|
+
0,
|
|
124
|
+
last - 1,
|
|
125
|
+
])) as string[]
|
|
126
|
+
return rows.map((r) => decode<ScheduleRun>(r) as ScheduleRun)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Last time the loop ticked (epoch ms), for health checks. */
|
|
130
|
+
async heartbeat(): Promise<number | undefined> {
|
|
131
|
+
const v = this.store ? await this.store.send('GET', [this.store.key('schedule:heartbeat')]) : null
|
|
132
|
+
return v ? Number(v) : undefined
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Tick at the start of every minute until `stop()`. */
|
|
136
|
+
start(): void {
|
|
137
|
+
if (this.running) return
|
|
138
|
+
this.running = true
|
|
139
|
+
this.loop = (async () => {
|
|
140
|
+
await this.catchUp().catch((error) => this.log.error('schedule.catch_up_failed', { error }))
|
|
141
|
+
while (this.running) {
|
|
142
|
+
await this.store?.send('SET', [this.store.key('schedule:heartbeat'), Date.now()]).catch(() => {})
|
|
143
|
+
const wait = 60_000 - (Date.now() % 60_000) + 50
|
|
144
|
+
await new Promise<void>((r) => {
|
|
145
|
+
const timer = setTimeout(r, wait)
|
|
146
|
+
this.wake = () => {
|
|
147
|
+
clearTimeout(timer)
|
|
148
|
+
r()
|
|
149
|
+
}
|
|
150
|
+
})
|
|
151
|
+
if (!this.running) break
|
|
152
|
+
await this.runDue().catch((error) => this.log.error('schedule.tick_failed', { error }))
|
|
153
|
+
}
|
|
154
|
+
})()
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Stop after the current tick. */
|
|
158
|
+
async stop(): Promise<void> {
|
|
159
|
+
this.running = false
|
|
160
|
+
this.wake?.()
|
|
161
|
+
await this.loop
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
private now(): Date {
|
|
165
|
+
return this.app.resolve(Clock).now()
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
private async record(run: ScheduleRun): Promise<void> {
|
|
169
|
+
if (!this.store) return
|
|
170
|
+
const key = this.store.key(`schedule:history:${run.name}`)
|
|
171
|
+
await this.store.send('LPUSH', [key, encode(run)]).catch(() => {})
|
|
172
|
+
await this.store.send('LTRIM', [key, 0, KEEP - 1]).catch(() => {})
|
|
173
|
+
}
|
|
174
|
+
}
|
package/src/worker.ts
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { hostname } from 'node:os'
|
|
2
|
+
import { type Application, type Logger, type RateLimit, RateLimiter } from '@cslug/core'
|
|
3
|
+
import { decode, type Redis } from '@cslug/redis'
|
|
4
|
+
import { backoffDelay, findJob, settingsOf } from './job'
|
|
5
|
+
import { type Envelope, runFailedHook, runJob } from './queue'
|
|
6
|
+
import { BANDS, GROUP, type RedisQueue } from './redis-queue'
|
|
7
|
+
|
|
8
|
+
export type WorkerOptions = {
|
|
9
|
+
queues: { name: string; concurrency: number; rateLimit?: RateLimit }[]
|
|
10
|
+
/** A job whose worker stopped renewing it for this long is taken over by another worker. Default 30 s. */
|
|
11
|
+
leaseMs?: number
|
|
12
|
+
/** How long one blocking read waits (also the delay before a due delayed job is noticed). Default 1 s. */
|
|
13
|
+
blockMs?: number
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
type Entry = { stream: string; id: string; envelope: Envelope; deliveries: number }
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Runs jobs from one or more queues: a read loop per queue on its own Redis connection (spike c), at most
|
|
20
|
+
* `concurrency` jobs at a time per queue, retries with backoff, the failed store after the last attempt,
|
|
21
|
+
* lease renewal while a job runs and takeover (`XAUTOCLAIM`) of jobs whose worker died.
|
|
22
|
+
*/
|
|
23
|
+
export class Worker {
|
|
24
|
+
readonly consumer = `${hostname()}:${process.pid}:${Math.random().toString(36).slice(2, 8)}`
|
|
25
|
+
private running = false
|
|
26
|
+
private readonly loops: Promise<void>[] = []
|
|
27
|
+
private readonly readers = new Set<Redis>()
|
|
28
|
+
private readonly active = new Set<Promise<void>>()
|
|
29
|
+
private readonly leaseMs: number
|
|
30
|
+
private readonly blockMs: number
|
|
31
|
+
|
|
32
|
+
constructor(
|
|
33
|
+
private readonly app: Application,
|
|
34
|
+
private readonly queue: RedisQueue,
|
|
35
|
+
private readonly options: WorkerOptions,
|
|
36
|
+
private readonly log: Logger,
|
|
37
|
+
) {
|
|
38
|
+
this.leaseMs = options.leaseMs ?? 30_000
|
|
39
|
+
this.blockMs = options.blockMs ?? 1000
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
get isRunning(): boolean {
|
|
43
|
+
return this.running
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Start the loops (returns at once). */
|
|
47
|
+
async start(): Promise<void> {
|
|
48
|
+
this.running = true
|
|
49
|
+
for (const q of this.options.queues) {
|
|
50
|
+
await this.queue.ensureGroups(q.name)
|
|
51
|
+
this.loops.push(this.loop(q.name, q.concurrency))
|
|
52
|
+
}
|
|
53
|
+
this.log.info('queue.worker.started', { consumer: this.consumer, queues: this.options.queues.map((q) => q.name) })
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Stop reading, let running jobs finish (up to `timeoutMs`); unfinished ones are taken over after their lease. */
|
|
57
|
+
async stop(timeoutMs = 30_000): Promise<void> {
|
|
58
|
+
if (!this.running) return
|
|
59
|
+
this.running = false
|
|
60
|
+
for (const r of this.readers) r.close() // a blocked read rejects at once (spike c)
|
|
61
|
+
const done = Promise.allSettled([...this.loops, ...this.active])
|
|
62
|
+
const finished = await Promise.race([done.then(() => true), Bun.sleep(timeoutMs).then(() => false)])
|
|
63
|
+
if (!finished) this.log.warn('queue.worker.shutdown_timeout', { running: this.active.size })
|
|
64
|
+
this.log.info('queue.worker.stopped', { consumer: this.consumer })
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
private async loop(queue: string, concurrency: number): Promise<void> {
|
|
68
|
+
const streams = BANDS.map((b) => this.queue.stream(queue, b))
|
|
69
|
+
let reader: Redis | undefined
|
|
70
|
+
let failures = 0
|
|
71
|
+
let lastClaim = 0
|
|
72
|
+
const mine = new Set<Promise<void>>()
|
|
73
|
+
while (this.running) {
|
|
74
|
+
try {
|
|
75
|
+
while (mine.size >= concurrency && this.running) await Promise.race(mine)
|
|
76
|
+
if (!this.running) break
|
|
77
|
+
await this.queue.promote(queue)
|
|
78
|
+
await this.queue.redis.send('SET', [this.queue.redis.key('heartbeat'), Date.now()])
|
|
79
|
+
if (Date.now() - lastClaim > this.leaseMs / 2) {
|
|
80
|
+
lastClaim = Date.now()
|
|
81
|
+
for (const entry of await this.reclaim(streams, concurrency - mine.size)) this.track(mine, entry)
|
|
82
|
+
}
|
|
83
|
+
if (!reader) {
|
|
84
|
+
reader = this.queue.redis.dedicated()
|
|
85
|
+
this.readers.add(reader)
|
|
86
|
+
await this.queue.ensureGroups(queue, reader)
|
|
87
|
+
}
|
|
88
|
+
const entries = await this.read(reader, streams, concurrency - mine.size)
|
|
89
|
+
failures = 0
|
|
90
|
+
for (const entry of entries) this.track(mine, entry)
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (!this.running) break
|
|
93
|
+
if (reader) {
|
|
94
|
+
this.readers.delete(reader)
|
|
95
|
+
reader.close()
|
|
96
|
+
reader = undefined
|
|
97
|
+
}
|
|
98
|
+
failures++
|
|
99
|
+
this.log.warn('queue.worker.read_failed', { queue, error, retryInMs: Math.min(30_000, 250 * 2 ** failures) })
|
|
100
|
+
await Bun.sleep(Math.min(30_000, 250 * 2 ** failures))
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (reader) {
|
|
104
|
+
this.readers.delete(reader)
|
|
105
|
+
reader.close()
|
|
106
|
+
}
|
|
107
|
+
await Promise.allSettled(mine)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
private track(mine: Set<Promise<void>>, entry: Entry): void {
|
|
111
|
+
const p: Promise<void> = this.process(entry).finally(() => {
|
|
112
|
+
mine.delete(p)
|
|
113
|
+
this.active.delete(p)
|
|
114
|
+
})
|
|
115
|
+
mine.add(p)
|
|
116
|
+
this.active.add(p)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** One blocking read for new entries, with a client-side deadline in case the connection is wedged. */
|
|
120
|
+
private async read(reader: Redis, streams: string[], count: number): Promise<Entry[]> {
|
|
121
|
+
const keys = streams.map((s) => reader.key(s))
|
|
122
|
+
const args = [
|
|
123
|
+
'GROUP',
|
|
124
|
+
GROUP,
|
|
125
|
+
this.consumer,
|
|
126
|
+
'COUNT',
|
|
127
|
+
Math.max(1, count),
|
|
128
|
+
'BLOCK',
|
|
129
|
+
this.blockMs,
|
|
130
|
+
'STREAMS',
|
|
131
|
+
...keys,
|
|
132
|
+
...keys.map(() => '>'),
|
|
133
|
+
]
|
|
134
|
+
let timer: Timer | undefined
|
|
135
|
+
const deadline = new Promise<never>((_, reject) => {
|
|
136
|
+
timer = setTimeout(() => reject(new Error('XREADGROUP did not return in time')), this.blockMs + 5000)
|
|
137
|
+
})
|
|
138
|
+
try {
|
|
139
|
+
const reply = await Promise.race([reader.send('XREADGROUP', args), deadline])
|
|
140
|
+
return parseRead(reply).flatMap(([key, rows]) => {
|
|
141
|
+
const stream = streams[keys.indexOf(key)] ?? key.slice(reader.prefix.length)
|
|
142
|
+
return rows.flatMap(([id, fields]) =>
|
|
143
|
+
fields ? [{ stream, id, envelope: envelopeFrom(fields), deliveries: 1 }] : [],
|
|
144
|
+
)
|
|
145
|
+
})
|
|
146
|
+
} finally {
|
|
147
|
+
clearTimeout(timer)
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Take over entries idle longer than the lease (their worker died), with their delivery counts. */
|
|
152
|
+
private async reclaim(streams: string[], count: number): Promise<Entry[]> {
|
|
153
|
+
if (count <= 0) return []
|
|
154
|
+
const out: Entry[] = []
|
|
155
|
+
const redis = this.queue.redis
|
|
156
|
+
for (const stream of streams) {
|
|
157
|
+
const key = redis.key(stream)
|
|
158
|
+
const reply = (await redis.send('XAUTOCLAIM', [
|
|
159
|
+
key,
|
|
160
|
+
GROUP,
|
|
161
|
+
this.consumer,
|
|
162
|
+
this.leaseMs,
|
|
163
|
+
'0',
|
|
164
|
+
'COUNT',
|
|
165
|
+
count,
|
|
166
|
+
])) as [string, [string, string[] | null][], string[]?]
|
|
167
|
+
for (const [id, fields] of reply[1] ?? []) {
|
|
168
|
+
if (!fields) continue
|
|
169
|
+
const pending = (await redis.send('XPENDING', [key, GROUP, id, id, 1])) as [string, string, number, number][]
|
|
170
|
+
const deliveries = Number(pending[0]?.[3] ?? 2)
|
|
171
|
+
const envelope = envelopeFrom(fields)
|
|
172
|
+
out.push({ stream, id, envelope, deliveries })
|
|
173
|
+
this.log.warn('queue.job.reclaimed', { jobId: envelope.id, job: envelope.name, deliveries })
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return out
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Wait for the queue's `rateLimit` (shared by all workers through core's RateLimiter); the lease keeps renewing. */
|
|
180
|
+
private async throttle(queue: string): Promise<void> {
|
|
181
|
+
const rate = this.options.queues.find((q) => q.name === queue)?.rateLimit
|
|
182
|
+
if (!rate) return
|
|
183
|
+
const limiter = this.app.resolve(RateLimiter)
|
|
184
|
+
for (;;) {
|
|
185
|
+
const r = await limiter.hit(`queue:${queue}`, rate)
|
|
186
|
+
if (r.allowed || !this.running) return
|
|
187
|
+
await Bun.sleep(Math.min(1000, Math.max(50, r.retryAfter * 1000)))
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
private async process({ stream, id, envelope, deliveries }: Entry): Promise<void> {
|
|
192
|
+
const attempt = envelope.attempt + deliveries
|
|
193
|
+
const fields = { jobId: envelope.id, job: envelope.name, queue: envelope.queue, attempt }
|
|
194
|
+
const renew = setInterval(
|
|
195
|
+
() => {
|
|
196
|
+
this.queue.redis
|
|
197
|
+
.send('XCLAIM', [this.queue.redis.key(stream), GROUP, this.consumer, 0, id, 'JUSTID'])
|
|
198
|
+
.catch(() => {})
|
|
199
|
+
},
|
|
200
|
+
Math.max(100, Math.floor(this.leaseMs / 3)),
|
|
201
|
+
)
|
|
202
|
+
const started = Date.now()
|
|
203
|
+
try {
|
|
204
|
+
if (attempt > envelope.tries)
|
|
205
|
+
throw new Error(`gave up after ${envelope.tries} attempts (the worker running it stopped)`)
|
|
206
|
+
await this.throttle(envelope.queue)
|
|
207
|
+
await runJob(this.app, envelope, attempt)
|
|
208
|
+
await this.queue.complete(stream, id, envelope)
|
|
209
|
+
await this.queue
|
|
210
|
+
.finished(envelope, true)
|
|
211
|
+
.catch((e) => this.log.error('queue.chain_failed', { ...fields, error: e }))
|
|
212
|
+
this.log.info('queue.job.done', { ...fields, ms: Date.now() - started })
|
|
213
|
+
} catch (thrown) {
|
|
214
|
+
const error = thrown instanceof Error ? thrown : new Error(String(thrown))
|
|
215
|
+
if (attempt < envelope.tries) {
|
|
216
|
+
const cls = findJob(envelope.name)
|
|
217
|
+
const wait = cls ? backoffDelay(settingsOf(cls).backoff, attempt) : 0
|
|
218
|
+
await this.queue
|
|
219
|
+
.retry(stream, id, envelope, this.queue.now() + wait)
|
|
220
|
+
.catch((e) => this.log.error('queue.retry_failed', { ...fields, error: e }))
|
|
221
|
+
this.log.warn('queue.job.retrying', { ...fields, error, retryInMs: wait })
|
|
222
|
+
} else {
|
|
223
|
+
const hookError = await runFailedHook(this.app, envelope, error)
|
|
224
|
+
if (hookError) this.log.error('queue.job.failed_hook_threw', { ...fields, error: hookError })
|
|
225
|
+
await this.queue
|
|
226
|
+
.fail(stream, id, envelope, error)
|
|
227
|
+
.catch((e) => this.log.error('queue.fail_failed', { ...fields, error: e }))
|
|
228
|
+
this.log.error('queue.job.failed', { ...fields, error })
|
|
229
|
+
await this.queue
|
|
230
|
+
.finished(envelope, false)
|
|
231
|
+
.catch((e) => this.log.error('queue.batch_failed', { ...fields, error: e }))
|
|
232
|
+
}
|
|
233
|
+
} finally {
|
|
234
|
+
clearInterval(renew)
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
type Rows = [string, [string, string[] | null][]][]
|
|
240
|
+
|
|
241
|
+
/** XREADGROUP replies: RESP3 map `{ stream: entries }` (Bun.redis) or RESP2 `[[stream, entries]]` (spike c). */
|
|
242
|
+
export function parseRead(reply: unknown): Rows {
|
|
243
|
+
if (!reply) return []
|
|
244
|
+
if (Array.isArray(reply)) return reply as Rows
|
|
245
|
+
return Object.entries(reply as Record<string, [string, string[] | null][]>)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** The envelope in an entry's fields (`['job', json]`, or a RESP3 map). */
|
|
249
|
+
function envelopeFrom(fields: string[] | Record<string, string>): Envelope {
|
|
250
|
+
const json = Array.isArray(fields) ? fields[fields.indexOf('job') + 1] : fields.job
|
|
251
|
+
return decode<Envelope>(json) as Envelope
|
|
252
|
+
}
|