@nicnocquee/dataqueue 1.26.0 → 1.31.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/dist/index.js ADDED
@@ -0,0 +1,3953 @@
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+ import { randomUUID } from 'crypto';
3
+ import { Worker } from 'worker_threads';
4
+ import { Pool } from 'pg';
5
+ import { parse } from 'pg-connection-string';
6
+ import fs from 'fs';
7
+ import { createRequire } from 'module';
8
+ import { Cron } from 'croner';
9
+
10
+ // src/types.ts
11
+ var JobEventType = /* @__PURE__ */ ((JobEventType2) => {
12
+ JobEventType2["Added"] = "added";
13
+ JobEventType2["Processing"] = "processing";
14
+ JobEventType2["Completed"] = "completed";
15
+ JobEventType2["Failed"] = "failed";
16
+ JobEventType2["Cancelled"] = "cancelled";
17
+ JobEventType2["Retried"] = "retried";
18
+ JobEventType2["Edited"] = "edited";
19
+ JobEventType2["Prolonged"] = "prolonged";
20
+ JobEventType2["Waiting"] = "waiting";
21
+ return JobEventType2;
22
+ })(JobEventType || {});
23
+ var FailureReason = /* @__PURE__ */ ((FailureReason5) => {
24
+ FailureReason5["Timeout"] = "timeout";
25
+ FailureReason5["HandlerError"] = "handler_error";
26
+ FailureReason5["NoHandler"] = "no_handler";
27
+ return FailureReason5;
28
+ })(FailureReason || {});
29
+ var WaitSignal = class extends Error {
30
+ constructor(type, waitUntil, tokenId, stepData) {
31
+ super("WaitSignal");
32
+ this.type = type;
33
+ this.waitUntil = waitUntil;
34
+ this.tokenId = tokenId;
35
+ this.stepData = stepData;
36
+ this.isWaitSignal = true;
37
+ this.name = "WaitSignal";
38
+ }
39
+ };
40
+ var logStorage = new AsyncLocalStorage();
41
+ var setLogContext = (verbose) => {
42
+ logStorage.enterWith({ verbose });
43
+ };
44
+ var getLogContext = () => {
45
+ return logStorage.getStore();
46
+ };
47
+ var log = (message) => {
48
+ const context = getLogContext();
49
+ if (context?.verbose) {
50
+ console.log(message);
51
+ }
52
+ };
53
+
54
+ // src/backends/postgres.ts
55
+ var PostgresBackend = class {
56
+ constructor(pool) {
57
+ this.pool = pool;
58
+ }
59
+ /** Expose the raw pool for advanced usage. */
60
+ getPool() {
61
+ return this.pool;
62
+ }
63
+ // ── Events ──────────────────────────────────────────────────────────
64
+ async recordJobEvent(jobId, eventType, metadata) {
65
+ const client = await this.pool.connect();
66
+ try {
67
+ await client.query(
68
+ `INSERT INTO job_events (job_id, event_type, metadata) VALUES ($1, $2, $3)`,
69
+ [jobId, eventType, metadata ? JSON.stringify(metadata) : null]
70
+ );
71
+ } catch (error) {
72
+ log(`Error recording job event for job ${jobId}: ${error}`);
73
+ } finally {
74
+ client.release();
75
+ }
76
+ }
77
+ async getJobEvents(jobId) {
78
+ const client = await this.pool.connect();
79
+ try {
80
+ const res = await client.query(
81
+ `SELECT id, job_id AS "jobId", event_type AS "eventType", metadata, created_at AS "createdAt" FROM job_events WHERE job_id = $1 ORDER BY created_at ASC`,
82
+ [jobId]
83
+ );
84
+ return res.rows;
85
+ } finally {
86
+ client.release();
87
+ }
88
+ }
89
+ // ── Job CRUD ──────────────────────────────────────────────────────────
90
+ async addJob({
91
+ jobType,
92
+ payload,
93
+ maxAttempts = 3,
94
+ priority = 0,
95
+ runAt = null,
96
+ timeoutMs = void 0,
97
+ forceKillOnTimeout = false,
98
+ tags = void 0,
99
+ idempotencyKey = void 0
100
+ }) {
101
+ const client = await this.pool.connect();
102
+ try {
103
+ let result;
104
+ const onConflict = idempotencyKey ? `ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING` : "";
105
+ if (runAt) {
106
+ result = await client.query(
107
+ `INSERT INTO job_queue
108
+ (job_type, payload, max_attempts, priority, run_at, timeout_ms, force_kill_on_timeout, tags, idempotency_key)
109
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
110
+ ${onConflict}
111
+ RETURNING id`,
112
+ [
113
+ jobType,
114
+ payload,
115
+ maxAttempts,
116
+ priority,
117
+ runAt,
118
+ timeoutMs ?? null,
119
+ forceKillOnTimeout ?? false,
120
+ tags ?? null,
121
+ idempotencyKey ?? null
122
+ ]
123
+ );
124
+ } else {
125
+ result = await client.query(
126
+ `INSERT INTO job_queue
127
+ (job_type, payload, max_attempts, priority, timeout_ms, force_kill_on_timeout, tags, idempotency_key)
128
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
129
+ ${onConflict}
130
+ RETURNING id`,
131
+ [
132
+ jobType,
133
+ payload,
134
+ maxAttempts,
135
+ priority,
136
+ timeoutMs ?? null,
137
+ forceKillOnTimeout ?? false,
138
+ tags ?? null,
139
+ idempotencyKey ?? null
140
+ ]
141
+ );
142
+ }
143
+ if (result.rows.length === 0 && idempotencyKey) {
144
+ const existing = await client.query(
145
+ `SELECT id FROM job_queue WHERE idempotency_key = $1`,
146
+ [idempotencyKey]
147
+ );
148
+ if (existing.rows.length > 0) {
149
+ log(
150
+ `Job with idempotency key "${idempotencyKey}" already exists (id: ${existing.rows[0].id}), returning existing job`
151
+ );
152
+ return existing.rows[0].id;
153
+ }
154
+ throw new Error(
155
+ `Failed to insert job and could not find existing job with idempotency key "${idempotencyKey}"`
156
+ );
157
+ }
158
+ const jobId = result.rows[0].id;
159
+ log(
160
+ `Added job ${jobId}: payload ${JSON.stringify(payload)}, ${runAt ? `runAt ${runAt.toISOString()}, ` : ""}priority ${priority}, maxAttempts ${maxAttempts}, jobType ${jobType}, tags ${JSON.stringify(tags)}${idempotencyKey ? `, idempotencyKey "${idempotencyKey}"` : ""}`
161
+ );
162
+ await this.recordJobEvent(jobId, "added" /* Added */, {
163
+ jobType,
164
+ payload,
165
+ tags,
166
+ idempotencyKey
167
+ });
168
+ return jobId;
169
+ } catch (error) {
170
+ log(`Error adding job: ${error}`);
171
+ throw error;
172
+ } finally {
173
+ client.release();
174
+ }
175
+ }
176
+ async getJob(id) {
177
+ const client = await this.pool.connect();
178
+ try {
179
+ const result = await client.query(
180
+ `SELECT id, job_type AS "jobType", payload, status, max_attempts AS "maxAttempts", attempts, priority, run_at AS "runAt", timeout_ms AS "timeoutMs", force_kill_on_timeout AS "forceKillOnTimeout", created_at AS "createdAt", updated_at AS "updatedAt", started_at AS "startedAt", completed_at AS "completedAt", last_failed_at AS "lastFailedAt", locked_at AS "lockedAt", locked_by AS "lockedBy", error_history AS "errorHistory", failure_reason AS "failureReason", next_attempt_at AS "nextAttemptAt", last_failed_at AS "lastFailedAt", last_retried_at AS "lastRetriedAt", last_cancelled_at AS "lastCancelledAt", pending_reason AS "pendingReason", tags, idempotency_key AS "idempotencyKey", wait_until AS "waitUntil", wait_token_id AS "waitTokenId", step_data AS "stepData", progress FROM job_queue WHERE id = $1`,
181
+ [id]
182
+ );
183
+ if (result.rows.length === 0) {
184
+ log(`Job ${id} not found`);
185
+ return null;
186
+ }
187
+ log(`Found job ${id}`);
188
+ const job = result.rows[0];
189
+ return {
190
+ ...job,
191
+ payload: job.payload,
192
+ timeoutMs: job.timeoutMs,
193
+ forceKillOnTimeout: job.forceKillOnTimeout,
194
+ failureReason: job.failureReason
195
+ };
196
+ } catch (error) {
197
+ log(`Error getting job ${id}: ${error}`);
198
+ throw error;
199
+ } finally {
200
+ client.release();
201
+ }
202
+ }
203
+ async getJobsByStatus(status, limit = 100, offset = 0) {
204
+ const client = await this.pool.connect();
205
+ try {
206
+ const result = await client.query(
207
+ `SELECT id, job_type AS "jobType", payload, status, max_attempts AS "maxAttempts", attempts, priority, run_at AS "runAt", timeout_ms AS "timeoutMs", force_kill_on_timeout AS "forceKillOnTimeout", created_at AS "createdAt", updated_at AS "updatedAt", started_at AS "startedAt", completed_at AS "completedAt", last_failed_at AS "lastFailedAt", locked_at AS "lockedAt", locked_by AS "lockedBy", error_history AS "errorHistory", failure_reason AS "failureReason", next_attempt_at AS "nextAttemptAt", last_failed_at AS "lastFailedAt", last_retried_at AS "lastRetriedAt", last_cancelled_at AS "lastCancelledAt", pending_reason AS "pendingReason", idempotency_key AS "idempotencyKey", wait_until AS "waitUntil", wait_token_id AS "waitTokenId", step_data AS "stepData", progress FROM job_queue WHERE status = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3`,
208
+ [status, limit, offset]
209
+ );
210
+ log(`Found ${result.rows.length} jobs by status ${status}`);
211
+ return result.rows.map((job) => ({
212
+ ...job,
213
+ payload: job.payload,
214
+ timeoutMs: job.timeoutMs,
215
+ forceKillOnTimeout: job.forceKillOnTimeout,
216
+ failureReason: job.failureReason
217
+ }));
218
+ } catch (error) {
219
+ log(`Error getting jobs by status ${status}: ${error}`);
220
+ throw error;
221
+ } finally {
222
+ client.release();
223
+ }
224
+ }
225
+ async getAllJobs(limit = 100, offset = 0) {
226
+ const client = await this.pool.connect();
227
+ try {
228
+ const result = await client.query(
229
+ `SELECT id, job_type AS "jobType", payload, status, max_attempts AS "maxAttempts", attempts, priority, run_at AS "runAt", timeout_ms AS "timeoutMs", force_kill_on_timeout AS "forceKillOnTimeout", created_at AS "createdAt", updated_at AS "updatedAt", started_at AS "startedAt", completed_at AS "completedAt", last_failed_at AS "lastFailedAt", locked_at AS "lockedAt", locked_by AS "lockedBy", error_history AS "errorHistory", failure_reason AS "failureReason", next_attempt_at AS "nextAttemptAt", last_failed_at AS "lastFailedAt", last_retried_at AS "lastRetriedAt", last_cancelled_at AS "lastCancelledAt", pending_reason AS "pendingReason", idempotency_key AS "idempotencyKey", wait_until AS "waitUntil", wait_token_id AS "waitTokenId", step_data AS "stepData", progress FROM job_queue ORDER BY created_at DESC LIMIT $1 OFFSET $2`,
230
+ [limit, offset]
231
+ );
232
+ log(`Found ${result.rows.length} jobs (all)`);
233
+ return result.rows.map((job) => ({
234
+ ...job,
235
+ payload: job.payload,
236
+ timeoutMs: job.timeoutMs,
237
+ forceKillOnTimeout: job.forceKillOnTimeout
238
+ }));
239
+ } catch (error) {
240
+ log(`Error getting all jobs: ${error}`);
241
+ throw error;
242
+ } finally {
243
+ client.release();
244
+ }
245
+ }
246
+ async getJobs(filters, limit = 100, offset = 0) {
247
+ const client = await this.pool.connect();
248
+ try {
249
+ let query = `SELECT id, job_type AS "jobType", payload, status, max_attempts AS "maxAttempts", attempts, priority, run_at AS "runAt", timeout_ms AS "timeoutMs", force_kill_on_timeout AS "forceKillOnTimeout", created_at AS "createdAt", updated_at AS "updatedAt", started_at AS "startedAt", completed_at AS "completedAt", last_failed_at AS "lastFailedAt", locked_at AS "lockedAt", locked_by AS "lockedBy", error_history AS "errorHistory", failure_reason AS "failureReason", next_attempt_at AS "nextAttemptAt", last_failed_at AS "lastFailedAt", last_retried_at AS "lastRetriedAt", last_cancelled_at AS "lastCancelledAt", pending_reason AS "pendingReason", tags, idempotency_key AS "idempotencyKey", wait_until AS "waitUntil", wait_token_id AS "waitTokenId", step_data AS "stepData", progress FROM job_queue`;
250
+ const params = [];
251
+ const where = [];
252
+ let paramIdx = 1;
253
+ if (filters) {
254
+ if (filters.jobType) {
255
+ where.push(`job_type = $${paramIdx++}`);
256
+ params.push(filters.jobType);
257
+ }
258
+ if (filters.priority !== void 0) {
259
+ where.push(`priority = $${paramIdx++}`);
260
+ params.push(filters.priority);
261
+ }
262
+ if (filters.runAt) {
263
+ if (filters.runAt instanceof Date) {
264
+ where.push(`run_at = $${paramIdx++}`);
265
+ params.push(filters.runAt);
266
+ } else if (typeof filters.runAt === "object" && (filters.runAt.gt !== void 0 || filters.runAt.gte !== void 0 || filters.runAt.lt !== void 0 || filters.runAt.lte !== void 0 || filters.runAt.eq !== void 0)) {
267
+ const ops = filters.runAt;
268
+ if (ops.gt) {
269
+ where.push(`run_at > $${paramIdx++}`);
270
+ params.push(ops.gt);
271
+ }
272
+ if (ops.gte) {
273
+ where.push(`run_at >= $${paramIdx++}`);
274
+ params.push(ops.gte);
275
+ }
276
+ if (ops.lt) {
277
+ where.push(`run_at < $${paramIdx++}`);
278
+ params.push(ops.lt);
279
+ }
280
+ if (ops.lte) {
281
+ where.push(`run_at <= $${paramIdx++}`);
282
+ params.push(ops.lte);
283
+ }
284
+ if (ops.eq) {
285
+ where.push(`run_at = $${paramIdx++}`);
286
+ params.push(ops.eq);
287
+ }
288
+ }
289
+ }
290
+ if (filters.tags && filters.tags.values && filters.tags.values.length > 0) {
291
+ const mode = filters.tags.mode || "all";
292
+ const tagValues = filters.tags.values;
293
+ switch (mode) {
294
+ case "exact":
295
+ where.push(`tags = $${paramIdx++}`);
296
+ params.push(tagValues);
297
+ break;
298
+ case "all":
299
+ where.push(`tags @> $${paramIdx++}`);
300
+ params.push(tagValues);
301
+ break;
302
+ case "any":
303
+ where.push(`tags && $${paramIdx++}`);
304
+ params.push(tagValues);
305
+ break;
306
+ case "none":
307
+ where.push(`NOT (tags && $${paramIdx++})`);
308
+ params.push(tagValues);
309
+ break;
310
+ default:
311
+ where.push(`tags @> $${paramIdx++}`);
312
+ params.push(tagValues);
313
+ }
314
+ }
315
+ if (filters.cursor !== void 0) {
316
+ where.push(`id < $${paramIdx++}`);
317
+ params.push(filters.cursor);
318
+ }
319
+ }
320
+ if (where.length > 0) {
321
+ query += ` WHERE ${where.join(" AND ")}`;
322
+ }
323
+ paramIdx = params.length + 1;
324
+ query += ` ORDER BY id DESC LIMIT $${paramIdx++}`;
325
+ if (!filters?.cursor) {
326
+ query += ` OFFSET $${paramIdx}`;
327
+ params.push(limit, offset);
328
+ } else {
329
+ params.push(limit);
330
+ }
331
+ const result = await client.query(query, params);
332
+ log(`Found ${result.rows.length} jobs`);
333
+ return result.rows.map((job) => ({
334
+ ...job,
335
+ payload: job.payload,
336
+ timeoutMs: job.timeoutMs,
337
+ forceKillOnTimeout: job.forceKillOnTimeout,
338
+ failureReason: job.failureReason
339
+ }));
340
+ } catch (error) {
341
+ log(`Error getting jobs: ${error}`);
342
+ throw error;
343
+ } finally {
344
+ client.release();
345
+ }
346
+ }
347
+ async getJobsByTags(tags, mode = "all", limit = 100, offset = 0) {
348
+ const client = await this.pool.connect();
349
+ try {
350
+ let query = `SELECT id, job_type AS "jobType", payload, status, max_attempts AS "maxAttempts", attempts, priority, run_at AS "runAt", timeout_ms AS "timeoutMs", created_at AS "createdAt", updated_at AS "updatedAt", started_at AS "startedAt", completed_at AS "completedAt", last_failed_at AS "lastFailedAt", locked_at AS "lockedAt", locked_by AS "lockedBy", error_history AS "errorHistory", failure_reason AS "failureReason", next_attempt_at AS "nextAttemptAt", last_failed_at AS "lastFailedAt", last_retried_at AS "lastRetriedAt", last_cancelled_at AS "lastCancelledAt", pending_reason AS "pendingReason", tags, idempotency_key AS "idempotencyKey", wait_until AS "waitUntil", wait_token_id AS "waitTokenId", step_data AS "stepData", progress
351
+ FROM job_queue`;
352
+ let params = [];
353
+ switch (mode) {
354
+ case "exact":
355
+ query += " WHERE tags = $1";
356
+ params = [tags];
357
+ break;
358
+ case "all":
359
+ query += " WHERE tags @> $1";
360
+ params = [tags];
361
+ break;
362
+ case "any":
363
+ query += " WHERE tags && $1";
364
+ params = [tags];
365
+ break;
366
+ case "none":
367
+ query += " WHERE NOT (tags && $1)";
368
+ params = [tags];
369
+ break;
370
+ default:
371
+ query += " WHERE tags @> $1";
372
+ params = [tags];
373
+ }
374
+ query += " ORDER BY created_at DESC LIMIT $2 OFFSET $3";
375
+ params.push(limit, offset);
376
+ const result = await client.query(query, params);
377
+ log(
378
+ `Found ${result.rows.length} jobs by tags ${JSON.stringify(tags)} (mode: ${mode})`
379
+ );
380
+ return result.rows.map((job) => ({
381
+ ...job,
382
+ payload: job.payload,
383
+ timeoutMs: job.timeoutMs,
384
+ forceKillOnTimeout: job.forceKillOnTimeout,
385
+ failureReason: job.failureReason
386
+ }));
387
+ } catch (error) {
388
+ log(
389
+ `Error getting jobs by tags ${JSON.stringify(tags)} (mode: ${mode}): ${error}`
390
+ );
391
+ throw error;
392
+ } finally {
393
+ client.release();
394
+ }
395
+ }
396
+ // ── Processing lifecycle ──────────────────────────────────────────────
397
+ async getNextBatch(workerId, batchSize = 10, jobType) {
398
+ const client = await this.pool.connect();
399
+ try {
400
+ await client.query("BEGIN");
401
+ let jobTypeFilter = "";
402
+ const params = [workerId, batchSize];
403
+ if (jobType) {
404
+ if (Array.isArray(jobType)) {
405
+ jobTypeFilter = ` AND job_type = ANY($3)`;
406
+ params.push(jobType);
407
+ } else {
408
+ jobTypeFilter = ` AND job_type = $3`;
409
+ params.push(jobType);
410
+ }
411
+ }
412
+ const result = await client.query(
413
+ `
414
+ UPDATE job_queue
415
+ SET status = 'processing',
416
+ locked_at = NOW(),
417
+ locked_by = $1,
418
+ attempts = CASE WHEN status = 'waiting' THEN attempts ELSE attempts + 1 END,
419
+ updated_at = NOW(),
420
+ pending_reason = NULL,
421
+ started_at = COALESCE(started_at, NOW()),
422
+ last_retried_at = CASE WHEN status != 'waiting' AND attempts > 0 THEN NOW() ELSE last_retried_at END,
423
+ wait_until = NULL
424
+ WHERE id IN (
425
+ SELECT id FROM job_queue
426
+ WHERE (
427
+ (
428
+ (status = 'pending' OR (status = 'failed' AND next_attempt_at <= NOW()))
429
+ AND (attempts < max_attempts)
430
+ AND run_at <= NOW()
431
+ )
432
+ OR (
433
+ status = 'waiting'
434
+ AND wait_until IS NOT NULL
435
+ AND wait_until <= NOW()
436
+ AND wait_token_id IS NULL
437
+ )
438
+ )
439
+ ${jobTypeFilter}
440
+ ORDER BY priority DESC, created_at ASC
441
+ LIMIT $2
442
+ FOR UPDATE SKIP LOCKED
443
+ )
444
+ RETURNING id, job_type AS "jobType", payload, status, max_attempts AS "maxAttempts", attempts, priority, run_at AS "runAt", timeout_ms AS "timeoutMs", force_kill_on_timeout AS "forceKillOnTimeout", created_at AS "createdAt", updated_at AS "updatedAt", started_at AS "startedAt", completed_at AS "completedAt", last_failed_at AS "lastFailedAt", locked_at AS "lockedAt", locked_by AS "lockedBy", error_history AS "errorHistory", failure_reason AS "failureReason", next_attempt_at AS "nextAttemptAt", last_retried_at AS "lastRetriedAt", last_cancelled_at AS "lastCancelledAt", pending_reason AS "pendingReason", idempotency_key AS "idempotencyKey", wait_until AS "waitUntil", wait_token_id AS "waitTokenId", step_data AS "stepData", progress
445
+ `,
446
+ params
447
+ );
448
+ log(`Found ${result.rows.length} jobs to process`);
449
+ await client.query("COMMIT");
450
+ if (result.rows.length > 0) {
451
+ await this.recordJobEventsBatch(
452
+ result.rows.map((row) => ({
453
+ jobId: row.id,
454
+ eventType: "processing" /* Processing */
455
+ }))
456
+ );
457
+ }
458
+ return result.rows.map((job) => ({
459
+ ...job,
460
+ payload: job.payload,
461
+ timeoutMs: job.timeoutMs,
462
+ forceKillOnTimeout: job.forceKillOnTimeout
463
+ }));
464
+ } catch (error) {
465
+ log(`Error getting next batch: ${error}`);
466
+ await client.query("ROLLBACK");
467
+ throw error;
468
+ } finally {
469
+ client.release();
470
+ }
471
+ }
472
+ async completeJob(jobId) {
473
+ const client = await this.pool.connect();
474
+ try {
475
+ const result = await client.query(
476
+ `
477
+ UPDATE job_queue
478
+ SET status = 'completed', updated_at = NOW(), completed_at = NOW(),
479
+ step_data = NULL, wait_until = NULL, wait_token_id = NULL
480
+ WHERE id = $1 AND status = 'processing'
481
+ `,
482
+ [jobId]
483
+ );
484
+ if (result.rowCount === 0) {
485
+ log(
486
+ `Job ${jobId} could not be completed (not in processing state or does not exist)`
487
+ );
488
+ }
489
+ await this.recordJobEvent(jobId, "completed" /* Completed */);
490
+ log(`Completed job ${jobId}`);
491
+ } catch (error) {
492
+ log(`Error completing job ${jobId}: ${error}`);
493
+ throw error;
494
+ } finally {
495
+ client.release();
496
+ }
497
+ }
498
+ async failJob(jobId, error, failureReason) {
499
+ const client = await this.pool.connect();
500
+ try {
501
+ const result = await client.query(
502
+ `
503
+ UPDATE job_queue
504
+ SET status = 'failed',
505
+ updated_at = NOW(),
506
+ next_attempt_at = CASE
507
+ WHEN attempts < max_attempts THEN NOW() + (POWER(2, attempts) * INTERVAL '1 minute')
508
+ ELSE NULL
509
+ END,
510
+ error_history = COALESCE(error_history, '[]'::jsonb) || $2::jsonb,
511
+ failure_reason = $3,
512
+ last_failed_at = NOW()
513
+ WHERE id = $1 AND status IN ('processing', 'pending')
514
+ `,
515
+ [
516
+ jobId,
517
+ JSON.stringify([
518
+ {
519
+ message: error.message || String(error),
520
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
521
+ }
522
+ ]),
523
+ failureReason ?? null
524
+ ]
525
+ );
526
+ if (result.rowCount === 0) {
527
+ log(
528
+ `Job ${jobId} could not be failed (not in processing/pending state or does not exist)`
529
+ );
530
+ }
531
+ await this.recordJobEvent(jobId, "failed" /* Failed */, {
532
+ message: error.message || String(error),
533
+ failureReason
534
+ });
535
+ log(`Failed job ${jobId}`);
536
+ } catch (err) {
537
+ log(`Error failing job ${jobId}: ${err}`);
538
+ throw err;
539
+ } finally {
540
+ client.release();
541
+ }
542
+ }
543
+ async prolongJob(jobId) {
544
+ const client = await this.pool.connect();
545
+ try {
546
+ await client.query(
547
+ `
548
+ UPDATE job_queue
549
+ SET locked_at = NOW(), updated_at = NOW()
550
+ WHERE id = $1 AND status = 'processing'
551
+ `,
552
+ [jobId]
553
+ );
554
+ await this.recordJobEvent(jobId, "prolonged" /* Prolonged */);
555
+ log(`Prolonged job ${jobId}`);
556
+ } catch (error) {
557
+ log(`Error prolonging job ${jobId}: ${error}`);
558
+ } finally {
559
+ client.release();
560
+ }
561
+ }
562
+ // ── Progress ──────────────────────────────────────────────────────────
563
+ async updateProgress(jobId, progress) {
564
+ const client = await this.pool.connect();
565
+ try {
566
+ await client.query(
567
+ `UPDATE job_queue SET progress = $2, updated_at = NOW() WHERE id = $1`,
568
+ [jobId, progress]
569
+ );
570
+ log(`Updated progress for job ${jobId}: ${progress}%`);
571
+ } catch (error) {
572
+ log(`Error updating progress for job ${jobId}: ${error}`);
573
+ } finally {
574
+ client.release();
575
+ }
576
+ }
577
+ // ── Job management ────────────────────────────────────────────────────
578
+ async retryJob(jobId) {
579
+ const client = await this.pool.connect();
580
+ try {
581
+ const result = await client.query(
582
+ `
583
+ UPDATE job_queue
584
+ SET status = 'pending',
585
+ updated_at = NOW(),
586
+ locked_at = NULL,
587
+ locked_by = NULL,
588
+ next_attempt_at = NOW(),
589
+ last_retried_at = NOW()
590
+ WHERE id = $1 AND status IN ('failed', 'processing')
591
+ `,
592
+ [jobId]
593
+ );
594
+ if (result.rowCount === 0) {
595
+ log(
596
+ `Job ${jobId} could not be retried (not in failed/processing state or does not exist)`
597
+ );
598
+ }
599
+ await this.recordJobEvent(jobId, "retried" /* Retried */);
600
+ log(`Retried job ${jobId}`);
601
+ } catch (error) {
602
+ log(`Error retrying job ${jobId}: ${error}`);
603
+ throw error;
604
+ } finally {
605
+ client.release();
606
+ }
607
+ }
608
+ async cancelJob(jobId) {
609
+ const client = await this.pool.connect();
610
+ try {
611
+ await client.query(
612
+ `
613
+ UPDATE job_queue
614
+ SET status = 'cancelled', updated_at = NOW(), last_cancelled_at = NOW(),
615
+ wait_until = NULL, wait_token_id = NULL
616
+ WHERE id = $1 AND status IN ('pending', 'waiting')
617
+ `,
618
+ [jobId]
619
+ );
620
+ await this.recordJobEvent(jobId, "cancelled" /* Cancelled */);
621
+ log(`Cancelled job ${jobId}`);
622
+ } catch (error) {
623
+ log(`Error cancelling job ${jobId}: ${error}`);
624
+ throw error;
625
+ } finally {
626
+ client.release();
627
+ }
628
+ }
629
+ async cancelAllUpcomingJobs(filters) {
630
+ const client = await this.pool.connect();
631
+ try {
632
+ let query = `
633
+ UPDATE job_queue
634
+ SET status = 'cancelled', updated_at = NOW()
635
+ WHERE status = 'pending'`;
636
+ const params = [];
637
+ let paramIdx = 1;
638
+ if (filters) {
639
+ if (filters.jobType) {
640
+ query += ` AND job_type = $${paramIdx++}`;
641
+ params.push(filters.jobType);
642
+ }
643
+ if (filters.priority !== void 0) {
644
+ query += ` AND priority = $${paramIdx++}`;
645
+ params.push(filters.priority);
646
+ }
647
+ if (filters.runAt) {
648
+ if (filters.runAt instanceof Date) {
649
+ query += ` AND run_at = $${paramIdx++}`;
650
+ params.push(filters.runAt);
651
+ } else if (typeof filters.runAt === "object") {
652
+ const ops = filters.runAt;
653
+ if (ops.gt) {
654
+ query += ` AND run_at > $${paramIdx++}`;
655
+ params.push(ops.gt);
656
+ }
657
+ if (ops.gte) {
658
+ query += ` AND run_at >= $${paramIdx++}`;
659
+ params.push(ops.gte);
660
+ }
661
+ if (ops.lt) {
662
+ query += ` AND run_at < $${paramIdx++}`;
663
+ params.push(ops.lt);
664
+ }
665
+ if (ops.lte) {
666
+ query += ` AND run_at <= $${paramIdx++}`;
667
+ params.push(ops.lte);
668
+ }
669
+ if (ops.eq) {
670
+ query += ` AND run_at = $${paramIdx++}`;
671
+ params.push(ops.eq);
672
+ }
673
+ }
674
+ }
675
+ if (filters.tags && filters.tags.values && filters.tags.values.length > 0) {
676
+ const mode = filters.tags.mode || "all";
677
+ const tagValues = filters.tags.values;
678
+ switch (mode) {
679
+ case "exact":
680
+ query += ` AND tags = $${paramIdx++}`;
681
+ params.push(tagValues);
682
+ break;
683
+ case "all":
684
+ query += ` AND tags @> $${paramIdx++}`;
685
+ params.push(tagValues);
686
+ break;
687
+ case "any":
688
+ query += ` AND tags && $${paramIdx++}`;
689
+ params.push(tagValues);
690
+ break;
691
+ case "none":
692
+ query += ` AND NOT (tags && $${paramIdx++})`;
693
+ params.push(tagValues);
694
+ break;
695
+ default:
696
+ query += ` AND tags @> $${paramIdx++}`;
697
+ params.push(tagValues);
698
+ }
699
+ }
700
+ }
701
+ query += "\nRETURNING id";
702
+ const result = await client.query(query, params);
703
+ log(`Cancelled ${result.rowCount} jobs`);
704
+ return result.rowCount || 0;
705
+ } catch (error) {
706
+ log(`Error cancelling upcoming jobs: ${error}`);
707
+ throw error;
708
+ } finally {
709
+ client.release();
710
+ }
711
+ }
712
+ async editJob(jobId, updates) {
713
+ const client = await this.pool.connect();
714
+ try {
715
+ const updateFields = [];
716
+ const params = [];
717
+ let paramIdx = 1;
718
+ if (updates.payload !== void 0) {
719
+ updateFields.push(`payload = $${paramIdx++}`);
720
+ params.push(updates.payload);
721
+ }
722
+ if (updates.maxAttempts !== void 0) {
723
+ updateFields.push(`max_attempts = $${paramIdx++}`);
724
+ params.push(updates.maxAttempts);
725
+ }
726
+ if (updates.priority !== void 0) {
727
+ updateFields.push(`priority = $${paramIdx++}`);
728
+ params.push(updates.priority);
729
+ }
730
+ if (updates.runAt !== void 0) {
731
+ if (updates.runAt === null) {
732
+ updateFields.push(`run_at = NOW()`);
733
+ } else {
734
+ updateFields.push(`run_at = $${paramIdx++}`);
735
+ params.push(updates.runAt);
736
+ }
737
+ }
738
+ if (updates.timeoutMs !== void 0) {
739
+ updateFields.push(`timeout_ms = $${paramIdx++}`);
740
+ params.push(updates.timeoutMs ?? null);
741
+ }
742
+ if (updates.tags !== void 0) {
743
+ updateFields.push(`tags = $${paramIdx++}`);
744
+ params.push(updates.tags ?? null);
745
+ }
746
+ if (updateFields.length === 0) {
747
+ log(`No fields to update for job ${jobId}`);
748
+ return;
749
+ }
750
+ updateFields.push(`updated_at = NOW()`);
751
+ params.push(jobId);
752
+ const query = `
753
+ UPDATE job_queue
754
+ SET ${updateFields.join(", ")}
755
+ WHERE id = $${paramIdx} AND status = 'pending'
756
+ `;
757
+ await client.query(query, params);
758
+ const metadata = {};
759
+ if (updates.payload !== void 0) metadata.payload = updates.payload;
760
+ if (updates.maxAttempts !== void 0)
761
+ metadata.maxAttempts = updates.maxAttempts;
762
+ if (updates.priority !== void 0) metadata.priority = updates.priority;
763
+ if (updates.runAt !== void 0) metadata.runAt = updates.runAt;
764
+ if (updates.timeoutMs !== void 0)
765
+ metadata.timeoutMs = updates.timeoutMs;
766
+ if (updates.tags !== void 0) metadata.tags = updates.tags;
767
+ await this.recordJobEvent(jobId, "edited" /* Edited */, metadata);
768
+ log(`Edited job ${jobId}: ${JSON.stringify(metadata)}`);
769
+ } catch (error) {
770
+ log(`Error editing job ${jobId}: ${error}`);
771
+ throw error;
772
+ } finally {
773
+ client.release();
774
+ }
775
+ }
776
+ async editAllPendingJobs(filters = void 0, updates) {
777
+ const client = await this.pool.connect();
778
+ try {
779
+ const updateFields = [];
780
+ const params = [];
781
+ let paramIdx = 1;
782
+ if (updates.payload !== void 0) {
783
+ updateFields.push(`payload = $${paramIdx++}`);
784
+ params.push(updates.payload);
785
+ }
786
+ if (updates.maxAttempts !== void 0) {
787
+ updateFields.push(`max_attempts = $${paramIdx++}`);
788
+ params.push(updates.maxAttempts);
789
+ }
790
+ if (updates.priority !== void 0) {
791
+ updateFields.push(`priority = $${paramIdx++}`);
792
+ params.push(updates.priority);
793
+ }
794
+ if (updates.runAt !== void 0) {
795
+ if (updates.runAt === null) {
796
+ updateFields.push(`run_at = NOW()`);
797
+ } else {
798
+ updateFields.push(`run_at = $${paramIdx++}`);
799
+ params.push(updates.runAt);
800
+ }
801
+ }
802
+ if (updates.timeoutMs !== void 0) {
803
+ updateFields.push(`timeout_ms = $${paramIdx++}`);
804
+ params.push(updates.timeoutMs ?? null);
805
+ }
806
+ if (updates.tags !== void 0) {
807
+ updateFields.push(`tags = $${paramIdx++}`);
808
+ params.push(updates.tags ?? null);
809
+ }
810
+ if (updateFields.length === 0) {
811
+ log(`No fields to update for batch edit`);
812
+ return 0;
813
+ }
814
+ updateFields.push(`updated_at = NOW()`);
815
+ let query = `
816
+ UPDATE job_queue
817
+ SET ${updateFields.join(", ")}
818
+ WHERE status = 'pending'`;
819
+ if (filters) {
820
+ if (filters.jobType) {
821
+ query += ` AND job_type = $${paramIdx++}`;
822
+ params.push(filters.jobType);
823
+ }
824
+ if (filters.priority !== void 0) {
825
+ query += ` AND priority = $${paramIdx++}`;
826
+ params.push(filters.priority);
827
+ }
828
+ if (filters.runAt) {
829
+ if (filters.runAt instanceof Date) {
830
+ query += ` AND run_at = $${paramIdx++}`;
831
+ params.push(filters.runAt);
832
+ } else if (typeof filters.runAt === "object") {
833
+ const ops = filters.runAt;
834
+ if (ops.gt) {
835
+ query += ` AND run_at > $${paramIdx++}`;
836
+ params.push(ops.gt);
837
+ }
838
+ if (ops.gte) {
839
+ query += ` AND run_at >= $${paramIdx++}`;
840
+ params.push(ops.gte);
841
+ }
842
+ if (ops.lt) {
843
+ query += ` AND run_at < $${paramIdx++}`;
844
+ params.push(ops.lt);
845
+ }
846
+ if (ops.lte) {
847
+ query += ` AND run_at <= $${paramIdx++}`;
848
+ params.push(ops.lte);
849
+ }
850
+ if (ops.eq) {
851
+ query += ` AND run_at = $${paramIdx++}`;
852
+ params.push(ops.eq);
853
+ }
854
+ }
855
+ }
856
+ if (filters.tags && filters.tags.values && filters.tags.values.length > 0) {
857
+ const mode = filters.tags.mode || "all";
858
+ const tagValues = filters.tags.values;
859
+ switch (mode) {
860
+ case "exact":
861
+ query += ` AND tags = $${paramIdx++}`;
862
+ params.push(tagValues);
863
+ break;
864
+ case "all":
865
+ query += ` AND tags @> $${paramIdx++}`;
866
+ params.push(tagValues);
867
+ break;
868
+ case "any":
869
+ query += ` AND tags && $${paramIdx++}`;
870
+ params.push(tagValues);
871
+ break;
872
+ case "none":
873
+ query += ` AND NOT (tags && $${paramIdx++})`;
874
+ params.push(tagValues);
875
+ break;
876
+ default:
877
+ query += ` AND tags @> $${paramIdx++}`;
878
+ params.push(tagValues);
879
+ }
880
+ }
881
+ }
882
+ query += "\nRETURNING id";
883
+ const result = await client.query(query, params);
884
+ const editedCount = result.rowCount || 0;
885
+ const metadata = {};
886
+ if (updates.payload !== void 0) metadata.payload = updates.payload;
887
+ if (updates.maxAttempts !== void 0)
888
+ metadata.maxAttempts = updates.maxAttempts;
889
+ if (updates.priority !== void 0) metadata.priority = updates.priority;
890
+ if (updates.runAt !== void 0) metadata.runAt = updates.runAt;
891
+ if (updates.timeoutMs !== void 0)
892
+ metadata.timeoutMs = updates.timeoutMs;
893
+ if (updates.tags !== void 0) metadata.tags = updates.tags;
894
+ for (const row of result.rows) {
895
+ await this.recordJobEvent(row.id, "edited" /* Edited */, metadata);
896
+ }
897
+ log(`Edited ${editedCount} pending jobs: ${JSON.stringify(metadata)}`);
898
+ return editedCount;
899
+ } catch (error) {
900
+ log(`Error editing pending jobs: ${error}`);
901
+ throw error;
902
+ } finally {
903
+ client.release();
904
+ }
905
+ }
906
+ async cleanupOldJobs(daysToKeep = 30) {
907
+ const client = await this.pool.connect();
908
+ try {
909
+ const result = await client.query(
910
+ `
911
+ DELETE FROM job_queue
912
+ WHERE status = 'completed'
913
+ AND updated_at < NOW() - INTERVAL '1 day' * $1::int
914
+ RETURNING id
915
+ `,
916
+ [daysToKeep]
917
+ );
918
+ log(`Deleted ${result.rowCount} old jobs`);
919
+ return result.rowCount || 0;
920
+ } catch (error) {
921
+ log(`Error cleaning up old jobs: ${error}`);
922
+ throw error;
923
+ } finally {
924
+ client.release();
925
+ }
926
+ }
927
+ async cleanupOldJobEvents(daysToKeep = 30) {
928
+ const client = await this.pool.connect();
929
+ try {
930
+ const result = await client.query(
931
+ `
932
+ DELETE FROM job_events
933
+ WHERE created_at < NOW() - INTERVAL '1 day' * $1::int
934
+ RETURNING id
935
+ `,
936
+ [daysToKeep]
937
+ );
938
+ log(`Deleted ${result.rowCount} old job events`);
939
+ return result.rowCount || 0;
940
+ } catch (error) {
941
+ log(`Error cleaning up old job events: ${error}`);
942
+ throw error;
943
+ } finally {
944
+ client.release();
945
+ }
946
+ }
947
+ async reclaimStuckJobs(maxProcessingTimeMinutes = 10) {
948
+ const client = await this.pool.connect();
949
+ try {
950
+ const result = await client.query(
951
+ `
952
+ UPDATE job_queue
953
+ SET status = 'pending', locked_at = NULL, locked_by = NULL, updated_at = NOW()
954
+ WHERE status = 'processing'
955
+ AND locked_at < NOW() - GREATEST(
956
+ INTERVAL '1 minute' * $1::int,
957
+ INTERVAL '1 millisecond' * COALESCE(timeout_ms, 0)
958
+ )
959
+ RETURNING id
960
+ `,
961
+ [maxProcessingTimeMinutes]
962
+ );
963
+ log(`Reclaimed ${result.rowCount} stuck jobs`);
964
+ return result.rowCount || 0;
965
+ } catch (error) {
966
+ log(`Error reclaiming stuck jobs: ${error}`);
967
+ throw error;
968
+ } finally {
969
+ client.release();
970
+ }
971
+ }
972
+ // ── Internal helpers ──────────────────────────────────────────────────
973
+ /**
974
+ * Batch-insert multiple job events in a single query.
975
+ * More efficient than individual recordJobEvent calls.
976
+ */
977
+ async recordJobEventsBatch(events) {
978
+ if (events.length === 0) return;
979
+ const client = await this.pool.connect();
980
+ try {
981
+ const values = [];
982
+ const params = [];
983
+ let paramIdx = 1;
984
+ for (const event of events) {
985
+ values.push(`($${paramIdx++}, $${paramIdx++}, $${paramIdx++})`);
986
+ params.push(
987
+ event.jobId,
988
+ event.eventType,
989
+ event.metadata ? JSON.stringify(event.metadata) : null
990
+ );
991
+ }
992
+ await client.query(
993
+ `INSERT INTO job_events (job_id, event_type, metadata) VALUES ${values.join(", ")}`,
994
+ params
995
+ );
996
+ } catch (error) {
997
+ log(`Error recording batch job events: ${error}`);
998
+ } finally {
999
+ client.release();
1000
+ }
1001
+ }
1002
+ // ── Cron schedules ──────────────────────────────────────────────────
1003
+ /** Create a cron schedule and return its ID. */
1004
+ async addCronSchedule(input) {
1005
+ const client = await this.pool.connect();
1006
+ try {
1007
+ const result = await client.query(
1008
+ `INSERT INTO cron_schedules
1009
+ (schedule_name, cron_expression, job_type, payload, max_attempts,
1010
+ priority, timeout_ms, force_kill_on_timeout, tags, timezone,
1011
+ allow_overlap, next_run_at)
1012
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
1013
+ RETURNING id`,
1014
+ [
1015
+ input.scheduleName,
1016
+ input.cronExpression,
1017
+ input.jobType,
1018
+ input.payload,
1019
+ input.maxAttempts,
1020
+ input.priority,
1021
+ input.timeoutMs,
1022
+ input.forceKillOnTimeout,
1023
+ input.tags ?? null,
1024
+ input.timezone,
1025
+ input.allowOverlap,
1026
+ input.nextRunAt
1027
+ ]
1028
+ );
1029
+ const id = result.rows[0].id;
1030
+ log(`Added cron schedule ${id}: "${input.scheduleName}"`);
1031
+ return id;
1032
+ } catch (error) {
1033
+ if (error?.code === "23505") {
1034
+ throw new Error(
1035
+ `Cron schedule with name "${input.scheduleName}" already exists`
1036
+ );
1037
+ }
1038
+ log(`Error adding cron schedule: ${error}`);
1039
+ throw error;
1040
+ } finally {
1041
+ client.release();
1042
+ }
1043
+ }
1044
+ /** Get a cron schedule by ID. */
1045
+ async getCronSchedule(id) {
1046
+ const client = await this.pool.connect();
1047
+ try {
1048
+ const result = await client.query(
1049
+ `SELECT id, schedule_name AS "scheduleName", cron_expression AS "cronExpression",
1050
+ job_type AS "jobType", payload, max_attempts AS "maxAttempts",
1051
+ priority, timeout_ms AS "timeoutMs",
1052
+ force_kill_on_timeout AS "forceKillOnTimeout", tags,
1053
+ timezone, allow_overlap AS "allowOverlap", status,
1054
+ last_enqueued_at AS "lastEnqueuedAt", last_job_id AS "lastJobId",
1055
+ next_run_at AS "nextRunAt",
1056
+ created_at AS "createdAt", updated_at AS "updatedAt"
1057
+ FROM cron_schedules WHERE id = $1`,
1058
+ [id]
1059
+ );
1060
+ if (result.rows.length === 0) return null;
1061
+ return result.rows[0];
1062
+ } catch (error) {
1063
+ log(`Error getting cron schedule ${id}: ${error}`);
1064
+ throw error;
1065
+ } finally {
1066
+ client.release();
1067
+ }
1068
+ }
1069
+ /** Get a cron schedule by its unique name. */
1070
+ async getCronScheduleByName(name) {
1071
+ const client = await this.pool.connect();
1072
+ try {
1073
+ const result = await client.query(
1074
+ `SELECT id, schedule_name AS "scheduleName", cron_expression AS "cronExpression",
1075
+ job_type AS "jobType", payload, max_attempts AS "maxAttempts",
1076
+ priority, timeout_ms AS "timeoutMs",
1077
+ force_kill_on_timeout AS "forceKillOnTimeout", tags,
1078
+ timezone, allow_overlap AS "allowOverlap", status,
1079
+ last_enqueued_at AS "lastEnqueuedAt", last_job_id AS "lastJobId",
1080
+ next_run_at AS "nextRunAt",
1081
+ created_at AS "createdAt", updated_at AS "updatedAt"
1082
+ FROM cron_schedules WHERE schedule_name = $1`,
1083
+ [name]
1084
+ );
1085
+ if (result.rows.length === 0) return null;
1086
+ return result.rows[0];
1087
+ } catch (error) {
1088
+ log(`Error getting cron schedule by name "${name}": ${error}`);
1089
+ throw error;
1090
+ } finally {
1091
+ client.release();
1092
+ }
1093
+ }
1094
+ /** List cron schedules, optionally filtered by status. */
1095
+ async listCronSchedules(status) {
1096
+ const client = await this.pool.connect();
1097
+ try {
1098
+ let query = `SELECT id, schedule_name AS "scheduleName", cron_expression AS "cronExpression",
1099
+ job_type AS "jobType", payload, max_attempts AS "maxAttempts",
1100
+ priority, timeout_ms AS "timeoutMs",
1101
+ force_kill_on_timeout AS "forceKillOnTimeout", tags,
1102
+ timezone, allow_overlap AS "allowOverlap", status,
1103
+ last_enqueued_at AS "lastEnqueuedAt", last_job_id AS "lastJobId",
1104
+ next_run_at AS "nextRunAt",
1105
+ created_at AS "createdAt", updated_at AS "updatedAt"
1106
+ FROM cron_schedules`;
1107
+ const params = [];
1108
+ if (status) {
1109
+ query += ` WHERE status = $1`;
1110
+ params.push(status);
1111
+ }
1112
+ query += ` ORDER BY created_at ASC`;
1113
+ const result = await client.query(query, params);
1114
+ return result.rows;
1115
+ } catch (error) {
1116
+ log(`Error listing cron schedules: ${error}`);
1117
+ throw error;
1118
+ } finally {
1119
+ client.release();
1120
+ }
1121
+ }
1122
+ /** Delete a cron schedule by ID. */
1123
+ async removeCronSchedule(id) {
1124
+ const client = await this.pool.connect();
1125
+ try {
1126
+ await client.query(`DELETE FROM cron_schedules WHERE id = $1`, [id]);
1127
+ log(`Removed cron schedule ${id}`);
1128
+ } catch (error) {
1129
+ log(`Error removing cron schedule ${id}: ${error}`);
1130
+ throw error;
1131
+ } finally {
1132
+ client.release();
1133
+ }
1134
+ }
1135
+ /** Pause a cron schedule. */
1136
+ async pauseCronSchedule(id) {
1137
+ const client = await this.pool.connect();
1138
+ try {
1139
+ await client.query(
1140
+ `UPDATE cron_schedules SET status = 'paused', updated_at = NOW() WHERE id = $1`,
1141
+ [id]
1142
+ );
1143
+ log(`Paused cron schedule ${id}`);
1144
+ } catch (error) {
1145
+ log(`Error pausing cron schedule ${id}: ${error}`);
1146
+ throw error;
1147
+ } finally {
1148
+ client.release();
1149
+ }
1150
+ }
1151
+ /** Resume a paused cron schedule. */
1152
+ async resumeCronSchedule(id) {
1153
+ const client = await this.pool.connect();
1154
+ try {
1155
+ await client.query(
1156
+ `UPDATE cron_schedules SET status = 'active', updated_at = NOW() WHERE id = $1`,
1157
+ [id]
1158
+ );
1159
+ log(`Resumed cron schedule ${id}`);
1160
+ } catch (error) {
1161
+ log(`Error resuming cron schedule ${id}: ${error}`);
1162
+ throw error;
1163
+ } finally {
1164
+ client.release();
1165
+ }
1166
+ }
1167
+ /** Edit a cron schedule. */
1168
+ async editCronSchedule(id, updates, nextRunAt) {
1169
+ const client = await this.pool.connect();
1170
+ try {
1171
+ const updateFields = [];
1172
+ const params = [];
1173
+ let paramIdx = 1;
1174
+ if (updates.cronExpression !== void 0) {
1175
+ updateFields.push(`cron_expression = $${paramIdx++}`);
1176
+ params.push(updates.cronExpression);
1177
+ }
1178
+ if (updates.payload !== void 0) {
1179
+ updateFields.push(`payload = $${paramIdx++}`);
1180
+ params.push(updates.payload);
1181
+ }
1182
+ if (updates.maxAttempts !== void 0) {
1183
+ updateFields.push(`max_attempts = $${paramIdx++}`);
1184
+ params.push(updates.maxAttempts);
1185
+ }
1186
+ if (updates.priority !== void 0) {
1187
+ updateFields.push(`priority = $${paramIdx++}`);
1188
+ params.push(updates.priority);
1189
+ }
1190
+ if (updates.timeoutMs !== void 0) {
1191
+ updateFields.push(`timeout_ms = $${paramIdx++}`);
1192
+ params.push(updates.timeoutMs);
1193
+ }
1194
+ if (updates.forceKillOnTimeout !== void 0) {
1195
+ updateFields.push(`force_kill_on_timeout = $${paramIdx++}`);
1196
+ params.push(updates.forceKillOnTimeout);
1197
+ }
1198
+ if (updates.tags !== void 0) {
1199
+ updateFields.push(`tags = $${paramIdx++}`);
1200
+ params.push(updates.tags);
1201
+ }
1202
+ if (updates.timezone !== void 0) {
1203
+ updateFields.push(`timezone = $${paramIdx++}`);
1204
+ params.push(updates.timezone);
1205
+ }
1206
+ if (updates.allowOverlap !== void 0) {
1207
+ updateFields.push(`allow_overlap = $${paramIdx++}`);
1208
+ params.push(updates.allowOverlap);
1209
+ }
1210
+ if (nextRunAt !== void 0) {
1211
+ updateFields.push(`next_run_at = $${paramIdx++}`);
1212
+ params.push(nextRunAt);
1213
+ }
1214
+ if (updateFields.length === 0) {
1215
+ log(`No fields to update for cron schedule ${id}`);
1216
+ return;
1217
+ }
1218
+ updateFields.push(`updated_at = NOW()`);
1219
+ params.push(id);
1220
+ const query = `UPDATE cron_schedules SET ${updateFields.join(", ")} WHERE id = $${paramIdx}`;
1221
+ await client.query(query, params);
1222
+ log(`Edited cron schedule ${id}`);
1223
+ } catch (error) {
1224
+ log(`Error editing cron schedule ${id}: ${error}`);
1225
+ throw error;
1226
+ } finally {
1227
+ client.release();
1228
+ }
1229
+ }
1230
+ /**
1231
+ * Atomically fetch all active cron schedules whose nextRunAt <= NOW().
1232
+ * Uses FOR UPDATE SKIP LOCKED to prevent duplicate enqueuing across workers.
1233
+ */
1234
+ async getDueCronSchedules() {
1235
+ const client = await this.pool.connect();
1236
+ try {
1237
+ const result = await client.query(
1238
+ `SELECT id, schedule_name AS "scheduleName", cron_expression AS "cronExpression",
1239
+ job_type AS "jobType", payload, max_attempts AS "maxAttempts",
1240
+ priority, timeout_ms AS "timeoutMs",
1241
+ force_kill_on_timeout AS "forceKillOnTimeout", tags,
1242
+ timezone, allow_overlap AS "allowOverlap", status,
1243
+ last_enqueued_at AS "lastEnqueuedAt", last_job_id AS "lastJobId",
1244
+ next_run_at AS "nextRunAt",
1245
+ created_at AS "createdAt", updated_at AS "updatedAt"
1246
+ FROM cron_schedules
1247
+ WHERE status = 'active'
1248
+ AND next_run_at IS NOT NULL
1249
+ AND next_run_at <= NOW()
1250
+ ORDER BY next_run_at ASC
1251
+ FOR UPDATE SKIP LOCKED`
1252
+ );
1253
+ log(`Found ${result.rows.length} due cron schedules`);
1254
+ return result.rows;
1255
+ } catch (error) {
1256
+ if (error?.code === "42P01") {
1257
+ log("cron_schedules table does not exist, skipping cron enqueue");
1258
+ return [];
1259
+ }
1260
+ log(`Error getting due cron schedules: ${error}`);
1261
+ throw error;
1262
+ } finally {
1263
+ client.release();
1264
+ }
1265
+ }
1266
+ /**
1267
+ * Update a cron schedule after a job has been enqueued.
1268
+ * Sets lastEnqueuedAt, lastJobId, and advances nextRunAt.
1269
+ */
1270
+ async updateCronScheduleAfterEnqueue(id, lastEnqueuedAt, lastJobId, nextRunAt) {
1271
+ const client = await this.pool.connect();
1272
+ try {
1273
+ await client.query(
1274
+ `UPDATE cron_schedules
1275
+ SET last_enqueued_at = $2,
1276
+ last_job_id = $3,
1277
+ next_run_at = $4,
1278
+ updated_at = NOW()
1279
+ WHERE id = $1`,
1280
+ [id, lastEnqueuedAt, lastJobId, nextRunAt]
1281
+ );
1282
+ log(
1283
+ `Updated cron schedule ${id}: lastJobId=${lastJobId}, nextRunAt=${nextRunAt?.toISOString() ?? "null"}`
1284
+ );
1285
+ } catch (error) {
1286
+ log(`Error updating cron schedule ${id} after enqueue: ${error}`);
1287
+ throw error;
1288
+ } finally {
1289
+ client.release();
1290
+ }
1291
+ }
1292
+ // ── Internal helpers ──────────────────────────────────────────────────
1293
+ async setPendingReasonForUnpickedJobs(reason, jobType) {
1294
+ const client = await this.pool.connect();
1295
+ try {
1296
+ let jobTypeFilter = "";
1297
+ const params = [reason];
1298
+ if (jobType) {
1299
+ if (Array.isArray(jobType)) {
1300
+ jobTypeFilter = ` AND job_type = ANY($2)`;
1301
+ params.push(jobType);
1302
+ } else {
1303
+ jobTypeFilter = ` AND job_type = $2`;
1304
+ params.push(jobType);
1305
+ }
1306
+ }
1307
+ await client.query(
1308
+ `UPDATE job_queue SET pending_reason = $1 WHERE status = 'pending'${jobTypeFilter}`,
1309
+ params
1310
+ );
1311
+ } finally {
1312
+ client.release();
1313
+ }
1314
+ }
1315
+ };
1316
+ var recordJobEvent = async (pool, jobId, eventType, metadata) => new PostgresBackend(pool).recordJobEvent(jobId, eventType, metadata);
1317
+ var waitJob = async (pool, jobId, options) => {
1318
+ const client = await pool.connect();
1319
+ try {
1320
+ const result = await client.query(
1321
+ `
1322
+ UPDATE job_queue
1323
+ SET status = 'waiting',
1324
+ wait_until = $2,
1325
+ wait_token_id = $3,
1326
+ step_data = $4,
1327
+ locked_at = NULL,
1328
+ locked_by = NULL,
1329
+ updated_at = NOW()
1330
+ WHERE id = $1 AND status = 'processing'
1331
+ `,
1332
+ [
1333
+ jobId,
1334
+ options.waitUntil ?? null,
1335
+ options.waitTokenId ?? null,
1336
+ JSON.stringify(options.stepData)
1337
+ ]
1338
+ );
1339
+ if (result.rowCount === 0) {
1340
+ log(
1341
+ `Job ${jobId} could not be set to waiting (may have been reclaimed or is no longer processing)`
1342
+ );
1343
+ return;
1344
+ }
1345
+ await recordJobEvent(pool, jobId, "waiting" /* Waiting */, {
1346
+ waitUntil: options.waitUntil?.toISOString() ?? null,
1347
+ waitTokenId: options.waitTokenId ?? null
1348
+ });
1349
+ log(`Job ${jobId} set to waiting`);
1350
+ } catch (error) {
1351
+ log(`Error setting job ${jobId} to waiting: ${error}`);
1352
+ throw error;
1353
+ } finally {
1354
+ client.release();
1355
+ }
1356
+ };
1357
+ var updateStepData = async (pool, jobId, stepData) => {
1358
+ const client = await pool.connect();
1359
+ try {
1360
+ await client.query(
1361
+ `UPDATE job_queue SET step_data = $2, updated_at = NOW() WHERE id = $1`,
1362
+ [jobId, JSON.stringify(stepData)]
1363
+ );
1364
+ } catch (error) {
1365
+ log(`Error updating step_data for job ${jobId}: ${error}`);
1366
+ } finally {
1367
+ client.release();
1368
+ }
1369
+ };
1370
+ var MAX_TIMEOUT_MS = 365 * 24 * 60 * 60 * 1e3;
1371
+ function parseTimeoutString(timeout) {
1372
+ const match = timeout.match(/^(\d+)(s|m|h|d)$/);
1373
+ if (!match) {
1374
+ throw new Error(
1375
+ `Invalid timeout format: "${timeout}". Expected format like "10m", "1h", "24h", "7d".`
1376
+ );
1377
+ }
1378
+ const value = parseInt(match[1], 10);
1379
+ const unit = match[2];
1380
+ let ms;
1381
+ switch (unit) {
1382
+ case "s":
1383
+ ms = value * 1e3;
1384
+ break;
1385
+ case "m":
1386
+ ms = value * 60 * 1e3;
1387
+ break;
1388
+ case "h":
1389
+ ms = value * 60 * 60 * 1e3;
1390
+ break;
1391
+ case "d":
1392
+ ms = value * 24 * 60 * 60 * 1e3;
1393
+ break;
1394
+ default:
1395
+ throw new Error(`Unknown timeout unit: "${unit}"`);
1396
+ }
1397
+ if (!Number.isFinite(ms) || ms > MAX_TIMEOUT_MS) {
1398
+ throw new Error(
1399
+ `Timeout value "${timeout}" is too large. Maximum allowed is 365 days.`
1400
+ );
1401
+ }
1402
+ return ms;
1403
+ }
1404
+ var createWaitpoint = async (pool, jobId, options) => {
1405
+ const client = await pool.connect();
1406
+ try {
1407
+ const id = `wp_${randomUUID()}`;
1408
+ let timeoutAt = null;
1409
+ if (options?.timeout) {
1410
+ const ms = parseTimeoutString(options.timeout);
1411
+ timeoutAt = new Date(Date.now() + ms);
1412
+ }
1413
+ await client.query(
1414
+ `INSERT INTO waitpoints (id, job_id, status, timeout_at, tags) VALUES ($1, $2, 'waiting', $3, $4)`,
1415
+ [id, jobId, timeoutAt, options?.tags ?? null]
1416
+ );
1417
+ log(`Created waitpoint ${id} for job ${jobId}`);
1418
+ return { id };
1419
+ } catch (error) {
1420
+ log(`Error creating waitpoint: ${error}`);
1421
+ throw error;
1422
+ } finally {
1423
+ client.release();
1424
+ }
1425
+ };
1426
+ var completeWaitpoint = async (pool, tokenId, data) => {
1427
+ const client = await pool.connect();
1428
+ try {
1429
+ await client.query("BEGIN");
1430
+ const wpResult = await client.query(
1431
+ `UPDATE waitpoints SET status = 'completed', output = $2, completed_at = NOW()
1432
+ WHERE id = $1 AND status = 'waiting'
1433
+ RETURNING job_id`,
1434
+ [tokenId, data != null ? JSON.stringify(data) : null]
1435
+ );
1436
+ if (wpResult.rows.length === 0) {
1437
+ await client.query("ROLLBACK");
1438
+ log(`Waitpoint ${tokenId} not found or already completed`);
1439
+ return;
1440
+ }
1441
+ const jobId = wpResult.rows[0].job_id;
1442
+ if (jobId != null) {
1443
+ await client.query(
1444
+ `UPDATE job_queue
1445
+ SET status = 'pending', wait_token_id = NULL, wait_until = NULL, updated_at = NOW()
1446
+ WHERE id = $1 AND status = 'waiting'`,
1447
+ [jobId]
1448
+ );
1449
+ }
1450
+ await client.query("COMMIT");
1451
+ log(`Completed waitpoint ${tokenId} for job ${jobId}`);
1452
+ } catch (error) {
1453
+ await client.query("ROLLBACK");
1454
+ log(`Error completing waitpoint ${tokenId}: ${error}`);
1455
+ throw error;
1456
+ } finally {
1457
+ client.release();
1458
+ }
1459
+ };
1460
+ var getWaitpoint = async (pool, tokenId) => {
1461
+ const client = await pool.connect();
1462
+ try {
1463
+ const result = await client.query(
1464
+ `SELECT id, job_id AS "jobId", status, output, timeout_at AS "timeoutAt", created_at AS "createdAt", completed_at AS "completedAt", tags FROM waitpoints WHERE id = $1`,
1465
+ [tokenId]
1466
+ );
1467
+ if (result.rows.length === 0) return null;
1468
+ return result.rows[0];
1469
+ } catch (error) {
1470
+ log(`Error getting waitpoint ${tokenId}: ${error}`);
1471
+ throw error;
1472
+ } finally {
1473
+ client.release();
1474
+ }
1475
+ };
1476
+ var expireTimedOutWaitpoints = async (pool) => {
1477
+ const client = await pool.connect();
1478
+ try {
1479
+ await client.query("BEGIN");
1480
+ const result = await client.query(
1481
+ `UPDATE waitpoints
1482
+ SET status = 'timed_out'
1483
+ WHERE status = 'waiting' AND timeout_at IS NOT NULL AND timeout_at <= NOW()
1484
+ RETURNING id, job_id`
1485
+ );
1486
+ for (const row of result.rows) {
1487
+ if (row.job_id != null) {
1488
+ await client.query(
1489
+ `UPDATE job_queue
1490
+ SET status = 'pending', wait_token_id = NULL, wait_until = NULL, updated_at = NOW()
1491
+ WHERE id = $1 AND status = 'waiting'`,
1492
+ [row.job_id]
1493
+ );
1494
+ }
1495
+ }
1496
+ await client.query("COMMIT");
1497
+ const count = result.rowCount || 0;
1498
+ if (count > 0) {
1499
+ log(`Expired ${count} timed-out waitpoints`);
1500
+ }
1501
+ return count;
1502
+ } catch (error) {
1503
+ await client.query("ROLLBACK");
1504
+ log(`Error expiring timed-out waitpoints: ${error}`);
1505
+ throw error;
1506
+ } finally {
1507
+ client.release();
1508
+ }
1509
+ };
1510
+ function tryExtractPool(backend) {
1511
+ if (backend instanceof PostgresBackend) {
1512
+ return backend.getPool();
1513
+ }
1514
+ return null;
1515
+ }
1516
+ function buildBasicContext(backend, jobId, baseCtx) {
1517
+ const waitError = () => new Error(
1518
+ "Wait features (waitFor, waitUntil, createToken, waitForToken, ctx.run) are currently only supported with the PostgreSQL backend."
1519
+ );
1520
+ return {
1521
+ prolong: baseCtx.prolong,
1522
+ onTimeout: baseCtx.onTimeout,
1523
+ run: async (_stepName, fn) => {
1524
+ return fn();
1525
+ },
1526
+ waitFor: async () => {
1527
+ throw waitError();
1528
+ },
1529
+ waitUntil: async () => {
1530
+ throw waitError();
1531
+ },
1532
+ createToken: async () => {
1533
+ throw waitError();
1534
+ },
1535
+ waitForToken: async () => {
1536
+ throw waitError();
1537
+ },
1538
+ setProgress: async (percent) => {
1539
+ if (percent < 0 || percent > 100)
1540
+ throw new Error("Progress must be between 0 and 100");
1541
+ await backend.updateProgress(jobId, Math.round(percent));
1542
+ }
1543
+ };
1544
+ }
1545
+ function validateHandlerSerializable(handler, jobType) {
1546
+ try {
1547
+ const handlerString = handler.toString();
1548
+ if (handlerString.includes("this.") && !handlerString.match(/\([^)]*this[^)]*\)/)) {
1549
+ throw new Error(
1550
+ `Handler for job type "${jobType}" uses 'this' context which cannot be serialized. Use a regular function or avoid 'this' references when forceKillOnTimeout is enabled.`
1551
+ );
1552
+ }
1553
+ if (handlerString.includes("[native code]")) {
1554
+ throw new Error(
1555
+ `Handler for job type "${jobType}" contains native code which cannot be serialized. Ensure your handler is a plain function when forceKillOnTimeout is enabled.`
1556
+ );
1557
+ }
1558
+ try {
1559
+ new Function("return " + handlerString);
1560
+ } catch (parseError) {
1561
+ throw new Error(
1562
+ `Handler for job type "${jobType}" cannot be serialized: ${parseError instanceof Error ? parseError.message : String(parseError)}. When using forceKillOnTimeout, handlers must be serializable functions without closures over external variables.`
1563
+ );
1564
+ }
1565
+ } catch (error) {
1566
+ if (error instanceof Error) {
1567
+ throw error;
1568
+ }
1569
+ throw new Error(
1570
+ `Failed to validate handler serialization for job type "${jobType}": ${String(error)}`
1571
+ );
1572
+ }
1573
+ }
1574
+ async function runHandlerInWorker(handler, payload, timeoutMs, jobType) {
1575
+ validateHandlerSerializable(handler, jobType);
1576
+ return new Promise((resolve, reject) => {
1577
+ const workerCode = `
1578
+ (function() {
1579
+ const { parentPort, workerData } = require('worker_threads');
1580
+ const { handlerCode, payload, timeoutMs } = workerData;
1581
+
1582
+ // Create an AbortController for the handler
1583
+ const controller = new AbortController();
1584
+ const signal = controller.signal;
1585
+
1586
+ // Set up timeout
1587
+ const timeoutId = setTimeout(() => {
1588
+ controller.abort();
1589
+ parentPort.postMessage({ type: 'timeout' });
1590
+ }, timeoutMs);
1591
+
1592
+ try {
1593
+ // Execute the handler
1594
+ // Note: This uses Function constructor which requires the handler to be serializable.
1595
+ // The handler should be validated before reaching this point.
1596
+ let handlerFn;
1597
+ try {
1598
+ // Wrap handlerCode in parentheses to ensure it's treated as an expression
1599
+ // This handles both arrow functions and regular functions
1600
+ const wrappedCode = handlerCode.trim().startsWith('async') || handlerCode.trim().startsWith('function')
1601
+ ? handlerCode
1602
+ : '(' + handlerCode + ')';
1603
+ handlerFn = new Function('return ' + wrappedCode)();
1604
+ } catch (parseError) {
1605
+ clearTimeout(timeoutId);
1606
+ parentPort.postMessage({
1607
+ type: 'error',
1608
+ error: {
1609
+ message: 'Handler cannot be deserialized in worker thread. ' +
1610
+ 'Ensure your handler is a standalone function without closures over external variables. ' +
1611
+ 'Original error: ' + (parseError instanceof Error ? parseError.message : String(parseError)),
1612
+ stack: parseError instanceof Error ? parseError.stack : undefined,
1613
+ name: 'SerializationError',
1614
+ },
1615
+ });
1616
+ return;
1617
+ }
1618
+
1619
+ // Ensure handlerFn is actually a function
1620
+ if (typeof handlerFn !== 'function') {
1621
+ clearTimeout(timeoutId);
1622
+ parentPort.postMessage({
1623
+ type: 'error',
1624
+ error: {
1625
+ message: 'Handler deserialization did not produce a function. ' +
1626
+ 'Ensure your handler is a valid function when forceKillOnTimeout is enabled.',
1627
+ name: 'SerializationError',
1628
+ },
1629
+ });
1630
+ return;
1631
+ }
1632
+
1633
+ handlerFn(payload, signal)
1634
+ .then(() => {
1635
+ clearTimeout(timeoutId);
1636
+ parentPort.postMessage({ type: 'success' });
1637
+ })
1638
+ .catch((error) => {
1639
+ clearTimeout(timeoutId);
1640
+ parentPort.postMessage({
1641
+ type: 'error',
1642
+ error: {
1643
+ message: error.message,
1644
+ stack: error.stack,
1645
+ name: error.name,
1646
+ },
1647
+ });
1648
+ });
1649
+ } catch (error) {
1650
+ clearTimeout(timeoutId);
1651
+ parentPort.postMessage({
1652
+ type: 'error',
1653
+ error: {
1654
+ message: error.message,
1655
+ stack: error.stack,
1656
+ name: error.name,
1657
+ },
1658
+ });
1659
+ }
1660
+ })();
1661
+ `;
1662
+ const worker = new Worker(workerCode, {
1663
+ eval: true,
1664
+ workerData: {
1665
+ handlerCode: handler.toString(),
1666
+ payload,
1667
+ timeoutMs
1668
+ }
1669
+ });
1670
+ let resolved = false;
1671
+ worker.on("message", (message) => {
1672
+ if (resolved) return;
1673
+ resolved = true;
1674
+ if (message.type === "success") {
1675
+ resolve();
1676
+ } else if (message.type === "timeout") {
1677
+ const timeoutError = new Error(
1678
+ `Job timed out after ${timeoutMs} ms and was forcefully terminated`
1679
+ );
1680
+ timeoutError.failureReason = "timeout" /* Timeout */;
1681
+ reject(timeoutError);
1682
+ } else if (message.type === "error") {
1683
+ const error = new Error(message.error.message);
1684
+ error.stack = message.error.stack;
1685
+ error.name = message.error.name;
1686
+ reject(error);
1687
+ }
1688
+ });
1689
+ worker.on("error", (error) => {
1690
+ if (resolved) return;
1691
+ resolved = true;
1692
+ reject(error);
1693
+ });
1694
+ worker.on("exit", (code) => {
1695
+ if (resolved) return;
1696
+ if (code !== 0) {
1697
+ resolved = true;
1698
+ reject(new Error(`Worker stopped with exit code ${code}`));
1699
+ }
1700
+ });
1701
+ setTimeout(() => {
1702
+ if (!resolved) {
1703
+ resolved = true;
1704
+ worker.terminate().then(() => {
1705
+ const timeoutError = new Error(
1706
+ `Job timed out after ${timeoutMs} ms and was forcefully terminated`
1707
+ );
1708
+ timeoutError.failureReason = "timeout" /* Timeout */;
1709
+ reject(timeoutError);
1710
+ }).catch((err) => {
1711
+ reject(err);
1712
+ });
1713
+ }
1714
+ }, timeoutMs + 100);
1715
+ });
1716
+ }
1717
+ function calculateWaitUntil(duration) {
1718
+ const now = Date.now();
1719
+ let ms = 0;
1720
+ if (duration.seconds) ms += duration.seconds * 1e3;
1721
+ if (duration.minutes) ms += duration.minutes * 60 * 1e3;
1722
+ if (duration.hours) ms += duration.hours * 60 * 60 * 1e3;
1723
+ if (duration.days) ms += duration.days * 24 * 60 * 60 * 1e3;
1724
+ if (duration.weeks) ms += duration.weeks * 7 * 24 * 60 * 60 * 1e3;
1725
+ if (duration.months) ms += duration.months * 30 * 24 * 60 * 60 * 1e3;
1726
+ if (duration.years) ms += duration.years * 365 * 24 * 60 * 60 * 1e3;
1727
+ if (ms <= 0) {
1728
+ throw new Error(
1729
+ "waitFor duration must be positive. Provide at least one positive duration field."
1730
+ );
1731
+ }
1732
+ return new Date(now + ms);
1733
+ }
1734
+ async function resolveCompletedWaits(pool, stepData) {
1735
+ for (const key of Object.keys(stepData)) {
1736
+ if (!key.startsWith("__wait_")) continue;
1737
+ const entry = stepData[key];
1738
+ if (!entry || typeof entry !== "object" || entry.completed) continue;
1739
+ if (entry.type === "duration" || entry.type === "date") {
1740
+ stepData[key] = { ...entry, completed: true };
1741
+ } else if (entry.type === "token" && entry.tokenId) {
1742
+ const wp = await getWaitpoint(pool, entry.tokenId);
1743
+ if (wp && wp.status === "completed") {
1744
+ stepData[key] = {
1745
+ ...entry,
1746
+ completed: true,
1747
+ result: { ok: true, output: wp.output }
1748
+ };
1749
+ } else if (wp && wp.status === "timed_out") {
1750
+ stepData[key] = {
1751
+ ...entry,
1752
+ completed: true,
1753
+ result: { ok: false, error: "Token timed out" }
1754
+ };
1755
+ }
1756
+ }
1757
+ }
1758
+ }
1759
+ function buildWaitContext(backend, pool, jobId, stepData, baseCtx) {
1760
+ let waitCounter = 0;
1761
+ const ctx = {
1762
+ prolong: baseCtx.prolong,
1763
+ onTimeout: baseCtx.onTimeout,
1764
+ run: async (stepName, fn) => {
1765
+ const cached = stepData[stepName];
1766
+ if (cached && typeof cached === "object" && cached.__completed) {
1767
+ log(`Step "${stepName}" replayed from cache for job ${jobId}`);
1768
+ return cached.result;
1769
+ }
1770
+ const result = await fn();
1771
+ stepData[stepName] = { __completed: true, result };
1772
+ await updateStepData(pool, jobId, stepData);
1773
+ return result;
1774
+ },
1775
+ waitFor: async (duration) => {
1776
+ const waitKey = `__wait_${waitCounter++}`;
1777
+ const cached = stepData[waitKey];
1778
+ if (cached && typeof cached === "object" && cached.completed) {
1779
+ log(`Wait "${waitKey}" already completed for job ${jobId}, skipping`);
1780
+ return;
1781
+ }
1782
+ const waitUntilDate = calculateWaitUntil(duration);
1783
+ stepData[waitKey] = { type: "duration", completed: false };
1784
+ throw new WaitSignal("duration", waitUntilDate, void 0, stepData);
1785
+ },
1786
+ waitUntil: async (date) => {
1787
+ const waitKey = `__wait_${waitCounter++}`;
1788
+ const cached = stepData[waitKey];
1789
+ if (cached && typeof cached === "object" && cached.completed) {
1790
+ log(`Wait "${waitKey}" already completed for job ${jobId}, skipping`);
1791
+ return;
1792
+ }
1793
+ stepData[waitKey] = { type: "date", completed: false };
1794
+ throw new WaitSignal("date", date, void 0, stepData);
1795
+ },
1796
+ createToken: async (options) => {
1797
+ const token = await createWaitpoint(pool, jobId, options);
1798
+ return token;
1799
+ },
1800
+ waitForToken: async (tokenId) => {
1801
+ const waitKey = `__wait_${waitCounter++}`;
1802
+ const cached = stepData[waitKey];
1803
+ if (cached && typeof cached === "object" && cached.completed) {
1804
+ log(
1805
+ `Token wait "${waitKey}" already completed for job ${jobId}, returning cached result`
1806
+ );
1807
+ return cached.result;
1808
+ }
1809
+ const wp = await getWaitpoint(pool, tokenId);
1810
+ if (wp && wp.status === "completed") {
1811
+ const result = {
1812
+ ok: true,
1813
+ output: wp.output
1814
+ };
1815
+ stepData[waitKey] = {
1816
+ type: "token",
1817
+ tokenId,
1818
+ completed: true,
1819
+ result
1820
+ };
1821
+ await updateStepData(pool, jobId, stepData);
1822
+ return result;
1823
+ }
1824
+ if (wp && wp.status === "timed_out") {
1825
+ const result = {
1826
+ ok: false,
1827
+ error: "Token timed out"
1828
+ };
1829
+ stepData[waitKey] = {
1830
+ type: "token",
1831
+ tokenId,
1832
+ completed: true,
1833
+ result
1834
+ };
1835
+ await updateStepData(pool, jobId, stepData);
1836
+ return result;
1837
+ }
1838
+ stepData[waitKey] = { type: "token", tokenId, completed: false };
1839
+ throw new WaitSignal("token", void 0, tokenId, stepData);
1840
+ },
1841
+ setProgress: async (percent) => {
1842
+ if (percent < 0 || percent > 100)
1843
+ throw new Error("Progress must be between 0 and 100");
1844
+ await backend.updateProgress(jobId, Math.round(percent));
1845
+ }
1846
+ };
1847
+ return ctx;
1848
+ }
1849
+ async function processJobWithHandlers(backend, job, jobHandlers) {
1850
+ const handler = jobHandlers[job.jobType];
1851
+ if (!handler) {
1852
+ await backend.setPendingReasonForUnpickedJobs(
1853
+ `No handler registered for job type: ${job.jobType}`,
1854
+ job.jobType
1855
+ );
1856
+ await backend.failJob(
1857
+ job.id,
1858
+ new Error(`No handler registered for job type: ${job.jobType}`),
1859
+ "no_handler" /* NoHandler */
1860
+ );
1861
+ return;
1862
+ }
1863
+ const stepData = { ...job.stepData || {} };
1864
+ const pool = tryExtractPool(backend);
1865
+ const hasStepHistory = Object.keys(stepData).some(
1866
+ (k) => k.startsWith("__wait_")
1867
+ );
1868
+ if (hasStepHistory && pool) {
1869
+ await resolveCompletedWaits(pool, stepData);
1870
+ await updateStepData(pool, job.id, stepData);
1871
+ }
1872
+ const timeoutMs = job.timeoutMs ?? void 0;
1873
+ const forceKillOnTimeout = job.forceKillOnTimeout ?? false;
1874
+ let timeoutId;
1875
+ const controller = new AbortController();
1876
+ try {
1877
+ if (forceKillOnTimeout && timeoutMs && timeoutMs > 0) {
1878
+ await runHandlerInWorker(handler, job.payload, timeoutMs, job.jobType);
1879
+ } else {
1880
+ let onTimeoutCallback;
1881
+ let timeoutReject;
1882
+ const armTimeout = (ms) => {
1883
+ if (timeoutId) clearTimeout(timeoutId);
1884
+ timeoutId = setTimeout(() => {
1885
+ if (onTimeoutCallback) {
1886
+ try {
1887
+ const extension = onTimeoutCallback();
1888
+ if (typeof extension === "number" && extension > 0) {
1889
+ backend.prolongJob(job.id).catch(() => {
1890
+ });
1891
+ armTimeout(extension);
1892
+ return;
1893
+ }
1894
+ } catch (callbackError) {
1895
+ log(
1896
+ `onTimeout callback threw for job ${job.id}: ${callbackError}`
1897
+ );
1898
+ }
1899
+ }
1900
+ controller.abort();
1901
+ const timeoutError = new Error(`Job timed out after ${ms} ms`);
1902
+ timeoutError.failureReason = "timeout" /* Timeout */;
1903
+ if (timeoutReject) {
1904
+ timeoutReject(timeoutError);
1905
+ }
1906
+ }, ms);
1907
+ };
1908
+ const hasTimeout = timeoutMs != null && timeoutMs > 0;
1909
+ const baseCtx = hasTimeout ? {
1910
+ prolong: (ms) => {
1911
+ const duration = ms ?? timeoutMs;
1912
+ if (duration != null && duration > 0) {
1913
+ armTimeout(duration);
1914
+ backend.prolongJob(job.id).catch(() => {
1915
+ });
1916
+ }
1917
+ },
1918
+ onTimeout: (callback) => {
1919
+ onTimeoutCallback = callback;
1920
+ }
1921
+ } : {
1922
+ prolong: () => {
1923
+ log("prolong() called but ignored: job has no timeout set");
1924
+ },
1925
+ onTimeout: () => {
1926
+ log("onTimeout() called but ignored: job has no timeout set");
1927
+ }
1928
+ };
1929
+ const ctx = pool ? buildWaitContext(backend, pool, job.id, stepData, baseCtx) : buildBasicContext(backend, job.id, baseCtx);
1930
+ if (forceKillOnTimeout && !hasTimeout) {
1931
+ log(
1932
+ `forceKillOnTimeout is set but no timeoutMs for job ${job.id}, running without force kill`
1933
+ );
1934
+ }
1935
+ const jobPromise = handler(job.payload, controller.signal, ctx);
1936
+ if (hasTimeout) {
1937
+ await Promise.race([
1938
+ jobPromise,
1939
+ new Promise((_, reject) => {
1940
+ timeoutReject = reject;
1941
+ armTimeout(timeoutMs);
1942
+ })
1943
+ ]);
1944
+ } else {
1945
+ await jobPromise;
1946
+ }
1947
+ }
1948
+ if (timeoutId) clearTimeout(timeoutId);
1949
+ await backend.completeJob(job.id);
1950
+ } catch (error) {
1951
+ if (timeoutId) clearTimeout(timeoutId);
1952
+ if (error instanceof WaitSignal) {
1953
+ if (!pool) {
1954
+ await backend.failJob(
1955
+ job.id,
1956
+ new Error(
1957
+ "WaitSignal received but wait features require the PostgreSQL backend."
1958
+ ),
1959
+ "handler_error" /* HandlerError */
1960
+ );
1961
+ return;
1962
+ }
1963
+ log(
1964
+ `Job ${job.id} entering wait: type=${error.type}, waitUntil=${error.waitUntil?.toISOString() ?? "none"}, tokenId=${error.tokenId ?? "none"}`
1965
+ );
1966
+ await waitJob(pool, job.id, {
1967
+ waitUntil: error.waitUntil,
1968
+ waitTokenId: error.tokenId,
1969
+ stepData: error.stepData
1970
+ });
1971
+ return;
1972
+ }
1973
+ console.error(`Error processing job ${job.id}:`, error);
1974
+ let failureReason = "handler_error" /* HandlerError */;
1975
+ if (error && typeof error === "object" && "failureReason" in error && error.failureReason === "timeout" /* Timeout */) {
1976
+ failureReason = "timeout" /* Timeout */;
1977
+ }
1978
+ await backend.failJob(
1979
+ job.id,
1980
+ error instanceof Error ? error : new Error(String(error)),
1981
+ failureReason
1982
+ );
1983
+ }
1984
+ }
1985
+ async function processBatchWithHandlers(backend, workerId, batchSize, jobType, jobHandlers, concurrency, onError) {
1986
+ const jobs = await backend.getNextBatch(
1987
+ workerId,
1988
+ batchSize,
1989
+ jobType
1990
+ );
1991
+ if (!concurrency || concurrency >= jobs.length) {
1992
+ await Promise.all(
1993
+ jobs.map((job) => processJobWithHandlers(backend, job, jobHandlers))
1994
+ );
1995
+ return jobs.length;
1996
+ }
1997
+ let idx = 0;
1998
+ let running = 0;
1999
+ let finished = 0;
2000
+ return new Promise((resolve, reject) => {
2001
+ const next = () => {
2002
+ if (finished === jobs.length) return resolve(jobs.length);
2003
+ while (running < concurrency && idx < jobs.length) {
2004
+ const job = jobs[idx++];
2005
+ running++;
2006
+ processJobWithHandlers(backend, job, jobHandlers).then(() => {
2007
+ running--;
2008
+ finished++;
2009
+ next();
2010
+ }).catch((err) => {
2011
+ running--;
2012
+ finished++;
2013
+ if (onError) {
2014
+ onError(err instanceof Error ? err : new Error(String(err)));
2015
+ }
2016
+ next();
2017
+ });
2018
+ }
2019
+ };
2020
+ next();
2021
+ });
2022
+ }
2023
+ var createProcessor = (backend, handlers, options = {}, onBeforeBatch) => {
2024
+ const {
2025
+ workerId = `worker-${Math.random().toString(36).substring(2, 9)}`,
2026
+ batchSize = 10,
2027
+ pollInterval = 5e3,
2028
+ onError = (error) => console.error("Job processor error:", error),
2029
+ jobType,
2030
+ concurrency = 3
2031
+ } = options;
2032
+ let running = false;
2033
+ let intervalId = null;
2034
+ let currentBatchPromise = null;
2035
+ setLogContext(options.verbose ?? false);
2036
+ const processJobs = async () => {
2037
+ if (!running) return 0;
2038
+ if (onBeforeBatch) {
2039
+ try {
2040
+ await onBeforeBatch();
2041
+ } catch (hookError) {
2042
+ log(`onBeforeBatch hook error: ${hookError}`);
2043
+ if (onError) {
2044
+ onError(
2045
+ hookError instanceof Error ? hookError : new Error(String(hookError))
2046
+ );
2047
+ }
2048
+ }
2049
+ }
2050
+ log(
2051
+ `Processing jobs with workerId: ${workerId}${jobType ? ` and jobType: ${Array.isArray(jobType) ? jobType.join(",") : jobType}` : ""}`
2052
+ );
2053
+ try {
2054
+ const processed = await processBatchWithHandlers(
2055
+ backend,
2056
+ workerId,
2057
+ batchSize,
2058
+ jobType,
2059
+ handlers,
2060
+ concurrency,
2061
+ onError
2062
+ );
2063
+ return processed;
2064
+ } catch (error) {
2065
+ onError(error instanceof Error ? error : new Error(String(error)));
2066
+ }
2067
+ return 0;
2068
+ };
2069
+ return {
2070
+ /**
2071
+ * Start the job processor in the background.
2072
+ * - This will run periodically (every pollInterval milliseconds or 5 seconds if not provided) and process jobs as they become available.
2073
+ * - You have to call the stop method to stop the processor.
2074
+ */
2075
+ startInBackground: () => {
2076
+ if (running) return;
2077
+ log(`Starting job processor with workerId: ${workerId}`);
2078
+ running = true;
2079
+ const scheduleNext = (immediate) => {
2080
+ if (!running) return;
2081
+ if (immediate) {
2082
+ intervalId = setTimeout(loop, 0);
2083
+ } else {
2084
+ intervalId = setTimeout(loop, pollInterval);
2085
+ }
2086
+ };
2087
+ const loop = async () => {
2088
+ if (!running) return;
2089
+ currentBatchPromise = processJobs();
2090
+ const processed = await currentBatchPromise;
2091
+ currentBatchPromise = null;
2092
+ scheduleNext(processed === batchSize);
2093
+ };
2094
+ loop();
2095
+ },
2096
+ /**
2097
+ * Stop the job processor that runs in the background.
2098
+ * Does not wait for in-flight jobs.
2099
+ */
2100
+ stop: () => {
2101
+ log(`Stopping job processor with workerId: ${workerId}`);
2102
+ running = false;
2103
+ if (intervalId) {
2104
+ clearTimeout(intervalId);
2105
+ intervalId = null;
2106
+ }
2107
+ },
2108
+ /**
2109
+ * Stop the job processor and wait for all in-flight jobs to complete.
2110
+ * Useful for graceful shutdown (e.g., SIGTERM handling).
2111
+ */
2112
+ stopAndDrain: async (drainTimeoutMs = 3e4) => {
2113
+ log(`Stopping and draining job processor with workerId: ${workerId}`);
2114
+ running = false;
2115
+ if (intervalId) {
2116
+ clearTimeout(intervalId);
2117
+ intervalId = null;
2118
+ }
2119
+ if (currentBatchPromise) {
2120
+ await Promise.race([
2121
+ currentBatchPromise.catch(() => {
2122
+ }),
2123
+ new Promise((resolve) => setTimeout(resolve, drainTimeoutMs))
2124
+ ]);
2125
+ currentBatchPromise = null;
2126
+ }
2127
+ log(`Job processor ${workerId} drained`);
2128
+ },
2129
+ /**
2130
+ * Start the job processor synchronously.
2131
+ * - This will process all jobs immediately and then stop.
2132
+ * - The pollInterval is ignored.
2133
+ */
2134
+ start: async () => {
2135
+ log(`Starting job processor with workerId: ${workerId}`);
2136
+ running = true;
2137
+ const processed = await processJobs();
2138
+ running = false;
2139
+ return processed;
2140
+ },
2141
+ isRunning: () => running
2142
+ };
2143
+ };
2144
+ function loadPemOrFile(value) {
2145
+ if (!value) return void 0;
2146
+ if (value.startsWith("file://")) {
2147
+ const filePath = value.slice(7);
2148
+ return fs.readFileSync(filePath, "utf8");
2149
+ }
2150
+ return value;
2151
+ }
2152
+ var createPool = (config) => {
2153
+ let searchPath;
2154
+ let ssl = void 0;
2155
+ let customCA;
2156
+ let sslmode;
2157
+ if (config.connectionString) {
2158
+ try {
2159
+ const url = new URL(config.connectionString);
2160
+ searchPath = url.searchParams.get("search_path") || void 0;
2161
+ sslmode = url.searchParams.get("sslmode") || void 0;
2162
+ if (sslmode === "no-verify") {
2163
+ ssl = { rejectUnauthorized: false };
2164
+ }
2165
+ } catch (e) {
2166
+ const parsed = parse(config.connectionString);
2167
+ if (parsed.options) {
2168
+ const match = parsed.options.match(/search_path=([^\s]+)/);
2169
+ if (match) {
2170
+ searchPath = match[1];
2171
+ }
2172
+ }
2173
+ sslmode = typeof parsed.sslmode === "string" ? parsed.sslmode : void 0;
2174
+ if (sslmode === "no-verify") {
2175
+ ssl = { rejectUnauthorized: false };
2176
+ }
2177
+ }
2178
+ }
2179
+ if (config.ssl) {
2180
+ if (typeof config.ssl.ca === "string") {
2181
+ customCA = config.ssl.ca;
2182
+ } else if (typeof process.env.PGSSLROOTCERT === "string") {
2183
+ customCA = process.env.PGSSLROOTCERT;
2184
+ } else {
2185
+ customCA = void 0;
2186
+ }
2187
+ const caValue = typeof customCA === "string" ? loadPemOrFile(customCA) : void 0;
2188
+ ssl = {
2189
+ ...ssl,
2190
+ ...caValue ? { ca: caValue } : {},
2191
+ cert: loadPemOrFile(
2192
+ typeof config.ssl.cert === "string" ? config.ssl.cert : process.env.PGSSLCERT
2193
+ ),
2194
+ key: loadPemOrFile(
2195
+ typeof config.ssl.key === "string" ? config.ssl.key : process.env.PGSSLKEY
2196
+ ),
2197
+ rejectUnauthorized: config.ssl.rejectUnauthorized !== void 0 ? config.ssl.rejectUnauthorized : true
2198
+ };
2199
+ }
2200
+ if (sslmode && customCA) {
2201
+ const warning = `
2202
+
2203
+ \x1B[33m**************************************************
2204
+ \u26A0\uFE0F WARNING: SSL CONFIGURATION ISSUE
2205
+ **************************************************
2206
+ Both sslmode ('${sslmode}') is set in the connection string
2207
+ and a custom CA is provided (via config.ssl.ca or PGSSLROOTCERT).
2208
+ This combination may cause connection failures or unexpected behavior.
2209
+
2210
+ Recommended: Remove sslmode from the connection string when using a custom CA.
2211
+ **************************************************\x1B[0m
2212
+ `;
2213
+ console.warn(warning);
2214
+ }
2215
+ const pool = new Pool({
2216
+ ...config,
2217
+ ...ssl ? { ssl } : {}
2218
+ });
2219
+ if (searchPath) {
2220
+ pool.on("connect", (client) => {
2221
+ client.query(`SET search_path TO ${searchPath}`);
2222
+ });
2223
+ }
2224
+ return pool;
2225
+ };
2226
+
2227
+ // src/backends/redis-scripts.ts
2228
+ var SCORE_RANGE = "1000000000000000";
2229
+ var ADD_JOB_SCRIPT = `
2230
+ local prefix = KEYS[1]
2231
+ local jobType = ARGV[1]
2232
+ local payloadJson = ARGV[2]
2233
+ local maxAttempts = tonumber(ARGV[3])
2234
+ local priority = tonumber(ARGV[4])
2235
+ local runAtMs = ARGV[5] -- "0" means now
2236
+ local timeoutMs = ARGV[6] -- "null" string if not set
2237
+ local forceKillOnTimeout = ARGV[7]
2238
+ local tagsJson = ARGV[8] -- "null" or JSON array string
2239
+ local idempotencyKey = ARGV[9] -- "null" string if not set
2240
+ local nowMs = tonumber(ARGV[10])
2241
+
2242
+ -- Idempotency check
2243
+ if idempotencyKey ~= "null" then
2244
+ local existing = redis.call('GET', prefix .. 'idempotency:' .. idempotencyKey)
2245
+ if existing then
2246
+ return existing
2247
+ end
2248
+ end
2249
+
2250
+ -- Generate ID
2251
+ local id = redis.call('INCR', prefix .. 'id_seq')
2252
+ local jobKey = prefix .. 'job:' .. id
2253
+ local runAt = runAtMs ~= "0" and tonumber(runAtMs) or nowMs
2254
+
2255
+ -- Store the job hash
2256
+ redis.call('HMSET', jobKey,
2257
+ 'id', id,
2258
+ 'jobType', jobType,
2259
+ 'payload', payloadJson,
2260
+ 'status', 'pending',
2261
+ 'maxAttempts', maxAttempts,
2262
+ 'attempts', 0,
2263
+ 'priority', priority,
2264
+ 'runAt', runAt,
2265
+ 'timeoutMs', timeoutMs,
2266
+ 'forceKillOnTimeout', forceKillOnTimeout,
2267
+ 'createdAt', nowMs,
2268
+ 'updatedAt', nowMs,
2269
+ 'lockedAt', 'null',
2270
+ 'lockedBy', 'null',
2271
+ 'nextAttemptAt', 'null',
2272
+ 'pendingReason', 'null',
2273
+ 'errorHistory', '[]',
2274
+ 'failureReason', 'null',
2275
+ 'completedAt', 'null',
2276
+ 'startedAt', 'null',
2277
+ 'lastRetriedAt', 'null',
2278
+ 'lastFailedAt', 'null',
2279
+ 'lastCancelledAt', 'null',
2280
+ 'tags', tagsJson,
2281
+ 'idempotencyKey', idempotencyKey
2282
+ )
2283
+
2284
+ -- Status index
2285
+ redis.call('SADD', prefix .. 'status:pending', id)
2286
+
2287
+ -- Type index
2288
+ redis.call('SADD', prefix .. 'type:' .. jobType, id)
2289
+
2290
+ -- Tag indexes
2291
+ if tagsJson ~= "null" then
2292
+ local tags = cjson.decode(tagsJson)
2293
+ for _, tag in ipairs(tags) do
2294
+ redis.call('SADD', prefix .. 'tag:' .. tag, id)
2295
+ end
2296
+ -- Store tags for exact-match queries
2297
+ for _, tag in ipairs(tags) do
2298
+ redis.call('SADD', prefix .. 'job:' .. id .. ':tags', tag)
2299
+ end
2300
+ end
2301
+
2302
+ -- Idempotency mapping
2303
+ if idempotencyKey ~= "null" then
2304
+ redis.call('SET', prefix .. 'idempotency:' .. idempotencyKey, id)
2305
+ end
2306
+
2307
+ -- All-jobs sorted set (for ordering by createdAt)
2308
+ redis.call('ZADD', prefix .. 'all', nowMs, id)
2309
+
2310
+ -- Queue or delayed
2311
+ if runAt <= nowMs then
2312
+ -- Ready now: add to queue with priority score
2313
+ local score = priority * ${SCORE_RANGE} + (${SCORE_RANGE} - nowMs)
2314
+ redis.call('ZADD', prefix .. 'queue', score, id)
2315
+ else
2316
+ -- Future: add to delayed set
2317
+ redis.call('ZADD', prefix .. 'delayed', runAt, id)
2318
+ end
2319
+
2320
+ return id
2321
+ `;
2322
+ var GET_NEXT_BATCH_SCRIPT = `
2323
+ local prefix = KEYS[1]
2324
+ local workerId = ARGV[1]
2325
+ local batchSize = tonumber(ARGV[2])
2326
+ local nowMs = tonumber(ARGV[3])
2327
+ local jobTypeFilter = ARGV[4] -- "null" or JSON array or single string
2328
+
2329
+ -- 1. Move ready delayed jobs into queue
2330
+ local delayed = redis.call('ZRANGEBYSCORE', prefix .. 'delayed', '-inf', nowMs, 'LIMIT', 0, 200)
2331
+ for _, jobId in ipairs(delayed) do
2332
+ local jk = prefix .. 'job:' .. jobId
2333
+ local status = redis.call('HGET', jk, 'status')
2334
+ local attempts = tonumber(redis.call('HGET', jk, 'attempts'))
2335
+ local maxAttempts = tonumber(redis.call('HGET', jk, 'maxAttempts'))
2336
+ if status == 'pending' and attempts < maxAttempts then
2337
+ local pri = tonumber(redis.call('HGET', jk, 'priority') or '0')
2338
+ local ca = tonumber(redis.call('HGET', jk, 'createdAt'))
2339
+ local score = pri * ${SCORE_RANGE} + (${SCORE_RANGE} - ca)
2340
+ redis.call('ZADD', prefix .. 'queue', score, jobId)
2341
+ end
2342
+ redis.call('ZREM', prefix .. 'delayed', jobId)
2343
+ end
2344
+
2345
+ -- 2. Move ready retry jobs into queue
2346
+ local retries = redis.call('ZRANGEBYSCORE', prefix .. 'retry', '-inf', nowMs, 'LIMIT', 0, 200)
2347
+ for _, jobId in ipairs(retries) do
2348
+ local jk = prefix .. 'job:' .. jobId
2349
+ local status = redis.call('HGET', jk, 'status')
2350
+ local attempts = tonumber(redis.call('HGET', jk, 'attempts'))
2351
+ local maxAttempts = tonumber(redis.call('HGET', jk, 'maxAttempts'))
2352
+ if status == 'failed' and attempts < maxAttempts then
2353
+ local pri = tonumber(redis.call('HGET', jk, 'priority') or '0')
2354
+ local ca = tonumber(redis.call('HGET', jk, 'createdAt'))
2355
+ local score = pri * ${SCORE_RANGE} + (${SCORE_RANGE} - ca)
2356
+ redis.call('ZADD', prefix .. 'queue', score, jobId)
2357
+ redis.call('SREM', prefix .. 'status:failed', jobId)
2358
+ redis.call('SADD', prefix .. 'status:pending', jobId)
2359
+ redis.call('HMSET', jk, 'status', 'pending')
2360
+ end
2361
+ redis.call('ZREM', prefix .. 'retry', jobId)
2362
+ end
2363
+
2364
+ -- 3. Parse job type filter
2365
+ local filterTypes = nil
2366
+ if jobTypeFilter ~= "null" then
2367
+ -- Could be a JSON array or a plain string
2368
+ local ok, decoded = pcall(cjson.decode, jobTypeFilter)
2369
+ if ok and type(decoded) == 'table' then
2370
+ filterTypes = {}
2371
+ for _, t in ipairs(decoded) do filterTypes[t] = true end
2372
+ else
2373
+ filterTypes = { [jobTypeFilter] = true }
2374
+ end
2375
+ end
2376
+
2377
+ -- 4. Pop candidates from queue (highest score first)
2378
+ -- We pop more than batchSize because some may be filtered out
2379
+ local popCount = batchSize * 3
2380
+ local candidates = redis.call('ZPOPMAX', prefix .. 'queue', popCount)
2381
+ -- candidates: [member1, score1, member2, score2, ...]
2382
+
2383
+ local results = {}
2384
+ local jobsClaimed = 0
2385
+ local putBack = {} -- {score, id} pairs to put back
2386
+
2387
+ for i = 1, #candidates, 2 do
2388
+ local jobId = candidates[i]
2389
+ local score = candidates[i + 1]
2390
+ local jk = prefix .. 'job:' .. jobId
2391
+
2392
+ if jobsClaimed >= batchSize then
2393
+ -- We have enough; put the rest back
2394
+ table.insert(putBack, score)
2395
+ table.insert(putBack, jobId)
2396
+ else
2397
+ -- Check job type filter
2398
+ local jt = redis.call('HGET', jk, 'jobType')
2399
+ if filterTypes and not filterTypes[jt] then
2400
+ -- Doesn't match filter: put back
2401
+ table.insert(putBack, score)
2402
+ table.insert(putBack, jobId)
2403
+ else
2404
+ -- Check run_at
2405
+ local runAt = tonumber(redis.call('HGET', jk, 'runAt'))
2406
+ if runAt > nowMs then
2407
+ -- Not ready yet: move to delayed
2408
+ redis.call('ZADD', prefix .. 'delayed', runAt, jobId)
2409
+ else
2410
+ -- Claim this job
2411
+ local attempts = tonumber(redis.call('HGET', jk, 'attempts'))
2412
+ local startedAt = redis.call('HGET', jk, 'startedAt')
2413
+ local lastRetriedAt = redis.call('HGET', jk, 'lastRetriedAt')
2414
+ if startedAt == 'null' then startedAt = nowMs end
2415
+ if attempts > 0 then lastRetriedAt = nowMs end
2416
+
2417
+ redis.call('HMSET', jk,
2418
+ 'status', 'processing',
2419
+ 'lockedAt', nowMs,
2420
+ 'lockedBy', workerId,
2421
+ 'attempts', attempts + 1,
2422
+ 'updatedAt', nowMs,
2423
+ 'pendingReason', 'null',
2424
+ 'startedAt', startedAt,
2425
+ 'lastRetriedAt', lastRetriedAt
2426
+ )
2427
+
2428
+ -- Update status sets
2429
+ redis.call('SREM', prefix .. 'status:pending', jobId)
2430
+ redis.call('SADD', prefix .. 'status:processing', jobId)
2431
+
2432
+ -- Return job data as flat array
2433
+ local data = redis.call('HGETALL', jk)
2434
+ for _, v in ipairs(data) do
2435
+ table.insert(results, v)
2436
+ end
2437
+ -- Separator
2438
+ table.insert(results, '__JOB_SEP__')
2439
+ jobsClaimed = jobsClaimed + 1
2440
+ end
2441
+ end
2442
+ end
2443
+ end
2444
+
2445
+ -- Put back jobs we didn't claim
2446
+ if #putBack > 0 then
2447
+ redis.call('ZADD', prefix .. 'queue', unpack(putBack))
2448
+ end
2449
+
2450
+ return results
2451
+ `;
2452
+ var COMPLETE_JOB_SCRIPT = `
2453
+ local prefix = KEYS[1]
2454
+ local jobId = ARGV[1]
2455
+ local nowMs = ARGV[2]
2456
+ local jk = prefix .. 'job:' .. jobId
2457
+
2458
+ redis.call('HMSET', jk,
2459
+ 'status', 'completed',
2460
+ 'updatedAt', nowMs,
2461
+ 'completedAt', nowMs
2462
+ )
2463
+ redis.call('SREM', prefix .. 'status:processing', jobId)
2464
+ redis.call('SADD', prefix .. 'status:completed', jobId)
2465
+
2466
+ return 1
2467
+ `;
2468
+ var FAIL_JOB_SCRIPT = `
2469
+ local prefix = KEYS[1]
2470
+ local jobId = ARGV[1]
2471
+ local errorJson = ARGV[2]
2472
+ local failureReason = ARGV[3]
2473
+ local nowMs = tonumber(ARGV[4])
2474
+ local jk = prefix .. 'job:' .. jobId
2475
+
2476
+ local attempts = tonumber(redis.call('HGET', jk, 'attempts'))
2477
+ local maxAttempts = tonumber(redis.call('HGET', jk, 'maxAttempts'))
2478
+
2479
+ -- Compute next_attempt_at: 2^attempts minutes from now
2480
+ local nextAttemptAt = 'null'
2481
+ if attempts < maxAttempts then
2482
+ local delayMs = math.pow(2, attempts) * 60000
2483
+ nextAttemptAt = nowMs + delayMs
2484
+ end
2485
+
2486
+ -- Append to error_history
2487
+ local history = redis.call('HGET', jk, 'errorHistory') or '[]'
2488
+ local ok, arr = pcall(cjson.decode, history)
2489
+ if not ok then arr = {} end
2490
+ local newErrors = cjson.decode(errorJson)
2491
+ for _, e in ipairs(newErrors) do
2492
+ table.insert(arr, e)
2493
+ end
2494
+
2495
+ redis.call('HMSET', jk,
2496
+ 'status', 'failed',
2497
+ 'updatedAt', nowMs,
2498
+ 'nextAttemptAt', tostring(nextAttemptAt),
2499
+ 'errorHistory', cjson.encode(arr),
2500
+ 'failureReason', failureReason,
2501
+ 'lastFailedAt', nowMs
2502
+ )
2503
+ redis.call('SREM', prefix .. 'status:processing', jobId)
2504
+ redis.call('SADD', prefix .. 'status:failed', jobId)
2505
+
2506
+ -- Schedule retry if applicable
2507
+ if nextAttemptAt ~= 'null' then
2508
+ redis.call('ZADD', prefix .. 'retry', nextAttemptAt, jobId)
2509
+ end
2510
+
2511
+ return 1
2512
+ `;
2513
+ var RETRY_JOB_SCRIPT = `
2514
+ local prefix = KEYS[1]
2515
+ local jobId = ARGV[1]
2516
+ local nowMs = tonumber(ARGV[2])
2517
+ local jk = prefix .. 'job:' .. jobId
2518
+
2519
+ local oldStatus = redis.call('HGET', jk, 'status')
2520
+
2521
+ redis.call('HMSET', jk,
2522
+ 'status', 'pending',
2523
+ 'updatedAt', nowMs,
2524
+ 'lockedAt', 'null',
2525
+ 'lockedBy', 'null',
2526
+ 'nextAttemptAt', nowMs,
2527
+ 'lastRetriedAt', nowMs
2528
+ )
2529
+
2530
+ -- Remove from old status, add to pending
2531
+ if oldStatus then
2532
+ redis.call('SREM', prefix .. 'status:' .. oldStatus, jobId)
2533
+ end
2534
+ redis.call('SADD', prefix .. 'status:pending', jobId)
2535
+
2536
+ -- Remove from retry sorted set if present
2537
+ redis.call('ZREM', prefix .. 'retry', jobId)
2538
+
2539
+ -- Add to queue (ready now)
2540
+ local priority = tonumber(redis.call('HGET', jk, 'priority') or '0')
2541
+ local createdAt = tonumber(redis.call('HGET', jk, 'createdAt'))
2542
+ local score = priority * ${SCORE_RANGE} + (${SCORE_RANGE} - createdAt)
2543
+ redis.call('ZADD', prefix .. 'queue', score, jobId)
2544
+
2545
+ return 1
2546
+ `;
2547
+ var CANCEL_JOB_SCRIPT = `
2548
+ local prefix = KEYS[1]
2549
+ local jobId = ARGV[1]
2550
+ local nowMs = ARGV[2]
2551
+ local jk = prefix .. 'job:' .. jobId
2552
+
2553
+ local status = redis.call('HGET', jk, 'status')
2554
+ if status ~= 'pending' then return 0 end
2555
+
2556
+ redis.call('HMSET', jk,
2557
+ 'status', 'cancelled',
2558
+ 'updatedAt', nowMs,
2559
+ 'lastCancelledAt', nowMs
2560
+ )
2561
+ redis.call('SREM', prefix .. 'status:pending', jobId)
2562
+ redis.call('SADD', prefix .. 'status:cancelled', jobId)
2563
+ -- Remove from queue / delayed
2564
+ redis.call('ZREM', prefix .. 'queue', jobId)
2565
+ redis.call('ZREM', prefix .. 'delayed', jobId)
2566
+
2567
+ return 1
2568
+ `;
2569
+ var PROLONG_JOB_SCRIPT = `
2570
+ local prefix = KEYS[1]
2571
+ local jobId = ARGV[1]
2572
+ local nowMs = ARGV[2]
2573
+ local jk = prefix .. 'job:' .. jobId
2574
+
2575
+ local status = redis.call('HGET', jk, 'status')
2576
+ if status ~= 'processing' then return 0 end
2577
+
2578
+ redis.call('HMSET', jk,
2579
+ 'lockedAt', nowMs,
2580
+ 'updatedAt', nowMs
2581
+ )
2582
+
2583
+ return 1
2584
+ `;
2585
+ var RECLAIM_STUCK_JOBS_SCRIPT = `
2586
+ local prefix = KEYS[1]
2587
+ local maxAgeMs = tonumber(ARGV[1])
2588
+ local nowMs = tonumber(ARGV[2])
2589
+
2590
+ local processing = redis.call('SMEMBERS', prefix .. 'status:processing')
2591
+ local count = 0
2592
+
2593
+ for _, jobId in ipairs(processing) do
2594
+ local jk = prefix .. 'job:' .. jobId
2595
+ local lockedAt = redis.call('HGET', jk, 'lockedAt')
2596
+ if lockedAt and lockedAt ~= 'null' then
2597
+ local lockedAtNum = tonumber(lockedAt)
2598
+ if lockedAtNum then
2599
+ -- Use the greater of maxAgeMs and the job's own timeoutMs
2600
+ local jobMaxAge = maxAgeMs
2601
+ local timeoutMs = redis.call('HGET', jk, 'timeoutMs')
2602
+ if timeoutMs and timeoutMs ~= 'null' then
2603
+ local tMs = tonumber(timeoutMs)
2604
+ if tMs and tMs > jobMaxAge then
2605
+ jobMaxAge = tMs
2606
+ end
2607
+ end
2608
+ local cutoff = nowMs - jobMaxAge
2609
+ if lockedAtNum < cutoff then
2610
+ redis.call('HMSET', jk,
2611
+ 'status', 'pending',
2612
+ 'lockedAt', 'null',
2613
+ 'lockedBy', 'null',
2614
+ 'updatedAt', nowMs
2615
+ )
2616
+ redis.call('SREM', prefix .. 'status:processing', jobId)
2617
+ redis.call('SADD', prefix .. 'status:pending', jobId)
2618
+
2619
+ -- Re-add to queue
2620
+ local priority = tonumber(redis.call('HGET', jk, 'priority') or '0')
2621
+ local createdAt = tonumber(redis.call('HGET', jk, 'createdAt'))
2622
+ local score = priority * ${SCORE_RANGE} + (${SCORE_RANGE} - createdAt)
2623
+ redis.call('ZADD', prefix .. 'queue', score, jobId)
2624
+
2625
+ count = count + 1
2626
+ end
2627
+ end
2628
+ end
2629
+ end
2630
+
2631
+ return count
2632
+ `;
2633
+ var CLEANUP_OLD_JOBS_SCRIPT = `
2634
+ local prefix = KEYS[1]
2635
+ local cutoffMs = tonumber(ARGV[1])
2636
+
2637
+ local completed = redis.call('SMEMBERS', prefix .. 'status:completed')
2638
+ local count = 0
2639
+
2640
+ for _, jobId in ipairs(completed) do
2641
+ local jk = prefix .. 'job:' .. jobId
2642
+ local updatedAt = tonumber(redis.call('HGET', jk, 'updatedAt'))
2643
+ if updatedAt and updatedAt < cutoffMs then
2644
+ -- Remove all indexes
2645
+ local jobType = redis.call('HGET', jk, 'jobType')
2646
+ local tagsJson = redis.call('HGET', jk, 'tags')
2647
+ local idempotencyKey = redis.call('HGET', jk, 'idempotencyKey')
2648
+
2649
+ redis.call('DEL', jk)
2650
+ redis.call('SREM', prefix .. 'status:completed', jobId)
2651
+ redis.call('ZREM', prefix .. 'all', jobId)
2652
+ if jobType then
2653
+ redis.call('SREM', prefix .. 'type:' .. jobType, jobId)
2654
+ end
2655
+ if tagsJson and tagsJson ~= 'null' then
2656
+ local ok, tags = pcall(cjson.decode, tagsJson)
2657
+ if ok and type(tags) == 'table' then
2658
+ for _, tag in ipairs(tags) do
2659
+ redis.call('SREM', prefix .. 'tag:' .. tag, jobId)
2660
+ end
2661
+ end
2662
+ redis.call('DEL', prefix .. 'job:' .. jobId .. ':tags')
2663
+ end
2664
+ if idempotencyKey and idempotencyKey ~= 'null' then
2665
+ redis.call('DEL', prefix .. 'idempotency:' .. idempotencyKey)
2666
+ end
2667
+ -- Delete events
2668
+ redis.call('DEL', prefix .. 'events:' .. jobId)
2669
+
2670
+ count = count + 1
2671
+ end
2672
+ end
2673
+
2674
+ return count
2675
+ `;
2676
+
2677
+ // src/backends/redis.ts
2678
+ function hashToObject(arr) {
2679
+ const obj = {};
2680
+ for (let i = 0; i < arr.length; i += 2) {
2681
+ obj[arr[i]] = arr[i + 1];
2682
+ }
2683
+ return obj;
2684
+ }
2685
+ function deserializeJob(h) {
2686
+ const nullish = (v) => v === void 0 || v === "null" || v === "" ? null : v;
2687
+ const numOrNull = (v) => {
2688
+ const n = nullish(v);
2689
+ return n === null ? null : Number(n);
2690
+ };
2691
+ const dateOrNull = (v) => {
2692
+ const n = numOrNull(v);
2693
+ return n === null ? null : new Date(n);
2694
+ };
2695
+ let errorHistory = [];
2696
+ try {
2697
+ const raw = h.errorHistory;
2698
+ if (raw && raw !== "[]") {
2699
+ errorHistory = JSON.parse(raw);
2700
+ }
2701
+ } catch {
2702
+ }
2703
+ let tags;
2704
+ try {
2705
+ const raw = h.tags;
2706
+ if (raw && raw !== "null") {
2707
+ tags = JSON.parse(raw);
2708
+ }
2709
+ } catch {
2710
+ }
2711
+ let payload;
2712
+ try {
2713
+ payload = JSON.parse(h.payload);
2714
+ } catch {
2715
+ payload = h.payload;
2716
+ }
2717
+ return {
2718
+ id: Number(h.id),
2719
+ jobType: h.jobType,
2720
+ payload,
2721
+ status: h.status,
2722
+ createdAt: new Date(Number(h.createdAt)),
2723
+ updatedAt: new Date(Number(h.updatedAt)),
2724
+ lockedAt: dateOrNull(h.lockedAt),
2725
+ lockedBy: nullish(h.lockedBy),
2726
+ attempts: Number(h.attempts),
2727
+ maxAttempts: Number(h.maxAttempts),
2728
+ nextAttemptAt: dateOrNull(h.nextAttemptAt),
2729
+ priority: Number(h.priority),
2730
+ runAt: new Date(Number(h.runAt)),
2731
+ pendingReason: nullish(h.pendingReason),
2732
+ errorHistory,
2733
+ timeoutMs: numOrNull(h.timeoutMs),
2734
+ forceKillOnTimeout: h.forceKillOnTimeout === "true" || h.forceKillOnTimeout === "1" ? true : h.forceKillOnTimeout === "false" || h.forceKillOnTimeout === "0" ? false : null,
2735
+ failureReason: nullish(h.failureReason) ?? null,
2736
+ completedAt: dateOrNull(h.completedAt),
2737
+ startedAt: dateOrNull(h.startedAt),
2738
+ lastRetriedAt: dateOrNull(h.lastRetriedAt),
2739
+ lastFailedAt: dateOrNull(h.lastFailedAt),
2740
+ lastCancelledAt: dateOrNull(h.lastCancelledAt),
2741
+ tags,
2742
+ idempotencyKey: nullish(h.idempotencyKey),
2743
+ progress: numOrNull(h.progress)
2744
+ };
2745
+ }
2746
+ var RedisBackend = class {
2747
+ constructor(redisConfig) {
2748
+ let IORedis;
2749
+ try {
2750
+ const _require = createRequire(import.meta.url);
2751
+ IORedis = _require("ioredis");
2752
+ } catch {
2753
+ throw new Error(
2754
+ 'Redis backend requires the "ioredis" package. Install it with: npm install ioredis'
2755
+ );
2756
+ }
2757
+ this.prefix = redisConfig.keyPrefix ?? "dq:";
2758
+ if (redisConfig.url) {
2759
+ this.client = new IORedis(redisConfig.url, {
2760
+ ...redisConfig.tls ? { tls: redisConfig.tls } : {},
2761
+ ...redisConfig.db !== void 0 ? { db: redisConfig.db } : {}
2762
+ });
2763
+ } else {
2764
+ this.client = new IORedis({
2765
+ host: redisConfig.host ?? "127.0.0.1",
2766
+ port: redisConfig.port ?? 6379,
2767
+ password: redisConfig.password,
2768
+ db: redisConfig.db ?? 0,
2769
+ ...redisConfig.tls ? { tls: redisConfig.tls } : {}
2770
+ });
2771
+ }
2772
+ }
2773
+ /** Expose the raw ioredis client for advanced usage. */
2774
+ getClient() {
2775
+ return this.client;
2776
+ }
2777
+ nowMs() {
2778
+ return Date.now();
2779
+ }
2780
+ // ── Events ──────────────────────────────────────────────────────────
2781
+ async recordJobEvent(jobId, eventType, metadata) {
2782
+ try {
2783
+ const eventId = await this.client.incr(`${this.prefix}event_id_seq`);
2784
+ const event = JSON.stringify({
2785
+ id: eventId,
2786
+ jobId,
2787
+ eventType,
2788
+ createdAt: this.nowMs(),
2789
+ metadata: metadata ?? null
2790
+ });
2791
+ await this.client.rpush(`${this.prefix}events:${jobId}`, event);
2792
+ } catch (error) {
2793
+ log(`Error recording job event for job ${jobId}: ${error}`);
2794
+ }
2795
+ }
2796
+ async getJobEvents(jobId) {
2797
+ const raw = await this.client.lrange(
2798
+ `${this.prefix}events:${jobId}`,
2799
+ 0,
2800
+ -1
2801
+ );
2802
+ return raw.map((r) => {
2803
+ const e = JSON.parse(r);
2804
+ return {
2805
+ ...e,
2806
+ createdAt: new Date(e.createdAt)
2807
+ };
2808
+ });
2809
+ }
2810
+ // ── Job CRUD ──────────────────────────────────────────────────────────
2811
+ async addJob({
2812
+ jobType,
2813
+ payload,
2814
+ maxAttempts = 3,
2815
+ priority = 0,
2816
+ runAt = null,
2817
+ timeoutMs = void 0,
2818
+ forceKillOnTimeout = false,
2819
+ tags = void 0,
2820
+ idempotencyKey = void 0
2821
+ }) {
2822
+ const now = this.nowMs();
2823
+ const runAtMs = runAt ? runAt.getTime() : 0;
2824
+ const result = await this.client.eval(
2825
+ ADD_JOB_SCRIPT,
2826
+ 1,
2827
+ this.prefix,
2828
+ jobType,
2829
+ JSON.stringify(payload),
2830
+ maxAttempts,
2831
+ priority,
2832
+ runAtMs.toString(),
2833
+ timeoutMs !== void 0 ? timeoutMs.toString() : "null",
2834
+ forceKillOnTimeout ? "true" : "false",
2835
+ tags ? JSON.stringify(tags) : "null",
2836
+ idempotencyKey ?? "null",
2837
+ now
2838
+ );
2839
+ const jobId = Number(result);
2840
+ log(
2841
+ `Added job ${jobId}: payload ${JSON.stringify(payload)}, ${runAt ? `runAt ${runAt.toISOString()}, ` : ""}priority ${priority}, maxAttempts ${maxAttempts}, jobType ${jobType}, tags ${JSON.stringify(tags)}${idempotencyKey ? `, idempotencyKey "${idempotencyKey}"` : ""}`
2842
+ );
2843
+ await this.recordJobEvent(jobId, "added" /* Added */, {
2844
+ jobType,
2845
+ payload,
2846
+ tags,
2847
+ idempotencyKey
2848
+ });
2849
+ return jobId;
2850
+ }
2851
+ async getJob(id) {
2852
+ const data = await this.client.hgetall(`${this.prefix}job:${id}`);
2853
+ if (!data || Object.keys(data).length === 0) {
2854
+ log(`Job ${id} not found`);
2855
+ return null;
2856
+ }
2857
+ log(`Found job ${id}`);
2858
+ return deserializeJob(data);
2859
+ }
2860
+ async getJobsByStatus(status, limit = 100, offset = 0) {
2861
+ const ids = await this.client.smembers(`${this.prefix}status:${status}`);
2862
+ if (ids.length === 0) return [];
2863
+ const jobs = await this.loadJobsByIds(ids);
2864
+ jobs.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2865
+ return jobs.slice(offset, offset + limit);
2866
+ }
2867
+ async getAllJobs(limit = 100, offset = 0) {
2868
+ const ids = await this.client.zrevrange(
2869
+ `${this.prefix}all`,
2870
+ offset,
2871
+ offset + limit - 1
2872
+ );
2873
+ if (ids.length === 0) return [];
2874
+ return this.loadJobsByIds(ids);
2875
+ }
2876
+ async getJobs(filters, limit = 100, offset = 0) {
2877
+ let candidateIds;
2878
+ if (filters?.jobType) {
2879
+ candidateIds = await this.client.smembers(
2880
+ `${this.prefix}type:${filters.jobType}`
2881
+ );
2882
+ } else {
2883
+ candidateIds = await this.client.zrevrange(`${this.prefix}all`, 0, -1);
2884
+ }
2885
+ if (candidateIds.length === 0) return [];
2886
+ if (filters?.tags && filters.tags.values.length > 0) {
2887
+ candidateIds = await this.filterByTags(
2888
+ candidateIds,
2889
+ filters.tags.values,
2890
+ filters.tags.mode || "all"
2891
+ );
2892
+ }
2893
+ let jobs = await this.loadJobsByIds(candidateIds);
2894
+ if (filters) {
2895
+ if (filters.priority !== void 0) {
2896
+ jobs = jobs.filter((j) => j.priority === filters.priority);
2897
+ }
2898
+ if (filters.runAt) {
2899
+ jobs = this.filterByRunAt(jobs, filters.runAt);
2900
+ }
2901
+ }
2902
+ jobs.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2903
+ return jobs.slice(offset, offset + limit);
2904
+ }
2905
+ async getJobsByTags(tags, mode = "all", limit = 100, offset = 0) {
2906
+ const allIds = await this.client.zrevrange(`${this.prefix}all`, 0, -1);
2907
+ if (allIds.length === 0) return [];
2908
+ const filtered = await this.filterByTags(allIds, tags, mode);
2909
+ if (filtered.length === 0) return [];
2910
+ const jobs = await this.loadJobsByIds(filtered);
2911
+ jobs.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2912
+ return jobs.slice(offset, offset + limit);
2913
+ }
2914
+ // ── Processing lifecycle ──────────────────────────────────────────────
2915
+ async getNextBatch(workerId, batchSize = 10, jobType) {
2916
+ const now = this.nowMs();
2917
+ const jobTypeFilter = jobType === void 0 ? "null" : Array.isArray(jobType) ? JSON.stringify(jobType) : jobType;
2918
+ const result = await this.client.eval(
2919
+ GET_NEXT_BATCH_SCRIPT,
2920
+ 1,
2921
+ this.prefix,
2922
+ workerId,
2923
+ batchSize,
2924
+ now,
2925
+ jobTypeFilter
2926
+ );
2927
+ if (!result || result.length === 0) {
2928
+ log("Found 0 jobs to process");
2929
+ return [];
2930
+ }
2931
+ const jobs = [];
2932
+ let current = [];
2933
+ for (const item of result) {
2934
+ if (item === "__JOB_SEP__") {
2935
+ if (current.length > 0) {
2936
+ const h = hashToObject(current);
2937
+ jobs.push(deserializeJob(h));
2938
+ }
2939
+ current = [];
2940
+ } else {
2941
+ current.push(item);
2942
+ }
2943
+ }
2944
+ log(`Found ${jobs.length} jobs to process`);
2945
+ for (const job of jobs) {
2946
+ await this.recordJobEvent(job.id, "processing" /* Processing */);
2947
+ }
2948
+ return jobs;
2949
+ }
2950
+ async completeJob(jobId) {
2951
+ const now = this.nowMs();
2952
+ await this.client.eval(COMPLETE_JOB_SCRIPT, 1, this.prefix, jobId, now);
2953
+ await this.recordJobEvent(jobId, "completed" /* Completed */);
2954
+ log(`Completed job ${jobId}`);
2955
+ }
2956
+ async failJob(jobId, error, failureReason) {
2957
+ const now = this.nowMs();
2958
+ const errorJson = JSON.stringify([
2959
+ {
2960
+ message: error.message || String(error),
2961
+ timestamp: new Date(now).toISOString()
2962
+ }
2963
+ ]);
2964
+ await this.client.eval(
2965
+ FAIL_JOB_SCRIPT,
2966
+ 1,
2967
+ this.prefix,
2968
+ jobId,
2969
+ errorJson,
2970
+ failureReason ?? "null",
2971
+ now
2972
+ );
2973
+ await this.recordJobEvent(jobId, "failed" /* Failed */, {
2974
+ message: error.message || String(error),
2975
+ failureReason
2976
+ });
2977
+ log(`Failed job ${jobId}`);
2978
+ }
2979
+ async prolongJob(jobId) {
2980
+ try {
2981
+ const now = this.nowMs();
2982
+ await this.client.eval(PROLONG_JOB_SCRIPT, 1, this.prefix, jobId, now);
2983
+ await this.recordJobEvent(jobId, "prolonged" /* Prolonged */);
2984
+ log(`Prolonged job ${jobId}`);
2985
+ } catch (error) {
2986
+ log(`Error prolonging job ${jobId}: ${error}`);
2987
+ }
2988
+ }
2989
+ // ── Progress ──────────────────────────────────────────────────────────
2990
+ async updateProgress(jobId, progress) {
2991
+ try {
2992
+ const now = this.nowMs();
2993
+ await this.client.hset(
2994
+ `${this.prefix}job:${jobId}`,
2995
+ "progress",
2996
+ progress.toString(),
2997
+ "updatedAt",
2998
+ now.toString()
2999
+ );
3000
+ log(`Updated progress for job ${jobId}: ${progress}%`);
3001
+ } catch (error) {
3002
+ log(`Error updating progress for job ${jobId}: ${error}`);
3003
+ }
3004
+ }
3005
+ // ── Job management ────────────────────────────────────────────────────
3006
+ async retryJob(jobId) {
3007
+ const now = this.nowMs();
3008
+ await this.client.eval(RETRY_JOB_SCRIPT, 1, this.prefix, jobId, now);
3009
+ await this.recordJobEvent(jobId, "retried" /* Retried */);
3010
+ log(`Retried job ${jobId}`);
3011
+ }
3012
+ async cancelJob(jobId) {
3013
+ const now = this.nowMs();
3014
+ await this.client.eval(CANCEL_JOB_SCRIPT, 1, this.prefix, jobId, now);
3015
+ await this.recordJobEvent(jobId, "cancelled" /* Cancelled */);
3016
+ log(`Cancelled job ${jobId}`);
3017
+ }
3018
+ async cancelAllUpcomingJobs(filters) {
3019
+ let ids = await this.client.smembers(`${this.prefix}status:pending`);
3020
+ if (ids.length === 0) return 0;
3021
+ if (filters) {
3022
+ ids = await this.applyFilters(ids, filters);
3023
+ }
3024
+ const now = this.nowMs();
3025
+ let count = 0;
3026
+ for (const id of ids) {
3027
+ const result = await this.client.eval(
3028
+ CANCEL_JOB_SCRIPT,
3029
+ 1,
3030
+ this.prefix,
3031
+ id,
3032
+ now
3033
+ );
3034
+ if (Number(result) === 1) count++;
3035
+ }
3036
+ log(`Cancelled ${count} jobs`);
3037
+ return count;
3038
+ }
3039
+ async editJob(jobId, updates) {
3040
+ const jk = `${this.prefix}job:${jobId}`;
3041
+ const status = await this.client.hget(jk, "status");
3042
+ if (status !== "pending") {
3043
+ log(`Job ${jobId} is not pending (status: ${status}), skipping edit`);
3044
+ return;
3045
+ }
3046
+ const now = this.nowMs();
3047
+ const fields = [];
3048
+ const metadata = {};
3049
+ if (updates.payload !== void 0) {
3050
+ fields.push("payload", JSON.stringify(updates.payload));
3051
+ metadata.payload = updates.payload;
3052
+ }
3053
+ if (updates.maxAttempts !== void 0) {
3054
+ fields.push("maxAttempts", updates.maxAttempts.toString());
3055
+ metadata.maxAttempts = updates.maxAttempts;
3056
+ }
3057
+ if (updates.priority !== void 0) {
3058
+ fields.push("priority", updates.priority.toString());
3059
+ metadata.priority = updates.priority;
3060
+ const createdAt = await this.client.hget(jk, "createdAt");
3061
+ const score = updates.priority * 1e15 + (1e15 - Number(createdAt));
3062
+ const inQueue = await this.client.zscore(
3063
+ `${this.prefix}queue`,
3064
+ jobId.toString()
3065
+ );
3066
+ if (inQueue !== null) {
3067
+ await this.client.zadd(`${this.prefix}queue`, score, jobId.toString());
3068
+ }
3069
+ }
3070
+ if (updates.runAt !== void 0) {
3071
+ if (updates.runAt === null) {
3072
+ fields.push("runAt", now.toString());
3073
+ } else {
3074
+ fields.push("runAt", updates.runAt.getTime().toString());
3075
+ }
3076
+ metadata.runAt = updates.runAt;
3077
+ }
3078
+ if (updates.timeoutMs !== void 0) {
3079
+ fields.push(
3080
+ "timeoutMs",
3081
+ updates.timeoutMs !== null ? updates.timeoutMs.toString() : "null"
3082
+ );
3083
+ metadata.timeoutMs = updates.timeoutMs;
3084
+ }
3085
+ if (updates.tags !== void 0) {
3086
+ const oldTagsJson = await this.client.hget(jk, "tags");
3087
+ if (oldTagsJson && oldTagsJson !== "null") {
3088
+ try {
3089
+ const oldTags = JSON.parse(oldTagsJson);
3090
+ for (const tag of oldTags) {
3091
+ await this.client.srem(
3092
+ `${this.prefix}tag:${tag}`,
3093
+ jobId.toString()
3094
+ );
3095
+ }
3096
+ } catch {
3097
+ }
3098
+ }
3099
+ await this.client.del(`${this.prefix}job:${jobId}:tags`);
3100
+ if (updates.tags !== null) {
3101
+ for (const tag of updates.tags) {
3102
+ await this.client.sadd(`${this.prefix}tag:${tag}`, jobId.toString());
3103
+ await this.client.sadd(`${this.prefix}job:${jobId}:tags`, tag);
3104
+ }
3105
+ fields.push("tags", JSON.stringify(updates.tags));
3106
+ } else {
3107
+ fields.push("tags", "null");
3108
+ }
3109
+ metadata.tags = updates.tags;
3110
+ }
3111
+ if (fields.length === 0) {
3112
+ log(`No fields to update for job ${jobId}`);
3113
+ return;
3114
+ }
3115
+ fields.push("updatedAt", now.toString());
3116
+ await this.client.hmset(jk, ...fields);
3117
+ await this.recordJobEvent(jobId, "edited" /* Edited */, metadata);
3118
+ log(`Edited job ${jobId}: ${JSON.stringify(metadata)}`);
3119
+ }
3120
+ async editAllPendingJobs(filters, updates) {
3121
+ let ids = await this.client.smembers(`${this.prefix}status:pending`);
3122
+ if (ids.length === 0) return 0;
3123
+ if (filters) {
3124
+ ids = await this.applyFilters(ids, filters);
3125
+ }
3126
+ let count = 0;
3127
+ for (const id of ids) {
3128
+ await this.editJob(Number(id), updates);
3129
+ count++;
3130
+ }
3131
+ log(`Edited ${count} pending jobs`);
3132
+ return count;
3133
+ }
3134
+ async cleanupOldJobs(daysToKeep = 30) {
3135
+ const cutoffMs = this.nowMs() - daysToKeep * 24 * 60 * 60 * 1e3;
3136
+ const result = await this.client.eval(
3137
+ CLEANUP_OLD_JOBS_SCRIPT,
3138
+ 1,
3139
+ this.prefix,
3140
+ cutoffMs
3141
+ );
3142
+ log(`Deleted ${result} old jobs`);
3143
+ return Number(result);
3144
+ }
3145
+ async cleanupOldJobEvents(daysToKeep = 30) {
3146
+ log(
3147
+ `cleanupOldJobEvents is a no-op for Redis backend (events are cleaned up with their jobs)`
3148
+ );
3149
+ return 0;
3150
+ }
3151
+ async reclaimStuckJobs(maxProcessingTimeMinutes = 10) {
3152
+ const maxAgeMs = maxProcessingTimeMinutes * 60 * 1e3;
3153
+ const now = this.nowMs();
3154
+ const result = await this.client.eval(
3155
+ RECLAIM_STUCK_JOBS_SCRIPT,
3156
+ 1,
3157
+ this.prefix,
3158
+ maxAgeMs,
3159
+ now
3160
+ );
3161
+ log(`Reclaimed ${result} stuck jobs`);
3162
+ return Number(result);
3163
+ }
3164
+ // ── Internal helpers ──────────────────────────────────────────────────
3165
+ async setPendingReasonForUnpickedJobs(reason, jobType) {
3166
+ let ids = await this.client.smembers(`${this.prefix}status:pending`);
3167
+ if (ids.length === 0) return;
3168
+ if (jobType) {
3169
+ const types = Array.isArray(jobType) ? jobType : [jobType];
3170
+ const typeSet = /* @__PURE__ */ new Set();
3171
+ for (const t of types) {
3172
+ const typeIds = await this.client.smembers(`${this.prefix}type:${t}`);
3173
+ for (const id of typeIds) typeSet.add(id);
3174
+ }
3175
+ ids = ids.filter((id) => typeSet.has(id));
3176
+ }
3177
+ for (const id of ids) {
3178
+ await this.client.hset(
3179
+ `${this.prefix}job:${id}`,
3180
+ "pendingReason",
3181
+ reason
3182
+ );
3183
+ }
3184
+ }
3185
+ // ── Private helpers ───────────────────────────────────────────────────
3186
+ async loadJobsByIds(ids) {
3187
+ const pipeline = this.client.pipeline();
3188
+ for (const id of ids) {
3189
+ pipeline.hgetall(`${this.prefix}job:${id}`);
3190
+ }
3191
+ const results = await pipeline.exec();
3192
+ const jobs = [];
3193
+ if (results) {
3194
+ for (const [err, data] of results) {
3195
+ if (!err && data && typeof data === "object" && Object.keys(data).length > 0) {
3196
+ jobs.push(
3197
+ deserializeJob(data)
3198
+ );
3199
+ }
3200
+ }
3201
+ }
3202
+ return jobs;
3203
+ }
3204
+ async filterByTags(candidateIds, tags, mode) {
3205
+ const candidateSet = new Set(candidateIds.map(String));
3206
+ if (mode === "exact") {
3207
+ const tagSet = new Set(tags);
3208
+ const result = [];
3209
+ for (const id of candidateIds) {
3210
+ const jobTags = await this.client.smembers(
3211
+ `${this.prefix}job:${id}:tags`
3212
+ );
3213
+ if (jobTags.length === tagSet.size && jobTags.every((t) => tagSet.has(t))) {
3214
+ result.push(id);
3215
+ }
3216
+ }
3217
+ return result;
3218
+ }
3219
+ if (mode === "all") {
3220
+ let intersection = new Set(candidateIds.map(String));
3221
+ for (const tag of tags) {
3222
+ const tagMembers = await this.client.smembers(
3223
+ `${this.prefix}tag:${tag}`
3224
+ );
3225
+ const tagSet = new Set(tagMembers.map(String));
3226
+ intersection = new Set(
3227
+ [...intersection].filter((id) => tagSet.has(id))
3228
+ );
3229
+ }
3230
+ return [...intersection].filter((id) => candidateSet.has(id));
3231
+ }
3232
+ if (mode === "any") {
3233
+ const union = /* @__PURE__ */ new Set();
3234
+ for (const tag of tags) {
3235
+ const tagMembers = await this.client.smembers(
3236
+ `${this.prefix}tag:${tag}`
3237
+ );
3238
+ for (const id of tagMembers) union.add(String(id));
3239
+ }
3240
+ return [...union].filter((id) => candidateSet.has(id));
3241
+ }
3242
+ if (mode === "none") {
3243
+ const exclude = /* @__PURE__ */ new Set();
3244
+ for (const tag of tags) {
3245
+ const tagMembers = await this.client.smembers(
3246
+ `${this.prefix}tag:${tag}`
3247
+ );
3248
+ for (const id of tagMembers) exclude.add(String(id));
3249
+ }
3250
+ return candidateIds.filter((id) => !exclude.has(String(id)));
3251
+ }
3252
+ return this.filterByTags(candidateIds, tags, "all");
3253
+ }
3254
+ filterByRunAt(jobs, runAt) {
3255
+ if (runAt instanceof Date) {
3256
+ return jobs.filter((j) => j.runAt.getTime() === runAt.getTime());
3257
+ }
3258
+ return jobs.filter((j) => {
3259
+ const t = j.runAt.getTime();
3260
+ if (runAt.gt && !(t > runAt.gt.getTime())) return false;
3261
+ if (runAt.gte && !(t >= runAt.gte.getTime())) return false;
3262
+ if (runAt.lt && !(t < runAt.lt.getTime())) return false;
3263
+ if (runAt.lte && !(t <= runAt.lte.getTime())) return false;
3264
+ if (runAt.eq && t !== runAt.eq.getTime()) return false;
3265
+ return true;
3266
+ });
3267
+ }
3268
+ // ── Cron schedules ──────────────────────────────────────────────────
3269
+ /** Create a cron schedule and return its ID. */
3270
+ async addCronSchedule(input) {
3271
+ const existingId = await this.client.get(
3272
+ `${this.prefix}cron_name:${input.scheduleName}`
3273
+ );
3274
+ if (existingId !== null) {
3275
+ throw new Error(
3276
+ `Cron schedule with name "${input.scheduleName}" already exists`
3277
+ );
3278
+ }
3279
+ const id = await this.client.incr(`${this.prefix}cron_id_seq`);
3280
+ const now = this.nowMs();
3281
+ const key = `${this.prefix}cron:${id}`;
3282
+ const fields = [
3283
+ "id",
3284
+ id.toString(),
3285
+ "scheduleName",
3286
+ input.scheduleName,
3287
+ "cronExpression",
3288
+ input.cronExpression,
3289
+ "jobType",
3290
+ input.jobType,
3291
+ "payload",
3292
+ JSON.stringify(input.payload),
3293
+ "maxAttempts",
3294
+ input.maxAttempts.toString(),
3295
+ "priority",
3296
+ input.priority.toString(),
3297
+ "timeoutMs",
3298
+ input.timeoutMs !== null ? input.timeoutMs.toString() : "null",
3299
+ "forceKillOnTimeout",
3300
+ input.forceKillOnTimeout ? "true" : "false",
3301
+ "tags",
3302
+ input.tags ? JSON.stringify(input.tags) : "null",
3303
+ "timezone",
3304
+ input.timezone,
3305
+ "allowOverlap",
3306
+ input.allowOverlap ? "true" : "false",
3307
+ "status",
3308
+ "active",
3309
+ "lastEnqueuedAt",
3310
+ "null",
3311
+ "lastJobId",
3312
+ "null",
3313
+ "nextRunAt",
3314
+ input.nextRunAt ? input.nextRunAt.getTime().toString() : "null",
3315
+ "createdAt",
3316
+ now.toString(),
3317
+ "updatedAt",
3318
+ now.toString()
3319
+ ];
3320
+ await this.client.hmset(key, ...fields);
3321
+ await this.client.set(
3322
+ `${this.prefix}cron_name:${input.scheduleName}`,
3323
+ id.toString()
3324
+ );
3325
+ await this.client.sadd(`${this.prefix}crons`, id.toString());
3326
+ await this.client.sadd(`${this.prefix}cron_status:active`, id.toString());
3327
+ if (input.nextRunAt) {
3328
+ await this.client.zadd(
3329
+ `${this.prefix}cron_due`,
3330
+ input.nextRunAt.getTime(),
3331
+ id.toString()
3332
+ );
3333
+ }
3334
+ log(`Added cron schedule ${id}: "${input.scheduleName}"`);
3335
+ return id;
3336
+ }
3337
+ /** Get a cron schedule by ID. */
3338
+ async getCronSchedule(id) {
3339
+ const data = await this.client.hgetall(`${this.prefix}cron:${id}`);
3340
+ if (!data || Object.keys(data).length === 0) return null;
3341
+ return this.deserializeCronSchedule(data);
3342
+ }
3343
+ /** Get a cron schedule by its unique name. */
3344
+ async getCronScheduleByName(name) {
3345
+ const id = await this.client.get(`${this.prefix}cron_name:${name}`);
3346
+ if (id === null) return null;
3347
+ return this.getCronSchedule(Number(id));
3348
+ }
3349
+ /** List cron schedules, optionally filtered by status. */
3350
+ async listCronSchedules(status) {
3351
+ let ids;
3352
+ if (status) {
3353
+ ids = await this.client.smembers(`${this.prefix}cron_status:${status}`);
3354
+ } else {
3355
+ ids = await this.client.smembers(`${this.prefix}crons`);
3356
+ }
3357
+ if (ids.length === 0) return [];
3358
+ const pipeline = this.client.pipeline();
3359
+ for (const id of ids) {
3360
+ pipeline.hgetall(`${this.prefix}cron:${id}`);
3361
+ }
3362
+ const results = await pipeline.exec();
3363
+ const schedules = [];
3364
+ if (results) {
3365
+ for (const [err, data] of results) {
3366
+ if (!err && data && typeof data === "object" && Object.keys(data).length > 0) {
3367
+ schedules.push(
3368
+ this.deserializeCronSchedule(data)
3369
+ );
3370
+ }
3371
+ }
3372
+ }
3373
+ schedules.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
3374
+ return schedules;
3375
+ }
3376
+ /** Delete a cron schedule by ID. */
3377
+ async removeCronSchedule(id) {
3378
+ const data = await this.client.hgetall(`${this.prefix}cron:${id}`);
3379
+ if (!data || Object.keys(data).length === 0) return;
3380
+ const name = data.scheduleName;
3381
+ const status = data.status;
3382
+ await this.client.del(`${this.prefix}cron:${id}`);
3383
+ await this.client.del(`${this.prefix}cron_name:${name}`);
3384
+ await this.client.srem(`${this.prefix}crons`, id.toString());
3385
+ await this.client.srem(
3386
+ `${this.prefix}cron_status:${status}`,
3387
+ id.toString()
3388
+ );
3389
+ await this.client.zrem(`${this.prefix}cron_due`, id.toString());
3390
+ log(`Removed cron schedule ${id}`);
3391
+ }
3392
+ /** Pause a cron schedule. */
3393
+ async pauseCronSchedule(id) {
3394
+ const now = this.nowMs();
3395
+ await this.client.hset(
3396
+ `${this.prefix}cron:${id}`,
3397
+ "status",
3398
+ "paused",
3399
+ "updatedAt",
3400
+ now.toString()
3401
+ );
3402
+ await this.client.srem(`${this.prefix}cron_status:active`, id.toString());
3403
+ await this.client.sadd(`${this.prefix}cron_status:paused`, id.toString());
3404
+ await this.client.zrem(`${this.prefix}cron_due`, id.toString());
3405
+ log(`Paused cron schedule ${id}`);
3406
+ }
3407
+ /** Resume a paused cron schedule. */
3408
+ async resumeCronSchedule(id) {
3409
+ const now = this.nowMs();
3410
+ await this.client.hset(
3411
+ `${this.prefix}cron:${id}`,
3412
+ "status",
3413
+ "active",
3414
+ "updatedAt",
3415
+ now.toString()
3416
+ );
3417
+ await this.client.srem(`${this.prefix}cron_status:paused`, id.toString());
3418
+ await this.client.sadd(`${this.prefix}cron_status:active`, id.toString());
3419
+ const nextRunAt = await this.client.hget(
3420
+ `${this.prefix}cron:${id}`,
3421
+ "nextRunAt"
3422
+ );
3423
+ if (nextRunAt && nextRunAt !== "null") {
3424
+ await this.client.zadd(
3425
+ `${this.prefix}cron_due`,
3426
+ Number(nextRunAt),
3427
+ id.toString()
3428
+ );
3429
+ }
3430
+ log(`Resumed cron schedule ${id}`);
3431
+ }
3432
+ /** Edit a cron schedule. */
3433
+ async editCronSchedule(id, updates, nextRunAt) {
3434
+ const now = this.nowMs();
3435
+ const fields = [];
3436
+ if (updates.cronExpression !== void 0) {
3437
+ fields.push("cronExpression", updates.cronExpression);
3438
+ }
3439
+ if (updates.payload !== void 0) {
3440
+ fields.push("payload", JSON.stringify(updates.payload));
3441
+ }
3442
+ if (updates.maxAttempts !== void 0) {
3443
+ fields.push("maxAttempts", updates.maxAttempts.toString());
3444
+ }
3445
+ if (updates.priority !== void 0) {
3446
+ fields.push("priority", updates.priority.toString());
3447
+ }
3448
+ if (updates.timeoutMs !== void 0) {
3449
+ fields.push(
3450
+ "timeoutMs",
3451
+ updates.timeoutMs !== null ? updates.timeoutMs.toString() : "null"
3452
+ );
3453
+ }
3454
+ if (updates.forceKillOnTimeout !== void 0) {
3455
+ fields.push(
3456
+ "forceKillOnTimeout",
3457
+ updates.forceKillOnTimeout ? "true" : "false"
3458
+ );
3459
+ }
3460
+ if (updates.tags !== void 0) {
3461
+ fields.push(
3462
+ "tags",
3463
+ updates.tags !== null ? JSON.stringify(updates.tags) : "null"
3464
+ );
3465
+ }
3466
+ if (updates.timezone !== void 0) {
3467
+ fields.push("timezone", updates.timezone);
3468
+ }
3469
+ if (updates.allowOverlap !== void 0) {
3470
+ fields.push("allowOverlap", updates.allowOverlap ? "true" : "false");
3471
+ }
3472
+ if (nextRunAt !== void 0) {
3473
+ const val = nextRunAt !== null ? nextRunAt.getTime().toString() : "null";
3474
+ fields.push("nextRunAt", val);
3475
+ if (nextRunAt !== null) {
3476
+ await this.client.zadd(
3477
+ `${this.prefix}cron_due`,
3478
+ nextRunAt.getTime(),
3479
+ id.toString()
3480
+ );
3481
+ } else {
3482
+ await this.client.zrem(`${this.prefix}cron_due`, id.toString());
3483
+ }
3484
+ }
3485
+ if (fields.length === 0) {
3486
+ log(`No fields to update for cron schedule ${id}`);
3487
+ return;
3488
+ }
3489
+ fields.push("updatedAt", now.toString());
3490
+ await this.client.hmset(`${this.prefix}cron:${id}`, ...fields);
3491
+ log(`Edited cron schedule ${id}`);
3492
+ }
3493
+ /**
3494
+ * Fetch all active cron schedules whose nextRunAt <= now.
3495
+ * Uses a sorted set (cron_due) for efficient range query.
3496
+ */
3497
+ async getDueCronSchedules() {
3498
+ const now = this.nowMs();
3499
+ const ids = await this.client.zrangebyscore(
3500
+ `${this.prefix}cron_due`,
3501
+ 0,
3502
+ now
3503
+ );
3504
+ if (ids.length === 0) {
3505
+ log("Found 0 due cron schedules");
3506
+ return [];
3507
+ }
3508
+ const schedules = [];
3509
+ for (const id of ids) {
3510
+ const data = await this.client.hgetall(`${this.prefix}cron:${id}`);
3511
+ if (data && Object.keys(data).length > 0 && data.status === "active") {
3512
+ schedules.push(this.deserializeCronSchedule(data));
3513
+ }
3514
+ }
3515
+ log(`Found ${schedules.length} due cron schedules`);
3516
+ return schedules;
3517
+ }
3518
+ /**
3519
+ * Update a cron schedule after a job has been enqueued.
3520
+ * Sets lastEnqueuedAt, lastJobId, and advances nextRunAt.
3521
+ */
3522
+ async updateCronScheduleAfterEnqueue(id, lastEnqueuedAt, lastJobId, nextRunAt) {
3523
+ const fields = [
3524
+ "lastEnqueuedAt",
3525
+ lastEnqueuedAt.getTime().toString(),
3526
+ "lastJobId",
3527
+ lastJobId.toString(),
3528
+ "nextRunAt",
3529
+ nextRunAt ? nextRunAt.getTime().toString() : "null",
3530
+ "updatedAt",
3531
+ this.nowMs().toString()
3532
+ ];
3533
+ await this.client.hmset(`${this.prefix}cron:${id}`, ...fields);
3534
+ if (nextRunAt) {
3535
+ await this.client.zadd(
3536
+ `${this.prefix}cron_due`,
3537
+ nextRunAt.getTime(),
3538
+ id.toString()
3539
+ );
3540
+ } else {
3541
+ await this.client.zrem(`${this.prefix}cron_due`, id.toString());
3542
+ }
3543
+ log(
3544
+ `Updated cron schedule ${id}: lastJobId=${lastJobId}, nextRunAt=${nextRunAt?.toISOString() ?? "null"}`
3545
+ );
3546
+ }
3547
+ /** Deserialize a Redis hash into a CronScheduleRecord. */
3548
+ deserializeCronSchedule(h) {
3549
+ const nullish = (v) => v === void 0 || v === "null" || v === "" ? null : v;
3550
+ const numOrNull = (v) => {
3551
+ const n = nullish(v);
3552
+ return n === null ? null : Number(n);
3553
+ };
3554
+ const dateOrNull = (v) => {
3555
+ const n = numOrNull(v);
3556
+ return n === null ? null : new Date(n);
3557
+ };
3558
+ let payload;
3559
+ try {
3560
+ payload = JSON.parse(h.payload);
3561
+ } catch {
3562
+ payload = h.payload;
3563
+ }
3564
+ let tags;
3565
+ try {
3566
+ const raw = h.tags;
3567
+ if (raw && raw !== "null") {
3568
+ tags = JSON.parse(raw);
3569
+ }
3570
+ } catch {
3571
+ }
3572
+ return {
3573
+ id: Number(h.id),
3574
+ scheduleName: h.scheduleName,
3575
+ cronExpression: h.cronExpression,
3576
+ jobType: h.jobType,
3577
+ payload,
3578
+ maxAttempts: Number(h.maxAttempts),
3579
+ priority: Number(h.priority),
3580
+ timeoutMs: numOrNull(h.timeoutMs),
3581
+ forceKillOnTimeout: h.forceKillOnTimeout === "true",
3582
+ tags,
3583
+ timezone: h.timezone,
3584
+ allowOverlap: h.allowOverlap === "true",
3585
+ status: h.status,
3586
+ lastEnqueuedAt: dateOrNull(h.lastEnqueuedAt),
3587
+ lastJobId: numOrNull(h.lastJobId),
3588
+ nextRunAt: dateOrNull(h.nextRunAt),
3589
+ createdAt: new Date(Number(h.createdAt)),
3590
+ updatedAt: new Date(Number(h.updatedAt))
3591
+ };
3592
+ }
3593
+ // ── Private helpers (filters) ─────────────────────────────────────────
3594
+ async applyFilters(ids, filters) {
3595
+ let result = ids;
3596
+ if (filters.jobType) {
3597
+ const typeIds = new Set(
3598
+ await this.client.smembers(`${this.prefix}type:${filters.jobType}`)
3599
+ );
3600
+ result = result.filter((id) => typeIds.has(id));
3601
+ }
3602
+ if (filters.tags && filters.tags.values.length > 0) {
3603
+ result = await this.filterByTags(
3604
+ result,
3605
+ filters.tags.values,
3606
+ filters.tags.mode || "all"
3607
+ );
3608
+ }
3609
+ if (filters.priority !== void 0 || filters.runAt) {
3610
+ const jobs = await this.loadJobsByIds(result);
3611
+ let filtered = jobs;
3612
+ if (filters.priority !== void 0) {
3613
+ filtered = filtered.filter((j) => j.priority === filters.priority);
3614
+ }
3615
+ if (filters.runAt) {
3616
+ filtered = this.filterByRunAt(filtered, filters.runAt);
3617
+ }
3618
+ result = filtered.map((j) => j.id.toString());
3619
+ }
3620
+ return result;
3621
+ }
3622
+ };
3623
+ function getNextCronOccurrence(cronExpression, timezone = "UTC", after, CronImpl = Cron) {
3624
+ const cron = new CronImpl(cronExpression, { timezone });
3625
+ const next = cron.nextRun(after ?? /* @__PURE__ */ new Date());
3626
+ return next ?? null;
3627
+ }
3628
+ function validateCronExpression(cronExpression, CronImpl = Cron) {
3629
+ try {
3630
+ new CronImpl(cronExpression);
3631
+ return true;
3632
+ } catch {
3633
+ return false;
3634
+ }
3635
+ }
3636
+
3637
+ // src/handler-validation.ts
3638
+ function validateHandlerSerializable2(handler, jobType) {
3639
+ try {
3640
+ const handlerString = handler.toString();
3641
+ const typeLabel = jobType ? `job type "${jobType}"` : "handler";
3642
+ if (handlerString.includes("this.") && !handlerString.match(/\([^)]*this[^)]*\)/)) {
3643
+ return {
3644
+ isSerializable: false,
3645
+ error: `Handler for ${typeLabel} uses 'this' context which cannot be serialized. Use a regular function or avoid 'this' references when forceKillOnTimeout is enabled.`
3646
+ };
3647
+ }
3648
+ if (handlerString.includes("[native code]")) {
3649
+ return {
3650
+ isSerializable: false,
3651
+ error: `Handler for ${typeLabel} contains native code which cannot be serialized. Ensure your handler is a plain function when forceKillOnTimeout is enabled.`
3652
+ };
3653
+ }
3654
+ try {
3655
+ new Function("return " + handlerString);
3656
+ } catch (parseError) {
3657
+ return {
3658
+ isSerializable: false,
3659
+ error: `Handler for ${typeLabel} cannot be serialized: ${parseError instanceof Error ? parseError.message : String(parseError)}. When using forceKillOnTimeout, handlers must be serializable functions without closures over external variables.`
3660
+ };
3661
+ }
3662
+ const hasPotentialClosure = /const\s+\w+\s*=\s*[^;]+;\s*async\s*\(/.test(handlerString) || /let\s+\w+\s*=\s*[^;]+;\s*async\s*\(/.test(handlerString);
3663
+ if (hasPotentialClosure) {
3664
+ return {
3665
+ isSerializable: true,
3666
+ // Still serializable, but might have issues
3667
+ error: `Warning: Handler for ${typeLabel} may have closures over external variables. Test thoroughly with forceKillOnTimeout enabled. If the handler fails to execute in a worker thread, ensure all dependencies are imported within the handler function.`
3668
+ };
3669
+ }
3670
+ return { isSerializable: true };
3671
+ } catch (error) {
3672
+ return {
3673
+ isSerializable: false,
3674
+ error: `Failed to validate handler serialization${jobType ? ` for job type "${jobType}"` : ""}: ${error instanceof Error ? error.message : String(error)}`
3675
+ };
3676
+ }
3677
+ }
3678
+ async function testHandlerSerialization(handler, jobType) {
3679
+ const basicValidation = validateHandlerSerializable2(handler, jobType);
3680
+ if (!basicValidation.isSerializable) {
3681
+ return basicValidation;
3682
+ }
3683
+ try {
3684
+ const handlerString = handler.toString();
3685
+ const handlerFn = new Function("return " + handlerString)();
3686
+ const testPromise = handlerFn({}, new AbortController().signal);
3687
+ const timeoutPromise = new Promise(
3688
+ (_, reject) => setTimeout(() => reject(new Error("Handler test timeout")), 100)
3689
+ );
3690
+ try {
3691
+ await Promise.race([testPromise, timeoutPromise]);
3692
+ } catch (execError) {
3693
+ if (execError instanceof Error && execError.message === "Handler test timeout") {
3694
+ return { isSerializable: true };
3695
+ }
3696
+ }
3697
+ return { isSerializable: true };
3698
+ } catch (error) {
3699
+ return {
3700
+ isSerializable: false,
3701
+ error: `Handler failed serialization test: ${error instanceof Error ? error.message : String(error)}`
3702
+ };
3703
+ }
3704
+ }
3705
+
3706
+ // src/index.ts
3707
+ var initJobQueue = (config) => {
3708
+ const backendType = config.backend ?? "postgres";
3709
+ setLogContext(config.verbose ?? false);
3710
+ let backend;
3711
+ let pool;
3712
+ if (backendType === "postgres") {
3713
+ const pgConfig = config;
3714
+ pool = createPool(pgConfig.databaseConfig);
3715
+ backend = new PostgresBackend(pool);
3716
+ } else if (backendType === "redis") {
3717
+ const redisConfig = config.redisConfig;
3718
+ backend = new RedisBackend(redisConfig);
3719
+ } else {
3720
+ throw new Error(`Unknown backend: ${backendType}`);
3721
+ }
3722
+ const requirePool = () => {
3723
+ if (!pool) {
3724
+ throw new Error(
3725
+ 'Wait/Token features require the PostgreSQL backend. Configure with backend: "postgres" to use these features.'
3726
+ );
3727
+ }
3728
+ return pool;
3729
+ };
3730
+ const enqueueDueCronJobsImpl = async () => {
3731
+ const dueSchedules = await backend.getDueCronSchedules();
3732
+ let count = 0;
3733
+ for (const schedule of dueSchedules) {
3734
+ if (!schedule.allowOverlap && schedule.lastJobId !== null) {
3735
+ const lastJob = await backend.getJob(schedule.lastJobId);
3736
+ if (lastJob && (lastJob.status === "pending" || lastJob.status === "processing" || lastJob.status === "waiting")) {
3737
+ const nextRunAt2 = getNextCronOccurrence(
3738
+ schedule.cronExpression,
3739
+ schedule.timezone
3740
+ );
3741
+ await backend.updateCronScheduleAfterEnqueue(
3742
+ schedule.id,
3743
+ /* @__PURE__ */ new Date(),
3744
+ schedule.lastJobId,
3745
+ nextRunAt2
3746
+ );
3747
+ continue;
3748
+ }
3749
+ }
3750
+ const jobId = await backend.addJob({
3751
+ jobType: schedule.jobType,
3752
+ payload: schedule.payload,
3753
+ maxAttempts: schedule.maxAttempts,
3754
+ priority: schedule.priority,
3755
+ timeoutMs: schedule.timeoutMs ?? void 0,
3756
+ forceKillOnTimeout: schedule.forceKillOnTimeout,
3757
+ tags: schedule.tags
3758
+ });
3759
+ const nextRunAt = getNextCronOccurrence(
3760
+ schedule.cronExpression,
3761
+ schedule.timezone
3762
+ );
3763
+ await backend.updateCronScheduleAfterEnqueue(
3764
+ schedule.id,
3765
+ /* @__PURE__ */ new Date(),
3766
+ jobId,
3767
+ nextRunAt
3768
+ );
3769
+ count++;
3770
+ }
3771
+ return count;
3772
+ };
3773
+ return {
3774
+ // Job queue operations
3775
+ addJob: withLogContext(
3776
+ (job) => backend.addJob(job),
3777
+ config.verbose ?? false
3778
+ ),
3779
+ getJob: withLogContext(
3780
+ (id) => backend.getJob(id),
3781
+ config.verbose ?? false
3782
+ ),
3783
+ getJobsByStatus: withLogContext(
3784
+ (status, limit, offset) => backend.getJobsByStatus(status, limit, offset),
3785
+ config.verbose ?? false
3786
+ ),
3787
+ getAllJobs: withLogContext(
3788
+ (limit, offset) => backend.getAllJobs(limit, offset),
3789
+ config.verbose ?? false
3790
+ ),
3791
+ getJobs: withLogContext(
3792
+ (filters, limit, offset) => backend.getJobs(filters, limit, offset),
3793
+ config.verbose ?? false
3794
+ ),
3795
+ retryJob: (jobId) => backend.retryJob(jobId),
3796
+ cleanupOldJobs: (daysToKeep) => backend.cleanupOldJobs(daysToKeep),
3797
+ cleanupOldJobEvents: (daysToKeep) => backend.cleanupOldJobEvents(daysToKeep),
3798
+ cancelJob: withLogContext(
3799
+ (jobId) => backend.cancelJob(jobId),
3800
+ config.verbose ?? false
3801
+ ),
3802
+ editJob: withLogContext(
3803
+ (jobId, updates) => backend.editJob(jobId, updates),
3804
+ config.verbose ?? false
3805
+ ),
3806
+ editAllPendingJobs: withLogContext(
3807
+ (filters, updates) => backend.editAllPendingJobs(
3808
+ filters,
3809
+ updates
3810
+ ),
3811
+ config.verbose ?? false
3812
+ ),
3813
+ cancelAllUpcomingJobs: withLogContext(
3814
+ (filters) => backend.cancelAllUpcomingJobs(filters),
3815
+ config.verbose ?? false
3816
+ ),
3817
+ reclaimStuckJobs: withLogContext(
3818
+ (maxProcessingTimeMinutes) => backend.reclaimStuckJobs(maxProcessingTimeMinutes),
3819
+ config.verbose ?? false
3820
+ ),
3821
+ getJobsByTags: withLogContext(
3822
+ (tags, mode = "all", limit, offset) => backend.getJobsByTags(tags, mode, limit, offset),
3823
+ config.verbose ?? false
3824
+ ),
3825
+ // Job processing — automatically enqueues due cron jobs before each batch
3826
+ createProcessor: (handlers, options) => createProcessor(backend, handlers, options, async () => {
3827
+ await enqueueDueCronJobsImpl();
3828
+ }),
3829
+ // Job events
3830
+ getJobEvents: withLogContext(
3831
+ (jobId) => backend.getJobEvents(jobId),
3832
+ config.verbose ?? false
3833
+ ),
3834
+ // Wait / Token support (PostgreSQL-only for now)
3835
+ createToken: withLogContext(
3836
+ (options) => createWaitpoint(requirePool(), null, options),
3837
+ config.verbose ?? false
3838
+ ),
3839
+ completeToken: withLogContext(
3840
+ (tokenId, data) => completeWaitpoint(requirePool(), tokenId, data),
3841
+ config.verbose ?? false
3842
+ ),
3843
+ getToken: withLogContext(
3844
+ (tokenId) => getWaitpoint(requirePool(), tokenId),
3845
+ config.verbose ?? false
3846
+ ),
3847
+ expireTimedOutTokens: withLogContext(
3848
+ () => expireTimedOutWaitpoints(requirePool()),
3849
+ config.verbose ?? false
3850
+ ),
3851
+ // Cron schedule operations
3852
+ addCronJob: withLogContext(
3853
+ (options) => {
3854
+ if (!validateCronExpression(options.cronExpression)) {
3855
+ return Promise.reject(
3856
+ new Error(`Invalid cron expression: "${options.cronExpression}"`)
3857
+ );
3858
+ }
3859
+ const nextRunAt = getNextCronOccurrence(
3860
+ options.cronExpression,
3861
+ options.timezone ?? "UTC"
3862
+ );
3863
+ const input = {
3864
+ scheduleName: options.scheduleName,
3865
+ cronExpression: options.cronExpression,
3866
+ jobType: options.jobType,
3867
+ payload: options.payload,
3868
+ maxAttempts: options.maxAttempts ?? 3,
3869
+ priority: options.priority ?? 0,
3870
+ timeoutMs: options.timeoutMs ?? null,
3871
+ forceKillOnTimeout: options.forceKillOnTimeout ?? false,
3872
+ tags: options.tags,
3873
+ timezone: options.timezone ?? "UTC",
3874
+ allowOverlap: options.allowOverlap ?? false,
3875
+ nextRunAt
3876
+ };
3877
+ return backend.addCronSchedule(input);
3878
+ },
3879
+ config.verbose ?? false
3880
+ ),
3881
+ getCronJob: withLogContext(
3882
+ (id) => backend.getCronSchedule(id),
3883
+ config.verbose ?? false
3884
+ ),
3885
+ getCronJobByName: withLogContext(
3886
+ (name) => backend.getCronScheduleByName(name),
3887
+ config.verbose ?? false
3888
+ ),
3889
+ listCronJobs: withLogContext(
3890
+ (status) => backend.listCronSchedules(status),
3891
+ config.verbose ?? false
3892
+ ),
3893
+ removeCronJob: withLogContext(
3894
+ (id) => backend.removeCronSchedule(id),
3895
+ config.verbose ?? false
3896
+ ),
3897
+ pauseCronJob: withLogContext(
3898
+ (id) => backend.pauseCronSchedule(id),
3899
+ config.verbose ?? false
3900
+ ),
3901
+ resumeCronJob: withLogContext(
3902
+ (id) => backend.resumeCronSchedule(id),
3903
+ config.verbose ?? false
3904
+ ),
3905
+ editCronJob: withLogContext(
3906
+ async (id, updates) => {
3907
+ if (updates.cronExpression !== void 0 && !validateCronExpression(updates.cronExpression)) {
3908
+ throw new Error(
3909
+ `Invalid cron expression: "${updates.cronExpression}"`
3910
+ );
3911
+ }
3912
+ let nextRunAt;
3913
+ if (updates.cronExpression !== void 0 || updates.timezone !== void 0) {
3914
+ const existing = await backend.getCronSchedule(id);
3915
+ const expr = updates.cronExpression ?? existing?.cronExpression ?? "";
3916
+ const tz = updates.timezone ?? existing?.timezone ?? "UTC";
3917
+ nextRunAt = getNextCronOccurrence(expr, tz);
3918
+ }
3919
+ await backend.editCronSchedule(id, updates, nextRunAt);
3920
+ },
3921
+ config.verbose ?? false
3922
+ ),
3923
+ enqueueDueCronJobs: withLogContext(
3924
+ () => enqueueDueCronJobsImpl(),
3925
+ config.verbose ?? false
3926
+ ),
3927
+ // Advanced access
3928
+ getPool: () => {
3929
+ if (backendType !== "postgres") {
3930
+ throw new Error(
3931
+ "getPool() is only available with the PostgreSQL backend."
3932
+ );
3933
+ }
3934
+ return backend.getPool();
3935
+ },
3936
+ getRedisClient: () => {
3937
+ if (backendType !== "redis") {
3938
+ throw new Error(
3939
+ "getRedisClient() is only available with the Redis backend."
3940
+ );
3941
+ }
3942
+ return backend.getClient();
3943
+ }
3944
+ };
3945
+ };
3946
+ var withLogContext = (fn, verbose) => (...args) => {
3947
+ setLogContext(verbose);
3948
+ return fn(...args);
3949
+ };
3950
+
3951
+ export { FailureReason, JobEventType, PostgresBackend, WaitSignal, getNextCronOccurrence, initJobQueue, testHandlerSerialization, validateCronExpression, validateHandlerSerializable2 as validateHandlerSerializable };
3952
+ //# sourceMappingURL=index.js.map
3953
+ //# sourceMappingURL=index.js.map