@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/LICENSE +21 -0
- package/llms.txt +76 -0
- package/package.json +24 -4
- package/src/cron.ts +321 -0
- package/src/index.ts +291 -0
- package/src/runner.ts +473 -0
- package/src/store.ts +399 -0
- package/src/types.ts +260 -0
- package/README.md +0 -3
package/src/store.ts
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
// Durable bun:sqlite store for @prunellejs/jobs (WAL, busy_timeout, BEGIN IMMEDIATE leases, dedup keys, schedule ticks).
|
|
2
|
+
|
|
3
|
+
import type { EnqueueResult, JobListFilter, JobRecord, JobStats, JobStatus } from './types'
|
|
4
|
+
import { mkdirSync } from 'node:fs'
|
|
5
|
+
import { dirname } from 'node:path'
|
|
6
|
+
import { Database } from 'bun:sqlite'
|
|
7
|
+
|
|
8
|
+
interface JobRow {
|
|
9
|
+
id: string
|
|
10
|
+
queue: string
|
|
11
|
+
payload: string
|
|
12
|
+
dedup_key: string | null
|
|
13
|
+
status: JobStatus
|
|
14
|
+
attempts: number
|
|
15
|
+
max_attempts: number
|
|
16
|
+
run_at: number
|
|
17
|
+
lease_owner: string | null
|
|
18
|
+
lease_expires_at: number | null
|
|
19
|
+
last_error: string | null
|
|
20
|
+
created_at: number
|
|
21
|
+
updated_at: number
|
|
22
|
+
completed_at: number | null
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface ExistingDedupRow {
|
|
26
|
+
id: string
|
|
27
|
+
run_at: number
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface StatusCountRow {
|
|
31
|
+
status: JobStatus
|
|
32
|
+
count: number
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface ClaimedJob {
|
|
36
|
+
readonly id: string
|
|
37
|
+
readonly queue: string
|
|
38
|
+
readonly payload: string
|
|
39
|
+
readonly key?: string | undefined
|
|
40
|
+
readonly attempts: number
|
|
41
|
+
readonly maxAttempts: number
|
|
42
|
+
readonly runAt: number
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface ClaimNextParams {
|
|
46
|
+
readonly queues: readonly string[]
|
|
47
|
+
readonly workerId: string
|
|
48
|
+
readonly now: number
|
|
49
|
+
readonly leaseMs: number
|
|
50
|
+
readonly includeDelayed: boolean
|
|
51
|
+
readonly resolveMaxAttempts: (queue: string, currentMax: number) => number
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface EnqueueParams {
|
|
55
|
+
readonly id: string
|
|
56
|
+
readonly queue: string
|
|
57
|
+
readonly payload: string
|
|
58
|
+
readonly key: string | undefined
|
|
59
|
+
readonly maxAttempts: number
|
|
60
|
+
readonly runAt: number
|
|
61
|
+
readonly now: number
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface JobsStore {
|
|
65
|
+
readonly db: Database
|
|
66
|
+
isClosed(): boolean
|
|
67
|
+
ping(): boolean
|
|
68
|
+
enqueue(params: EnqueueParams): EnqueueResult
|
|
69
|
+
claimNext(params: ClaimNextParams): ClaimedJob | undefined
|
|
70
|
+
completeJob(id: string, workerId: string, now: number): void
|
|
71
|
+
rescheduleJob(id: string, workerId: string, nextRunAt: number, errorMessage: string, now: number): void
|
|
72
|
+
failJob(id: string, workerId: string, errorMessage: string, now: number): void
|
|
73
|
+
renewOwnerLeases(workerId: string, leaseExpiresAt: number, now: number): number
|
|
74
|
+
releaseOwnerJobs(workerId: string, now: number): number
|
|
75
|
+
claimScheduleTick(scheduleName: string, tickMs: number, workerId: string, now: number): boolean
|
|
76
|
+
finishScheduleTick(scheduleName: string, tickMs: number, status: 'completed' | 'failed', errorMessage: string | undefined, now: number): void
|
|
77
|
+
getJob<T = unknown>(id: string): JobRecord<T> | undefined
|
|
78
|
+
listJobs<T = unknown>(filter?: JobListFilter): JobRecord<T>[]
|
|
79
|
+
stats(): JobStats
|
|
80
|
+
close(): void
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function isInMemoryDb(dbOrPath: string | Database | undefined): boolean {
|
|
84
|
+
if (dbOrPath === undefined)
|
|
85
|
+
return true
|
|
86
|
+
if (typeof dbOrPath === 'string') {
|
|
87
|
+
const trimmed = dbOrPath.trim()
|
|
88
|
+
return trimmed === '' || trimmed === ':memory:' || /(?:^|[?&])mode=memory(?:&|$)/i.test(trimmed)
|
|
89
|
+
}
|
|
90
|
+
return dbOrPath.filename === '' || dbOrPath.filename === ':memory:'
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function createSchema(db: Database): void {
|
|
94
|
+
db.exec(`
|
|
95
|
+
PRAGMA busy_timeout = 5000;
|
|
96
|
+
PRAGMA journal_mode = WAL;
|
|
97
|
+
PRAGMA synchronous = NORMAL;
|
|
98
|
+
`)
|
|
99
|
+
db.exec(`
|
|
100
|
+
CREATE TABLE IF NOT EXISTS prunelle_jobs (
|
|
101
|
+
id TEXT PRIMARY KEY,
|
|
102
|
+
queue TEXT NOT NULL,
|
|
103
|
+
payload TEXT NOT NULL,
|
|
104
|
+
dedup_key TEXT,
|
|
105
|
+
status TEXT NOT NULL DEFAULT 'pending',
|
|
106
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
107
|
+
max_attempts INTEGER NOT NULL DEFAULT 3,
|
|
108
|
+
run_at INTEGER NOT NULL,
|
|
109
|
+
lease_owner TEXT,
|
|
110
|
+
lease_expires_at INTEGER,
|
|
111
|
+
last_error TEXT,
|
|
112
|
+
created_at INTEGER NOT NULL,
|
|
113
|
+
updated_at INTEGER NOT NULL,
|
|
114
|
+
completed_at INTEGER
|
|
115
|
+
);
|
|
116
|
+
|
|
117
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_prunelle_jobs_dedup
|
|
118
|
+
ON prunelle_jobs(queue, dedup_key)
|
|
119
|
+
WHERE dedup_key IS NOT NULL;
|
|
120
|
+
|
|
121
|
+
CREATE INDEX IF NOT EXISTS idx_prunelle_jobs_due
|
|
122
|
+
ON prunelle_jobs(status, run_at, created_at);
|
|
123
|
+
|
|
124
|
+
CREATE INDEX IF NOT EXISTS idx_prunelle_jobs_lease
|
|
125
|
+
ON prunelle_jobs(status, lease_expires_at);
|
|
126
|
+
|
|
127
|
+
CREATE TABLE IF NOT EXISTS prunelle_job_schedule_runs (
|
|
128
|
+
schedule_name TEXT NOT NULL,
|
|
129
|
+
tick_ms INTEGER NOT NULL,
|
|
130
|
+
worker_id TEXT NOT NULL,
|
|
131
|
+
status TEXT NOT NULL DEFAULT 'running',
|
|
132
|
+
started_at INTEGER NOT NULL,
|
|
133
|
+
finished_at INTEGER,
|
|
134
|
+
last_error TEXT,
|
|
135
|
+
PRIMARY KEY (schedule_name, tick_ms)
|
|
136
|
+
);
|
|
137
|
+
`)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function rowToRecord<T>(row: JobRow): JobRecord<T> {
|
|
141
|
+
return {
|
|
142
|
+
id: row.id,
|
|
143
|
+
queue: row.queue,
|
|
144
|
+
data: JSON.parse(row.payload) as T,
|
|
145
|
+
status: row.status,
|
|
146
|
+
attempts: row.attempts,
|
|
147
|
+
maxAttempts: row.max_attempts,
|
|
148
|
+
runAt: row.run_at,
|
|
149
|
+
createdAt: row.created_at,
|
|
150
|
+
updatedAt: row.updated_at,
|
|
151
|
+
...(row.completed_at !== null ? { completedAt: row.completed_at } : {}),
|
|
152
|
+
...(row.last_error !== null ? { lastError: row.last_error } : {}),
|
|
153
|
+
...(row.dedup_key !== null ? { key: row.dedup_key } : {}),
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function prepareQueries(db: Database) {
|
|
158
|
+
return {
|
|
159
|
+
insert: db.query<null, [string, string, string, string | null, number, number, number, number]>(
|
|
160
|
+
`INSERT OR IGNORE INTO prunelle_jobs
|
|
161
|
+
(id, queue, payload, dedup_key, status, attempts, max_attempts, run_at, created_at, updated_at)
|
|
162
|
+
VALUES (?, ?, ?, ?, 'pending', 0, ?, ?, ?, ?)`,
|
|
163
|
+
),
|
|
164
|
+
findDedup: db.query<ExistingDedupRow, [string, string]>(
|
|
165
|
+
'SELECT id, run_at FROM prunelle_jobs WHERE queue = ? AND dedup_key = ?',
|
|
166
|
+
),
|
|
167
|
+
expireExhausted: db.query<null, [number, number]>(
|
|
168
|
+
`UPDATE prunelle_jobs
|
|
169
|
+
SET status = 'failed',
|
|
170
|
+
lease_owner = NULL,
|
|
171
|
+
lease_expires_at = NULL,
|
|
172
|
+
last_error = COALESCE(last_error, 'Job lease expired after max attempts'),
|
|
173
|
+
updated_at = ?
|
|
174
|
+
WHERE status = 'running'
|
|
175
|
+
AND lease_expires_at IS NOT NULL
|
|
176
|
+
AND lease_expires_at <= ?
|
|
177
|
+
AND attempts >= max_attempts`,
|
|
178
|
+
),
|
|
179
|
+
claimUpdate: db.query<null, [number, string, number, number, string]>(
|
|
180
|
+
`UPDATE prunelle_jobs
|
|
181
|
+
SET status = 'running',
|
|
182
|
+
attempts = attempts + 1,
|
|
183
|
+
max_attempts = ?,
|
|
184
|
+
lease_owner = ?,
|
|
185
|
+
lease_expires_at = ?,
|
|
186
|
+
updated_at = ?
|
|
187
|
+
WHERE id = ?`,
|
|
188
|
+
),
|
|
189
|
+
complete: db.query<null, [number, number, string, string]>(
|
|
190
|
+
`UPDATE prunelle_jobs
|
|
191
|
+
SET status = 'completed',
|
|
192
|
+
lease_owner = NULL,
|
|
193
|
+
lease_expires_at = NULL,
|
|
194
|
+
completed_at = ?,
|
|
195
|
+
updated_at = ?
|
|
196
|
+
WHERE id = ? AND lease_owner = ?`,
|
|
197
|
+
),
|
|
198
|
+
reschedule: db.query<null, [number, string, number, string, string]>(
|
|
199
|
+
`UPDATE prunelle_jobs
|
|
200
|
+
SET status = 'pending',
|
|
201
|
+
run_at = ?,
|
|
202
|
+
last_error = ?,
|
|
203
|
+
lease_owner = NULL,
|
|
204
|
+
lease_expires_at = NULL,
|
|
205
|
+
updated_at = ?
|
|
206
|
+
WHERE id = ? AND lease_owner = ?`,
|
|
207
|
+
),
|
|
208
|
+
fail: db.query<null, [string, number, string, string]>(
|
|
209
|
+
`UPDATE prunelle_jobs
|
|
210
|
+
SET status = 'failed',
|
|
211
|
+
last_error = ?,
|
|
212
|
+
lease_owner = NULL,
|
|
213
|
+
lease_expires_at = NULL,
|
|
214
|
+
updated_at = ?
|
|
215
|
+
WHERE id = ? AND lease_owner = ?`,
|
|
216
|
+
),
|
|
217
|
+
renewOwnerLeases: db.query<null, [number, number, string]>(
|
|
218
|
+
`UPDATE prunelle_jobs
|
|
219
|
+
SET lease_expires_at = ?,
|
|
220
|
+
updated_at = ?
|
|
221
|
+
WHERE status = 'running' AND lease_owner = ?`,
|
|
222
|
+
),
|
|
223
|
+
releaseOwner: db.query<null, [number, string]>(
|
|
224
|
+
`UPDATE prunelle_jobs
|
|
225
|
+
SET status = 'pending',
|
|
226
|
+
attempts = CASE WHEN attempts > 0 THEN attempts - 1 ELSE 0 END,
|
|
227
|
+
lease_owner = NULL,
|
|
228
|
+
lease_expires_at = NULL,
|
|
229
|
+
updated_at = ?
|
|
230
|
+
WHERE status = 'running' AND lease_owner = ?`,
|
|
231
|
+
),
|
|
232
|
+
claimSchedule: db.query<null, [string, number, string, number]>(
|
|
233
|
+
`INSERT OR IGNORE INTO prunelle_job_schedule_runs
|
|
234
|
+
(schedule_name, tick_ms, worker_id, status, started_at)
|
|
235
|
+
VALUES (?, ?, ?, 'running', ?)`,
|
|
236
|
+
),
|
|
237
|
+
finishSchedule: db.query<null, [string, number, string | null, string, number]>(
|
|
238
|
+
`UPDATE prunelle_job_schedule_runs
|
|
239
|
+
SET status = ?, finished_at = ?, last_error = ?
|
|
240
|
+
WHERE schedule_name = ? AND tick_ms = ?`,
|
|
241
|
+
),
|
|
242
|
+
getById: db.query<JobRow, [string]>('SELECT * FROM prunelle_jobs WHERE id = ?'),
|
|
243
|
+
stats: db.query<StatusCountRow, []>('SELECT status, COUNT(*) AS count FROM prunelle_jobs GROUP BY status'),
|
|
244
|
+
ping: db.query<{ ok: number }, []>('SELECT 1 AS ok'),
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function buildClaimQuery(queues: readonly string[], now: number, includeDelayed: boolean): { sql: string, params: Array<string | number> } {
|
|
249
|
+
const placeholders = queues.map(() => '?').join(', ')
|
|
250
|
+
if (includeDelayed) {
|
|
251
|
+
return {
|
|
252
|
+
sql: `SELECT * FROM prunelle_jobs
|
|
253
|
+
WHERE queue IN (${placeholders})
|
|
254
|
+
AND (
|
|
255
|
+
status = 'pending'
|
|
256
|
+
OR (status = 'running' AND lease_expires_at IS NOT NULL AND lease_expires_at <= ? AND attempts < max_attempts)
|
|
257
|
+
)
|
|
258
|
+
ORDER BY run_at ASC, created_at ASC
|
|
259
|
+
LIMIT 1`,
|
|
260
|
+
params: [...queues, now],
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
return {
|
|
264
|
+
sql: `SELECT * FROM prunelle_jobs
|
|
265
|
+
WHERE queue IN (${placeholders})
|
|
266
|
+
AND (
|
|
267
|
+
(status = 'pending' AND run_at <= ?)
|
|
268
|
+
OR (status = 'running' AND lease_expires_at IS NOT NULL AND lease_expires_at <= ? AND attempts < max_attempts)
|
|
269
|
+
)
|
|
270
|
+
ORDER BY run_at ASC, created_at ASC
|
|
271
|
+
LIMIT 1`,
|
|
272
|
+
params: [...queues, now, now],
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function listJobsFromDb<T>(db: Database, filter?: JobListFilter): JobRecord<T>[] {
|
|
277
|
+
const clauses: string[] = []
|
|
278
|
+
const values: Array<string | number> = []
|
|
279
|
+
if (filter?.queue !== undefined) {
|
|
280
|
+
clauses.push('queue = ?')
|
|
281
|
+
values.push(filter.queue)
|
|
282
|
+
}
|
|
283
|
+
if (filter?.status !== undefined) {
|
|
284
|
+
clauses.push('status = ?')
|
|
285
|
+
values.push(filter.status)
|
|
286
|
+
}
|
|
287
|
+
const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : ''
|
|
288
|
+
values.push(filter?.limit ?? 100)
|
|
289
|
+
const rows = db.query<JobRow, Array<string | number>>(
|
|
290
|
+
`SELECT * FROM prunelle_jobs ${where} ORDER BY created_at ASC LIMIT ?`,
|
|
291
|
+
).all(...values)
|
|
292
|
+
return rows.map(row => rowToRecord<T>(row))
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
export function createSqliteJobsStore(dbOrPath: string | Database = ':memory:'): JobsStore {
|
|
296
|
+
const ownsDb = typeof dbOrPath === 'string'
|
|
297
|
+
if (ownsDb && !isInMemoryDb(dbOrPath) && !dbOrPath.startsWith('file:'))
|
|
298
|
+
mkdirSync(dirname(dbOrPath), { recursive: true })
|
|
299
|
+
const db = ownsDb ? new Database(dbOrPath, { create: true }) : dbOrPath
|
|
300
|
+
let closed = false
|
|
301
|
+
|
|
302
|
+
createSchema(db)
|
|
303
|
+
const q = prepareQueries(db)
|
|
304
|
+
|
|
305
|
+
const enqueueTx = db.transaction((params: EnqueueParams): EnqueueResult => {
|
|
306
|
+
const res = q.insert.run(
|
|
307
|
+
params.id,
|
|
308
|
+
params.queue,
|
|
309
|
+
params.payload,
|
|
310
|
+
params.key ?? null,
|
|
311
|
+
params.maxAttempts,
|
|
312
|
+
params.runAt,
|
|
313
|
+
params.now,
|
|
314
|
+
params.now,
|
|
315
|
+
)
|
|
316
|
+
if (res.changes === 1)
|
|
317
|
+
return { id: params.id, queue: params.queue, runAt: params.runAt, deduplicated: false }
|
|
318
|
+
if (params.key !== undefined) {
|
|
319
|
+
const existing = q.findDedup.get(params.queue, params.key)
|
|
320
|
+
if (existing)
|
|
321
|
+
return { id: existing.id, queue: params.queue, runAt: existing.run_at, deduplicated: true }
|
|
322
|
+
}
|
|
323
|
+
return { id: params.id, queue: params.queue, runAt: params.runAt, deduplicated: true }
|
|
324
|
+
})
|
|
325
|
+
|
|
326
|
+
const claimNextTx = db.transaction((params: ClaimNextParams): ClaimedJob | undefined => {
|
|
327
|
+
q.expireExhausted.run(params.now, params.now)
|
|
328
|
+
const { sql, params: bindParams } = buildClaimQuery(params.queues, params.now, params.includeDelayed)
|
|
329
|
+
const row = db.query<JobRow, Array<string | number>>(sql).get(...bindParams)
|
|
330
|
+
if (!row)
|
|
331
|
+
return undefined
|
|
332
|
+
|
|
333
|
+
const maxAttempts = params.resolveMaxAttempts(row.queue, row.max_attempts)
|
|
334
|
+
q.claimUpdate.run(maxAttempts, params.workerId, params.now + params.leaseMs, params.now, row.id)
|
|
335
|
+
return {
|
|
336
|
+
id: row.id,
|
|
337
|
+
queue: row.queue,
|
|
338
|
+
payload: row.payload,
|
|
339
|
+
...(row.dedup_key !== null ? { key: row.dedup_key } : {}),
|
|
340
|
+
attempts: row.attempts + 1,
|
|
341
|
+
maxAttempts,
|
|
342
|
+
runAt: row.run_at,
|
|
343
|
+
}
|
|
344
|
+
})
|
|
345
|
+
|
|
346
|
+
const claimScheduleTx = db.transaction((name: string, tickMs: number, workerId: string, now: number): boolean => {
|
|
347
|
+
return q.claimSchedule.run(name, tickMs, workerId, now).changes === 1
|
|
348
|
+
})
|
|
349
|
+
|
|
350
|
+
return {
|
|
351
|
+
db,
|
|
352
|
+
isClosed: () => closed,
|
|
353
|
+
ping() {
|
|
354
|
+
if (closed)
|
|
355
|
+
return false
|
|
356
|
+
try {
|
|
357
|
+
return q.ping.get()?.ok === 1
|
|
358
|
+
}
|
|
359
|
+
catch {
|
|
360
|
+
return false
|
|
361
|
+
}
|
|
362
|
+
},
|
|
363
|
+
enqueue: params => enqueueTx.immediate(params),
|
|
364
|
+
claimNext: params => (params.queues.length === 0 ? undefined : claimNextTx.immediate(params)),
|
|
365
|
+
completeJob: (id, workerId, now) => {
|
|
366
|
+
q.complete.run(now, now, id, workerId)
|
|
367
|
+
},
|
|
368
|
+
rescheduleJob: (id, workerId, nextRunAt, errorMessage, now) => {
|
|
369
|
+
q.reschedule.run(nextRunAt, errorMessage, now, id, workerId)
|
|
370
|
+
},
|
|
371
|
+
failJob: (id, workerId, errorMessage, now) => {
|
|
372
|
+
q.fail.run(errorMessage, now, id, workerId)
|
|
373
|
+
},
|
|
374
|
+
renewOwnerLeases: (workerId, leaseExpiresAt, now) => q.renewOwnerLeases.run(leaseExpiresAt, now, workerId).changes,
|
|
375
|
+
releaseOwnerJobs: (workerId, now) => q.releaseOwner.run(now, workerId).changes,
|
|
376
|
+
claimScheduleTick: (name, tickMs, workerId, now) => claimScheduleTx.immediate(name, tickMs, workerId, now),
|
|
377
|
+
finishScheduleTick: (name, tickMs, status, errorMessage, now) => {
|
|
378
|
+
q.finishSchedule.run(status, now, errorMessage ?? null, name, tickMs)
|
|
379
|
+
},
|
|
380
|
+
getJob<T = unknown>(id: string): JobRecord<T> | undefined {
|
|
381
|
+
const row = q.getById.get(id)
|
|
382
|
+
return row ? rowToRecord<T>(row) : undefined
|
|
383
|
+
},
|
|
384
|
+
listJobs: <T = unknown>(filter?: JobListFilter) => listJobsFromDb<T>(db, filter),
|
|
385
|
+
stats(): JobStats {
|
|
386
|
+
const counts = { pending: 0, running: 0, completed: 0, failed: 0 }
|
|
387
|
+
for (const row of q.stats.all())
|
|
388
|
+
counts[row.status] = row.count
|
|
389
|
+
return counts
|
|
390
|
+
},
|
|
391
|
+
close() {
|
|
392
|
+
if (closed)
|
|
393
|
+
return
|
|
394
|
+
closed = true
|
|
395
|
+
if (ownsDb)
|
|
396
|
+
db.close()
|
|
397
|
+
},
|
|
398
|
+
}
|
|
399
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
// Public types, error classes, duration parsing, and retry backoff helpers for @prunellejs/jobs.
|
|
2
|
+
|
|
3
|
+
import type { Database } from 'bun:sqlite'
|
|
4
|
+
import type { PrunellePlugin, ServiceKey } from 'prunelle/config'
|
|
5
|
+
import type { InferOutput, StandardSchemaIssue, StandardSchemaV1 } from 'prunelle/server'
|
|
6
|
+
|
|
7
|
+
export type DurationUnit = 'ms' | 's' | 'm' | 'h' | 'd'
|
|
8
|
+
export type DurationString = `${number}${DurationUnit}`
|
|
9
|
+
export type Duration = number | DurationString
|
|
10
|
+
|
|
11
|
+
export type BackoffStrategy = 'exponential' | 'fixed' | number
|
|
12
|
+
export type JobStatus = 'pending' | 'running' | 'completed' | 'failed'
|
|
13
|
+
|
|
14
|
+
export interface QueueBaseOptions {
|
|
15
|
+
/** Max total execution attempts before marking the job as failed. Default: `3`. */
|
|
16
|
+
attempts?: number | undefined
|
|
17
|
+
/** Delay strategy between retries (`'exponential'`, `'fixed'`, or fixed ms number). Default: `'exponential'`. */
|
|
18
|
+
backoff?: BackoffStrategy | undefined
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface QueueOptions<S extends StandardSchemaV1 | undefined = undefined> extends QueueBaseOptions {
|
|
22
|
+
/** Optional Standard Schema v1 validator for runtime-checked and statically-typed payloads. */
|
|
23
|
+
schema?: S | undefined
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface EnqueueOptions {
|
|
27
|
+
/** Delay before first execution, in milliseconds or duration string (`'5s'`, `'10m'`, `'2h'`, `'1d'`). */
|
|
28
|
+
delay?: Duration | undefined
|
|
29
|
+
/** Optional deduplication key (scoped per queue); re-enqueuing the same key is a no-op across restarts. */
|
|
30
|
+
key?: string | undefined
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface ScheduleOptions {
|
|
34
|
+
/** IANA timezone used to evaluate the cron expression (e.g. `'Europe/Paris'`, `'America/New_York'`). Default: `'UTC'`. */
|
|
35
|
+
timeZone?: string | undefined
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface JobContext {
|
|
39
|
+
readonly id: string
|
|
40
|
+
readonly queue: string
|
|
41
|
+
readonly attempt: number
|
|
42
|
+
readonly maxAttempts: number
|
|
43
|
+
readonly key?: string | undefined
|
|
44
|
+
readonly signal: AbortSignal
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface ScheduleContext {
|
|
48
|
+
readonly name: string
|
|
49
|
+
readonly scheduledAt: Date
|
|
50
|
+
readonly tickMs: number
|
|
51
|
+
readonly timeZone: string
|
|
52
|
+
readonly signal: AbortSignal
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export type JobHandler<T = unknown> = (data: T, ctx: JobContext) => void | Promise<void>
|
|
56
|
+
export type ScheduleHandler = (ctx: ScheduleContext) => void | Promise<void>
|
|
57
|
+
|
|
58
|
+
export interface JobRecord<T = unknown> {
|
|
59
|
+
readonly id: string
|
|
60
|
+
readonly queue: string
|
|
61
|
+
readonly data: T
|
|
62
|
+
readonly status: JobStatus
|
|
63
|
+
readonly attempts: number
|
|
64
|
+
readonly maxAttempts: number
|
|
65
|
+
readonly runAt: number
|
|
66
|
+
readonly createdAt: number
|
|
67
|
+
readonly updatedAt: number
|
|
68
|
+
readonly completedAt?: number | undefined
|
|
69
|
+
readonly lastError?: string | undefined
|
|
70
|
+
readonly key?: string | undefined
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface EnqueueResult {
|
|
74
|
+
readonly id: string
|
|
75
|
+
readonly queue: string
|
|
76
|
+
readonly runAt: number
|
|
77
|
+
readonly deduplicated: boolean
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface JobStats {
|
|
81
|
+
readonly pending: number
|
|
82
|
+
readonly running: number
|
|
83
|
+
readonly completed: number
|
|
84
|
+
readonly failed: number
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface JobListFilter {
|
|
88
|
+
queue?: string | undefined
|
|
89
|
+
status?: JobStatus | undefined
|
|
90
|
+
limit?: number | undefined
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface DrainOptions {
|
|
94
|
+
/** Also execute jobs whose `runAt` is in the future (delayed or waiting for backoff). Default: `false`. */
|
|
95
|
+
includeDelayed?: boolean | undefined
|
|
96
|
+
/** Override the current epoch timestamp in ms for deterministic due-job selection. */
|
|
97
|
+
now?: number | undefined
|
|
98
|
+
/** Maximum number of job executions to run before returning. */
|
|
99
|
+
maxJobs?: number | undefined
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export interface JobErrorInfo {
|
|
103
|
+
readonly kind: 'job' | 'schedule'
|
|
104
|
+
readonly name: string
|
|
105
|
+
readonly id?: string | undefined
|
|
106
|
+
readonly attempt?: number | undefined
|
|
107
|
+
readonly maxAttempts?: number | undefined
|
|
108
|
+
readonly error: unknown
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface JobsOptions {
|
|
112
|
+
/** SQLite file path or existing `bun:sqlite` `Database` instance. Defaults to `':memory:'`. */
|
|
113
|
+
db?: string | Database | undefined
|
|
114
|
+
/** Allow an in-memory SQLite store in production without failing `requires()`. Default: `false`. */
|
|
115
|
+
allowMemoryInProd?: boolean | undefined
|
|
116
|
+
/** Background worker poll interval in ms. Default: `500`. */
|
|
117
|
+
pollIntervalMs?: number | undefined
|
|
118
|
+
/** Background cron schedule check interval in ms. Default: `1000`. */
|
|
119
|
+
scheduleIntervalMs?: number | undefined
|
|
120
|
+
/** Maximum concurrent jobs per worker instance. Default: `4`. */
|
|
121
|
+
concurrency?: number | undefined
|
|
122
|
+
/** Lease duration in ms before a running job from a crashed worker becomes reclaimable. Default: `60_000`. */
|
|
123
|
+
leaseMs?: number | undefined
|
|
124
|
+
/** Maximum ms `onShutdown()` waits for in-flight jobs before releasing remaining claims back to `pending`. Default: `5000`. */
|
|
125
|
+
shutdownTimeoutMs?: number | undefined
|
|
126
|
+
/** Default max attempts for queues that do not set `attempts`. Default: `3`. */
|
|
127
|
+
defaultAttempts?: number | undefined
|
|
128
|
+
/** Default backoff strategy for queues that do not set `backoff`. Default: `'exponential'`. */
|
|
129
|
+
defaultBackoff?: BackoffStrategy | undefined
|
|
130
|
+
/** Base delay in ms for `'fixed'` and `'exponential'` backoff. Default: `1000`. */
|
|
131
|
+
backoffBaseMs?: number | undefined
|
|
132
|
+
/** Maximum delay cap in ms for `'exponential'` backoff. Default: `3_600_000`. */
|
|
133
|
+
maxBackoffMs?: number | undefined
|
|
134
|
+
/** Automatically start background poll & schedule loops inside `server(api)`. Defaults to `true` outside `NODE_ENV=test`. */
|
|
135
|
+
autoStart?: boolean | undefined
|
|
136
|
+
/** Optional clock function returning epoch ms (defaults to `Date.now`). */
|
|
137
|
+
now?: (() => number) | undefined
|
|
138
|
+
/** Optional hook notified whenever a job or schedule handler fails. */
|
|
139
|
+
onError?: ((info: JobErrorInfo) => void) | undefined
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export interface Jobs extends PrunellePlugin {
|
|
143
|
+
queue<S extends StandardSchemaV1>(
|
|
144
|
+
name: string,
|
|
145
|
+
schema: S,
|
|
146
|
+
handler: JobHandler<InferOutput<S>>,
|
|
147
|
+
options?: QueueBaseOptions,
|
|
148
|
+
): Jobs
|
|
149
|
+
queue<S extends StandardSchemaV1>(
|
|
150
|
+
name: string,
|
|
151
|
+
handler: JobHandler<InferOutput<S>>,
|
|
152
|
+
options: QueueBaseOptions & { schema: S },
|
|
153
|
+
): Jobs
|
|
154
|
+
queue<T = unknown>(
|
|
155
|
+
name: string,
|
|
156
|
+
handler: JobHandler<T>,
|
|
157
|
+
options?: QueueBaseOptions,
|
|
158
|
+
): Jobs
|
|
159
|
+
enqueue<T = unknown>(name: string, data: T, options?: EnqueueOptions): Promise<EnqueueResult>
|
|
160
|
+
schedule(name: string, cronExpr: string, handler: ScheduleHandler, options?: ScheduleOptions): Jobs
|
|
161
|
+
drain(options?: DrainOptions): Promise<number>
|
|
162
|
+
runDueSchedules(now?: number): Promise<number>
|
|
163
|
+
start(): void
|
|
164
|
+
get<T = unknown>(id: string): JobRecord<T> | undefined
|
|
165
|
+
list<T = unknown>(filter?: JobListFilter): JobRecord<T>[]
|
|
166
|
+
stats(): JobStats
|
|
167
|
+
dispose(): Promise<void>
|
|
168
|
+
[Symbol.asyncDispose](): Promise<void>
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export type DrainTarget =
|
|
172
|
+
| Pick<Jobs, 'drain'>
|
|
173
|
+
| { readonly app: { readonly inject?: (<T>(key: ServiceKey<T>) => T | undefined) | undefined } }
|
|
174
|
+
| { readonly inject?: (<T>(key: ServiceKey<T>) => T | undefined) | undefined }
|
|
175
|
+
|
|
176
|
+
export class JobValidationError extends Error {
|
|
177
|
+
readonly queue: string
|
|
178
|
+
readonly issues: ReadonlyArray<StandardSchemaIssue>
|
|
179
|
+
readonly fieldErrors: Record<string, string>
|
|
180
|
+
|
|
181
|
+
constructor(queue: string, message: string, issues: ReadonlyArray<StandardSchemaIssue>, fieldErrors: Record<string, string>) {
|
|
182
|
+
super(`@prunellejs/jobs: invalid payload for queue "${queue}": ${message}`)
|
|
183
|
+
this.name = 'JobValidationError'
|
|
184
|
+
this.queue = queue
|
|
185
|
+
this.issues = issues
|
|
186
|
+
this.fieldErrors = fieldErrors
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const DURATION_RE = /^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)\s*$/i
|
|
191
|
+
const UNIT_MS: Record<DurationUnit, number> = {
|
|
192
|
+
ms: 1,
|
|
193
|
+
s: 1000,
|
|
194
|
+
m: 60_000,
|
|
195
|
+
h: 3_600_000,
|
|
196
|
+
d: 86_400_000,
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export function parseDuration(value: Duration | undefined): number {
|
|
200
|
+
if (value === undefined)
|
|
201
|
+
return 0
|
|
202
|
+
if (typeof value === 'number') {
|
|
203
|
+
if (!Number.isFinite(value) || value < 0)
|
|
204
|
+
throw new RangeError(`@prunellejs/jobs: invalid delay ${String(value)}: pass a non-negative finite number of milliseconds or a duration string like "5s", "10m", "2h", or "1d".`)
|
|
205
|
+
return Math.round(value)
|
|
206
|
+
}
|
|
207
|
+
const match = DURATION_RE.exec(value)
|
|
208
|
+
if (!match)
|
|
209
|
+
throw new RangeError(`@prunellejs/jobs: invalid delay "${value}": use milliseconds or a duration string like "500ms", "5s", "10m", "2h", or "1d".`)
|
|
210
|
+
const amount = Number(match[1])
|
|
211
|
+
const unit = match[2]!.toLowerCase() as DurationUnit
|
|
212
|
+
const ms = Math.round(amount * UNIT_MS[unit])
|
|
213
|
+
if (!Number.isFinite(ms) || ms < 0)
|
|
214
|
+
throw new RangeError(`@prunellejs/jobs: invalid delay "${value}": value overflows safe millisecond range.`)
|
|
215
|
+
return ms
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function normalizeAttempts(attempts: number | undefined, fallback: number): number {
|
|
219
|
+
const resolved = attempts ?? fallback
|
|
220
|
+
if (!Number.isInteger(resolved) || resolved < 1)
|
|
221
|
+
throw new RangeError(`@prunellejs/jobs: invalid attempts ${String(resolved)}: pass an integer >= 1.`)
|
|
222
|
+
return resolved
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function normalizeBackoff(backoff: BackoffStrategy | undefined, fallback: BackoffStrategy): BackoffStrategy {
|
|
226
|
+
const resolved = backoff ?? fallback
|
|
227
|
+
if (typeof resolved === 'number') {
|
|
228
|
+
if (!Number.isFinite(resolved) || resolved < 0)
|
|
229
|
+
throw new RangeError(`@prunellejs/jobs: invalid backoff ${String(resolved)}: pass 'exponential', 'fixed', or a non-negative number of milliseconds.`)
|
|
230
|
+
return resolved
|
|
231
|
+
}
|
|
232
|
+
if (resolved !== 'exponential' && resolved !== 'fixed')
|
|
233
|
+
throw new RangeError(`@prunellejs/jobs: invalid backoff "${String(resolved)}": pass 'exponential', 'fixed', or a non-negative number of milliseconds.`)
|
|
234
|
+
return resolved
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export function computeBackoffDelay(
|
|
238
|
+
strategy: BackoffStrategy,
|
|
239
|
+
failedAttempt: number,
|
|
240
|
+
baseMs: number,
|
|
241
|
+
maxMs: number,
|
|
242
|
+
): number {
|
|
243
|
+
if (typeof strategy === 'number')
|
|
244
|
+
return Math.round(strategy)
|
|
245
|
+
if (strategy === 'fixed')
|
|
246
|
+
return Math.max(0, Math.round(baseMs))
|
|
247
|
+
const exponent = Math.max(0, failedAttempt - 1)
|
|
248
|
+
const raw = baseMs * (2 ** exponent)
|
|
249
|
+
if (!Number.isFinite(raw))
|
|
250
|
+
return maxMs
|
|
251
|
+
return Math.min(maxMs, Math.max(0, Math.round(raw)))
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export function isStandardSchema(value: unknown): value is StandardSchemaV1 {
|
|
255
|
+
if (typeof value !== 'object' || value === null || !('~standard' in value))
|
|
256
|
+
return false
|
|
257
|
+
const std = (value as { '~standard'?: unknown })['~standard']
|
|
258
|
+
return typeof std === 'object' && std !== null && (std as { version?: unknown }).version === 1
|
|
259
|
+
&& typeof (std as { validate?: unknown }).validate === 'function'
|
|
260
|
+
}
|
package/README.md
DELETED