@prunellejs/jobs 0.0.0-stage → 0.7.2

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,473 @@
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
+ activeLeaseCount: number
81
+ started: boolean
82
+ stopping: boolean
83
+ releasedOnShutdown: boolean
84
+ shutdownPromise: Promise<void> | undefined
85
+ pollTimer: ReturnType<typeof setInterval> | undefined
86
+ scheduleTimer: ReturnType<typeof setInterval> | undefined
87
+ leaseTimer: ReturnType<typeof setInterval> | undefined
88
+ }
89
+
90
+ const MAX_TIMER_MS = 2_147_483_647
91
+
92
+ function leaseRenewIntervalMs(leaseMs: number): number {
93
+ return Math.max(1, Math.min(Math.floor(leaseMs / 3), MAX_TIMER_MS))
94
+ }
95
+
96
+ function renewActiveLeases(state: RuntimeState, now = state.cfg.now()): void {
97
+ if (state.activeLeaseCount === 0 || state.releasedOnShutdown || state.cfg.store.isClosed())
98
+ return
99
+ state.cfg.store.renewOwnerLeases(state.workerId, now + state.cfg.leaseMs, now)
100
+ }
101
+
102
+ function stopLeaseHeartbeat(state: RuntimeState): void {
103
+ if (state.leaseTimer !== undefined) {
104
+ clearInterval(state.leaseTimer)
105
+ state.leaseTimer = undefined
106
+ }
107
+ }
108
+
109
+ function acquireLeaseHeartbeat(state: RuntimeState): void {
110
+ state.activeLeaseCount++
111
+ if (state.leaseTimer === undefined && !state.releasedOnShutdown && !state.cfg.store.isClosed()) {
112
+ state.leaseTimer = setInterval(() => renewActiveLeases(state), leaseRenewIntervalMs(state.cfg.leaseMs))
113
+ unrefTimer(state.leaseTimer)
114
+ }
115
+ }
116
+
117
+ function releaseLeaseHeartbeat(state: RuntimeState): void {
118
+ if (state.activeLeaseCount > 0)
119
+ state.activeLeaseCount--
120
+ if (state.activeLeaseCount === 0)
121
+ stopLeaseHeartbeat(state)
122
+ }
123
+
124
+ function errorToMessage(err: unknown): string {
125
+ return err instanceof Error ? err.message : String(err)
126
+ }
127
+
128
+ function unrefTimer(timer: ReturnType<typeof setInterval> | ReturnType<typeof setTimeout>): void {
129
+ if (typeof timer === 'object' && timer !== null && 'unref' in timer && typeof timer.unref === 'function')
130
+ timer.unref()
131
+ }
132
+
133
+ function getQueue(state: RuntimeState, name: string): RegisteredQueue | undefined {
134
+ return state.localQueues.get(name) ?? state.cfg.handleQueues.get(name)
135
+ }
136
+
137
+ function registeredQueueNames(state: RuntimeState): string[] {
138
+ if (state.localQueues.size === 0)
139
+ return [...state.cfg.handleQueues.keys()]
140
+ const names = new Set<string>(state.cfg.handleQueues.keys())
141
+ for (const name of state.localQueues.keys())
142
+ names.add(name)
143
+ return [...names]
144
+ }
145
+
146
+ function reportError(state: RuntimeState, info: JobErrorInfo): void {
147
+ try {
148
+ state.cfg.onError?.(info)
149
+ }
150
+ catch (hookErr) {
151
+ console.error('@prunellejs/jobs: onError hook threw:', hookErr)
152
+ }
153
+ }
154
+
155
+ async function validatePayload(queueName: string, schema: StandardSchemaV1, data: unknown): Promise<unknown> {
156
+ const result = await validateSchema(schema, data)
157
+ if (!result.ok)
158
+ throw new JobValidationError(queueName, formatSchemaIssues(result.issues), result.issues, result.fieldErrors)
159
+ return result.value
160
+ }
161
+
162
+ async function executeClaimedJob(state: RuntimeState, job: ClaimedJob, nowFn: () => number): Promise<void> {
163
+ const { cfg, workerId } = state
164
+ const def = getQueue(state, job.queue)
165
+ if (def === undefined) {
166
+ if (!state.releasedOnShutdown && !cfg.store.isClosed())
167
+ cfg.store.failJob(job.id, workerId, `No handler registered for queue "${job.queue}"`, nowFn())
168
+ return
169
+ }
170
+
171
+ let input: unknown
172
+ try {
173
+ const parsed: unknown = JSON.parse(job.payload)
174
+ input = def.schema !== undefined ? await validatePayload(job.queue, def.schema, parsed) : parsed
175
+ }
176
+ catch (err) {
177
+ reportError(state, { kind: 'job', name: job.queue, id: job.id, attempt: job.attempts, maxAttempts: job.maxAttempts, error: err })
178
+ if (!state.releasedOnShutdown && !cfg.store.isClosed())
179
+ cfg.store.failJob(job.id, workerId, errorToMessage(err), nowFn())
180
+ return
181
+ }
182
+
183
+ const ctx: JobContext = {
184
+ id: job.id,
185
+ queue: job.queue,
186
+ attempt: job.attempts,
187
+ maxAttempts: job.maxAttempts,
188
+ ...(job.key !== undefined ? { key: job.key } : {}),
189
+ signal: state.abortController.signal,
190
+ }
191
+
192
+ try {
193
+ await def.handler(input, ctx)
194
+ if (!state.releasedOnShutdown && !cfg.store.isClosed())
195
+ cfg.store.completeJob(job.id, workerId, nowFn())
196
+ }
197
+ catch (err) {
198
+ const msg = errorToMessage(err)
199
+ reportError(state, { kind: 'job', name: job.queue, id: job.id, attempt: job.attempts, maxAttempts: job.maxAttempts, error: err })
200
+ if (state.releasedOnShutdown || cfg.store.isClosed())
201
+ return
202
+ if (job.attempts < job.maxAttempts) {
203
+ const delayMs = computeBackoffDelay(def.backoff, job.attempts, cfg.backoffBaseMs, cfg.maxBackoffMs)
204
+ const now = nowFn()
205
+ cfg.store.rescheduleJob(job.id, workerId, now + delayMs, msg, now)
206
+ }
207
+ else {
208
+ cfg.store.failJob(job.id, workerId, msg, nowFn())
209
+ }
210
+ }
211
+ }
212
+
213
+ function pollAvailableJobs(state: RuntimeState): void {
214
+ const { cfg, workerId } = state
215
+ if (state.stopping || cfg.store.isClosed())
216
+ return
217
+ const queues = registeredQueueNames(state)
218
+ if (queues.length === 0)
219
+ return
220
+
221
+ while (!state.stopping && !cfg.store.isClosed() && state.activeJobs < cfg.concurrency) {
222
+ const now = cfg.now()
223
+ if (state.activeLeaseCount > 0)
224
+ renewActiveLeases(state, now)
225
+ const claimed = cfg.store.claimNext({
226
+ queues,
227
+ workerId,
228
+ now,
229
+ leaseMs: cfg.leaseMs,
230
+ includeDelayed: false,
231
+ resolveMaxAttempts: (queue, currentMax) => getQueue(state, queue)?.attempts ?? currentMax,
232
+ })
233
+ if (claimed === undefined)
234
+ break
235
+ state.activeJobs++
236
+ acquireLeaseHeartbeat(state)
237
+ const task = executeClaimedJob(state, claimed, cfg.now).finally(() => {
238
+ state.activeJobs--
239
+ releaseLeaseHeartbeat(state)
240
+ state.inFlight.delete(task)
241
+ if (state.started && !state.stopping && !cfg.store.isClosed())
242
+ queueMicrotask(() => pollAvailableJobs(state))
243
+ })
244
+ state.inFlight.add(task)
245
+ }
246
+ }
247
+
248
+ async function runSingleSchedule(state: RuntimeState, schedule: RegisteredSchedule, tickMs: number): Promise<void> {
249
+ const ctx: ScheduleContext = {
250
+ name: schedule.name,
251
+ scheduledAt: new Date(tickMs),
252
+ tickMs,
253
+ timeZone: schedule.timeZone,
254
+ signal: state.abortController.signal,
255
+ }
256
+ try {
257
+ await schedule.handler(ctx)
258
+ if (!state.releasedOnShutdown && !state.cfg.store.isClosed())
259
+ state.cfg.store.finishScheduleTick(schedule.name, tickMs, 'completed', undefined, state.cfg.now())
260
+ }
261
+ catch (err) {
262
+ reportError(state, { kind: 'schedule', name: schedule.name, error: err })
263
+ if (!state.releasedOnShutdown && !state.cfg.store.isClosed())
264
+ state.cfg.store.finishScheduleTick(schedule.name, tickMs, 'failed', errorToMessage(err), state.cfg.now())
265
+ }
266
+ }
267
+
268
+ async function executeDueSchedules(state: RuntimeState, overrideNow?: number): Promise<number> {
269
+ const { cfg, workerId } = state
270
+ if (state.stopping || cfg.store.isClosed() || cfg.handleSchedules.size === 0)
271
+ return 0
272
+ const now = overrideNow ?? cfg.now()
273
+ const tickMs = floorToMinute(now)
274
+ const triggered: Promise<void>[] = []
275
+
276
+ for (const schedule of cfg.handleSchedules.values()) {
277
+ if (state.stopping || cfg.store.isClosed())
278
+ break
279
+ if (!matchesCron(schedule.parsed, tickMs, schedule.timeZone))
280
+ continue
281
+ if (!cfg.store.claimScheduleTick(schedule.name, tickMs, workerId, now))
282
+ continue
283
+ const task = runSingleSchedule(state, schedule, tickMs).finally(() => {
284
+ state.inFlight.delete(task)
285
+ })
286
+ state.inFlight.add(task)
287
+ triggered.push(task)
288
+ }
289
+
290
+ if (triggered.length > 0)
291
+ await Promise.allSettled(triggered)
292
+ return triggered.length
293
+ }
294
+
295
+ async function waitForInFlight(state: RuntimeState): Promise<boolean> {
296
+ if (state.inFlight.size === 0)
297
+ return true
298
+ if (state.cfg.shutdownTimeoutMs <= 0)
299
+ return false
300
+ let timedOut = false
301
+ let timer: ReturnType<typeof setTimeout> | undefined
302
+ const timeoutPromise = new Promise<void>((resolve) => {
303
+ timer = setTimeout(() => {
304
+ timedOut = true
305
+ resolve()
306
+ }, state.cfg.shutdownTimeoutMs)
307
+ unrefTimer(timer)
308
+ })
309
+ await Promise.race([Promise.allSettled([...state.inFlight]), timeoutPromise])
310
+ if (timer !== undefined)
311
+ clearTimeout(timer)
312
+ return !timedOut && state.inFlight.size === 0
313
+ }
314
+
315
+ export function createJobsRuntime(cfg: JobsRuntimeConfig): JobsRuntime {
316
+ const state: RuntimeState = {
317
+ cfg,
318
+ workerId: crypto.randomUUID(),
319
+ localQueues: new Map(),
320
+ inFlight: new Set(),
321
+ abortController: new AbortController(),
322
+ activeJobs: 0,
323
+ activeLeaseCount: 0,
324
+ started: false,
325
+ stopping: false,
326
+ releasedOnShutdown: false,
327
+ shutdownPromise: undefined,
328
+ pollTimer: undefined,
329
+ scheduleTimer: undefined,
330
+ leaseTimer: undefined,
331
+ }
332
+
333
+ async function enqueue<T = unknown>(name: string, data: T, options?: EnqueueOptions): Promise<EnqueueResult> {
334
+ if (cfg.store.isClosed())
335
+ throw new Error(`@prunellejs/jobs: cannot enqueue("${name}") after the jobs store has been closed.`)
336
+ const delayMs = parseDuration(options?.delay)
337
+ const def = getQueue(state, name)
338
+ if (def?.schema !== undefined)
339
+ await validatePayload(name, def.schema, data)
340
+
341
+ const now = cfg.now()
342
+ const runAt = now + delayMs
343
+ const result = cfg.store.enqueue({
344
+ id: crypto.randomUUID(),
345
+ queue: name,
346
+ payload: JSON.stringify(data === undefined ? null : data),
347
+ key: options?.key,
348
+ maxAttempts: def?.attempts ?? cfg.defaultAttempts,
349
+ runAt,
350
+ now,
351
+ })
352
+
353
+ if (state.started && !state.stopping && !result.deduplicated && runAt <= now)
354
+ queueMicrotask(() => pollAvailableJobs(state))
355
+ return result
356
+ }
357
+
358
+ async function drain(options?: DrainOptions): Promise<number> {
359
+ if (cfg.store.isClosed())
360
+ return 0
361
+ const includeDelayed = options?.includeDelayed === true
362
+ const maxJobs = options?.maxJobs ?? Number.POSITIVE_INFINITY
363
+ const nowFn = options?.now !== undefined ? () => options.now! : cfg.now
364
+ let executed = 0
365
+
366
+ while (executed < maxJobs && !state.stopping && !cfg.store.isClosed()) {
367
+ const queues = registeredQueueNames(state)
368
+ if (queues.length === 0)
369
+ break
370
+ const claimed = cfg.store.claimNext({
371
+ queues,
372
+ workerId: state.workerId,
373
+ now: nowFn(),
374
+ leaseMs: cfg.leaseMs,
375
+ includeDelayed,
376
+ resolveMaxAttempts: (queue, currentMax) => getQueue(state, queue)?.attempts ?? currentMax,
377
+ })
378
+ if (claimed === undefined)
379
+ break
380
+ const renewDuringDrain = options?.now === undefined
381
+ if (renewDuringDrain)
382
+ acquireLeaseHeartbeat(state)
383
+ const task = executeClaimedJob(state, claimed, nowFn).finally(() => {
384
+ if (renewDuringDrain)
385
+ releaseLeaseHeartbeat(state)
386
+ state.inFlight.delete(task)
387
+ })
388
+ state.inFlight.add(task)
389
+ await task
390
+ executed++
391
+ }
392
+ return executed
393
+ }
394
+
395
+ function start(): void {
396
+ if (state.started || state.stopping || cfg.store.isClosed())
397
+ return
398
+ state.started = true
399
+ state.pollTimer = setInterval(() => pollAvailableJobs(state), cfg.pollIntervalMs)
400
+ unrefTimer(state.pollTimer)
401
+ state.scheduleTimer = setInterval(() => {
402
+ void executeDueSchedules(state)
403
+ }, cfg.scheduleIntervalMs)
404
+ unrefTimer(state.scheduleTimer)
405
+ queueMicrotask(() => {
406
+ pollAvailableJobs(state)
407
+ void executeDueSchedules(state)
408
+ })
409
+ }
410
+
411
+ function shutdown(): Promise<void> {
412
+ if (state.shutdownPromise !== undefined)
413
+ return state.shutdownPromise
414
+ state.stopping = true
415
+ state.started = false
416
+ if (state.pollTimer !== undefined) {
417
+ clearInterval(state.pollTimer)
418
+ state.pollTimer = undefined
419
+ }
420
+ if (state.scheduleTimer !== undefined) {
421
+ clearInterval(state.scheduleTimer)
422
+ state.scheduleTimer = undefined
423
+ }
424
+
425
+ state.shutdownPromise = (async () => {
426
+ if (!(await waitForInFlight(state))) {
427
+ state.releasedOnShutdown = true
428
+ state.abortController.abort(new Error('@prunellejs/jobs: shutdown timeout exceeded'))
429
+ }
430
+ stopLeaseHeartbeat(state)
431
+ if (!cfg.store.isClosed()) {
432
+ cfg.store.releaseOwnerJobs(state.workerId, cfg.now())
433
+ cfg.store.close()
434
+ }
435
+ })()
436
+ return state.shutdownPromise
437
+ }
438
+
439
+ const service: JobsService = {
440
+ queue<T = unknown>(name: string, handler: (data: T) => void | Promise<void>, options?: JobsQueueOptions) {
441
+ state.localQueues.set(name, {
442
+ name,
443
+ handler: handler as JobHandler<unknown>,
444
+ attempts: normalizeAttempts(options?.attempts, cfg.defaultAttempts),
445
+ backoff: normalizeBackoff(options?.backoff, cfg.defaultBackoff),
446
+ })
447
+ },
448
+ async enqueue<T = unknown>(name: string, data: T, options?: JobsEnqueueOptions) {
449
+ await enqueue(name, data, options)
450
+ },
451
+ drain: options => drain(options),
452
+ }
453
+
454
+ return {
455
+ workerId: state.workerId,
456
+ store: cfg.store,
457
+ service,
458
+ start,
459
+ enqueue,
460
+ drain,
461
+ runDueSchedules: overrideNow => executeDueSchedules(state, overrideNow),
462
+ get: <T = unknown>(id: string) => cfg.store.getJob<T>(id),
463
+ list: <T = unknown>(filter?: JobListFilter) => cfg.store.listJobs<T>(filter),
464
+ stats: () => cfg.store.stats(),
465
+ healthCheck() {
466
+ if (!cfg.store.ping())
467
+ return { ok: false, message: 'jobs store is closed or unreachable' }
468
+ const s = cfg.store.stats()
469
+ return { ok: true, message: `pending=${s.pending} running=${s.running} failed=${s.failed}` }
470
+ },
471
+ shutdown,
472
+ }
473
+ }