@prunellejs/jobs 0.0.0-stage → 0.6.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/runner.ts ADDED
@@ -0,0 +1,424 @@
1
+ // Server-scoped job worker runner, cron tick executor, deterministic drain(), and graceful shutdown for @prunellejs/jobs.
2
+
3
+ import type { JobsEnqueueOptions, JobsQueueOptions, JobsService } from 'prunelle/config'
4
+ import type { StandardSchemaV1 } from 'prunelle/server'
5
+ import type { ParsedCron } from './cron'
6
+ import type { ClaimedJob, JobsStore } from './store'
7
+ import type {
8
+ BackoffStrategy,
9
+ DrainOptions,
10
+ EnqueueOptions,
11
+ EnqueueResult,
12
+ JobContext,
13
+ JobErrorInfo,
14
+ JobHandler,
15
+ JobListFilter,
16
+ JobRecord,
17
+ JobStats,
18
+ ScheduleContext,
19
+ ScheduleHandler,
20
+ } from './types'
21
+ import { formatSchemaIssues, validateSchema } from 'prunelle/server'
22
+ import { floorToMinute, matchesCron } from './cron'
23
+ import { computeBackoffDelay, JobValidationError, normalizeAttempts, normalizeBackoff, parseDuration } from './types'
24
+
25
+ export interface RegisteredQueue {
26
+ readonly name: string
27
+ readonly handler: JobHandler<unknown>
28
+ readonly attempts: number
29
+ readonly backoff: BackoffStrategy
30
+ readonly schema?: StandardSchemaV1 | undefined
31
+ }
32
+
33
+ export interface RegisteredSchedule {
34
+ readonly name: string
35
+ readonly cron: string
36
+ readonly parsed: ParsedCron
37
+ readonly handler: ScheduleHandler
38
+ readonly timeZone: string
39
+ }
40
+
41
+ export interface JobsRuntimeConfig {
42
+ readonly store: JobsStore
43
+ readonly handleQueues: ReadonlyMap<string, RegisteredQueue>
44
+ readonly handleSchedules: ReadonlyMap<string, RegisteredSchedule>
45
+ readonly pollIntervalMs: number
46
+ readonly scheduleIntervalMs: number
47
+ readonly concurrency: number
48
+ readonly leaseMs: number
49
+ readonly shutdownTimeoutMs: number
50
+ readonly defaultAttempts: number
51
+ readonly defaultBackoff: BackoffStrategy
52
+ readonly backoffBaseMs: number
53
+ readonly maxBackoffMs: number
54
+ readonly now: () => number
55
+ readonly onError?: ((info: JobErrorInfo) => void) | undefined
56
+ }
57
+
58
+ export interface JobsRuntime {
59
+ readonly workerId: string
60
+ readonly store: JobsStore
61
+ readonly service: JobsService
62
+ start(): void
63
+ enqueue<T = unknown>(name: string, data: T, options?: EnqueueOptions): Promise<EnqueueResult>
64
+ drain(options?: DrainOptions): Promise<number>
65
+ runDueSchedules(overrideNow?: number): Promise<number>
66
+ get<T = unknown>(id: string): JobRecord<T> | undefined
67
+ list<T = unknown>(filter?: JobListFilter): JobRecord<T>[]
68
+ stats(): JobStats
69
+ healthCheck(): { ok: boolean, message: string }
70
+ shutdown(): Promise<void>
71
+ }
72
+
73
+ interface RuntimeState {
74
+ readonly cfg: JobsRuntimeConfig
75
+ readonly workerId: string
76
+ readonly localQueues: Map<string, RegisteredQueue>
77
+ readonly inFlight: Set<Promise<void>>
78
+ readonly abortController: AbortController
79
+ activeJobs: number
80
+ started: boolean
81
+ stopping: boolean
82
+ releasedOnShutdown: boolean
83
+ shutdownPromise: Promise<void> | undefined
84
+ pollTimer: ReturnType<typeof setInterval> | undefined
85
+ scheduleTimer: ReturnType<typeof setInterval> | undefined
86
+ }
87
+
88
+ function errorToMessage(err: unknown): string {
89
+ return err instanceof Error ? err.message : String(err)
90
+ }
91
+
92
+ function unrefTimer(timer: ReturnType<typeof setInterval> | ReturnType<typeof setTimeout>): void {
93
+ if (typeof timer === 'object' && timer !== null && 'unref' in timer && typeof timer.unref === 'function')
94
+ timer.unref()
95
+ }
96
+
97
+ function getQueue(state: RuntimeState, name: string): RegisteredQueue | undefined {
98
+ return state.localQueues.get(name) ?? state.cfg.handleQueues.get(name)
99
+ }
100
+
101
+ function registeredQueueNames(state: RuntimeState): string[] {
102
+ if (state.localQueues.size === 0)
103
+ return [...state.cfg.handleQueues.keys()]
104
+ const names = new Set<string>(state.cfg.handleQueues.keys())
105
+ for (const name of state.localQueues.keys())
106
+ names.add(name)
107
+ return [...names]
108
+ }
109
+
110
+ function reportError(state: RuntimeState, info: JobErrorInfo): void {
111
+ try {
112
+ state.cfg.onError?.(info)
113
+ }
114
+ catch (hookErr) {
115
+ console.error('@prunellejs/jobs: onError hook threw:', hookErr)
116
+ }
117
+ }
118
+
119
+ async function validatePayload(queueName: string, schema: StandardSchemaV1, data: unknown): Promise<unknown> {
120
+ const result = await validateSchema(schema, data)
121
+ if (!result.ok)
122
+ throw new JobValidationError(queueName, formatSchemaIssues(result.issues), result.issues, result.fieldErrors)
123
+ return result.value
124
+ }
125
+
126
+ async function executeClaimedJob(state: RuntimeState, job: ClaimedJob, nowFn: () => number): Promise<void> {
127
+ const { cfg, workerId } = state
128
+ const def = getQueue(state, job.queue)
129
+ if (def === undefined) {
130
+ if (!state.releasedOnShutdown && !cfg.store.isClosed())
131
+ cfg.store.failJob(job.id, workerId, `No handler registered for queue "${job.queue}"`, nowFn())
132
+ return
133
+ }
134
+
135
+ let input: unknown
136
+ try {
137
+ const parsed: unknown = JSON.parse(job.payload)
138
+ input = def.schema !== undefined ? await validatePayload(job.queue, def.schema, parsed) : parsed
139
+ }
140
+ catch (err) {
141
+ reportError(state, { kind: 'job', name: job.queue, id: job.id, attempt: job.attempts, maxAttempts: job.maxAttempts, error: err })
142
+ if (!state.releasedOnShutdown && !cfg.store.isClosed())
143
+ cfg.store.failJob(job.id, workerId, errorToMessage(err), nowFn())
144
+ return
145
+ }
146
+
147
+ const ctx: JobContext = {
148
+ id: job.id,
149
+ queue: job.queue,
150
+ attempt: job.attempts,
151
+ maxAttempts: job.maxAttempts,
152
+ ...(job.key !== undefined ? { key: job.key } : {}),
153
+ signal: state.abortController.signal,
154
+ }
155
+
156
+ try {
157
+ await def.handler(input, ctx)
158
+ if (!state.releasedOnShutdown && !cfg.store.isClosed())
159
+ cfg.store.completeJob(job.id, workerId, nowFn())
160
+ }
161
+ catch (err) {
162
+ const msg = errorToMessage(err)
163
+ reportError(state, { kind: 'job', name: job.queue, id: job.id, attempt: job.attempts, maxAttempts: job.maxAttempts, error: err })
164
+ if (state.releasedOnShutdown || cfg.store.isClosed())
165
+ return
166
+ if (job.attempts < job.maxAttempts) {
167
+ const delayMs = computeBackoffDelay(def.backoff, job.attempts, cfg.backoffBaseMs, cfg.maxBackoffMs)
168
+ const now = nowFn()
169
+ cfg.store.rescheduleJob(job.id, workerId, now + delayMs, msg, now)
170
+ }
171
+ else {
172
+ cfg.store.failJob(job.id, workerId, msg, nowFn())
173
+ }
174
+ }
175
+ }
176
+
177
+ function pollAvailableJobs(state: RuntimeState): void {
178
+ const { cfg, workerId } = state
179
+ if (state.stopping || cfg.store.isClosed())
180
+ return
181
+ const queues = registeredQueueNames(state)
182
+ if (queues.length === 0)
183
+ return
184
+
185
+ while (!state.stopping && !cfg.store.isClosed() && state.activeJobs < cfg.concurrency) {
186
+ const claimed = cfg.store.claimNext({
187
+ queues,
188
+ workerId,
189
+ now: cfg.now(),
190
+ leaseMs: cfg.leaseMs,
191
+ includeDelayed: false,
192
+ resolveMaxAttempts: (queue, currentMax) => getQueue(state, queue)?.attempts ?? currentMax,
193
+ })
194
+ if (claimed === undefined)
195
+ break
196
+ state.activeJobs++
197
+ const task = executeClaimedJob(state, claimed, cfg.now).finally(() => {
198
+ state.activeJobs--
199
+ state.inFlight.delete(task)
200
+ if (state.started && !state.stopping && !cfg.store.isClosed())
201
+ queueMicrotask(() => pollAvailableJobs(state))
202
+ })
203
+ state.inFlight.add(task)
204
+ }
205
+ }
206
+
207
+ async function runSingleSchedule(state: RuntimeState, schedule: RegisteredSchedule, tickMs: number): Promise<void> {
208
+ const ctx: ScheduleContext = {
209
+ name: schedule.name,
210
+ scheduledAt: new Date(tickMs),
211
+ tickMs,
212
+ timeZone: schedule.timeZone,
213
+ signal: state.abortController.signal,
214
+ }
215
+ try {
216
+ await schedule.handler(ctx)
217
+ if (!state.releasedOnShutdown && !state.cfg.store.isClosed())
218
+ state.cfg.store.finishScheduleTick(schedule.name, tickMs, 'completed', undefined, state.cfg.now())
219
+ }
220
+ catch (err) {
221
+ reportError(state, { kind: 'schedule', name: schedule.name, error: err })
222
+ if (!state.releasedOnShutdown && !state.cfg.store.isClosed())
223
+ state.cfg.store.finishScheduleTick(schedule.name, tickMs, 'failed', errorToMessage(err), state.cfg.now())
224
+ }
225
+ }
226
+
227
+ async function executeDueSchedules(state: RuntimeState, overrideNow?: number): Promise<number> {
228
+ const { cfg, workerId } = state
229
+ if (state.stopping || cfg.store.isClosed() || cfg.handleSchedules.size === 0)
230
+ return 0
231
+ const now = overrideNow ?? cfg.now()
232
+ const tickMs = floorToMinute(now)
233
+ const triggered: Promise<void>[] = []
234
+
235
+ for (const schedule of cfg.handleSchedules.values()) {
236
+ if (state.stopping || cfg.store.isClosed())
237
+ break
238
+ if (!matchesCron(schedule.parsed, tickMs, schedule.timeZone))
239
+ continue
240
+ if (!cfg.store.claimScheduleTick(schedule.name, tickMs, workerId, now))
241
+ continue
242
+ const task = runSingleSchedule(state, schedule, tickMs).finally(() => {
243
+ state.inFlight.delete(task)
244
+ })
245
+ state.inFlight.add(task)
246
+ triggered.push(task)
247
+ }
248
+
249
+ if (triggered.length > 0)
250
+ await Promise.allSettled(triggered)
251
+ return triggered.length
252
+ }
253
+
254
+ async function waitForInFlight(state: RuntimeState): Promise<boolean> {
255
+ if (state.inFlight.size === 0)
256
+ return true
257
+ if (state.cfg.shutdownTimeoutMs <= 0)
258
+ return false
259
+ let timedOut = false
260
+ let timer: ReturnType<typeof setTimeout> | undefined
261
+ const timeoutPromise = new Promise<void>((resolve) => {
262
+ timer = setTimeout(() => {
263
+ timedOut = true
264
+ resolve()
265
+ }, state.cfg.shutdownTimeoutMs)
266
+ unrefTimer(timer)
267
+ })
268
+ await Promise.race([Promise.allSettled([...state.inFlight]), timeoutPromise])
269
+ if (timer !== undefined)
270
+ clearTimeout(timer)
271
+ return !timedOut && state.inFlight.size === 0
272
+ }
273
+
274
+ export function createJobsRuntime(cfg: JobsRuntimeConfig): JobsRuntime {
275
+ const state: RuntimeState = {
276
+ cfg,
277
+ workerId: crypto.randomUUID(),
278
+ localQueues: new Map(),
279
+ inFlight: new Set(),
280
+ abortController: new AbortController(),
281
+ activeJobs: 0,
282
+ started: false,
283
+ stopping: false,
284
+ releasedOnShutdown: false,
285
+ shutdownPromise: undefined,
286
+ pollTimer: undefined,
287
+ scheduleTimer: undefined,
288
+ }
289
+
290
+ async function enqueue<T = unknown>(name: string, data: T, options?: EnqueueOptions): Promise<EnqueueResult> {
291
+ if (cfg.store.isClosed())
292
+ throw new Error(`@prunellejs/jobs: cannot enqueue("${name}") after the jobs store has been closed.`)
293
+ const delayMs = parseDuration(options?.delay)
294
+ const def = getQueue(state, name)
295
+ if (def?.schema !== undefined)
296
+ await validatePayload(name, def.schema, data)
297
+
298
+ const now = cfg.now()
299
+ const runAt = now + delayMs
300
+ const result = cfg.store.enqueue({
301
+ id: crypto.randomUUID(),
302
+ queue: name,
303
+ payload: JSON.stringify(data === undefined ? null : data),
304
+ key: options?.key,
305
+ maxAttempts: def?.attempts ?? cfg.defaultAttempts,
306
+ runAt,
307
+ now,
308
+ })
309
+
310
+ if (state.started && !state.stopping && !result.deduplicated && runAt <= now)
311
+ queueMicrotask(() => pollAvailableJobs(state))
312
+ return result
313
+ }
314
+
315
+ async function drain(options?: DrainOptions): Promise<number> {
316
+ if (cfg.store.isClosed())
317
+ return 0
318
+ const includeDelayed = options?.includeDelayed === true
319
+ const maxJobs = options?.maxJobs ?? Number.POSITIVE_INFINITY
320
+ const nowFn = options?.now !== undefined ? () => options.now! : cfg.now
321
+ let executed = 0
322
+
323
+ while (executed < maxJobs && !state.stopping && !cfg.store.isClosed()) {
324
+ const queues = registeredQueueNames(state)
325
+ if (queues.length === 0)
326
+ break
327
+ const claimed = cfg.store.claimNext({
328
+ queues,
329
+ workerId: state.workerId,
330
+ now: nowFn(),
331
+ leaseMs: cfg.leaseMs,
332
+ includeDelayed,
333
+ resolveMaxAttempts: (queue, currentMax) => getQueue(state, queue)?.attempts ?? currentMax,
334
+ })
335
+ if (claimed === undefined)
336
+ break
337
+ const task = executeClaimedJob(state, claimed, nowFn).finally(() => {
338
+ state.inFlight.delete(task)
339
+ })
340
+ state.inFlight.add(task)
341
+ await task
342
+ executed++
343
+ }
344
+ return executed
345
+ }
346
+
347
+ function start(): void {
348
+ if (state.started || state.stopping || cfg.store.isClosed())
349
+ return
350
+ state.started = true
351
+ state.pollTimer = setInterval(() => pollAvailableJobs(state), cfg.pollIntervalMs)
352
+ unrefTimer(state.pollTimer)
353
+ state.scheduleTimer = setInterval(() => {
354
+ void executeDueSchedules(state)
355
+ }, cfg.scheduleIntervalMs)
356
+ unrefTimer(state.scheduleTimer)
357
+ queueMicrotask(() => {
358
+ pollAvailableJobs(state)
359
+ void executeDueSchedules(state)
360
+ })
361
+ }
362
+
363
+ function shutdown(): Promise<void> {
364
+ if (state.shutdownPromise !== undefined)
365
+ return state.shutdownPromise
366
+ state.stopping = true
367
+ state.started = false
368
+ if (state.pollTimer !== undefined) {
369
+ clearInterval(state.pollTimer)
370
+ state.pollTimer = undefined
371
+ }
372
+ if (state.scheduleTimer !== undefined) {
373
+ clearInterval(state.scheduleTimer)
374
+ state.scheduleTimer = undefined
375
+ }
376
+
377
+ state.shutdownPromise = (async () => {
378
+ if (!(await waitForInFlight(state))) {
379
+ state.releasedOnShutdown = true
380
+ state.abortController.abort(new Error('@prunellejs/jobs: shutdown timeout exceeded'))
381
+ }
382
+ if (!cfg.store.isClosed()) {
383
+ cfg.store.releaseOwnerJobs(state.workerId, cfg.now())
384
+ cfg.store.close()
385
+ }
386
+ })()
387
+ return state.shutdownPromise
388
+ }
389
+
390
+ const service: JobsService = {
391
+ queue<T = unknown>(name: string, handler: (data: T) => void | Promise<void>, options?: JobsQueueOptions) {
392
+ state.localQueues.set(name, {
393
+ name,
394
+ handler: handler as JobHandler<unknown>,
395
+ attempts: normalizeAttempts(options?.attempts, cfg.defaultAttempts),
396
+ backoff: normalizeBackoff(options?.backoff, cfg.defaultBackoff),
397
+ })
398
+ },
399
+ async enqueue<T = unknown>(name: string, data: T, options?: JobsEnqueueOptions) {
400
+ await enqueue(name, data, options)
401
+ },
402
+ drain: options => drain(options),
403
+ }
404
+
405
+ return {
406
+ workerId: state.workerId,
407
+ store: cfg.store,
408
+ service,
409
+ start,
410
+ enqueue,
411
+ drain,
412
+ runDueSchedules: overrideNow => executeDueSchedules(state, overrideNow),
413
+ get: <T = unknown>(id: string) => cfg.store.getJob<T>(id),
414
+ list: <T = unknown>(filter?: JobListFilter) => cfg.store.listJobs<T>(filter),
415
+ stats: () => cfg.store.stats(),
416
+ healthCheck() {
417
+ if (!cfg.store.ping())
418
+ return { ok: false, message: 'jobs store is closed or unreachable' }
419
+ const s = cfg.store.stats()
420
+ return { ok: true, message: `pending=${s.pending} running=${s.running} failed=${s.failed}` }
421
+ },
422
+ shutdown,
423
+ }
424
+ }