@prunellejs/jobs 0.7.4 → 0.8.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/llms.txt +9 -4
- package/package.json +2 -2
- package/src/index.ts +27 -20
- package/src/runner.ts +90 -13
- package/src/store.ts +55 -1
- package/src/types.ts +58 -15
package/llms.txt
CHANGED
|
@@ -20,10 +20,12 @@
|
|
|
20
20
|
- `leaseMs`: running-job lease duration in ms (renewed automatically while the worker is alive) before a crashed worker's job is reclaimed (default `60_000`).
|
|
21
21
|
- `shutdownTimeoutMs`: max ms `onShutdown()` waits for in-flight jobs before releasing remaining claims back to `pending` (default `5000`).
|
|
22
22
|
- `defaultAttempts`: default max attempts per job (default `3`).
|
|
23
|
-
- `defaultBackoff`: `'exponential' | 'fixed' | number` (default `'exponential'`, base `backoffBaseMs` `1000` ms
|
|
23
|
+
- `defaultBackoff`: `'exponential' | 'fixed' | number` (default `'exponential'`, base `backoffBaseMs` `1000` ms). Every strategy is capped at `maxBackoffMs` (`3_600_000` ms), then jittered to 50-100% of the capped delay.
|
|
24
|
+
- `retention`: `{ completed?, failed?, scheduleRuns? }`, each a duration or `false` (keep forever); defaults `'1d'`, `'7d'`, `'7d'`. A completed job's payload is cleared at once (`get(id).data` is `null`); finished rows and cron tick records past their retention are deleted by the worker every minute. `jobs.purge()` does it now and returns the number of jobs deleted.
|
|
25
|
+
- Delivery is at least once: a handler must be safe to run twice. A cron tick missed because no process was alive is not caught up.
|
|
24
26
|
- `autoStart`: starts background poll/schedule loops inside `server(api)` (defaults to `true` outside `NODE_ENV=test`; disabled in tests so `drainJobs(app)` is deterministic).
|
|
25
27
|
- `now`: optional clock function (`() => number`) for deterministic time control.
|
|
26
|
-
- `onError`: optional callback notified whenever a job or schedule handler throws.
|
|
28
|
+
- `onError`: optional callback notified whenever a job or schedule handler throws, and with `kind: 'store'` when the store fails in the poll, lease or schedule loop (the loop keeps running).
|
|
27
29
|
|
|
28
30
|
## Queues & Standard Schema Validation
|
|
29
31
|
|
|
@@ -31,10 +33,13 @@
|
|
|
31
33
|
- Standard Schema (Zod, Valibot, ArkType, etc.), both forms supported with full static input inference and runtime validation on `enqueue()` and execution:
|
|
32
34
|
- `jobs.queue('emails', emailSchema, (data, ctx) => { ... }, { attempts: 5, backoff: 'exponential' })`
|
|
33
35
|
- `jobs.queue('emails', (data, ctx) => { ... }, { schema: emailSchema, attempts: 5, backoff: 'fixed' })`
|
|
36
|
+
- `timeout`: a time limit per run, in milliseconds or a duration string (`'30s'`, `'5m'`); past it `ctx.signal` aborts and the run counts as a failed attempt, retried with the queue's backoff. No limit by default: a live worker renews a running job's lease, so a handler that never settles holds its job until the process stops.
|
|
37
|
+
- A handler that throws an error with `retryable: false` is not retried: the job is marked `failed` at once (for a step that may already have taken effect, such as a mail the provider may have sent).
|
|
34
38
|
- Invalid payloads throw `JobValidationError` (with `.issues` and `.fieldErrors`).
|
|
35
|
-
- `await jobs.enqueue(name, data, { delay, key })`:
|
|
39
|
+
- `await jobs.enqueue(name, data, { delay, key, dedupWindow })`:
|
|
36
40
|
- `delay`: milliseconds or duration string (`'500ms'`, `'5s'`, `'10m'`, `'2h'`, `'1d'`).
|
|
37
|
-
- `key`: per-queue deduplication key enforced by a SQLite unique index
|
|
41
|
+
- `key`: per-queue deduplication key enforced by a SQLite unique index while the job is `pending`/`running` (survives restarts; re-enqueuing returns `{ id, queue, runAt, deduplicated: true }`). Free again once the job completes or fails. No personal data in a key: it stays on the finished row until purged.
|
|
42
|
+
- `dedupWindow`: duration; keeps `key` taken that long after the job finished (cut short when the finished row is purged).
|
|
38
43
|
|
|
39
44
|
## Cron Schedules & Multi-Process Lock
|
|
40
45
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/jobs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Zero-dependency durable SQLite job queue and cron scheduler plugin for Prunelle",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -21,6 +21,6 @@
|
|
|
21
21
|
"directory": "packages/plugin-jobs"
|
|
22
22
|
},
|
|
23
23
|
"peerDependencies": {
|
|
24
|
-
"prunelle": "^0.
|
|
24
|
+
"prunelle": "^0.8.0"
|
|
25
25
|
}
|
|
26
26
|
}
|
package/src/index.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import type { Database } from 'bun:sqlite'
|
|
5
5
|
import type { StandardSchemaV1 } from 'prunelle/server'
|
|
6
|
-
import type { JobsRuntime, RegisteredQueue, RegisteredSchedule } from './runner'
|
|
6
|
+
import type { JobsRuntime, JobsRuntimeConfig, RegisteredQueue, RegisteredSchedule } from './runner'
|
|
7
7
|
import type {
|
|
8
8
|
DrainOptions,
|
|
9
9
|
DrainTarget,
|
|
@@ -25,7 +25,7 @@ import { nodeEnv } from 'prunelle/server'
|
|
|
25
25
|
import { assertValidTimeZone, parseCron } from './cron'
|
|
26
26
|
import { createJobsRuntime } from './runner'
|
|
27
27
|
import { createSqliteJobsStore, isInMemoryDb } from './store'
|
|
28
|
-
import { isStandardSchema, normalizeAttempts, normalizeBackoff } from './types'
|
|
28
|
+
import { isStandardSchema, normalizeAttempts, normalizeBackoff, normalizeRetention, normalizeTimeout } from './types'
|
|
29
29
|
|
|
30
30
|
export { assertValidTimeZone, floorToMinute, getZonedParts, matchesCron, nextCronTick, parseCron } from './cron'
|
|
31
31
|
export type { ParsedCron, ZonedDateParts } from './cron'
|
|
@@ -50,6 +50,7 @@ export type {
|
|
|
50
50
|
JobStatus,
|
|
51
51
|
QueueBaseOptions,
|
|
52
52
|
QueueOptions,
|
|
53
|
+
RetentionOptions,
|
|
53
54
|
ScheduleContext,
|
|
54
55
|
ScheduleHandler,
|
|
55
56
|
ScheduleOptions,
|
|
@@ -129,16 +130,26 @@ export async function drainJobs(target: DrainTarget, options?: DrainOptions): Pr
|
|
|
129
130
|
return service.drain(options)
|
|
130
131
|
}
|
|
131
132
|
|
|
133
|
+
type RuntimeTuning = Omit<JobsRuntimeConfig, 'store' | 'handleQueues' | 'handleSchedules' | 'now' | 'onError'>
|
|
134
|
+
|
|
135
|
+
function resolveTuning(options: JobsOptions): RuntimeTuning {
|
|
136
|
+
return {
|
|
137
|
+
pollIntervalMs: validatePositiveNumber(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, 'pollIntervalMs'),
|
|
138
|
+
scheduleIntervalMs: validatePositiveNumber(options.scheduleIntervalMs, DEFAULT_SCHEDULE_INTERVAL_MS, 'scheduleIntervalMs'),
|
|
139
|
+
concurrency: Math.max(1, Math.floor(validatePositiveNumber(options.concurrency, DEFAULT_CONCURRENCY, 'concurrency'))),
|
|
140
|
+
leaseMs: validatePositiveNumber(options.leaseMs, DEFAULT_LEASE_MS, 'leaseMs'),
|
|
141
|
+
shutdownTimeoutMs: validateNonNegativeNumber(options.shutdownTimeoutMs, DEFAULT_SHUTDOWN_TIMEOUT_MS, 'shutdownTimeoutMs'),
|
|
142
|
+
defaultAttempts: normalizeAttempts(options.defaultAttempts, DEFAULT_ATTEMPTS),
|
|
143
|
+
defaultBackoff: normalizeBackoff(options.defaultBackoff, DEFAULT_BACKOFF),
|
|
144
|
+
backoffBaseMs: validateNonNegativeNumber(options.backoffBaseMs, DEFAULT_BACKOFF_BASE_MS, 'backoffBaseMs'),
|
|
145
|
+
maxBackoffMs: validateNonNegativeNumber(options.maxBackoffMs, DEFAULT_MAX_BACKOFF_MS, 'maxBackoffMs'),
|
|
146
|
+
retention: normalizeRetention(options.retention),
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
132
150
|
export function createJobs(options: JobsOptions = {}): Jobs {
|
|
133
|
-
const
|
|
134
|
-
const
|
|
135
|
-
const concurrency = Math.max(1, Math.floor(validatePositiveNumber(options.concurrency, DEFAULT_CONCURRENCY, 'concurrency')))
|
|
136
|
-
const leaseMs = validatePositiveNumber(options.leaseMs, DEFAULT_LEASE_MS, 'leaseMs')
|
|
137
|
-
const shutdownTimeoutMs = validateNonNegativeNumber(options.shutdownTimeoutMs, DEFAULT_SHUTDOWN_TIMEOUT_MS, 'shutdownTimeoutMs')
|
|
138
|
-
const defaultAttempts = normalizeAttempts(options.defaultAttempts, DEFAULT_ATTEMPTS)
|
|
139
|
-
const defaultBackoff = normalizeBackoff(options.defaultBackoff, DEFAULT_BACKOFF)
|
|
140
|
-
const backoffBaseMs = validateNonNegativeNumber(options.backoffBaseMs, DEFAULT_BACKOFF_BASE_MS, 'backoffBaseMs')
|
|
141
|
-
const maxBackoffMs = validateNonNegativeNumber(options.maxBackoffMs, DEFAULT_MAX_BACKOFF_MS, 'maxBackoffMs')
|
|
151
|
+
const tuning = resolveTuning(options)
|
|
152
|
+
const { defaultAttempts, defaultBackoff } = tuning
|
|
142
153
|
const clock = options.now ?? Date.now
|
|
143
154
|
|
|
144
155
|
const handleQueues = new Map<string, RegisteredQueue>()
|
|
@@ -153,15 +164,7 @@ export function createJobs(options: JobsOptions = {}): Jobs {
|
|
|
153
164
|
store,
|
|
154
165
|
handleQueues,
|
|
155
166
|
handleSchedules,
|
|
156
|
-
|
|
157
|
-
scheduleIntervalMs,
|
|
158
|
-
concurrency,
|
|
159
|
-
leaseMs,
|
|
160
|
-
shutdownTimeoutMs,
|
|
161
|
-
defaultAttempts,
|
|
162
|
-
defaultBackoff,
|
|
163
|
-
backoffBaseMs,
|
|
164
|
-
maxBackoffMs,
|
|
167
|
+
...tuning,
|
|
165
168
|
now: clock,
|
|
166
169
|
onError: options.onError,
|
|
167
170
|
})
|
|
@@ -243,6 +246,7 @@ export function createJobs(options: JobsOptions = {}): Jobs {
|
|
|
243
246
|
handler,
|
|
244
247
|
attempts: normalizeAttempts(qOpts?.attempts, defaultAttempts),
|
|
245
248
|
backoff: normalizeBackoff(qOpts?.backoff, defaultBackoff),
|
|
249
|
+
timeoutMs: normalizeTimeout(qOpts?.timeout),
|
|
246
250
|
...(schema !== undefined ? { schema } : {}),
|
|
247
251
|
})
|
|
248
252
|
return instance
|
|
@@ -283,6 +287,9 @@ export function createJobs(options: JobsOptions = {}): Jobs {
|
|
|
283
287
|
stats(): JobStats {
|
|
284
288
|
return ensureRuntime().stats()
|
|
285
289
|
},
|
|
290
|
+
purge(): number {
|
|
291
|
+
return ensureRuntime().purge()
|
|
292
|
+
},
|
|
286
293
|
dispose,
|
|
287
294
|
[Symbol.asyncDispose]: dispose,
|
|
288
295
|
}
|
package/src/runner.ts
CHANGED
|
@@ -20,13 +20,14 @@ import type {
|
|
|
20
20
|
} from './types'
|
|
21
21
|
import { formatSchemaIssues, validateSchema } from 'prunelle/server'
|
|
22
22
|
import { floorToMinute, matchesCron } from './cron'
|
|
23
|
-
import { computeBackoffDelay, JobValidationError, normalizeAttempts, normalizeBackoff, parseDuration } from './types'
|
|
23
|
+
import { computeBackoffDelay, JobValidationError, normalizeAttempts, normalizeBackoff, normalizeTimeout, parseDuration } from './types'
|
|
24
24
|
|
|
25
25
|
export interface RegisteredQueue {
|
|
26
26
|
readonly name: string
|
|
27
27
|
readonly handler: JobHandler<unknown>
|
|
28
28
|
readonly attempts: number
|
|
29
29
|
readonly backoff: BackoffStrategy
|
|
30
|
+
readonly timeoutMs?: number | undefined
|
|
30
31
|
readonly schema?: StandardSchemaV1 | undefined
|
|
31
32
|
}
|
|
32
33
|
|
|
@@ -51,6 +52,8 @@ export interface JobsRuntimeConfig {
|
|
|
51
52
|
readonly defaultBackoff: BackoffStrategy
|
|
52
53
|
readonly backoffBaseMs: number
|
|
53
54
|
readonly maxBackoffMs: number
|
|
55
|
+
/** Retention per kind of finished row in ms, `Infinity` to keep it. */
|
|
56
|
+
readonly retention: { readonly completed: number, readonly failed: number, readonly scheduleRuns: number }
|
|
54
57
|
readonly now: () => number
|
|
55
58
|
readonly onError?: ((info: JobErrorInfo) => void) | undefined
|
|
56
59
|
}
|
|
@@ -66,6 +69,7 @@ export interface JobsRuntime {
|
|
|
66
69
|
get<T = unknown>(id: string): JobRecord<T> | undefined
|
|
67
70
|
list<T = unknown>(filter?: JobListFilter): JobRecord<T>[]
|
|
68
71
|
stats(): JobStats
|
|
72
|
+
purge(): number
|
|
69
73
|
healthCheck(): { ok: boolean, message: string }
|
|
70
74
|
shutdown(): Promise<void>
|
|
71
75
|
}
|
|
@@ -78,6 +82,7 @@ interface RuntimeState {
|
|
|
78
82
|
readonly abortController: AbortController
|
|
79
83
|
activeJobs: number
|
|
80
84
|
activeLeaseCount: number
|
|
85
|
+
lastPurgeAt: number
|
|
81
86
|
started: boolean
|
|
82
87
|
stopping: boolean
|
|
83
88
|
releasedOnShutdown: boolean
|
|
@@ -93,6 +98,20 @@ function leaseRenewIntervalMs(leaseMs: number): number {
|
|
|
93
98
|
return Math.max(1, Math.min(Math.floor(leaseMs / 3), MAX_TIMER_MS))
|
|
94
99
|
}
|
|
95
100
|
|
|
101
|
+
// A store failure (disk full, database locked) in a background loop is reported and the next tick retries.
|
|
102
|
+
function reportStoreError(state: RuntimeState, name: string, err: unknown): void {
|
|
103
|
+
reportError(state, { kind: 'store', name, error: err })
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function renewActiveLeasesSafely(state: RuntimeState): void {
|
|
107
|
+
try {
|
|
108
|
+
renewActiveLeases(state)
|
|
109
|
+
}
|
|
110
|
+
catch (err) {
|
|
111
|
+
reportStoreError(state, 'lease', err)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
96
115
|
function renewActiveLeases(state: RuntimeState, now = state.cfg.now()): void {
|
|
97
116
|
if (state.activeLeaseCount === 0 || state.releasedOnShutdown || state.cfg.store.isClosed())
|
|
98
117
|
return
|
|
@@ -109,7 +128,7 @@ function stopLeaseHeartbeat(state: RuntimeState): void {
|
|
|
109
128
|
function acquireLeaseHeartbeat(state: RuntimeState): void {
|
|
110
129
|
state.activeLeaseCount++
|
|
111
130
|
if (state.leaseTimer === undefined && !state.releasedOnShutdown && !state.cfg.store.isClosed()) {
|
|
112
|
-
state.leaseTimer = setInterval(() =>
|
|
131
|
+
state.leaseTimer = setInterval(() => renewActiveLeasesSafely(state), leaseRenewIntervalMs(state.cfg.leaseMs))
|
|
113
132
|
unrefTimer(state.leaseTimer)
|
|
114
133
|
}
|
|
115
134
|
}
|
|
@@ -125,6 +144,11 @@ function errorToMessage(err: unknown): string {
|
|
|
125
144
|
return err instanceof Error ? err.message : String(err)
|
|
126
145
|
}
|
|
127
146
|
|
|
147
|
+
// A handler that throws an error with `retryable: false` fails the job at once, as a send that may already have gone out must not run twice.
|
|
148
|
+
function isNotRetryable(err: unknown): boolean {
|
|
149
|
+
return typeof err === 'object' && err !== null && 'retryable' in err && err.retryable === false
|
|
150
|
+
}
|
|
151
|
+
|
|
128
152
|
function unrefTimer(timer: ReturnType<typeof setInterval> | ReturnType<typeof setTimeout>): void {
|
|
129
153
|
if (typeof timer === 'object' && timer !== null && 'unref' in timer && typeof timer.unref === 'function')
|
|
130
154
|
timer.unref()
|
|
@@ -159,6 +183,30 @@ async function validatePayload(queueName: string, schema: StandardSchemaV1, data
|
|
|
159
183
|
return result.value
|
|
160
184
|
}
|
|
161
185
|
|
|
186
|
+
// Runs the handler; past the queue's timeout it aborts ctx.signal and rejects, though a handler that ignores the signal keeps running unwatched.
|
|
187
|
+
async function runHandler(def: RegisteredQueue, input: unknown, ctx: Omit<JobContext, 'signal'>, shutdown: AbortSignal): Promise<void> {
|
|
188
|
+
const timeoutMs = def.timeoutMs
|
|
189
|
+
if (timeoutMs === undefined) {
|
|
190
|
+
await def.handler(input, { ...ctx, signal: shutdown })
|
|
191
|
+
return
|
|
192
|
+
}
|
|
193
|
+
const limit = new AbortController()
|
|
194
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
195
|
+
const timedOut = new Promise<never>((_, reject) => {
|
|
196
|
+
timer = setTimeout(() => {
|
|
197
|
+
const err = new Error(`@prunellejs/jobs: the run of queue "${def.name}" passed its timeout of ${timeoutMs}ms.`)
|
|
198
|
+
limit.abort(err)
|
|
199
|
+
reject(err)
|
|
200
|
+
}, timeoutMs)
|
|
201
|
+
})
|
|
202
|
+
try {
|
|
203
|
+
await Promise.race([(async () => def.handler(input, { ...ctx, signal: AbortSignal.any([shutdown, limit.signal]) }))(), timedOut])
|
|
204
|
+
}
|
|
205
|
+
finally {
|
|
206
|
+
clearTimeout(timer)
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
162
210
|
async function executeClaimedJob(state: RuntimeState, job: ClaimedJob, nowFn: () => number): Promise<void> {
|
|
163
211
|
const { cfg, workerId } = state
|
|
164
212
|
const def = getQueue(state, job.queue)
|
|
@@ -180,17 +228,16 @@ async function executeClaimedJob(state: RuntimeState, job: ClaimedJob, nowFn: ()
|
|
|
180
228
|
return
|
|
181
229
|
}
|
|
182
230
|
|
|
183
|
-
const ctx: JobContext = {
|
|
231
|
+
const ctx: Omit<JobContext, 'signal'> = {
|
|
184
232
|
id: job.id,
|
|
185
233
|
queue: job.queue,
|
|
186
234
|
attempt: job.attempts,
|
|
187
235
|
maxAttempts: job.maxAttempts,
|
|
188
236
|
...(job.key !== undefined ? { key: job.key } : {}),
|
|
189
|
-
signal: state.abortController.signal,
|
|
190
237
|
}
|
|
191
238
|
|
|
192
239
|
try {
|
|
193
|
-
await def
|
|
240
|
+
await runHandler(def, input, ctx, state.abortController.signal)
|
|
194
241
|
if (!state.releasedOnShutdown && !cfg.store.isClosed())
|
|
195
242
|
cfg.store.completeJob(job.id, workerId, nowFn())
|
|
196
243
|
}
|
|
@@ -199,7 +246,7 @@ async function executeClaimedJob(state: RuntimeState, job: ClaimedJob, nowFn: ()
|
|
|
199
246
|
reportError(state, { kind: 'job', name: job.queue, id: job.id, attempt: job.attempts, maxAttempts: job.maxAttempts, error: err })
|
|
200
247
|
if (state.releasedOnShutdown || cfg.store.isClosed())
|
|
201
248
|
return
|
|
202
|
-
if (job.attempts < job.maxAttempts) {
|
|
249
|
+
if (job.attempts < job.maxAttempts && !isNotRetryable(err)) {
|
|
203
250
|
const delayMs = computeBackoffDelay(def.backoff, job.attempts, cfg.backoffBaseMs, cfg.maxBackoffMs)
|
|
204
251
|
const now = nowFn()
|
|
205
252
|
cfg.store.rescheduleJob(job.id, workerId, now + delayMs, msg, now)
|
|
@@ -211,9 +258,29 @@ async function executeClaimedJob(state: RuntimeState, job: ClaimedJob, nowFn: ()
|
|
|
211
258
|
}
|
|
212
259
|
|
|
213
260
|
function pollAvailableJobs(state: RuntimeState): void {
|
|
261
|
+
try {
|
|
262
|
+
pollStore(state)
|
|
263
|
+
}
|
|
264
|
+
catch (err) {
|
|
265
|
+
reportStoreError(state, 'poll', err)
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const PURGE_INTERVAL_MS = 60_000
|
|
270
|
+
|
|
271
|
+
function purgeFinished(state: RuntimeState): number {
|
|
272
|
+
const { cfg } = state
|
|
273
|
+
const now = cfg.now()
|
|
274
|
+
state.lastPurgeAt = now
|
|
275
|
+
return cfg.store.purge({ now, completedMs: cfg.retention.completed, failedMs: cfg.retention.failed, scheduleRunsMs: cfg.retention.scheduleRuns })
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function pollStore(state: RuntimeState): void {
|
|
214
279
|
const { cfg, workerId } = state
|
|
215
280
|
if (state.stopping || cfg.store.isClosed())
|
|
216
281
|
return
|
|
282
|
+
if (cfg.now() - state.lastPurgeAt >= PURGE_INTERVAL_MS)
|
|
283
|
+
purgeFinished(state)
|
|
217
284
|
const queues = registeredQueueNames(state)
|
|
218
285
|
if (queues.length === 0)
|
|
219
286
|
return
|
|
@@ -234,7 +301,7 @@ function pollAvailableJobs(state: RuntimeState): void {
|
|
|
234
301
|
break
|
|
235
302
|
state.activeJobs++
|
|
236
303
|
acquireLeaseHeartbeat(state)
|
|
237
|
-
const task = executeClaimedJob(state, claimed, cfg.now).finally(() => {
|
|
304
|
+
const task = executeClaimedJob(state, claimed, cfg.now).catch(err => reportStoreError(state, 'job', err)).finally(() => {
|
|
238
305
|
state.activeJobs--
|
|
239
306
|
releaseLeaseHeartbeat(state)
|
|
240
307
|
state.inFlight.delete(task)
|
|
@@ -292,6 +359,10 @@ async function executeDueSchedules(state: RuntimeState, overrideNow?: number): P
|
|
|
292
359
|
return triggered.length
|
|
293
360
|
}
|
|
294
361
|
|
|
362
|
+
function runDueSchedulesSafely(state: RuntimeState): void {
|
|
363
|
+
executeDueSchedules(state).catch(err => reportStoreError(state, 'schedule', err))
|
|
364
|
+
}
|
|
365
|
+
|
|
295
366
|
async function waitForInFlight(state: RuntimeState): Promise<boolean> {
|
|
296
367
|
if (state.inFlight.size === 0)
|
|
297
368
|
return true
|
|
@@ -312,8 +383,8 @@ async function waitForInFlight(state: RuntimeState): Promise<boolean> {
|
|
|
312
383
|
return !timedOut && state.inFlight.size === 0
|
|
313
384
|
}
|
|
314
385
|
|
|
315
|
-
|
|
316
|
-
|
|
386
|
+
function newRuntimeState(cfg: JobsRuntimeConfig): RuntimeState {
|
|
387
|
+
return {
|
|
317
388
|
cfg,
|
|
318
389
|
workerId: crypto.randomUUID(),
|
|
319
390
|
localQueues: new Map(),
|
|
@@ -321,6 +392,7 @@ export function createJobsRuntime(cfg: JobsRuntimeConfig): JobsRuntime {
|
|
|
321
392
|
abortController: new AbortController(),
|
|
322
393
|
activeJobs: 0,
|
|
323
394
|
activeLeaseCount: 0,
|
|
395
|
+
lastPurgeAt: Number.NEGATIVE_INFINITY,
|
|
324
396
|
started: false,
|
|
325
397
|
stopping: false,
|
|
326
398
|
releasedOnShutdown: false,
|
|
@@ -329,6 +401,10 @@ export function createJobsRuntime(cfg: JobsRuntimeConfig): JobsRuntime {
|
|
|
329
401
|
scheduleTimer: undefined,
|
|
330
402
|
leaseTimer: undefined,
|
|
331
403
|
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
export function createJobsRuntime(cfg: JobsRuntimeConfig): JobsRuntime {
|
|
407
|
+
const state = newRuntimeState(cfg)
|
|
332
408
|
|
|
333
409
|
async function enqueue<T = unknown>(name: string, data: T, options?: EnqueueOptions): Promise<EnqueueResult> {
|
|
334
410
|
if (cfg.store.isClosed())
|
|
@@ -345,6 +421,7 @@ export function createJobsRuntime(cfg: JobsRuntimeConfig): JobsRuntime {
|
|
|
345
421
|
queue: name,
|
|
346
422
|
payload: JSON.stringify(data === undefined ? null : data),
|
|
347
423
|
key: options?.key,
|
|
424
|
+
dedupWindowMs: parseDuration(options?.dedupWindow, 'dedupWindow'),
|
|
348
425
|
maxAttempts: def?.attempts ?? cfg.defaultAttempts,
|
|
349
426
|
runAt,
|
|
350
427
|
now,
|
|
@@ -398,13 +475,11 @@ export function createJobsRuntime(cfg: JobsRuntimeConfig): JobsRuntime {
|
|
|
398
475
|
state.started = true
|
|
399
476
|
state.pollTimer = setInterval(() => pollAvailableJobs(state), cfg.pollIntervalMs)
|
|
400
477
|
unrefTimer(state.pollTimer)
|
|
401
|
-
state.scheduleTimer = setInterval(() =>
|
|
402
|
-
void executeDueSchedules(state)
|
|
403
|
-
}, cfg.scheduleIntervalMs)
|
|
478
|
+
state.scheduleTimer = setInterval(() => runDueSchedulesSafely(state), cfg.scheduleIntervalMs)
|
|
404
479
|
unrefTimer(state.scheduleTimer)
|
|
405
480
|
queueMicrotask(() => {
|
|
406
481
|
pollAvailableJobs(state)
|
|
407
|
-
|
|
482
|
+
runDueSchedulesSafely(state)
|
|
408
483
|
})
|
|
409
484
|
}
|
|
410
485
|
|
|
@@ -443,6 +518,7 @@ export function createJobsRuntime(cfg: JobsRuntimeConfig): JobsRuntime {
|
|
|
443
518
|
handler: handler as JobHandler<unknown>,
|
|
444
519
|
attempts: normalizeAttempts(options?.attempts, cfg.defaultAttempts),
|
|
445
520
|
backoff: normalizeBackoff(options?.backoff, cfg.defaultBackoff),
|
|
521
|
+
timeoutMs: normalizeTimeout(options?.timeout),
|
|
446
522
|
})
|
|
447
523
|
},
|
|
448
524
|
async enqueue<T = unknown>(name: string, data: T, options?: JobsEnqueueOptions) {
|
|
@@ -462,6 +538,7 @@ export function createJobsRuntime(cfg: JobsRuntimeConfig): JobsRuntime {
|
|
|
462
538
|
get: <T = unknown>(id: string) => cfg.store.getJob<T>(id),
|
|
463
539
|
list: <T = unknown>(filter?: JobListFilter) => cfg.store.listJobs<T>(filter),
|
|
464
540
|
stats: () => cfg.store.stats(),
|
|
541
|
+
purge: () => purgeFinished(state),
|
|
465
542
|
healthCheck() {
|
|
466
543
|
if (!cfg.store.ping())
|
|
467
544
|
return { ok: false, message: 'jobs store is closed or unreachable' }
|
package/src/store.ts
CHANGED
|
@@ -59,6 +59,15 @@ export interface EnqueueParams {
|
|
|
59
59
|
readonly maxAttempts: number
|
|
60
60
|
readonly runAt: number
|
|
61
61
|
readonly now: number
|
|
62
|
+
/** How long after finishing a job still holds `key`, in ms. */
|
|
63
|
+
readonly dedupWindowMs: number
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface PurgeParams {
|
|
67
|
+
readonly now: number
|
|
68
|
+
readonly completedMs: number
|
|
69
|
+
readonly failedMs: number
|
|
70
|
+
readonly scheduleRunsMs: number
|
|
62
71
|
}
|
|
63
72
|
|
|
64
73
|
export interface JobsStore {
|
|
@@ -77,6 +86,7 @@ export interface JobsStore {
|
|
|
77
86
|
getJob<T = unknown>(id: string): JobRecord<T> | undefined
|
|
78
87
|
listJobs<T = unknown>(filter?: JobListFilter): JobRecord<T>[]
|
|
79
88
|
stats(): JobStats
|
|
89
|
+
purge(params: PurgeParams): number
|
|
80
90
|
close(): void
|
|
81
91
|
}
|
|
82
92
|
|
|
@@ -186,9 +196,25 @@ function prepareQueries(db: Database) {
|
|
|
186
196
|
updated_at = ?
|
|
187
197
|
WHERE id = ?`,
|
|
188
198
|
),
|
|
199
|
+
releaseDedup: db.query<null, [string, string, number]>(
|
|
200
|
+
`UPDATE prunelle_jobs SET dedup_key = NULL
|
|
201
|
+
WHERE queue = ? AND dedup_key = ?
|
|
202
|
+
AND status IN ('completed', 'failed')
|
|
203
|
+
AND COALESCE(completed_at, updated_at) <= ?`,
|
|
204
|
+
),
|
|
205
|
+
purgeCompleted: db.query<null, [number]>(
|
|
206
|
+
"DELETE FROM prunelle_jobs WHERE status = 'completed' AND completed_at <= ?",
|
|
207
|
+
),
|
|
208
|
+
purgeFailed: db.query<null, [number]>(
|
|
209
|
+
"DELETE FROM prunelle_jobs WHERE status = 'failed' AND updated_at <= ?",
|
|
210
|
+
),
|
|
211
|
+
purgeScheduleRuns: db.query<null, [number]>(
|
|
212
|
+
'DELETE FROM prunelle_job_schedule_runs WHERE started_at <= ?',
|
|
213
|
+
),
|
|
189
214
|
complete: db.query<null, [number, number, string, string]>(
|
|
190
215
|
`UPDATE prunelle_jobs
|
|
191
216
|
SET status = 'completed',
|
|
217
|
+
payload = 'null',
|
|
192
218
|
lease_owner = NULL,
|
|
193
219
|
lease_expires_at = NULL,
|
|
194
220
|
completed_at = ?,
|
|
@@ -273,6 +299,18 @@ function buildClaimQuery(queues: readonly string[], now: number, includeDelayed:
|
|
|
273
299
|
}
|
|
274
300
|
}
|
|
275
301
|
|
|
302
|
+
// A plain read, so an idle worker polling every few hundred ms never queues for SQLite's write lock.
|
|
303
|
+
function hasClaimable(db: Database, params: ClaimNextParams): boolean {
|
|
304
|
+
const placeholders = params.queues.map(() => '?').join(', ')
|
|
305
|
+
const pending = params.includeDelayed ? "status = 'pending'" : "(status = 'pending' AND run_at <= ?)"
|
|
306
|
+
const sql = `SELECT 1 AS ok FROM prunelle_jobs
|
|
307
|
+
WHERE queue IN (${placeholders})
|
|
308
|
+
AND (${pending} OR (status = 'running' AND lease_expires_at IS NOT NULL AND lease_expires_at <= ?))
|
|
309
|
+
LIMIT 1`
|
|
310
|
+
const values = params.includeDelayed ? [...params.queues, params.now] : [...params.queues, params.now, params.now]
|
|
311
|
+
return db.query<{ ok: number }, Array<string | number>>(sql).get(...values) !== null
|
|
312
|
+
}
|
|
313
|
+
|
|
276
314
|
function listJobsFromDb<T>(db: Database, filter?: JobListFilter): JobRecord<T>[] {
|
|
277
315
|
const clauses: string[] = []
|
|
278
316
|
const values: Array<string | number> = []
|
|
@@ -303,6 +341,8 @@ export function createSqliteJobsStore(dbOrPath: string | Database = ':memory:'):
|
|
|
303
341
|
const q = prepareQueries(db)
|
|
304
342
|
|
|
305
343
|
const enqueueTx = db.transaction((params: EnqueueParams): EnqueueResult => {
|
|
344
|
+
if (params.key !== undefined)
|
|
345
|
+
q.releaseDedup.run(params.queue, params.key, params.now - params.dedupWindowMs)
|
|
306
346
|
const res = q.insert.run(
|
|
307
347
|
params.id,
|
|
308
348
|
params.queue,
|
|
@@ -347,6 +387,17 @@ export function createSqliteJobsStore(dbOrPath: string | Database = ':memory:'):
|
|
|
347
387
|
return q.claimSchedule.run(name, tickMs, workerId, now).changes === 1
|
|
348
388
|
})
|
|
349
389
|
|
|
390
|
+
const purgeTx = db.transaction((params: PurgeParams): number => {
|
|
391
|
+
let removed = 0
|
|
392
|
+
if (Number.isFinite(params.completedMs))
|
|
393
|
+
removed += q.purgeCompleted.run(params.now - params.completedMs).changes
|
|
394
|
+
if (Number.isFinite(params.failedMs))
|
|
395
|
+
removed += q.purgeFailed.run(params.now - params.failedMs).changes
|
|
396
|
+
if (Number.isFinite(params.scheduleRunsMs))
|
|
397
|
+
q.purgeScheduleRuns.run(params.now - params.scheduleRunsMs)
|
|
398
|
+
return removed
|
|
399
|
+
})
|
|
400
|
+
|
|
350
401
|
return {
|
|
351
402
|
db,
|
|
352
403
|
isClosed: () => closed,
|
|
@@ -361,7 +412,7 @@ export function createSqliteJobsStore(dbOrPath: string | Database = ':memory:'):
|
|
|
361
412
|
}
|
|
362
413
|
},
|
|
363
414
|
enqueue: params => enqueueTx.immediate(params),
|
|
364
|
-
claimNext: params => (params.queues.length === 0 ? undefined : claimNextTx.immediate(params)),
|
|
415
|
+
claimNext: params => (params.queues.length === 0 || !hasClaimable(db, params) ? undefined : claimNextTx.immediate(params)),
|
|
365
416
|
completeJob: (id, workerId, now) => {
|
|
366
417
|
q.complete.run(now, now, id, workerId)
|
|
367
418
|
},
|
|
@@ -388,6 +439,9 @@ export function createSqliteJobsStore(dbOrPath: string | Database = ':memory:'):
|
|
|
388
439
|
counts[row.status] = row.count
|
|
389
440
|
return counts
|
|
390
441
|
},
|
|
442
|
+
purge(params) {
|
|
443
|
+
return purgeTx.immediate(params)
|
|
444
|
+
},
|
|
391
445
|
close() {
|
|
392
446
|
if (closed)
|
|
393
447
|
return
|
package/src/types.ts
CHANGED
|
@@ -16,6 +16,8 @@ export interface QueueBaseOptions {
|
|
|
16
16
|
attempts?: number | undefined
|
|
17
17
|
/** Delay strategy between retries (`'exponential'`, `'fixed'`, or fixed ms number). Default: `'exponential'`. */
|
|
18
18
|
backoff?: BackoffStrategy | undefined
|
|
19
|
+
/** Time limit for one run, in milliseconds or a duration string (`'30s'`, `'5m'`): past it `ctx.signal` aborts and the run counts as a failed attempt. Default: none. */
|
|
20
|
+
timeout?: Duration | undefined
|
|
19
21
|
}
|
|
20
22
|
|
|
21
23
|
export interface QueueOptions<S extends StandardSchemaV1 | undefined = undefined> extends QueueBaseOptions {
|
|
@@ -26,8 +28,10 @@ export interface QueueOptions<S extends StandardSchemaV1 | undefined = undefined
|
|
|
26
28
|
export interface EnqueueOptions {
|
|
27
29
|
/** Delay before first execution, in milliseconds or duration string (`'5s'`, `'10m'`, `'2h'`, `'1d'`). */
|
|
28
30
|
delay?: Duration | undefined
|
|
29
|
-
/** Optional deduplication key (scoped per queue); re-enqueuing the same key is a no-op across restarts. */
|
|
31
|
+
/** Optional deduplication key (scoped per queue); re-enqueuing the same key while its job is pending or running is a no-op across restarts. Keep personal data out of it: it stays on the row until the finished job is purged. */
|
|
30
32
|
key?: string | undefined
|
|
33
|
+
/** Keep `key` taken for this long after its job completed or failed, so a repeat inside the window is a no-op. Default: none, the key is free once the job finishes. The key is also freed when the finished job is purged (see `retention`). */
|
|
34
|
+
dedupWindow?: Duration | undefined
|
|
31
35
|
}
|
|
32
36
|
|
|
33
37
|
export interface ScheduleOptions {
|
|
@@ -100,7 +104,8 @@ export interface DrainOptions {
|
|
|
100
104
|
}
|
|
101
105
|
|
|
102
106
|
export interface JobErrorInfo {
|
|
103
|
-
|
|
107
|
+
/** `store` is a failure of the jobs store in a background loop (`name` is `poll`, `lease`, `schedule` or `job`), not of a handler. */
|
|
108
|
+
readonly kind: 'job' | 'schedule' | 'store'
|
|
104
109
|
readonly name: string
|
|
105
110
|
readonly id?: string | undefined
|
|
106
111
|
readonly attempt?: number | undefined
|
|
@@ -108,6 +113,15 @@ export interface JobErrorInfo {
|
|
|
108
113
|
readonly error: unknown
|
|
109
114
|
}
|
|
110
115
|
|
|
116
|
+
export interface RetentionOptions {
|
|
117
|
+
/** How long a completed job's row (its payload is cleared at once) is kept. `false` keeps it forever. Default: `'1d'`. */
|
|
118
|
+
completed?: Duration | false | undefined
|
|
119
|
+
/** How long a failed job's row, payload included, is kept for inspection. `false` keeps it forever. Default: `'7d'`. */
|
|
120
|
+
failed?: Duration | false | undefined
|
|
121
|
+
/** How long a cron tick's record is kept. `false` keeps it forever. Default: `'7d'`. */
|
|
122
|
+
scheduleRuns?: Duration | false | undefined
|
|
123
|
+
}
|
|
124
|
+
|
|
111
125
|
export interface JobsOptions {
|
|
112
126
|
/** SQLite file path or existing `bun:sqlite` `Database` instance. Defaults to `':memory:'`. */
|
|
113
127
|
db?: string | Database | undefined
|
|
@@ -129,8 +143,10 @@ export interface JobsOptions {
|
|
|
129
143
|
defaultBackoff?: BackoffStrategy | undefined
|
|
130
144
|
/** Base delay in ms for `'fixed'` and `'exponential'` backoff. Default: `1000`. */
|
|
131
145
|
backoffBaseMs?: number | undefined
|
|
132
|
-
/** Maximum delay
|
|
146
|
+
/** Maximum delay in ms for any backoff strategy, before jitter. Default: `3_600_000`. */
|
|
133
147
|
maxBackoffMs?: number | undefined
|
|
148
|
+
/** How long finished jobs and cron tick records are kept before they are deleted. */
|
|
149
|
+
retention?: RetentionOptions | undefined
|
|
134
150
|
/** Automatically start background poll & schedule loops inside `server(api)`. Defaults to `true` outside `NODE_ENV=test`. */
|
|
135
151
|
autoStart?: boolean | undefined
|
|
136
152
|
/** Optional clock function returning epoch ms (defaults to `Date.now`). */
|
|
@@ -164,6 +180,8 @@ export interface Jobs extends PrunellePlugin {
|
|
|
164
180
|
get<T = unknown>(id: string): JobRecord<T> | undefined
|
|
165
181
|
list<T = unknown>(filter?: JobListFilter): JobRecord<T>[]
|
|
166
182
|
stats(): JobStats
|
|
183
|
+
/** Deletes finished jobs and cron tick records past their `retention` now, and returns how many jobs went. The worker does it by itself every minute. */
|
|
184
|
+
purge(): number
|
|
167
185
|
dispose(): Promise<void>
|
|
168
186
|
[Symbol.asyncDispose](): Promise<void>
|
|
169
187
|
}
|
|
@@ -196,22 +214,34 @@ const UNIT_MS: Record<DurationUnit, number> = {
|
|
|
196
214
|
d: 86_400_000,
|
|
197
215
|
}
|
|
198
216
|
|
|
199
|
-
export function parseDuration(value: Duration | undefined): number {
|
|
217
|
+
export function parseDuration(value: Duration | undefined, label = 'delay'): number {
|
|
200
218
|
if (value === undefined)
|
|
201
219
|
return 0
|
|
202
220
|
if (typeof value === 'number') {
|
|
203
221
|
if (!Number.isFinite(value) || value < 0)
|
|
204
|
-
throw new RangeError(`@prunellejs/jobs: invalid
|
|
222
|
+
throw new RangeError(`@prunellejs/jobs: invalid ${label} ${String(value)}: pass a non-negative finite number of milliseconds or a duration string like "5s", "10m", "2h", or "1d".`)
|
|
205
223
|
return Math.round(value)
|
|
206
224
|
}
|
|
207
225
|
const match = DURATION_RE.exec(value)
|
|
208
226
|
if (!match)
|
|
209
|
-
throw new RangeError(`@prunellejs/jobs: invalid
|
|
227
|
+
throw new RangeError(`@prunellejs/jobs: invalid ${label} "${value}": use milliseconds or a duration string like "500ms", "5s", "10m", "2h", or "1d".`)
|
|
210
228
|
const amount = Number(match[1])
|
|
211
229
|
const unit = match[2]!.toLowerCase() as DurationUnit
|
|
212
230
|
const ms = Math.round(amount * UNIT_MS[unit])
|
|
213
231
|
if (!Number.isFinite(ms) || ms < 0)
|
|
214
|
-
throw new RangeError(`@prunellejs/jobs: invalid
|
|
232
|
+
throw new RangeError(`@prunellejs/jobs: invalid ${label} "${value}": value overflows safe millisecond range.`)
|
|
233
|
+
return ms
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const MAX_TIMEOUT_MS = 2_147_483_647
|
|
237
|
+
|
|
238
|
+
/** A queue's `timeout` in milliseconds, or `undefined` when it sets none. */
|
|
239
|
+
export function normalizeTimeout(timeout: Duration | undefined): number | undefined {
|
|
240
|
+
if (timeout === undefined)
|
|
241
|
+
return undefined
|
|
242
|
+
const ms = parseDuration(timeout, 'timeout')
|
|
243
|
+
if (ms < 1 || ms > MAX_TIMEOUT_MS)
|
|
244
|
+
throw new RangeError(`@prunellejs/jobs: invalid timeout ${JSON.stringify(timeout)}: pass a duration from 1 ms to 24 days, or leave timeout out for no limit.`)
|
|
215
245
|
return ms
|
|
216
246
|
}
|
|
217
247
|
|
|
@@ -234,21 +264,34 @@ export function normalizeBackoff(backoff: BackoffStrategy | undefined, fallback:
|
|
|
234
264
|
return resolved
|
|
235
265
|
}
|
|
236
266
|
|
|
267
|
+
const DEFAULT_RETENTION: Required<RetentionOptions> = { completed: '1d', failed: '7d', scheduleRuns: '7d' }
|
|
268
|
+
|
|
269
|
+
/** The retention of each kind of finished row in milliseconds, `Infinity` for one kept forever. */
|
|
270
|
+
export function normalizeRetention(retention: RetentionOptions | undefined): { completed: number, failed: number, scheduleRuns: number } {
|
|
271
|
+
const resolve = (key: keyof RetentionOptions): number => {
|
|
272
|
+
const value = retention?.[key] ?? DEFAULT_RETENTION[key]
|
|
273
|
+
return value === false ? Number.POSITIVE_INFINITY : parseDuration(value, `retention.${key}`)
|
|
274
|
+
}
|
|
275
|
+
return { completed: resolve('completed'), failed: resolve('failed'), scheduleRuns: resolve('scheduleRuns') }
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Every strategy is capped at maxMs, then spread over its upper half so retries of one outage do not land together.
|
|
237
279
|
export function computeBackoffDelay(
|
|
238
280
|
strategy: BackoffStrategy,
|
|
239
281
|
failedAttempt: number,
|
|
240
282
|
baseMs: number,
|
|
241
283
|
maxMs: number,
|
|
284
|
+
random: () => number = Math.random,
|
|
242
285
|
): number {
|
|
286
|
+
let raw: number
|
|
243
287
|
if (typeof strategy === 'number')
|
|
244
|
-
|
|
245
|
-
if (strategy === 'fixed')
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
return Math.min(maxMs, Math.max(0, Math.round(raw)))
|
|
288
|
+
raw = strategy
|
|
289
|
+
else if (strategy === 'fixed')
|
|
290
|
+
raw = baseMs
|
|
291
|
+
else
|
|
292
|
+
raw = baseMs * (2 ** Math.max(0, failedAttempt - 1))
|
|
293
|
+
const capped = Number.isFinite(raw) ? Math.min(maxMs, Math.max(0, raw)) : maxMs
|
|
294
|
+
return Math.round(capped * (0.5 + random() * 0.5))
|
|
252
295
|
}
|
|
253
296
|
|
|
254
297
|
export function isStandardSchema(value: unknown): value is StandardSchemaV1 {
|