@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/src/queue.ts ADDED
@@ -0,0 +1,200 @@
1
+ import { type Application, CslugError, resolve, runInContext } from '@cslug/core'
2
+ import { PendingDispatch } from './dispatch'
3
+ import {
4
+ findJob,
5
+ type Job,
6
+ type JobClass,
7
+ type JobHooks,
8
+ jobName,
9
+ type PayloadArgs,
10
+ registerJob,
11
+ settingsOf,
12
+ } from './job'
13
+
14
+ /** A job as stored in the queue. */
15
+ export type Envelope = {
16
+ id: string
17
+ name: string
18
+ queue: string
19
+ payload: unknown
20
+ /** Attempts already made before this delivery. */
21
+ attempt: number
22
+ tries: number
23
+ priority?: number
24
+ unique?: string
25
+ dispatchedAt: number
26
+ /** Jobs to dispatch, in order, after this one succeeds (`Queue.chain`). */
27
+ chain?: JobSpec[]
28
+ /** The batch this job belongs to (`Queue.batch`). */
29
+ batch?: string
30
+ }
31
+
32
+ /** A job and its payload, not dispatched yet: `SendCheckinJob.with({ bookingId })`. */
33
+ export type JobSpec = { name: string; payload: unknown }
34
+
35
+ type BatchState = { pending: number; failed: number; next?: JobSpec; allowFailures: boolean }
36
+
37
+ /** Where and when to push. */
38
+ export type PushOptions = {
39
+ /** Epoch ms; absent or past = now. */
40
+ runAt?: number
41
+ /** How long a `unique` key holds (ms). */
42
+ uniqueFor?: number
43
+ }
44
+
45
+ /**
46
+ * The queue: `resolve(Queue).dispatch(SendCheckinJob, payload)`, or `SendCheckinJob.dispatch(payload)`.
47
+ * `RedisQueue` is the real one, `QueueFake` records jobs in tests.
48
+ */
49
+ export abstract class Queue {
50
+ dispatch<J extends JobClass<never>>(job: J, ...[payload]: PayloadArgs<J>): PendingDispatch {
51
+ return new PendingDispatch(job as JobClass, payload, this)
52
+ }
53
+
54
+ /** Store the job. Resolves to its id, or null when its `unique` key is already held. */
55
+ abstract push(envelope: Envelope, options?: PushOptions): Promise<string | null>
56
+
57
+ /** Run jobs one after the other; the chain stops at a job that fails for good. */
58
+ static chain(specs: readonly JobSpec[]) {
59
+ return {
60
+ dispatch: async (): Promise<string | null> => {
61
+ const [first, ...rest] = specs
62
+ return first ? resolve(Queue).pushSpec(first, { chain: rest }) : null
63
+ },
64
+ }
65
+ }
66
+
67
+ /** Run jobs in parallel; `then(job)` runs once all have finished (unless one failed, without `allowFailures()`). */
68
+ static batch(specs: readonly JobSpec[]) {
69
+ let next: JobSpec | undefined
70
+ let allowFailures = false
71
+ const builder = {
72
+ // biome-ignore lint/suspicious/noThenProperty: guide 11's API (`.then(Job.with(…))`); do not await the builder itself
73
+ then(spec: JobSpec) {
74
+ next = spec
75
+ return builder
76
+ },
77
+ allowFailures() {
78
+ allowFailures = true
79
+ return builder
80
+ },
81
+ /** Resolves to the batch id. */
82
+ async dispatch(): Promise<string> {
83
+ const queue = resolve(Queue)
84
+ const id = Bun.randomUUIDv7()
85
+ if (!specs.length) {
86
+ if (next) await queue.pushSpec(next)
87
+ return id
88
+ }
89
+ await queue.startBatch(id, { pending: specs.length, failed: 0, next, allowFailures })
90
+ for (const spec of specs) await queue.pushSpec(spec, { batch: id })
91
+ return id
92
+ },
93
+ }
94
+ return builder
95
+ }
96
+
97
+ /** Called when a job has finished (`ok`) or failed for good: continue its chain, count it in its batch. */
98
+ async finished(envelope: Envelope, ok: boolean): Promise<void> {
99
+ const [next, ...rest] = envelope.chain ?? []
100
+ if (ok && next) await this.pushSpec(next, { chain: rest })
101
+ if (!envelope.batch) return
102
+ const done = await this.batchProgress(envelope.batch, ok)
103
+ if (done?.next && (done.failed === 0 || done.allowFailures)) await this.pushSpec(done.next)
104
+ }
105
+
106
+ /** Batch bookkeeping; in memory here (the fake), in Redis for `RedisQueue`. */
107
+ private readonly batches = new Map<string, BatchState>()
108
+ protected async startBatch(id: string, state: BatchState): Promise<void> {
109
+ this.batches.set(id, state)
110
+ }
111
+ /** Count one finished job; returns the batch state when it was the last one. */
112
+ protected async batchProgress(id: string, ok: boolean): Promise<BatchState | undefined> {
113
+ const state = this.batches.get(id)
114
+ if (!state) return undefined
115
+ state.pending--
116
+ if (!ok) state.failed++
117
+ if (state.pending > 0) return undefined
118
+ this.batches.delete(id)
119
+ return state
120
+ }
121
+
122
+ protected pushSpec(spec: JobSpec, extra: Partial<Envelope> = {}): Promise<string | null> {
123
+ const job = findJob(spec.name)
124
+ if (!job) throw new JobNotFoundError(spec.name)
125
+ return this.push({ ...envelopeOf(job, spec.payload), ...extra })
126
+ }
127
+ }
128
+
129
+ /** The envelope of a new job. */
130
+ export function envelopeOf(job: JobClass, payload: unknown, queue?: string): Envelope {
131
+ registerJob(job)
132
+ return {
133
+ id: Bun.randomUUIDv7(),
134
+ name: jobName(job),
135
+ queue: queue ?? settingsOf(job).queue,
136
+ payload,
137
+ attempt: 0,
138
+ tries: settingsOf(job).tries,
139
+ dispatchedAt: Date.now(),
140
+ }
141
+ }
142
+
143
+ export class JobNotFoundError extends CslugError {
144
+ constructor(name: string) {
145
+ super(
146
+ 'queue.job_not_found',
147
+ `No job class named ${name}. Workers load app/jobs/ and app/listeners/; is the file there, and does it export the class?`,
148
+ )
149
+ }
150
+ }
151
+
152
+ export class JobTimeoutError extends CslugError {
153
+ constructor(name: string, ms: number) {
154
+ super('queue.job_timeout', `${name} ran longer than its timeout (${ms} ms)`)
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Run one delivery in its own scope and context ({ jobId, attempt }): validate the payload, build the job (a fresh
160
+ * instance; `@inject` only when its constructor takes dependencies), call
161
+ * `handle`, under the job's timeout. Throws what the job threw.
162
+ */
163
+ export async function runJob(app: Application, envelope: Envelope, attempt: number): Promise<void> {
164
+ const cls = findJob(envelope.name)
165
+ if (!cls) throw new JobNotFoundError(envelope.name)
166
+ const timeout = settingsOf(cls).timeoutMs
167
+ const scope = app.createScope()
168
+ const context = { app, scope, jobId: envelope.id, attempt, requestId: `job:${envelope.id}` }
169
+ let timer: Timer | undefined
170
+ try {
171
+ const run = runInContext(context, async () => {
172
+ const payload = cls.payloadSchema ? cls.payloadSchema.parse(envelope.payload) : envelope.payload
173
+ await (scope.build(cls as never) as Job<unknown>).handle(payload)
174
+ })
175
+ const expire = new Promise<never>((_, reject) => {
176
+ timer = setTimeout(() => reject(new JobTimeoutError(envelope.name, timeout)), timeout)
177
+ })
178
+ await Promise.race([run, expire])
179
+ } finally {
180
+ clearTimeout(timer)
181
+ await scope.dispose()
182
+ }
183
+ }
184
+
185
+ /** Call the job's `failed(payload, error)` hook after its last attempt; its own errors are returned, not thrown. */
186
+ export async function runFailedHook(app: Application, envelope: Envelope, error: Error): Promise<unknown> {
187
+ const cls = findJob(envelope.name)
188
+ if (!cls || typeof (cls.prototype as JobHooks).failed !== 'function') return undefined
189
+ const scope = app.createScope()
190
+ try {
191
+ await runInContext({ app, scope, jobId: envelope.id, requestId: `job:${envelope.id}` }, async () => {
192
+ await (scope.build(cls as never) as JobHooks).failed?.(envelope.payload, error)
193
+ })
194
+ return undefined
195
+ } catch (hookError) {
196
+ return hookError
197
+ } finally {
198
+ await scope.dispose()
199
+ }
200
+ }
@@ -0,0 +1,234 @@
1
+ import { decode, encode, type Redis } from '@cslug/redis'
2
+ import { type Envelope, type JobSpec, type PushOptions, Queue } from './queue'
3
+
4
+ export const GROUP = 'workers'
5
+ /** Priority bands, read in this order. */
6
+ export const BANDS = ['high', 'normal', 'low'] as const
7
+ export type Band = (typeof BANDS)[number]
8
+
9
+ export const bandOf = (priority = 5): Band => (priority <= 3 ? 'high' : priority >= 8 ? 'low' : 'normal')
10
+
11
+ /** A job that failed its last attempt (`cslug queue:failed`). */
12
+ export type FailedJob = { envelope: Envelope; error: string; stack?: string; failedAt: number }
13
+
14
+ // Delayed members are "<band letter><envelope json>", so promotion knows which stream to use.
15
+ const PROMOTE = `
16
+ local due = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', ARGV[1], 'LIMIT', 0, tonumber(ARGV[2]))
17
+ for _, m in ipairs(due) do
18
+ local band = string.sub(m, 1, 1)
19
+ local stream = KEYS[3]
20
+ if band == 'h' then stream = KEYS[2] elseif band == 'l' then stream = KEYS[4] end
21
+ redis.call('XADD', stream, '*', 'job', string.sub(m, 2))
22
+ redis.call('ZREM', KEYS[1], m)
23
+ end
24
+ return #due`
25
+
26
+ // KEYS: stream, unique · ARGV: entry id, job id
27
+ const COMPLETE = `
28
+ redis.call('XACK', KEYS[1], '${GROUP}', ARGV[1])
29
+ redis.call('XDEL', KEYS[1], ARGV[1])
30
+ if redis.call('GET', KEYS[2]) == ARGV[2] then redis.call('DEL', KEYS[2]) end
31
+ return 1`
32
+
33
+ // KEYS: stream, delayed · ARGV: entry id, run at, member
34
+ const RETRY = `
35
+ redis.call('XACK', KEYS[1], '${GROUP}', ARGV[1])
36
+ redis.call('XDEL', KEYS[1], ARGV[1])
37
+ redis.call('ZADD', KEYS[2], ARGV[2], ARGV[3])
38
+ return 1`
39
+
40
+ // KEYS: stream, unique, failed, failed index · ARGV: entry id, job id, record, now, keep (ms)
41
+ const FAIL = `
42
+ redis.call('XACK', KEYS[1], '${GROUP}', ARGV[1])
43
+ redis.call('XDEL', KEYS[1], ARGV[1])
44
+ if redis.call('GET', KEYS[2]) == ARGV[2] then redis.call('DEL', KEYS[2]) end
45
+ redis.call('HSET', KEYS[3], ARGV[2], ARGV[3])
46
+ redis.call('ZADD', KEYS[4], ARGV[4], ARGV[2])
47
+ local old = redis.call('ZRANGEBYSCORE', KEYS[4], '-inf', tonumber(ARGV[4]) - tonumber(ARGV[5]), 'LIMIT', 0, 100)
48
+ for _, id in ipairs(old) do redis.call('HDEL', KEYS[3], id) redis.call('ZREM', KEYS[4], id) end
49
+ return 1`
50
+
51
+ // KEYS: batch · ARGV: ok (1/0). Returns [failed, next, allow] when the last job finished, else nil.
52
+ const BATCH_PROGRESS = `
53
+ if redis.call('EXISTS', KEYS[1]) == 0 then return nil end
54
+ if ARGV[1] == '0' then redis.call('HINCRBY', KEYS[1], 'failed', 1) end
55
+ if redis.call('HINCRBY', KEYS[1], 'pending', -1) > 0 then return nil end
56
+ local r = redis.call('HMGET', KEYS[1], 'failed', 'next', 'allow')
57
+ redis.call('DEL', KEYS[1])
58
+ return r`
59
+
60
+ /**
61
+ * The queue on Redis Streams (D8): one stream per queue and priority band, read by the consumer group `workers`;
62
+ * a sorted set per queue for delayed jobs and retries; `SET NX` keys for unique jobs; a hash of failed jobs.
63
+ * Keys live under the connection prefix + `queue:`.
64
+ */
65
+ export class RedisQueue extends Queue {
66
+ constructor(
67
+ readonly redis: Redis,
68
+ /** Epoch ms; the app's `Clock`, so delays follow a `FakeClock` in tests. */
69
+ readonly now: () => number = Date.now,
70
+ private readonly keepFailed = 30 * 86_400_000,
71
+ ) {
72
+ super()
73
+ }
74
+
75
+ stream(queue: string, band: Band = 'normal'): string {
76
+ return band === 'normal' ? `q:${queue}` : `q:${queue}:${band}`
77
+ }
78
+ delayedKey = (queue: string) => `delayed:${queue}`
79
+ uniqueKey = (key = '') => `unique:${key}`
80
+
81
+ async push(envelope: Envelope, options: PushOptions = {}): Promise<string | null> {
82
+ if (envelope.unique !== undefined) {
83
+ const held = await this.redis.send('SET', [
84
+ this.redis.key(this.uniqueKey(envelope.unique)),
85
+ envelope.id,
86
+ 'NX',
87
+ 'PX',
88
+ options.uniqueFor ?? 86_400_000,
89
+ ])
90
+ if (held !== 'OK') return null
91
+ }
92
+ await this.redis.send('SADD', [this.redis.key('queues'), envelope.queue])
93
+ const band = bandOf(envelope.priority)
94
+ if (options.runAt !== undefined && options.runAt > this.now()) {
95
+ await this.redis.send('ZADD', [
96
+ this.redis.key(this.delayedKey(envelope.queue)),
97
+ options.runAt,
98
+ member(band, envelope),
99
+ ])
100
+ } else {
101
+ await this.redis.send('XADD', [this.redis.key(this.stream(envelope.queue, band)), '*', 'job', encode(envelope)])
102
+ }
103
+ return envelope.id
104
+ }
105
+
106
+ /** Move due delayed jobs (and retries) of `queue` to its streams. */
107
+ async promote(queue: string, limit = 100): Promise<number> {
108
+ const keys = [this.delayedKey(queue), ...BANDS.map((b) => this.stream(queue, b))]
109
+ return Number(await this.redis.eval(PROMOTE, keys, [this.now(), limit]))
110
+ }
111
+
112
+ /** The consumer group on every band of `queue` (idempotent). */
113
+ async ensureGroups(queue: string, redis: Redis = this.redis): Promise<void> {
114
+ for (const band of BANDS) {
115
+ try {
116
+ await redis.send('XGROUP', ['CREATE', redis.key(this.stream(queue, band)), GROUP, '0', 'MKSTREAM'])
117
+ } catch (error) {
118
+ if (!String(error).includes('BUSYGROUP')) throw error
119
+ }
120
+ }
121
+ }
122
+
123
+ complete(stream: string, entryId: string, envelope: Envelope): Promise<unknown> {
124
+ return this.redis.eval(COMPLETE, [stream, this.uniqueKey(envelope.unique)], [entryId, envelope.id])
125
+ }
126
+
127
+ /** Acknowledge this delivery and queue the next attempt at `runAt`. */
128
+ retry(stream: string, entryId: string, envelope: Envelope, runAt: number): Promise<unknown> {
129
+ const next = { ...envelope, attempt: envelope.attempt + 1 }
130
+ return this.redis.eval(
131
+ RETRY,
132
+ [stream, this.delayedKey(envelope.queue)],
133
+ [entryId, runAt, member(bandOf(envelope.priority), next)],
134
+ )
135
+ }
136
+
137
+ /** Acknowledge this delivery and keep the job in the failed store (pruned after `failed.keep`). */
138
+ fail(stream: string, entryId: string, envelope: Envelope, error: Error): Promise<unknown> {
139
+ const record: FailedJob = { envelope, error: error.message, stack: error.stack, failedAt: this.now() }
140
+ return this.redis.eval(
141
+ FAIL,
142
+ [stream, this.uniqueKey(envelope.unique), 'failed', 'failed:index'],
143
+ [entryId, envelope.id, encode(record), this.now(), this.keepFailed],
144
+ )
145
+ }
146
+
147
+ protected override async startBatch(id: string, state: { pending: number; next?: JobSpec; allowFailures: boolean }) {
148
+ const key = this.redis.key(`batch:${id}`)
149
+ const next = state.next ? encode(state.next) : ''
150
+ await this.redis.send('HSET', [
151
+ key,
152
+ 'pending',
153
+ state.pending,
154
+ 'failed',
155
+ 0,
156
+ 'next',
157
+ next,
158
+ 'allow',
159
+ state.allowFailures ? 1 : 0,
160
+ ])
161
+ await this.redis.send('EXPIRE', [key, 7 * 86_400])
162
+ }
163
+
164
+ protected override async batchProgress(id: string, ok: boolean) {
165
+ const r = (await this.redis.eval(BATCH_PROGRESS, [`batch:${id}`], [ok ? 1 : 0])) as [string, string, string] | null
166
+ if (!r) return undefined
167
+ return {
168
+ pending: 0,
169
+ failed: Number(r[0]),
170
+ next: r[1] ? decode<JobSpec>(r[1]) : undefined,
171
+ allowFailures: r[2] === '1',
172
+ }
173
+ }
174
+
175
+ // ── failed store, stats ────────────────────────────────────────────────────────────────────────────
176
+
177
+ async failed(): Promise<FailedJob[]> {
178
+ const ids = (await this.redis.send('ZRANGE', [this.redis.key('failed:index'), 0, -1])) as string[]
179
+ if (!ids.length) return []
180
+ const values = (await this.redis.send('HMGET', [this.redis.key('failed'), ...ids])) as (string | null)[]
181
+ return values.flatMap((v) => (v ? [decode<FailedJob>(v) as FailedJob] : []))
182
+ }
183
+
184
+ async forget(id: string): Promise<boolean> {
185
+ const removed = Number(await this.redis.send('HDEL', [this.redis.key('failed'), id]))
186
+ await this.redis.send('ZREM', [this.redis.key('failed:index'), id])
187
+ return removed > 0
188
+ }
189
+
190
+ /** Queue a failed job again, from its first attempt. */
191
+ async retryFailed(id: string): Promise<boolean> {
192
+ const raw = (await this.redis.send('HGET', [this.redis.key('failed'), id])) as string | null
193
+ if (!raw) return false
194
+ const { envelope } = decode<FailedJob>(raw) as FailedJob
195
+ await this.push({ ...envelope, attempt: 0, unique: undefined })
196
+ await this.forget(id)
197
+ return true
198
+ }
199
+
200
+ /** Queues that ever had a job pushed. */
201
+ async queues(): Promise<string[]> {
202
+ return ((await this.redis.send('SMEMBERS', [this.redis.key('queues')])) as string[]).sort()
203
+ }
204
+
205
+ async stats(queue: string) {
206
+ let waiting = 0
207
+ let active = 0
208
+ let oldest: number | undefined
209
+ for (const band of BANDS) {
210
+ const key = this.redis.key(this.stream(queue, band))
211
+ const length = Number(await this.redis.send('XLEN', [key]))
212
+ const pending = await this.redis.send('XPENDING', [key, GROUP]).catch(() => null)
213
+ const busy = Array.isArray(pending) ? Number(pending[0]) : 0
214
+ waiting += length - busy
215
+ active += busy
216
+ const first = (await this.redis.send('XRANGE', [key, '-', '+', 'COUNT', 1])) as [string, unknown][] | null
217
+ const at = first?.[0] ? Number(first[0][0].split('-')[0]) : undefined
218
+ if (at !== undefined && (oldest === undefined || at < oldest)) oldest = at
219
+ }
220
+ const delayed = Number(await this.redis.send('ZCARD', [this.redis.key(this.delayedKey(queue))]))
221
+ const failed = (await this.failed()).filter((f) => f.envelope.queue === queue).length
222
+ return { queue, waiting, active, delayed, failed, oldestAgeMs: oldest === undefined ? 0 : this.now() - oldest }
223
+ }
224
+
225
+ /** Delete the waiting and delayed jobs of `queue` (running jobs finish; the failed store is kept). */
226
+ async clear(queue: string): Promise<void> {
227
+ await this.redis.send('DEL', [
228
+ ...BANDS.map((b) => this.redis.key(this.stream(queue, b))),
229
+ this.redis.key(this.delayedKey(queue)),
230
+ ])
231
+ }
232
+ }
233
+
234
+ const member = (band: Band, envelope: Envelope) => `${band[0]}${encode(envelope)}`
@@ -0,0 +1,146 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { arg, Command, CslugError, flag, Logger, ServiceProvider } from '@cslug/core'
4
+ import { QueueProvider } from './provider'
5
+ import { RedisQueue } from './redis-queue'
6
+ import { buildSchedule, type ScheduleDefinition } from './schedule'
7
+ import { Scheduler } from './scheduler'
8
+
9
+ /**
10
+ * Binds the `Scheduler`, loads `routes/schedule.ts` at boot, contributes the `schedule:*` commands and stops the
11
+ * scheduler loop at shutdown. Config: `schedule.timezone` (default UTC).
12
+ */
13
+ export class ScheduleProvider extends ServiceProvider {
14
+ static dependsOn = [QueueProvider]
15
+
16
+ register() {
17
+ this.commands(scheduleCommands)
18
+ this.app.singleton(
19
+ Scheduler,
20
+ (c) =>
21
+ new Scheduler(
22
+ this.app,
23
+ c.resolve(RedisQueue).redis,
24
+ this.app.config<string | undefined>('schedule.timezone') ?? 'UTC',
25
+ c.resolve(Logger),
26
+ ),
27
+ )
28
+ }
29
+
30
+ async boot() {
31
+ const path = join(this.app.rootDir, 'routes/schedule.ts')
32
+ if (!existsSync(path)) return
33
+ const mod = (await import(path)) as { default?: ScheduleDefinition }
34
+ if (!mod.default?.__schedule)
35
+ throw new CslugError(
36
+ 'schedule.no_definition',
37
+ 'routes/schedule.ts must `export default defineSchedule((s) => { … })`',
38
+ )
39
+ this.app.resolve(Scheduler).entries = buildSchedule(mod.default)
40
+ }
41
+
42
+ async shutdown() {
43
+ await this.app.resolve(Scheduler).stop()
44
+ }
45
+ }
46
+
47
+ abstract class ScheduleCommand extends Command {
48
+ protected get scheduler(): Scheduler {
49
+ return this.app.resolve(Scheduler)
50
+ }
51
+ }
52
+
53
+ /** `cslug schedule:work`: tick every minute until SIGTERM. */
54
+ export class ScheduleWorkCommand extends ScheduleCommand {
55
+ static signature = 'schedule:work'
56
+ static description = 'Run the scheduler (every minute)'
57
+ static longRunning = true
58
+
59
+ handle() {
60
+ this.scheduler.start()
61
+ this.log.info('schedule.started', { entries: this.scheduler.entries.length })
62
+ if (process.stdout.isTTY) this.info(`Scheduler running: ${this.scheduler.entries.length} entries`)
63
+ }
64
+ }
65
+
66
+ /** `cslug schedule:run`: one tick, for an external cron. */
67
+ export class ScheduleRunCommand extends ScheduleCommand {
68
+ static signature = 'schedule:run'
69
+ static description = 'Run the entries due this minute, once'
70
+
71
+ async handle() {
72
+ const runs = await this.scheduler.runDue()
73
+ for (const r of runs) this.line(`${r.name}: ${r.status}${r.error ? ` (${r.error})` : ''}`)
74
+ return runs.some((r) => r.status === 'failed') ? 1 : 0
75
+ }
76
+ }
77
+
78
+ /** `cslug schedule:list`: entries, when they run, their time zone and next run. */
79
+ export class ScheduleListCommand extends ScheduleCommand {
80
+ static signature = 'schedule:list'
81
+ static description = 'List the scheduled entries'
82
+ static args = { json: flag.boolean() }
83
+
84
+ handle({ json }: Command.Args<typeof ScheduleListCommand>) {
85
+ const now = this.clock.now()
86
+ const rows = this.scheduler.entries.map((e) => {
87
+ const next = this.scheduler.next(e, now)
88
+ return {
89
+ name: e.name,
90
+ when: e.description,
91
+ tz: this.scheduler.tzOf(e),
92
+ next: next ? `in ${ago(next.getTime() - now.getTime())}` : '-',
93
+ nextAt: next,
94
+ }
95
+ })
96
+ if (json) this.line(JSON.stringify(rows))
97
+ else this.table(rows.map(({ nextAt: _, ...r }) => r))
98
+ }
99
+ }
100
+
101
+ /** `cslug schedule:history <name> [--last=10]`. */
102
+ export class ScheduleHistoryCommand extends ScheduleCommand {
103
+ static signature = 'schedule:history'
104
+ static description = 'Recent runs of an entry'
105
+ static args = { name: arg.string(), last: flag.number().default(10), json: flag.boolean() }
106
+
107
+ async handle({ name, last, json }: Command.Args<typeof ScheduleHistoryCommand>) {
108
+ const runs = await this.scheduler.history(name, last)
109
+ if (json) this.line(JSON.stringify(runs))
110
+ else this.table(runs)
111
+ }
112
+ }
113
+
114
+ /** `cslug schedule:test <name>`: run an entry now, once, ignoring its schedule. */
115
+ export class ScheduleTestCommand extends ScheduleCommand {
116
+ static signature = 'schedule:test'
117
+ static description = 'Run one entry now, ignoring the schedule'
118
+ static args = { name: arg.string() }
119
+
120
+ async handle({ name }: Command.Args<typeof ScheduleTestCommand>) {
121
+ const entry = this.scheduler.find(name)
122
+ if (!entry) {
123
+ this.error(`No schedule entry "${name}" (cslug schedule:list)`)
124
+ return 1
125
+ }
126
+ const run = await this.scheduler.run(entry, this.clock.now(), false)
127
+ this.line(`${name}: ${run?.status}${run?.error ? ` (${run.error})` : ''}`)
128
+ return run?.status === 'failed' ? 1 : 0
129
+ }
130
+ }
131
+
132
+ /** `13h 2m`, `4d 18h`, `45s`. */
133
+ function ago(ms: number): string {
134
+ const m = Math.round(ms / 60_000)
135
+ if (m < 1) return `${Math.round(ms / 1000)}s`
136
+ const [d, h, min] = [Math.floor(m / 1440), Math.floor((m % 1440) / 60), m % 60]
137
+ return d ? `${d}d${h ? ` ${h}h` : ''}` : h ? `${h}h${min ? ` ${min}m` : ''}` : `${min}m`
138
+ }
139
+
140
+ export const scheduleCommands = [
141
+ ScheduleWorkCommand,
142
+ ScheduleRunCommand,
143
+ ScheduleListCommand,
144
+ ScheduleHistoryCommand,
145
+ ScheduleTestCommand,
146
+ ]