@prunellejs/jobs 0.7.3 → 0.7.7
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 +1 -0
- package/package.json +2 -2
- package/src/cron.ts +3 -2
- package/src/index.ts +2 -1
- package/src/runner.ts +29 -4
- package/src/types.ts +18 -4
package/llms.txt
CHANGED
|
@@ -31,6 +31,7 @@
|
|
|
31
31
|
- Standard Schema (Zod, Valibot, ArkType, etc.), both forms supported with full static input inference and runtime validation on `enqueue()` and execution:
|
|
32
32
|
- `jobs.queue('emails', emailSchema, (data, ctx) => { ... }, { attempts: 5, backoff: 'exponential' })`
|
|
33
33
|
- `jobs.queue('emails', (data, ctx) => { ... }, { schema: emailSchema, attempts: 5, backoff: 'fixed' })`
|
|
34
|
+
- `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.
|
|
34
35
|
- Invalid payloads throw `JobValidationError` (with `.issues` and `.fieldErrors`).
|
|
35
36
|
- `await jobs.enqueue(name, data, { delay, key })`:
|
|
36
37
|
- `delay`: milliseconds or duration string (`'500ms'`, `'5s'`, `'10m'`, `'2h'`, `'1d'`).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/jobs",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.7",
|
|
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.7.
|
|
24
|
+
"prunelle": "^0.7.7"
|
|
25
25
|
}
|
|
26
26
|
}
|
package/src/cron.ts
CHANGED
|
@@ -199,13 +199,14 @@ function parseFieldSegment(segment: string, spec: FieldSpec, expr: string, out:
|
|
|
199
199
|
throw new RangeError(`@prunellejs/jobs: invalid cron expression "${expr}": malformed ${spec.label} range "${segment}".`)
|
|
200
200
|
|
|
201
201
|
if (dashParts.length === 1) {
|
|
202
|
-
const
|
|
202
|
+
const rawStart = parseAtom(dashParts[0]!, spec, expr)
|
|
203
|
+
const start = wrapSeven && rawStart === 7 ? 0 : rawStart
|
|
203
204
|
if (slashParts.length === 2) {
|
|
204
205
|
const end = wrapSeven ? 6 : spec.max
|
|
205
206
|
addRange(out, start, end, step, wrapSeven)
|
|
206
207
|
}
|
|
207
208
|
else {
|
|
208
|
-
out.add(
|
|
209
|
+
out.add(start)
|
|
209
210
|
}
|
|
210
211
|
return
|
|
211
212
|
}
|
package/src/index.ts
CHANGED
|
@@ -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, normalizeTimeout } from './types'
|
|
29
29
|
|
|
30
30
|
export { assertValidTimeZone, floorToMinute, getZonedParts, matchesCron, nextCronTick, parseCron } from './cron'
|
|
31
31
|
export type { ParsedCron, ZonedDateParts } from './cron'
|
|
@@ -243,6 +243,7 @@ export function createJobs(options: JobsOptions = {}): Jobs {
|
|
|
243
243
|
handler,
|
|
244
244
|
attempts: normalizeAttempts(qOpts?.attempts, defaultAttempts),
|
|
245
245
|
backoff: normalizeBackoff(qOpts?.backoff, defaultBackoff),
|
|
246
|
+
timeoutMs: normalizeTimeout(qOpts?.timeout),
|
|
246
247
|
...(schema !== undefined ? { schema } : {}),
|
|
247
248
|
})
|
|
248
249
|
return instance
|
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
|
|
|
@@ -159,6 +160,30 @@ async function validatePayload(queueName: string, schema: StandardSchemaV1, data
|
|
|
159
160
|
return result.value
|
|
160
161
|
}
|
|
161
162
|
|
|
163
|
+
// Runs the handler; past the queue's timeout it aborts ctx.signal and rejects, though a handler that ignores the signal keeps running unwatched.
|
|
164
|
+
async function runHandler(def: RegisteredQueue, input: unknown, ctx: Omit<JobContext, 'signal'>, shutdown: AbortSignal): Promise<void> {
|
|
165
|
+
const timeoutMs = def.timeoutMs
|
|
166
|
+
if (timeoutMs === undefined) {
|
|
167
|
+
await def.handler(input, { ...ctx, signal: shutdown })
|
|
168
|
+
return
|
|
169
|
+
}
|
|
170
|
+
const limit = new AbortController()
|
|
171
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
172
|
+
const timedOut = new Promise<never>((_, reject) => {
|
|
173
|
+
timer = setTimeout(() => {
|
|
174
|
+
const err = new Error(`@prunellejs/jobs: the run of queue "${def.name}" passed its timeout of ${timeoutMs}ms.`)
|
|
175
|
+
limit.abort(err)
|
|
176
|
+
reject(err)
|
|
177
|
+
}, timeoutMs)
|
|
178
|
+
})
|
|
179
|
+
try {
|
|
180
|
+
await Promise.race([(async () => def.handler(input, { ...ctx, signal: AbortSignal.any([shutdown, limit.signal]) }))(), timedOut])
|
|
181
|
+
}
|
|
182
|
+
finally {
|
|
183
|
+
clearTimeout(timer)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
162
187
|
async function executeClaimedJob(state: RuntimeState, job: ClaimedJob, nowFn: () => number): Promise<void> {
|
|
163
188
|
const { cfg, workerId } = state
|
|
164
189
|
const def = getQueue(state, job.queue)
|
|
@@ -180,17 +205,16 @@ async function executeClaimedJob(state: RuntimeState, job: ClaimedJob, nowFn: ()
|
|
|
180
205
|
return
|
|
181
206
|
}
|
|
182
207
|
|
|
183
|
-
const ctx: JobContext = {
|
|
208
|
+
const ctx: Omit<JobContext, 'signal'> = {
|
|
184
209
|
id: job.id,
|
|
185
210
|
queue: job.queue,
|
|
186
211
|
attempt: job.attempts,
|
|
187
212
|
maxAttempts: job.maxAttempts,
|
|
188
213
|
...(job.key !== undefined ? { key: job.key } : {}),
|
|
189
|
-
signal: state.abortController.signal,
|
|
190
214
|
}
|
|
191
215
|
|
|
192
216
|
try {
|
|
193
|
-
await def
|
|
217
|
+
await runHandler(def, input, ctx, state.abortController.signal)
|
|
194
218
|
if (!state.releasedOnShutdown && !cfg.store.isClosed())
|
|
195
219
|
cfg.store.completeJob(job.id, workerId, nowFn())
|
|
196
220
|
}
|
|
@@ -443,6 +467,7 @@ export function createJobsRuntime(cfg: JobsRuntimeConfig): JobsRuntime {
|
|
|
443
467
|
handler: handler as JobHandler<unknown>,
|
|
444
468
|
attempts: normalizeAttempts(options?.attempts, cfg.defaultAttempts),
|
|
445
469
|
backoff: normalizeBackoff(options?.backoff, cfg.defaultBackoff),
|
|
470
|
+
timeoutMs: normalizeTimeout(options?.timeout),
|
|
446
471
|
})
|
|
447
472
|
},
|
|
448
473
|
async enqueue<T = unknown>(name: string, data: T, options?: JobsEnqueueOptions) {
|
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 {
|
|
@@ -196,22 +198,34 @@ const UNIT_MS: Record<DurationUnit, number> = {
|
|
|
196
198
|
d: 86_400_000,
|
|
197
199
|
}
|
|
198
200
|
|
|
199
|
-
export function parseDuration(value: Duration | undefined): number {
|
|
201
|
+
export function parseDuration(value: Duration | undefined, label = 'delay'): number {
|
|
200
202
|
if (value === undefined)
|
|
201
203
|
return 0
|
|
202
204
|
if (typeof value === 'number') {
|
|
203
205
|
if (!Number.isFinite(value) || value < 0)
|
|
204
|
-
throw new RangeError(`@prunellejs/jobs: invalid
|
|
206
|
+
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
207
|
return Math.round(value)
|
|
206
208
|
}
|
|
207
209
|
const match = DURATION_RE.exec(value)
|
|
208
210
|
if (!match)
|
|
209
|
-
throw new RangeError(`@prunellejs/jobs: invalid
|
|
211
|
+
throw new RangeError(`@prunellejs/jobs: invalid ${label} "${value}": use milliseconds or a duration string like "500ms", "5s", "10m", "2h", or "1d".`)
|
|
210
212
|
const amount = Number(match[1])
|
|
211
213
|
const unit = match[2]!.toLowerCase() as DurationUnit
|
|
212
214
|
const ms = Math.round(amount * UNIT_MS[unit])
|
|
213
215
|
if (!Number.isFinite(ms) || ms < 0)
|
|
214
|
-
throw new RangeError(`@prunellejs/jobs: invalid
|
|
216
|
+
throw new RangeError(`@prunellejs/jobs: invalid ${label} "${value}": value overflows safe millisecond range.`)
|
|
217
|
+
return ms
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const MAX_TIMEOUT_MS = 2_147_483_647
|
|
221
|
+
|
|
222
|
+
/** A queue's `timeout` in milliseconds, or `undefined` when it sets none. */
|
|
223
|
+
export function normalizeTimeout(timeout: Duration | undefined): number | undefined {
|
|
224
|
+
if (timeout === undefined)
|
|
225
|
+
return undefined
|
|
226
|
+
const ms = parseDuration(timeout, 'timeout')
|
|
227
|
+
if (ms < 1 || ms > MAX_TIMEOUT_MS)
|
|
228
|
+
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
229
|
return ms
|
|
216
230
|
}
|
|
217
231
|
|