@boringnode/queue 0.5.1 → 0.6.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/README.md +103 -20
- package/build/chunk-6IO4P6RB.js +145 -0
- package/build/chunk-6IO4P6RB.js.map +1 -0
- package/build/{chunk-VHN3XZDC.js → chunk-AHUVTAI7.js} +278 -29
- package/build/chunk-AHUVTAI7.js.map +1 -0
- package/build/chunk-S37X3CBO.js +500 -0
- package/build/chunk-S37X3CBO.js.map +1 -0
- package/build/index.d.ts +34 -8
- package/build/index.js +187 -31
- package/build/index.js.map +1 -1
- package/build/{job-DImdhRFO.d.ts → job-C4oyCVxR.d.ts} +275 -15
- package/build/src/contracts/adapter.d.ts +1 -1
- package/build/src/drivers/fake_adapter.d.ts +12 -6
- package/build/src/drivers/fake_adapter.js +1 -1
- package/build/src/drivers/knex_adapter.d.ts +6 -5
- package/build/src/drivers/knex_adapter.js +112 -0
- package/build/src/drivers/knex_adapter.js.map +1 -1
- package/build/src/drivers/redis_adapter.d.ts +6 -5
- package/build/src/drivers/redis_adapter.js +166 -402
- package/build/src/drivers/redis_adapter.js.map +1 -1
- package/build/src/drivers/redis_job_storage.d.ts +17 -0
- package/build/src/drivers/redis_job_storage.js +14 -0
- package/build/src/drivers/redis_job_storage.js.map +1 -0
- package/build/src/drivers/redis_scripts.d.ts +87 -0
- package/build/src/drivers/redis_scripts.js +29 -0
- package/build/src/drivers/redis_scripts.js.map +1 -0
- package/build/src/drivers/sync_adapter.d.ts +2 -1
- package/build/src/drivers/sync_adapter.js +7 -1
- package/build/src/drivers/sync_adapter.js.map +1 -1
- package/build/src/otel.d.ts +2 -2
- package/build/src/otel.js +3 -0
- package/build/src/otel.js.map +1 -1
- package/build/src/types/index.d.ts +1 -1
- package/build/src/types/main.d.ts +1 -1
- package/build/src/types/tracing_channels.d.ts +7 -1
- package/package.json +18 -19
- package/build/chunk-VHN3XZDC.js.map +0 -1
package/build/index.js
CHANGED
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
QueueManager,
|
|
10
10
|
ScheduleBuilder,
|
|
11
11
|
debug_default
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-AHUVTAI7.js";
|
|
13
13
|
import {
|
|
14
14
|
dispatchChannel,
|
|
15
15
|
executeChannel,
|
|
@@ -67,6 +67,27 @@ var JobPool = class {
|
|
|
67
67
|
add(job, queue, promise) {
|
|
68
68
|
this.#activeJobs.set(job.id, { promise, job, queue });
|
|
69
69
|
}
|
|
70
|
+
/**
|
|
71
|
+
* Get the ids of all currently running jobs, grouped by the queue they
|
|
72
|
+
* came from.
|
|
73
|
+
*
|
|
74
|
+
* Used by the worker heartbeat to renew the acquired timestamp of in-flight
|
|
75
|
+
* jobs so long-running handlers are not mistaken for stalled jobs.
|
|
76
|
+
*
|
|
77
|
+
* @returns A map of queue name to the job ids running for that queue
|
|
78
|
+
*/
|
|
79
|
+
activeJobIdsByQueue() {
|
|
80
|
+
const byQueue = /* @__PURE__ */ new Map();
|
|
81
|
+
for (const { job, queue } of this.#activeJobs.values()) {
|
|
82
|
+
const ids = byQueue.get(queue);
|
|
83
|
+
if (ids) {
|
|
84
|
+
ids.push(job.id);
|
|
85
|
+
} else {
|
|
86
|
+
byQueue.set(queue, [job.id]);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return byQueue;
|
|
90
|
+
}
|
|
70
91
|
/**
|
|
71
92
|
* Wait for the next job to complete and return it.
|
|
72
93
|
*
|
|
@@ -126,6 +147,8 @@ var Worker = class {
|
|
|
126
147
|
#pool;
|
|
127
148
|
#lastStalledCheck = 0;
|
|
128
149
|
#shutdownHandler;
|
|
150
|
+
#heartbeatTimer;
|
|
151
|
+
#renewingJobs = false;
|
|
129
152
|
/** Unique identifier for this worker instance */
|
|
130
153
|
get id() {
|
|
131
154
|
return this.#id;
|
|
@@ -219,6 +242,7 @@ var Worker = class {
|
|
|
219
242
|
debug_default("worker %s: waiting for %d running jobs to complete", this.#id, this.#pool.size);
|
|
220
243
|
await this.#pool.drain();
|
|
221
244
|
}
|
|
245
|
+
this.#stopHeartbeat();
|
|
222
246
|
this.#removeShutdownHandlers();
|
|
223
247
|
}
|
|
224
248
|
/**
|
|
@@ -286,31 +310,36 @@ var Worker = class {
|
|
|
286
310
|
*/
|
|
287
311
|
async *process(queues) {
|
|
288
312
|
this.#pool = new JobPool();
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
yield
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
this.#pool.
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
313
|
+
this.#startHeartbeat(queues);
|
|
314
|
+
try {
|
|
315
|
+
while (this.#running) {
|
|
316
|
+
try {
|
|
317
|
+
await this.#checkStalledJobs(queues);
|
|
318
|
+
await this.#dispatchDueSchedules();
|
|
319
|
+
yield* this.#fillPool(queues);
|
|
320
|
+
if (this.#pool.isEmpty()) {
|
|
321
|
+
yield { type: "idle", suggestedDelay: this.#idleDelay };
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
const hasCapacity = this.#pool.hasCapacity(this.#concurrency);
|
|
325
|
+
const result = await Promise.race([
|
|
326
|
+
this.#pool.waitForNextCompletion().then((completed) => ({ kind: "completed", completed })),
|
|
327
|
+
...hasCapacity ? [setTimeout(this.#idleDelay).then(() => ({ kind: "tick" }))] : []
|
|
328
|
+
]);
|
|
329
|
+
if (result.kind === "tick") {
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
yield { type: "completed", queue: result.completed.queue, job: result.completed.job };
|
|
333
|
+
} catch (error) {
|
|
334
|
+
yield {
|
|
335
|
+
type: "error",
|
|
336
|
+
error,
|
|
337
|
+
suggestedDelay: parse(DEFAULT_ERROR_RETRY_DELAY)
|
|
338
|
+
};
|
|
305
339
|
}
|
|
306
|
-
yield { type: "completed", queue: result.completed.queue, job: result.completed.job };
|
|
307
|
-
} catch (error) {
|
|
308
|
-
yield {
|
|
309
|
-
type: "error",
|
|
310
|
-
error,
|
|
311
|
-
suggestedDelay: parse(DEFAULT_ERROR_RETRY_DELAY)
|
|
312
|
-
};
|
|
313
340
|
}
|
|
341
|
+
} finally {
|
|
342
|
+
this.#stopHeartbeat();
|
|
314
343
|
}
|
|
315
344
|
}
|
|
316
345
|
async *#fillPool(queues) {
|
|
@@ -343,11 +372,26 @@ var Worker = class {
|
|
|
343
372
|
return executeChannel.tracePromise(async () => {
|
|
344
373
|
try {
|
|
345
374
|
await runtime.execute(instance, payload, context);
|
|
346
|
-
await this.#wrapInternal(
|
|
375
|
+
await this.#wrapInternal(
|
|
376
|
+
() => this.#adapter.completeJob(job.id, queue, retention.removeOnComplete)
|
|
377
|
+
);
|
|
347
378
|
executeMessage.status = "completed";
|
|
348
|
-
debug_default(
|
|
379
|
+
debug_default(
|
|
380
|
+
"worker %s: successfully executed job %s in %dms",
|
|
381
|
+
this.#id,
|
|
382
|
+
job.id,
|
|
383
|
+
(performance.now() - startTime).toFixed(2)
|
|
384
|
+
);
|
|
349
385
|
} catch (e) {
|
|
350
|
-
await this.#handleExecutionFailure({
|
|
386
|
+
await this.#handleExecutionFailure({
|
|
387
|
+
error: e,
|
|
388
|
+
job,
|
|
389
|
+
queue,
|
|
390
|
+
instance,
|
|
391
|
+
runtime,
|
|
392
|
+
retention,
|
|
393
|
+
executeMessage
|
|
394
|
+
});
|
|
351
395
|
}
|
|
352
396
|
executeMessage.duration = Number((performance.now() - startTime).toFixed(2));
|
|
353
397
|
}, executeMessage);
|
|
@@ -361,7 +405,12 @@ var Worker = class {
|
|
|
361
405
|
if (outcome.type === "failed") {
|
|
362
406
|
options.executeMessage.status = "failed";
|
|
363
407
|
await this.#wrapInternal(
|
|
364
|
-
() => this.#adapter.failJob(
|
|
408
|
+
() => this.#adapter.failJob(
|
|
409
|
+
options.job.id,
|
|
410
|
+
options.queue,
|
|
411
|
+
outcome.storageError,
|
|
412
|
+
options.retention.removeOnFail
|
|
413
|
+
)
|
|
365
414
|
);
|
|
366
415
|
await options.instance.failed?.(outcome.hookError);
|
|
367
416
|
return;
|
|
@@ -370,8 +419,15 @@ var Worker = class {
|
|
|
370
419
|
options.executeMessage.status = "retrying";
|
|
371
420
|
options.executeMessage.nextRetryAt = outcome.retryAt;
|
|
372
421
|
if (outcome.retryAt) {
|
|
373
|
-
debug_default(
|
|
374
|
-
|
|
422
|
+
debug_default(
|
|
423
|
+
"worker %s: job %s will retry at %s",
|
|
424
|
+
this.#id,
|
|
425
|
+
options.job.id,
|
|
426
|
+
outcome.retryAt.toISOString()
|
|
427
|
+
);
|
|
428
|
+
await this.#wrapInternal(
|
|
429
|
+
() => this.#adapter.retryJob(options.job.id, options.queue, outcome.retryAt)
|
|
430
|
+
);
|
|
375
431
|
} else {
|
|
376
432
|
await this.#wrapInternal(() => this.#adapter.retryJob(options.job.id, options.queue));
|
|
377
433
|
}
|
|
@@ -395,7 +451,9 @@ var Worker = class {
|
|
|
395
451
|
} catch (error) {
|
|
396
452
|
debug_default("worker %s: failed to initialize job %s (%s)", this.#id, job.id, job.name);
|
|
397
453
|
const retention = QueueManager.getConfigResolver().resolveJobOptions(queue);
|
|
398
|
-
await this.#wrapInternal(
|
|
454
|
+
await this.#wrapInternal(
|
|
455
|
+
() => this.#adapter.failJob(job.id, queue, error, retention.removeOnFail)
|
|
456
|
+
);
|
|
399
457
|
throw error;
|
|
400
458
|
}
|
|
401
459
|
}
|
|
@@ -425,6 +483,60 @@ var Worker = class {
|
|
|
425
483
|
}
|
|
426
484
|
}
|
|
427
485
|
}
|
|
486
|
+
/**
|
|
487
|
+
* Start the heartbeat timer that periodically renews the acquired timestamp
|
|
488
|
+
* of in-flight jobs.
|
|
489
|
+
*
|
|
490
|
+
* Renewal cannot piggyback on the main process loop: at full concurrency the
|
|
491
|
+
* loop blocks on `waitForNextCompletion()` with no idle tick, so exactly when
|
|
492
|
+
* long-running jobs are in flight the loop is not cycling. A dedicated timer
|
|
493
|
+
* guarantees healthy jobs are refreshed before `recoverStalledJobs` would
|
|
494
|
+
* consider them stalled and re-deliver them.
|
|
495
|
+
*
|
|
496
|
+
* The interval is half the stalled threshold so a job is renewed at least
|
|
497
|
+
* once within every stalled window.
|
|
498
|
+
*/
|
|
499
|
+
#startHeartbeat(queues) {
|
|
500
|
+
this.#stopHeartbeat();
|
|
501
|
+
const interval = Math.max(Math.floor(this.#stalledThreshold / 2), 1);
|
|
502
|
+
this.#heartbeatTimer = setInterval(() => {
|
|
503
|
+
void this.#renewActiveJobs(queues);
|
|
504
|
+
}, interval);
|
|
505
|
+
this.#heartbeatTimer.unref?.();
|
|
506
|
+
}
|
|
507
|
+
#stopHeartbeat() {
|
|
508
|
+
if (this.#heartbeatTimer) {
|
|
509
|
+
clearInterval(this.#heartbeatTimer);
|
|
510
|
+
this.#heartbeatTimer = void 0;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Renew the acquired timestamp of the jobs currently in the pool so that
|
|
515
|
+
* long-running handlers are not treated as stalled while they are still
|
|
516
|
+
* running. Only jobs still active in the adapter are renewed.
|
|
517
|
+
*/
|
|
518
|
+
async #renewActiveJobs(queues) {
|
|
519
|
+
if (this.#renewingJobs || !this.#pool || this.#pool.isEmpty()) {
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
this.#renewingJobs = true;
|
|
523
|
+
try {
|
|
524
|
+
const jobIdsByQueue = this.#pool.activeJobIdsByQueue();
|
|
525
|
+
for (const queue of queues) {
|
|
526
|
+
const jobIds = jobIdsByQueue.get(queue);
|
|
527
|
+
if (!jobIds || jobIds.length === 0) {
|
|
528
|
+
continue;
|
|
529
|
+
}
|
|
530
|
+
try {
|
|
531
|
+
await this.#wrapInternal(() => this.#adapter.renewJobs(queue, jobIds));
|
|
532
|
+
} catch (error) {
|
|
533
|
+
debug_default("worker %s: failed to renew jobs on queue %s: %O", this.#id, queue, error);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
} finally {
|
|
537
|
+
this.#renewingJobs = false;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
428
540
|
#setupGracefulShutdown() {
|
|
429
541
|
if (!this.#gracefulShutdown) {
|
|
430
542
|
return;
|
|
@@ -626,12 +738,56 @@ var QueueSchemaService = class {
|
|
|
626
738
|
table.bigint("execute_at").unsigned().nullable();
|
|
627
739
|
table.bigint("finished_at").unsigned().nullable();
|
|
628
740
|
table.text("error").nullable();
|
|
741
|
+
table.string("dedup_id", 510).nullable();
|
|
742
|
+
table.bigint("dedup_at").unsigned().nullable();
|
|
743
|
+
table.bigint("dedup_ttl").unsigned().nullable();
|
|
629
744
|
table.primary(["id", "queue"]);
|
|
630
745
|
table.index(["queue", "status", "score"]);
|
|
631
746
|
table.index(["queue", "status", "execute_at"]);
|
|
632
747
|
table.index(["queue", "status", "finished_at"]);
|
|
748
|
+
table.index(["queue", "dedup_id"]);
|
|
633
749
|
extend?.(table);
|
|
634
750
|
});
|
|
751
|
+
await this.#createDedupActiveUniqueIndex(tableName);
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* Idempotent migration: adds dedup columns (dedup_id, dedup_at, dedup_ttl)
|
|
755
|
+
* and a (queue, dedup_id) index to an existing jobs table.
|
|
756
|
+
*
|
|
757
|
+
* Safe to run multiple times. Uses hasColumn checks so it won't fail on re-runs.
|
|
758
|
+
* For large Postgres tables, consider pausing workers during the run.
|
|
759
|
+
*/
|
|
760
|
+
async addDedupColumns(tableName = "queue_jobs") {
|
|
761
|
+
const hasDedupId = await this.#connection.schema.hasColumn(tableName, "dedup_id");
|
|
762
|
+
const hasDedupAt = await this.#connection.schema.hasColumn(tableName, "dedup_at");
|
|
763
|
+
const hasDedupTtl = await this.#connection.schema.hasColumn(tableName, "dedup_ttl");
|
|
764
|
+
if (!hasDedupId || !hasDedupAt || !hasDedupTtl) {
|
|
765
|
+
await this.#connection.schema.alterTable(tableName, (table) => {
|
|
766
|
+
if (!hasDedupId) table.string("dedup_id", 510).nullable();
|
|
767
|
+
if (!hasDedupAt) table.bigint("dedup_at").unsigned().nullable();
|
|
768
|
+
if (!hasDedupTtl) table.bigint("dedup_ttl").unsigned().nullable();
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
if (!hasDedupId) {
|
|
772
|
+
await this.#connection.schema.alterTable(tableName, (table) => {
|
|
773
|
+
table.index(["queue", "dedup_id"]);
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
await this.#createDedupActiveUniqueIndex(tableName);
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* Partial unique index on (queue, dedup_id) for active dedup slots.
|
|
780
|
+
* Prevents two concurrent inserts with the same dedup_id from both succeeding.
|
|
781
|
+
* Only PG and SQLite support partial unique indexes; MySQL is skipped.
|
|
782
|
+
*/
|
|
783
|
+
async #createDedupActiveUniqueIndex(tableName) {
|
|
784
|
+
const client = this.#connection.client.config.client;
|
|
785
|
+
if (client !== "pg" && client !== "better-sqlite3" && client !== "sqlite3") return;
|
|
786
|
+
const indexName = `${tableName}_dedup_active_uidx`;
|
|
787
|
+
await this.#connection.raw(
|
|
788
|
+
`CREATE UNIQUE INDEX IF NOT EXISTS ?? ON ?? ("queue", "dedup_id") WHERE "dedup_id" IS NOT NULL AND "status" IN ('pending', 'delayed')`,
|
|
789
|
+
[indexName, tableName]
|
|
790
|
+
);
|
|
635
791
|
}
|
|
636
792
|
/**
|
|
637
793
|
* Creates the schedules table with the default schema.
|
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/worker.ts","../src/job_pool.ts","../src/schedule.ts","../src/services/queue_schema.ts","../src/strategies/backoff_strategy.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { setTimeout } from 'node:timers/promises'\nimport debug from './debug.js'\nimport { parse } from './utils.js'\nimport { QueueManager } from './queue_manager.js'\nimport { JobPool } from './job_pool.js'\nimport { JobExecutionRuntime } from './job_runtime.js'\nimport { dispatchChannel, executeChannel } from './tracing_channels.js'\nimport type { Adapter, AcquiredJob } from './contracts/adapter.js'\nimport type { JobContext, JobOptions, JobRetention, QueueManagerConfig, WorkerCycle } from './types/main.js'\nimport type { JobDispatchMessage, JobExecuteMessage } from './types/tracing_channels.js'\nimport { Locator } from './locator.js'\nimport { DEFAULT_PRIORITY } from './constants.js'\nimport type { Job } from './job.js'\nimport {\n DEFAULT_IDLE_DELAY,\n DEFAULT_STALLED_INTERVAL,\n DEFAULT_STALLED_THRESHOLD,\n DEFAULT_ERROR_RETRY_DELAY,\n} from './constants.js'\n\n/**\n * Job processing worker.\n *\n * The Worker continuously polls queues for jobs and executes them\n * with configurable concurrency. It handles:\n * - Concurrent job execution via JobPool\n * - Automatic retries with backoff strategies\n * - Stalled job detection and recovery\n * - Graceful shutdown on SIGINT/SIGTERM\n *\n * @example\n * ```typescript\n * import { Worker, redis } from '@boringnode/queue'\n *\n * const worker = new Worker({\n * default: 'redis',\n * adapters: { redis: redis() },\n * locations: ['./jobs/**\\/*.js'],\n * worker: {\n * concurrency: 5,\n * idleDelay: '1s',\n * },\n * })\n *\n * // Start processing jobs\n * await worker.start(['default', 'emails'])\n *\n * // Or for testing, process one cycle at a time\n * const cycle = await worker.processCycle(['default'])\n * ```\n */\nexport class Worker {\n readonly #id: string\n readonly #config: QueueManagerConfig\n readonly #idleDelay: number\n readonly #stalledInterval: number\n readonly #stalledThreshold: number\n readonly #maxStalledCount: number\n readonly #concurrency: number\n readonly #gracefulShutdown: boolean\n readonly #onShutdownSignal?: () => void | Promise<void>\n\n #adapter!: Adapter\n #wrapInternal: <T>(fn: () => Promise<T>) => Promise<T> = (fn) => fn()\n #running = false\n #initialized = false\n #generator?: AsyncGenerator<WorkerCycle, void, unknown>\n #pool?: JobPool\n #lastStalledCheck = 0\n #shutdownHandler?: () => Promise<void>\n\n /** Unique identifier for this worker instance */\n get id() {\n return this.#id\n }\n\n /**\n * Create a new worker instance.\n *\n * @param config - Queue configuration including adapter and worker settings\n */\n constructor(config: QueueManagerConfig) {\n this.#config = config\n this.#id = randomUUID()\n\n // Parse worker config once at construction\n this.#idleDelay = parse(config.worker?.idleDelay ?? DEFAULT_IDLE_DELAY)\n this.#stalledInterval = parse(config.worker?.stalledInterval ?? DEFAULT_STALLED_INTERVAL)\n this.#stalledThreshold = parse(config.worker?.stalledThreshold ?? DEFAULT_STALLED_THRESHOLD)\n this.#maxStalledCount = config.worker?.maxStalledCount ?? 1\n this.#concurrency = config.worker?.concurrency ?? 1\n this.#gracefulShutdown = config.worker?.gracefulShutdown ?? true\n this.#onShutdownSignal = config.worker?.onShutdownSignal\n\n debug('created worker with id %s and config %O', this.#id, config)\n }\n\n /**\n * Initialize the worker (called automatically by `start()`).\n *\n * Sets up the QueueManager and adapter connection.\n */\n async init() {\n if (this.#initialized) {\n return\n }\n\n debug('initializing worker %s', this.#id)\n\n await QueueManager.init(this.#config)\n\n this.#adapter = QueueManager.use()\n this.#adapter.setWorkerId(this.#id)\n this.#wrapInternal = QueueManager.getInternalOperationWrapper()\n\n this.#initialized = true\n\n debug('worker %s initialized', this.#id)\n }\n\n /**\n * Start processing jobs from the specified queues.\n *\n * This method blocks until the worker is stopped (via `stop()` or signal).\n * Jobs are processed concurrently up to the configured concurrency limit.\n *\n * @param queues - Queue names to process (default: ['default'])\n *\n * @example\n * ```typescript\n * // Process single queue\n * await worker.start()\n *\n * // Process multiple queues (priority order)\n * await worker.start(['high-priority', 'default', 'low-priority'])\n * ```\n */\n async start(queues: string[] = ['default']): Promise<void> {\n await this.init()\n\n if (this.#running) {\n debug('worker %s is already running', this.#id)\n return\n }\n\n this.#running = true\n\n debug('starting worker %s on queues: %O', this.#id, queues)\n\n this.#setupGracefulShutdown()\n\n for await (const cycle of this.process(queues)) {\n if (['started', 'completed'].includes(cycle.type)) {\n continue\n }\n\n if (['idle', 'error'].includes(cycle.type)) {\n // @ts-expect-error - we know suggestedDelay exists for these types\n const delay = parse(cycle.suggestedDelay)\n\n if (cycle.type === 'error') {\n debug('worker %s encountered an error: %O', this.#id, cycle.error)\n } else {\n debug('worker %s is idle, waiting for %dms', this.#id, delay)\n }\n\n await setTimeout(delay)\n }\n }\n }\n\n /**\n * Stop the worker gracefully.\n *\n * Waits for all running jobs to complete before stopping job consumption.\n * Adapter cleanup remains the responsibility of `QueueManager.destroy()`.\n * Called automatically on SIGINT/SIGTERM if gracefulShutdown is enabled.\n */\n async stop() {\n debug('stopping worker %s', this.#id)\n\n this.#running = false\n\n if (this.#pool) {\n debug('worker %s: waiting for %d running jobs to complete', this.#id, this.#pool.size)\n await this.#pool.drain()\n }\n\n this.#removeShutdownHandlers()\n }\n\n /**\n * Process a single cycle and return the result.\n *\n * Useful for testing or when you need fine-grained control.\n * Each cycle may start new jobs, complete a job, or return idle.\n *\n * @param queues - Queue names to process\n * @returns The cycle result, or null if the worker was stopped\n *\n * @example\n * ```typescript\n * const worker = new Worker(config)\n *\n * // Process cycles manually\n * let cycle = await worker.processCycle(['default'])\n * while (cycle) {\n * console.log('Cycle:', cycle.type)\n * cycle = await worker.processCycle(['default'])\n * }\n * ```\n */\n async processCycle(queues: string[]): Promise<WorkerCycle | null> {\n await this.init()\n\n this.#running = true\n\n if (!this.#generator) {\n this.#generator = this.process(queues)\n }\n\n const result = await this.#generator.next()\n\n if (result.done) {\n this.#generator = undefined\n return null\n }\n\n return result.value\n }\n\n /**\n * Generator that yields worker cycle events.\n *\n * Low-level API for processing jobs. Yields events for:\n * - `started`: A new job began execution\n * - `completed`: A job finished (success or failure)\n * - `idle`: No jobs available, suggest waiting\n * - `error`: An error occurred during processing\n *\n * @param queues - Queue names to process\n * @yields WorkerCycle events\n *\n * @example\n * ```typescript\n * for await (const cycle of worker.process(['default'])) {\n * switch (cycle.type) {\n * case 'started':\n * console.log(`Started job ${cycle.job.id}`)\n * break\n * case 'completed':\n * console.log(`Completed job ${cycle.job.id}`)\n * break\n * case 'idle':\n * await sleep(cycle.suggestedDelay)\n * break\n * }\n * }\n * ```\n */\n async *process(queues: string[]): AsyncGenerator<WorkerCycle, void, unknown> {\n this.#pool = new JobPool()\n\n while (this.#running) {\n try {\n // Check for stalled jobs periodically\n await this.#checkStalledJobs(queues)\n\n // Dispatch any due scheduled jobs\n await this.#dispatchDueSchedules()\n\n yield* this.#fillPool(queues)\n\n if (this.#pool.isEmpty()) {\n yield { type: 'idle', suggestedDelay: this.#idleDelay }\n continue\n }\n\n const hasCapacity = this.#pool.hasCapacity(this.#concurrency)\n\n // If we have capacity, don't block indefinitely waiting for a completion;\n // wake up periodically to try to acquire newly enqueued jobs.\n const result = await Promise.race([\n this.#pool\n .waitForNextCompletion()\n .then((completed) => ({ kind: 'completed' as const, completed })),\n ...(hasCapacity\n ? [setTimeout(this.#idleDelay).then(() => ({ kind: 'tick' as const }))]\n : []),\n ])\n\n if (result.kind === 'tick') {\n // No completion yet, but we woke up to check the queue again\n continue\n }\n\n yield { type: 'completed', queue: result.completed.queue, job: result.completed.job }\n } catch (error) {\n yield {\n type: 'error',\n error: error as Error,\n suggestedDelay: parse(DEFAULT_ERROR_RETRY_DELAY),\n }\n }\n }\n }\n\n async *#fillPool(queues: string[]): AsyncGenerator<WorkerCycle, void, unknown> {\n const slotsAvailable = this.#concurrency - this.#pool!.size\n\n if (slotsAvailable <= 0) return\n\n const popPromises = Array.from({ length: slotsAvailable }, () => this.#acquireNextJob(queues))\n\n const results = await Promise.all(popPromises)\n\n for (const result of results) {\n if (!result) continue\n\n const { job, queue } = result\n const promise = this.#execute(job, queue)\n this.#pool!.add(job, queue, promise)\n\n yield { type: 'started', queue, job }\n }\n }\n\n async #execute(job: AcquiredJob, queue: string): Promise<void> {\n const startTime = performance.now()\n\n debug('worker %s: executing job %s (%s)', this.#id, job.id, job.name)\n\n const { instance, options, context, payload } = await this.#initJob(job, queue)\n const configResolver = QueueManager.getConfigResolver()\n const retention = configResolver.resolveJobOptions(queue, options)\n const runtime = JobExecutionRuntime.from({\n jobName: job.name,\n options,\n retryConfig: configResolver.resolveRetryConfig(queue, options),\n defaultTimeout: configResolver.getWorkerTimeout(),\n })\n\n const executeMessage: JobExecuteMessage = { job, queue }\n\n const run = () => {\n return executeChannel.tracePromise(async () => {\n try {\n await runtime.execute(instance, payload, context)\n await this.#wrapInternal(() => this.#adapter.completeJob(job.id, queue, retention.removeOnComplete))\n executeMessage.status = 'completed'\n debug('worker %s: successfully executed job %s in %dms', this.#id, job.id, (performance.now() - startTime).toFixed(2))\n } catch (e) {\n await this.#handleExecutionFailure({ error: e as Error, job, queue, instance, runtime, retention, executeMessage })\n }\n\n executeMessage.duration = Number((performance.now() - startTime).toFixed(2))\n }, executeMessage)\n }\n\n const executionWrapper = QueueManager.getExecutionWrapper()\n await executionWrapper(run, job, queue)\n }\n\n async #handleExecutionFailure(options: {\n error: Error\n job: AcquiredJob\n queue: string\n instance: Job\n runtime: JobExecutionRuntime\n retention: { removeOnComplete?: JobRetention; removeOnFail?: JobRetention }\n executeMessage: JobExecuteMessage\n }) {\n const outcome = options.runtime.resolveFailure(options.error, options.job.attempts)\n options.executeMessage.error = options.error\n\n if (outcome.type === 'failed') {\n options.executeMessage.status = 'failed'\n await this.#wrapInternal(() =>\n this.#adapter.failJob(options.job.id, options.queue, outcome.storageError, options.retention.removeOnFail)\n )\n await options.instance.failed?.(outcome.hookError)\n return\n }\n\n if (outcome.type !== 'retry') return\n\n options.executeMessage.status = 'retrying'\n options.executeMessage.nextRetryAt = outcome.retryAt\n\n if (outcome.retryAt) {\n debug('worker %s: job %s will retry at %s', this.#id, options.job.id, outcome.retryAt.toISOString())\n await this.#wrapInternal(() => this.#adapter.retryJob(options.job.id, options.queue, outcome.retryAt))\n } else {\n await this.#wrapInternal(() => this.#adapter.retryJob(options.job.id, options.queue))\n }\n }\n\n async #initJob(\n job: AcquiredJob,\n queue: string\n ): Promise<{\n instance: Job\n options: JobOptions\n context: JobContext\n payload: unknown\n }> {\n try {\n const JobClass = Locator.getOrThrow(job.name)\n\n const context: JobContext = {\n jobId: job.id,\n name: job.name,\n attempt: job.attempts + 1,\n queue,\n priority: job.priority ?? DEFAULT_PRIORITY,\n acquiredAt: new Date(job.acquiredAt),\n stalledCount: job.stalledCount ?? 0,\n }\n\n const jobFactory = QueueManager.getJobFactory()\n const instance = jobFactory ? await jobFactory(JobClass) : new JobClass()\n const options = JobClass.options || {}\n\n return { instance, options, context, payload: job.payload }\n } catch (error) {\n debug('worker %s: failed to initialize job %s (%s)', this.#id, job.id, job.name)\n const retention = QueueManager.getConfigResolver().resolveJobOptions(queue)\n await this.#wrapInternal(() => this.#adapter.failJob(job.id, queue, error as Error, retention.removeOnFail))\n throw error\n }\n }\n\n async #acquireNextJob(queues: string[]): Promise<{ job: AcquiredJob; queue: string } | null> {\n for (const queue of queues) {\n const job = await this.#wrapInternal(() => this.#adapter.popFrom(queue))\n\n if (!job) {\n continue\n }\n\n debug('worker %s: acquired job %s', this.#id, job.id)\n return { job, queue }\n }\n\n return null\n }\n\n async #checkStalledJobs(queues: string[]): Promise<void> {\n const now = Date.now()\n\n // Only check if enough time has passed since last check\n if (now - this.#lastStalledCheck < this.#stalledInterval) {\n return\n }\n\n this.#lastStalledCheck = now\n\n for (const queue of queues) {\n const recovered = await this.#wrapInternal(() =>\n this.#adapter.recoverStalledJobs(queue, this.#stalledThreshold, this.#maxStalledCount)\n )\n\n if (recovered > 0) {\n debug('worker %s: recovered %d stalled jobs from queue %s', this.#id, recovered, queue)\n }\n }\n }\n\n #setupGracefulShutdown() {\n if (!this.#gracefulShutdown) {\n return\n }\n\n this.#shutdownHandler = async () => {\n debug('received shutdown signal, stopping worker...')\n\n if (this.#onShutdownSignal) {\n await this.#onShutdownSignal()\n }\n\n await this.stop()\n }\n\n process.on('SIGINT', this.#shutdownHandler)\n process.on('SIGTERM', this.#shutdownHandler)\n }\n\n #removeShutdownHandlers() {\n if (this.#shutdownHandler) {\n process.off('SIGINT', this.#shutdownHandler)\n process.off('SIGTERM', this.#shutdownHandler)\n this.#shutdownHandler = undefined\n }\n }\n\n /**\n * Dispatch any due scheduled jobs.\n *\n * Claims due schedules from the adapter and dispatches the corresponding\n * jobs to their configured queues.\n */\n async #dispatchDueSchedules(): Promise<void> {\n // Keep claiming due schedules until there are none left\n while (true) {\n const schedule = await this.#wrapInternal(() => this.#adapter.claimDueSchedule())\n\n if (!schedule) {\n break\n }\n\n debug(\n 'worker %s: dispatching scheduled job %s (schedule: %s, runCount: %d)',\n this.#id,\n schedule.name,\n schedule.id,\n schedule.runCount + 1\n )\n\n // Get the job class to determine the target queue\n const JobClass = Locator.get(schedule.name)\n const queue = JobClass?.options?.queue ?? 'default'\n\n const jobData = {\n id: randomUUID(),\n name: schedule.name,\n payload: schedule.payload,\n attempts: 0,\n priority: JobClass?.options?.priority,\n }\n\n const message: JobDispatchMessage = { jobs: [jobData], queue }\n await dispatchChannel.tracePromise(async () => {\n await this.#wrapInternal(() => this.#adapter.pushOn(queue, jobData))\n }, message)\n }\n }\n}\n","import type { AcquiredJob } from './contracts/adapter.js'\n\n/**\n * Entry representing an active job in the pool.\n */\ninterface PoolEntry {\n /** Promise that resolves when the job completes */\n promise: Promise<void>\n /** The acquired job data */\n job: AcquiredJob\n /** The queue this job came from */\n queue: string\n}\n\n/**\n * Manages concurrent job execution with a fixed pool size.\n *\n * The pool tracks running jobs and returns the first one to complete,\n * allowing maximum throughput regardless of individual job duration:\n *\n * ```\n * Job A: ████████████████████░░░░░░░░░░ (slow - 10s)\n * Job B: ████ done (fast - 100ms) ← returns first\n * Job C: ████████████░░░░░░░░░░░░░░░░░░ (medium - 2s)\n * ↑\n * Slot freed, new job can start immediately\n * ```\n *\n * Key insight: slow jobs don't block the pool. As soon as any job\n * completes, its slot becomes available for new work.\n */\nexport class JobPool {\n #activeJobs = new Map<string, PoolEntry>()\n\n /** Number of currently running jobs */\n get size() {\n return this.#activeJobs.size\n }\n\n /**\n * Check if the pool has no running jobs.\n *\n * @returns True if no jobs are running\n */\n isEmpty() {\n return this.#activeJobs.size === 0\n }\n\n /**\n * Check if the pool can accept more jobs.\n *\n * @param concurrency - Maximum number of concurrent jobs\n * @returns True if there's room for more jobs\n */\n hasCapacity(concurrency: number) {\n return this.#activeJobs.size < concurrency\n }\n\n /**\n * Add a job to the pool.\n *\n * @param job - The acquired job data\n * @param queue - The queue the job came from\n * @param promise - Promise that resolves when the job completes\n */\n add(job: AcquiredJob, queue: string, promise: Promise<void>) {\n this.#activeJobs.set(job.id, { promise, job, queue })\n }\n\n /**\n * Wait for the next job to complete and return it.\n *\n * Uses `Promise.race()` internally, so the fastest job wins.\n * The completed job is removed from the pool.\n *\n * @returns The first job to complete (success or failure)\n */\n async waitForNextCompletion(): Promise<PoolEntry> {\n const completedJobId = await Promise.race(\n [...this.#activeJobs.entries()].map(async ([id, { promise }]) => {\n try {\n await promise\n } catch {\n // Errors are handled in Worker#execute\n }\n return id\n })\n )\n\n const completed = this.#activeJobs.get(completedJobId)!\n this.#activeJobs.delete(completedJobId)\n\n return completed\n }\n\n /**\n * Wait for all running jobs to complete.\n *\n * Used during graceful shutdown to ensure no jobs are abandoned.\n * Clears the pool after all jobs finish.\n */\n async drain(): Promise<void> {\n const promises = [...this.#activeJobs.values()].map(async ({ promise }) => {\n try {\n await promise\n } catch {\n // Errors are handled in Worker#execute\n }\n })\n\n await Promise.all(promises)\n this.#activeJobs.clear()\n }\n}\n","import { QueueManager } from './queue_manager.js'\nimport { JobDispatcher } from './job_dispatcher.js'\nimport type { ScheduleData, ScheduleListOptions, ScheduleStatus } from './types/main.js'\n\n/**\n * Represents a persisted job schedule.\n *\n * Use `Schedule.find()` or `Schedule.list()` to retrieve schedules,\n * then use instance methods to manage them.\n *\n * @example\n * ```typescript\n * const schedule = await Schedule.find('cleanup-daily')\n * if (schedule) {\n * await schedule.pause()\n * // Later...\n * await schedule.resume()\n * }\n *\n * // List all active schedules\n * const activeSchedules = await Schedule.list({ status: 'active' })\n * ```\n */\nexport class Schedule {\n readonly #data: ScheduleData\n\n constructor(data: ScheduleData) {\n this.#data = data\n }\n\n get id(): string {\n return this.#data.id\n }\n\n get name(): string {\n return this.#data.name\n }\n\n get payload(): unknown {\n return this.#data.payload\n }\n\n get cronExpression(): string | null {\n return this.#data.cronExpression\n }\n\n get everyMs(): number | null {\n return this.#data.everyMs\n }\n\n get timezone(): string {\n return this.#data.timezone\n }\n\n get from(): Date | null {\n return this.#data.from\n }\n\n get to(): Date | null {\n return this.#data.to\n }\n\n get limit(): number | null {\n return this.#data.limit\n }\n\n get runCount(): number {\n return this.#data.runCount\n }\n\n get nextRunAt(): Date | null {\n return this.#data.nextRunAt\n }\n\n get lastRunAt(): Date | null {\n return this.#data.lastRunAt\n }\n\n get status(): ScheduleStatus {\n return this.#data.status\n }\n\n get createdAt(): Date {\n return this.#data.createdAt\n }\n\n /**\n * Find a schedule by ID.\n *\n * @param id - The schedule ID\n * @returns The schedule instance, or null if not found\n */\n static async find(id: string): Promise<Schedule | null> {\n const adapter = QueueManager.use()\n const data = await adapter.getSchedule(id)\n\n if (!data) return null\n\n return new Schedule(data)\n }\n\n /**\n * List all schedules matching the given options.\n *\n * @param options - Optional filters for listing\n * @returns Array of schedule instances\n */\n static async list(options?: ScheduleListOptions): Promise<Schedule[]> {\n const adapter = QueueManager.use()\n const schedules = await adapter.listSchedules(options)\n\n return schedules.map((data) => new Schedule(data))\n }\n\n /**\n * Pause this schedule.\n * No jobs will be dispatched while paused.\n */\n async pause(): Promise<void> {\n const adapter = QueueManager.use()\n await adapter.updateSchedule(this.#data.id, { status: 'paused' })\n this.#data.status = 'paused'\n }\n\n /**\n * Resume this schedule.\n * Jobs will be dispatched according to the schedule.\n */\n async resume(): Promise<void> {\n const adapter = QueueManager.use()\n await adapter.updateSchedule(this.#data.id, { status: 'active' })\n this.#data.status = 'active'\n }\n\n /**\n * Delete this schedule permanently.\n */\n async delete(): Promise<void> {\n const adapter = QueueManager.use()\n await adapter.deleteSchedule(this.#data.id)\n }\n\n /**\n * Trigger immediate execution of this schedule's job.\n * Also updates runCount and lastRunAt.\n *\n * If the schedule has reached its limit, the job will not be dispatched.\n *\n * @param payload - Optional custom payload for the job\n */\n async trigger(payload?: any): Promise<void> {\n // Check if limit is reached\n if (this.#data.limit !== null && this.#data.runCount >= this.#data.limit) {\n return\n }\n\n const adapter = QueueManager.use()\n\n // Dispatch the job\n const dispatcher = new JobDispatcher(this.#data.name, payload ?? this.#data.payload)\n await dispatcher.run()\n\n // Update run metadata\n const now = new Date()\n const newRunCount = this.#data.runCount + 1\n\n await adapter.updateSchedule(this.#data.id, {\n runCount: newRunCount,\n lastRunAt: now,\n })\n\n this.#data.runCount = newRunCount\n this.#data.lastRunAt = now\n }\n}\n","import type { Knex } from 'knex'\n\nexport class QueueSchemaService {\n #connection: Knex\n\n constructor(connection: Knex) {\n this.#connection = connection\n }\n\n /**\n * Creates the jobs table with the default schema.\n * The optional callback allows adding custom columns.\n */\n async createJobsTable(\n tableName: string = 'queue_jobs',\n extend?: (table: Knex.CreateTableBuilder) => void\n ): Promise<void> {\n await this.#connection.schema.createTable(tableName, (table) => {\n table.string('id', 255).notNullable()\n table.string('queue', 255).notNullable()\n table.enu('status', ['pending', 'active', 'delayed', 'completed', 'failed']).notNullable()\n table.text('data').notNullable()\n table.bigint('score').unsigned().nullable()\n table.string('worker_id', 255).nullable()\n table.bigint('acquired_at').unsigned().nullable()\n table.bigint('execute_at').unsigned().nullable()\n table.bigint('finished_at').unsigned().nullable()\n table.text('error').nullable()\n table.primary(['id', 'queue'])\n table.index(['queue', 'status', 'score'])\n table.index(['queue', 'status', 'execute_at'])\n table.index(['queue', 'status', 'finished_at'])\n\n extend?.(table)\n })\n }\n\n /**\n * Creates the schedules table with the default schema.\n * The optional callback allows adding custom columns.\n */\n async createSchedulesTable(\n tableName: string = 'queue_schedules',\n extend?: (table: Knex.CreateTableBuilder) => void\n ): Promise<void> {\n await this.#connection.schema.createTable(tableName, (table) => {\n table.string('id', 255).primary()\n table.string('status', 50).notNullable().defaultTo('active')\n table.string('name', 255).notNullable()\n table.text('payload').notNullable()\n table.string('cron_expression', 255).nullable()\n table.bigint('every_ms').unsigned().nullable()\n table.string('timezone', 100).notNullable().defaultTo('UTC')\n table.timestamp('from_date').nullable()\n table.timestamp('to_date').nullable()\n table.integer('run_limit').unsigned().nullable()\n table.integer('run_count').unsigned().notNullable().defaultTo(0)\n table.timestamp('next_run_at').nullable()\n table.timestamp('last_run_at').nullable()\n table\n .timestamp('created_at')\n .notNullable()\n .defaultTo(this.#connection.fn.now())\n table.index(['status', 'next_run_at'])\n\n extend?.(table)\n })\n }\n\n /**\n * Drops the jobs table if it exists.\n */\n async dropJobsTable(tableName: string = 'queue_jobs'): Promise<void> {\n await this.#connection.schema.dropTableIfExists(tableName)\n }\n\n /**\n * Drops the schedules table if it exists.\n */\n async dropSchedulesTable(tableName: string = 'queue_schedules'): Promise<void> {\n await this.#connection.schema.dropTableIfExists(tableName)\n }\n}\n","import type { BackoffConfig, Duration } from '../types/main.js'\nimport * as errors from '../exceptions.js'\nimport { parse } from '../utils.js'\nimport { RuntimeException } from '@poppinss/utils/exception'\nimport { assertUnreachable } from '@poppinss/utils/assert'\n\n/**\n * Calculates retry delays using configurable strategies.\n *\n * Supports three built-in strategies:\n * - `exponential`: Delay doubles each attempt (1s, 2s, 4s, 8s, ...)\n * - `linear`: Delay increases linearly (5s, 10s, 15s, 20s, ...)\n * - `fixed`: Same delay every time (10s, 10s, 10s, ...)\n *\n * All strategies support:\n * - `maxDelay`: Cap the maximum delay\n * - `jitter`: Add randomness to prevent thundering herd\n *\n * @example\n * ```typescript\n * const strategy = new BackoffStrategy({\n * strategy: 'exponential',\n * baseDelay: '1s',\n * maxDelay: '5m',\n * multiplier: 2,\n * jitter: true,\n * })\n *\n * strategy.calculateDelay(1) // ~1000ms\n * strategy.calculateDelay(2) // ~2000ms\n * strategy.calculateDelay(3) // ~4000ms\n * ```\n */\nexport class BackoffStrategy {\n readonly #config: BackoffConfig\n\n /**\n * Create a new backoff strategy.\n *\n * @param config - Backoff configuration\n * @throws {E_INVALID_BASE_DELAY} If baseDelay is not positive\n * @throws {E_INVALID_MAX_DELAY} If maxDelay is invalid\n * @throws {E_INVALID_MULTIPLIER} If multiplier is invalid\n */\n constructor(config: BackoffConfig) {\n this.#config = config\n this.#validateConfig()\n }\n\n /**\n * Calculate the delay for a given attempt number.\n *\n * @param attempt - The attempt number (1-based)\n * @returns Delay in milliseconds\n * @throws {RuntimeException} If attempt is less than 1\n *\n * @example\n * ```typescript\n * // Exponential: 1s, 2s, 4s, 8s, 16s, ...\n * strategy.calculateDelay(1) // 1000\n * strategy.calculateDelay(2) // 2000\n * strategy.calculateDelay(3) // 4000\n * ```\n */\n calculateDelay(attempt: number): number {\n if (attempt < 1) {\n throw new RuntimeException('Attempt number must be >= 1')\n }\n\n const baseDelayMs = parse(this.#config.baseDelay)\n const maxDelayMs = this.#config.maxDelay ? parse(this.#config.maxDelay) : Infinity\n const multiplier = this.#config.multiplier ?? 2\n\n let delay: number\n\n switch (this.#config.strategy) {\n case 'exponential':\n delay = baseDelayMs * Math.pow(multiplier, attempt - 1)\n break\n case 'linear':\n delay = baseDelayMs * attempt\n break\n case 'fixed':\n delay = baseDelayMs\n break\n default:\n assertUnreachable(this.#config.strategy)\n }\n\n // Apply max delay limit\n delay = Math.min(delay, maxDelayMs)\n\n if (this.#config.jitter) {\n delay = this.#applyJitter(delay)\n }\n\n return Math.floor(delay)\n }\n\n /**\n * Get the Date when the next retry should occur.\n *\n * @param attempt - The attempt number (1-based)\n * @returns Date for the next retry\n *\n * @example\n * ```typescript\n * const nextRetry = strategy.getNextRetryAt(3)\n * console.log(`Retry at: ${nextRetry.toISOString()}`)\n * ```\n */\n getNextRetryAt(attempt: number): Date {\n const delay = this.calculateDelay(attempt)\n return new Date(Date.now() + delay)\n }\n\n /**\n * Get a frozen copy of the configuration.\n *\n * @returns Readonly configuration object\n */\n getConfig(): Readonly<BackoffConfig> {\n return Object.freeze({ ...this.#config })\n }\n\n #validateConfig() {\n const baseDelayMs = parse(this.#config.baseDelay)\n\n if (baseDelayMs <= 0) {\n throw new errors.E_INVALID_BASE_DELAY([\n 'Base delay must be a positive integer greater than zero',\n ])\n }\n\n if (this.#config.maxDelay) {\n const maxDelayMs = parse(this.#config.maxDelay)\n\n if (maxDelayMs <= 0) {\n throw new errors.E_INVALID_MAX_DELAY([\n 'Max delay must be a positive integer greater than zero',\n ])\n }\n\n if (maxDelayMs <= baseDelayMs) {\n throw new errors.E_INVALID_MAX_DELAY(['Max delay should be greater than base delay'])\n }\n }\n\n if (this.#config.multiplier !== undefined) {\n if (this.#config.multiplier <= 0) {\n throw new errors.E_INVALID_MULTIPLIER([\n 'Multiplier must be a positive number greater than zero',\n ])\n }\n\n if (this.#config.strategy === 'exponential' && this.#config.multiplier < 1) {\n throw new errors.E_INVALID_MULTIPLIER(['Exponential strategy multiplier should be >= 1'])\n }\n }\n }\n\n #applyJitter(delay: number): number {\n const jitterRange = delay * 0.25\n const jitter = (Math.random() - 0.5) * 2 * jitterRange\n\n return Math.max(0, delay + jitter)\n }\n}\n\n/**\n * Create an exponential backoff strategy factory.\n *\n * Delay doubles with each attempt: 1s → 2s → 4s → 8s → ...\n *\n * Default config:\n * - baseDelay: 1s\n * - maxDelay: 5m\n * - multiplier: 2\n * - jitter: true\n *\n * @param config - Optional overrides for default config\n * @returns Factory function for creating BackoffStrategy instances\n *\n * @example\n * ```typescript\n * const config = {\n * retry: {\n * maxRetries: 5,\n * backoff: exponentialBackoff({ baseDelay: '500ms', maxDelay: '1m' }),\n * },\n * }\n * ```\n */\nexport function exponentialBackoff(config?: Partial<Omit<BackoffConfig, 'strategy'>>) {\n return () =>\n new BackoffStrategy({\n strategy: 'exponential',\n baseDelay: '1s',\n maxDelay: '5m',\n multiplier: 2,\n jitter: true,\n ...config,\n })\n}\n\n/**\n * Create a linear backoff strategy factory.\n *\n * Delay increases linearly: 5s → 10s → 15s → 20s → ...\n *\n * Default config:\n * - baseDelay: 5s\n * - maxDelay: 2m\n *\n * @param config - Optional overrides for default config\n * @returns Factory function for creating BackoffStrategy instances\n *\n * @example\n * ```typescript\n * const config = {\n * retry: {\n * maxRetries: 3,\n * backoff: linearBackoff({ baseDelay: '10s' }),\n * },\n * }\n * ```\n */\nexport function linearBackoff(config?: Partial<Omit<BackoffConfig, 'strategy'>>) {\n return () =>\n new BackoffStrategy({\n strategy: 'linear',\n baseDelay: '5s',\n maxDelay: '2m',\n ...config,\n })\n}\n\n/**\n * Create a fixed delay backoff strategy factory.\n *\n * Same delay every time: 10s → 10s → 10s → ...\n *\n * @param delay - The fixed delay (default: '10s')\n * @returns Factory function for creating BackoffStrategy instances\n *\n * @example\n * ```typescript\n * const config = {\n * retry: {\n * maxRetries: 3,\n * backoff: fixedBackoff('30s'),\n * },\n * }\n * ```\n */\nexport function fixedBackoff(delay: Duration = '10s') {\n return () =>\n new BackoffStrategy({\n strategy: 'fixed',\n baseDelay: delay,\n })\n}\n\n/**\n * Create a custom backoff strategy factory.\n *\n * Use this when you need full control over the configuration.\n *\n * @param config - Complete backoff configuration\n * @returns Factory function for creating BackoffStrategy instances\n *\n * @example\n * ```typescript\n * const config = {\n * retry: {\n * maxRetries: 5,\n * backoff: customBackoff({\n * strategy: 'exponential',\n * baseDelay: '100ms',\n * maxDelay: '30s',\n * multiplier: 3,\n * jitter: false,\n * }),\n * },\n * }\n * ```\n */\nexport function customBackoff(config: BackoffConfig) {\n return () => new BackoffStrategy(config)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,kBAAkB;;;AC8BpB,IAAM,UAAN,MAAc;AAAA,EACnB,cAAc,oBAAI,IAAuB;AAAA;AAAA,EAGzC,IAAI,OAAO;AACT,WAAO,KAAK,YAAY;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,UAAU;AACR,WAAO,KAAK,YAAY,SAAS;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA;A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AC1E,cAAM,IAAW,qBAAqB,CAAC,gDAAgD,CAAC;AAAA,MAC1F;AAAA,IACF;AAAA,EACF;AAAA,EAEA,aAAa,OAAuB;AAClC,UAAM,cAAc,QAAQ;AAC5B,UAAM,UAAU,KAAK,OAAO,IAAI,OAAO,IAAI;AAE3C,WAAO,KAAK,IAAI,GAAG,QAAQ,MAAM;AAAA,EACnC;AACF;AA0BO,SAAS,mBAAmB,QAAmD;AACpF,SAAO,MACL,IAAI,gBAAgB;AAAA,IAClB,UAAU;AAAA,IACV,WAAW;AAAA,IACX,UAAU;AAAA,IACV,YAAY;AAAA,IACZ,QAAQ;AAAA,IACR,GAAG;AAAA,EACL,CAAC;AACL;AAwBO,SAAS,cAAc,QAAmD;AAC/E,SAAO,MACL,IAAI,gBAAgB;AAAA,IAClB,UAAU;AAAA,IACV,WAAW;AAAA,IACX,UAAU;AAAA,IACV,GAAG;AAAA,EACL,CAAC;AACL;AAoBO,SAAS,aAAa,QAAkB,OAAO;AACpD,SAAO,MACL,IAAI,gBAAgB;AAAA,IAClB,UAAU;AAAA,IACV,WAAW;AAAA,EACb,CAAC;AACL;AA0BO,SAAS,cAAc,QAAuB;AACnD,SAAO,MAAM,IAAI,gBAAgB,MAAM;AACzC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/worker.ts","../src/job_pool.ts","../src/schedule.ts","../src/services/queue_schema.ts","../src/strategies/backoff_strategy.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { setTimeout } from 'node:timers/promises'\nimport debug from './debug.js'\nimport { parse } from './utils.js'\nimport { QueueManager } from './queue_manager.js'\nimport { JobPool } from './job_pool.js'\nimport { JobExecutionRuntime } from './job_runtime.js'\nimport { dispatchChannel, executeChannel } from './tracing_channels.js'\nimport type { Adapter, AcquiredJob } from './contracts/adapter.js'\nimport type {\n JobContext,\n JobOptions,\n JobRetention,\n QueueManagerConfig,\n WorkerCycle,\n} from './types/main.js'\nimport type { JobDispatchMessage, JobExecuteMessage } from './types/tracing_channels.js'\nimport { Locator } from './locator.js'\nimport { DEFAULT_PRIORITY } from './constants.js'\nimport type { Job } from './job.js'\nimport {\n DEFAULT_IDLE_DELAY,\n DEFAULT_STALLED_INTERVAL,\n DEFAULT_STALLED_THRESHOLD,\n DEFAULT_ERROR_RETRY_DELAY,\n} from './constants.js'\n\n/**\n * Job processing worker.\n *\n * The Worker continuously polls queues for jobs and executes them\n * with configurable concurrency. It handles:\n * - Concurrent job execution via JobPool\n * - Automatic retries with backoff strategies\n * - Stalled job detection and recovery\n * - Graceful shutdown on SIGINT/SIGTERM\n *\n * @example\n * ```typescript\n * import { Worker, redis } from '@boringnode/queue'\n *\n * const worker = new Worker({\n * default: 'redis',\n * adapters: { redis: redis() },\n * locations: ['./jobs/**\\/*.js'],\n * worker: {\n * concurrency: 5,\n * idleDelay: '1s',\n * },\n * })\n *\n * // Start processing jobs\n * await worker.start(['default', 'emails'])\n *\n * // Or for testing, process one cycle at a time\n * const cycle = await worker.processCycle(['default'])\n * ```\n */\nexport class Worker {\n readonly #id: string\n readonly #config: QueueManagerConfig\n readonly #idleDelay: number\n readonly #stalledInterval: number\n readonly #stalledThreshold: number\n readonly #maxStalledCount: number\n readonly #concurrency: number\n readonly #gracefulShutdown: boolean\n readonly #onShutdownSignal?: () => void | Promise<void>\n\n #adapter!: Adapter\n #wrapInternal: <T>(fn: () => Promise<T>) => Promise<T> = (fn) => fn()\n #running = false\n #initialized = false\n #generator?: AsyncGenerator<WorkerCycle, void, unknown>\n #pool?: JobPool\n #lastStalledCheck = 0\n #shutdownHandler?: () => Promise<void>\n #heartbeatTimer?: NodeJS.Timeout\n #renewingJobs = false\n\n /** Unique identifier for this worker instance */\n get id() {\n return this.#id\n }\n\n /**\n * Create a new worker instance.\n *\n * @param config - Queue configuration including adapter and worker settings\n */\n constructor(config: QueueManagerConfig) {\n this.#config = config\n this.#id = randomUUID()\n\n // Parse worker config once at construction\n this.#idleDelay = parse(config.worker?.idleDelay ?? DEFAULT_IDLE_DELAY)\n this.#stalledInterval = parse(config.worker?.stalledInterval ?? DEFAULT_STALLED_INTERVAL)\n this.#stalledThreshold = parse(config.worker?.stalledThreshold ?? DEFAULT_STALLED_THRESHOLD)\n this.#maxStalledCount = config.worker?.maxStalledCount ?? 1\n this.#concurrency = config.worker?.concurrency ?? 1\n this.#gracefulShutdown = config.worker?.gracefulShutdown ?? true\n this.#onShutdownSignal = config.worker?.onShutdownSignal\n\n debug('created worker with id %s and config %O', this.#id, config)\n }\n\n /**\n * Initialize the worker (called automatically by `start()`).\n *\n * Sets up the QueueManager and adapter connection.\n */\n async init() {\n if (this.#initialized) {\n return\n }\n\n debug('initializing worker %s', this.#id)\n\n await QueueManager.init(this.#config)\n\n this.#adapter = QueueManager.use()\n this.#adapter.setWorkerId(this.#id)\n this.#wrapInternal = QueueManager.getInternalOperationWrapper()\n\n this.#initialized = true\n\n debug('worker %s initialized', this.#id)\n }\n\n /**\n * Start processing jobs from the specified queues.\n *\n * This method blocks until the worker is stopped (via `stop()` or signal).\n * Jobs are processed concurrently up to the configured concurrency limit.\n *\n * @param queues - Queue names to process (default: ['default'])\n *\n * @example\n * ```typescript\n * // Process single queue\n * await worker.start()\n *\n * // Process multiple queues (priority order)\n * await worker.start(['high-priority', 'default', 'low-priority'])\n * ```\n */\n async start(queues: string[] = ['default']): Promise<void> {\n await this.init()\n\n if (this.#running) {\n debug('worker %s is already running', this.#id)\n return\n }\n\n this.#running = true\n\n debug('starting worker %s on queues: %O', this.#id, queues)\n\n this.#setupGracefulShutdown()\n\n for await (const cycle of this.process(queues)) {\n if (['started', 'completed'].includes(cycle.type)) {\n continue\n }\n\n if (['idle', 'error'].includes(cycle.type)) {\n // @ts-expect-error - we know suggestedDelay exists for these types\n const delay = parse(cycle.suggestedDelay)\n\n if (cycle.type === 'error') {\n debug('worker %s encountered an error: %O', this.#id, cycle.error)\n } else {\n debug('worker %s is idle, waiting for %dms', this.#id, delay)\n }\n\n await setTimeout(delay)\n }\n }\n }\n\n /**\n * Stop the worker gracefully.\n *\n * Waits for all running jobs to complete before stopping job consumption.\n * Adapter cleanup remains the responsibility of `QueueManager.destroy()`.\n * Called automatically on SIGINT/SIGTERM if gracefulShutdown is enabled.\n */\n async stop() {\n debug('stopping worker %s', this.#id)\n\n this.#running = false\n\n if (this.#pool) {\n debug('worker %s: waiting for %d running jobs to complete', this.#id, this.#pool.size)\n await this.#pool.drain()\n }\n\n // Stop the heartbeat only after draining, so jobs that are still finishing\n // keep being renewed until they actually complete. The process() generator\n // also clears it in its `finally`, but clearing here guarantees prompt and\n // deterministic cleanup regardless of how the worker was driven (start() vs\n // processCycle()).\n this.#stopHeartbeat()\n\n this.#removeShutdownHandlers()\n }\n\n /**\n * Process a single cycle and return the result.\n *\n * Useful for testing or when you need fine-grained control.\n * Each cycle may start new jobs, complete a job, or return idle.\n *\n * @param queues - Queue names to process\n * @returns The cycle result, or null if the worker was stopped\n *\n * @example\n * ```typescript\n * const worker = new Worker(config)\n *\n * // Process cycles manually\n * let cycle = await worker.processCycle(['default'])\n * while (cycle) {\n * console.log('Cycle:', cycle.type)\n * cycle = await worker.processCycle(['default'])\n * }\n * ```\n */\n async processCycle(queues: string[]): Promise<WorkerCycle | null> {\n await this.init()\n\n this.#running = true\n\n if (!this.#generator) {\n this.#generator = this.process(queues)\n }\n\n const result = await this.#generator.next()\n\n if (result.done) {\n this.#generator = undefined\n return null\n }\n\n return result.value\n }\n\n /**\n * Generator that yields worker cycle events.\n *\n * Low-level API for processing jobs. Yields events for:\n * - `started`: A new job began execution\n * - `completed`: A job finished (success or failure)\n * - `idle`: No jobs available, suggest waiting\n * - `error`: An error occurred during processing\n *\n * @param queues - Queue names to process\n * @yields WorkerCycle events\n *\n * @example\n * ```typescript\n * for await (const cycle of worker.process(['default'])) {\n * switch (cycle.type) {\n * case 'started':\n * console.log(`Started job ${cycle.job.id}`)\n * break\n * case 'completed':\n * console.log(`Completed job ${cycle.job.id}`)\n * break\n * case 'idle':\n * await sleep(cycle.suggestedDelay)\n * break\n * }\n * }\n * ```\n */\n async *process(queues: string[]): AsyncGenerator<WorkerCycle, void, unknown> {\n this.#pool = new JobPool()\n this.#startHeartbeat(queues)\n\n try {\n while (this.#running) {\n try {\n // Check for stalled jobs periodically\n await this.#checkStalledJobs(queues)\n\n // Dispatch any due scheduled jobs\n await this.#dispatchDueSchedules()\n\n yield* this.#fillPool(queues)\n\n if (this.#pool.isEmpty()) {\n yield { type: 'idle', suggestedDelay: this.#idleDelay }\n continue\n }\n\n const hasCapacity = this.#pool.hasCapacity(this.#concurrency)\n\n // If we have capacity, don't block indefinitely waiting for a completion;\n // wake up periodically to try to acquire newly enqueued jobs.\n const result = await Promise.race([\n this.#pool\n .waitForNextCompletion()\n .then((completed) => ({ kind: 'completed' as const, completed })),\n ...(hasCapacity\n ? [setTimeout(this.#idleDelay).then(() => ({ kind: 'tick' as const }))]\n : []),\n ])\n\n if (result.kind === 'tick') {\n // No completion yet, but we woke up to check the queue again\n continue\n }\n\n yield { type: 'completed', queue: result.completed.queue, job: result.completed.job }\n } catch (error) {\n yield {\n type: 'error',\n error: error as Error,\n suggestedDelay: parse(DEFAULT_ERROR_RETRY_DELAY),\n }\n }\n }\n } finally {\n this.#stopHeartbeat()\n }\n }\n\n async *#fillPool(queues: string[]): AsyncGenerator<WorkerCycle, void, unknown> {\n const slotsAvailable = this.#concurrency - this.#pool!.size\n\n if (slotsAvailable <= 0) return\n\n const popPromises = Array.from({ length: slotsAvailable }, () => this.#acquireNextJob(queues))\n\n const results = await Promise.all(popPromises)\n\n for (const result of results) {\n if (!result) continue\n\n const { job, queue } = result\n const promise = this.#execute(job, queue)\n this.#pool!.add(job, queue, promise)\n\n yield { type: 'started', queue, job }\n }\n }\n\n async #execute(job: AcquiredJob, queue: string): Promise<void> {\n const startTime = performance.now()\n\n debug('worker %s: executing job %s (%s)', this.#id, job.id, job.name)\n\n const { instance, options, context, payload } = await this.#initJob(job, queue)\n const configResolver = QueueManager.getConfigResolver()\n const retention = configResolver.resolveJobOptions(queue, options)\n const runtime = JobExecutionRuntime.from({\n jobName: job.name,\n options,\n retryConfig: configResolver.resolveRetryConfig(queue, options),\n defaultTimeout: configResolver.getWorkerTimeout(),\n })\n\n const executeMessage: JobExecuteMessage = { job, queue }\n\n const run = () => {\n return executeChannel.tracePromise(async () => {\n try {\n await runtime.execute(instance, payload, context)\n await this.#wrapInternal(() =>\n this.#adapter.completeJob(job.id, queue, retention.removeOnComplete)\n )\n executeMessage.status = 'completed'\n debug(\n 'worker %s: successfully executed job %s in %dms',\n this.#id,\n job.id,\n (performance.now() - startTime).toFixed(2)\n )\n } catch (e) {\n await this.#handleExecutionFailure({\n error: e as Error,\n job,\n queue,\n instance,\n runtime,\n retention,\n executeMessage,\n })\n }\n\n executeMessage.duration = Number((performance.now() - startTime).toFixed(2))\n }, executeMessage)\n }\n\n const executionWrapper = QueueManager.getExecutionWrapper()\n await executionWrapper(run, job, queue)\n }\n\n async #handleExecutionFailure(options: {\n error: Error\n job: AcquiredJob\n queue: string\n instance: Job\n runtime: JobExecutionRuntime\n retention: { removeOnComplete?: JobRetention; removeOnFail?: JobRetention }\n executeMessage: JobExecuteMessage\n }) {\n const outcome = options.runtime.resolveFailure(options.error, options.job.attempts)\n options.executeMessage.error = options.error\n\n if (outcome.type === 'failed') {\n options.executeMessage.status = 'failed'\n await this.#wrapInternal(() =>\n this.#adapter.failJob(\n options.job.id,\n options.queue,\n outcome.storageError,\n options.retention.removeOnFail\n )\n )\n await options.instance.failed?.(outcome.hookError)\n return\n }\n\n if (outcome.type !== 'retry') return\n\n options.executeMessage.status = 'retrying'\n options.executeMessage.nextRetryAt = outcome.retryAt\n\n if (outcome.retryAt) {\n debug(\n 'worker %s: job %s will retry at %s',\n this.#id,\n options.job.id,\n outcome.retryAt.toISOString()\n )\n await this.#wrapInternal(() =>\n this.#adapter.retryJob(options.job.id, options.queue, outcome.retryAt)\n )\n } else {\n await this.#wrapInternal(() => this.#adapter.retryJob(options.job.id, options.queue))\n }\n }\n\n async #initJob(\n job: AcquiredJob,\n queue: string\n ): Promise<{\n instance: Job\n options: JobOptions\n context: JobContext\n payload: unknown\n }> {\n try {\n const JobClass = Locator.getOrThrow(job.name)\n\n const context: JobContext = {\n jobId: job.id,\n name: job.name,\n attempt: job.attempts + 1,\n queue,\n priority: job.priority ?? DEFAULT_PRIORITY,\n acquiredAt: new Date(job.acquiredAt),\n stalledCount: job.stalledCount ?? 0,\n }\n\n const jobFactory = QueueManager.getJobFactory()\n const instance = jobFactory ? await jobFactory(JobClass) : new JobClass()\n const options = JobClass.options || {}\n\n return { instance, options, context, payload: job.payload }\n } catch (error) {\n debug('worker %s: failed to initialize job %s (%s)', this.#id, job.id, job.name)\n const retention = QueueManager.getConfigResolver().resolveJobOptions(queue)\n await this.#wrapInternal(() =>\n this.#adapter.failJob(job.id, queue, error as Error, retention.removeOnFail)\n )\n throw error\n }\n }\n\n async #acquireNextJob(queues: string[]): Promise<{ job: AcquiredJob; queue: string } | null> {\n for (const queue of queues) {\n const job = await this.#wrapInternal(() => this.#adapter.popFrom(queue))\n\n if (!job) {\n continue\n }\n\n debug('worker %s: acquired job %s', this.#id, job.id)\n return { job, queue }\n }\n\n return null\n }\n\n async #checkStalledJobs(queues: string[]): Promise<void> {\n const now = Date.now()\n\n // Only check if enough time has passed since last check\n if (now - this.#lastStalledCheck < this.#stalledInterval) {\n return\n }\n\n this.#lastStalledCheck = now\n\n for (const queue of queues) {\n const recovered = await this.#wrapInternal(() =>\n this.#adapter.recoverStalledJobs(queue, this.#stalledThreshold, this.#maxStalledCount)\n )\n\n if (recovered > 0) {\n debug('worker %s: recovered %d stalled jobs from queue %s', this.#id, recovered, queue)\n }\n }\n }\n\n /**\n * Start the heartbeat timer that periodically renews the acquired timestamp\n * of in-flight jobs.\n *\n * Renewal cannot piggyback on the main process loop: at full concurrency the\n * loop blocks on `waitForNextCompletion()` with no idle tick, so exactly when\n * long-running jobs are in flight the loop is not cycling. A dedicated timer\n * guarantees healthy jobs are refreshed before `recoverStalledJobs` would\n * consider them stalled and re-deliver them.\n *\n * The interval is half the stalled threshold so a job is renewed at least\n * once within every stalled window.\n */\n #startHeartbeat(queues: string[]) {\n // Never leave a previous timer running if the loop is somehow re-entered.\n this.#stopHeartbeat()\n\n const interval = Math.max(Math.floor(this.#stalledThreshold / 2), 1)\n\n this.#heartbeatTimer = setInterval(() => {\n void this.#renewActiveJobs(queues)\n }, interval)\n\n // Don't let the heartbeat keep the event loop alive on its own.\n this.#heartbeatTimer.unref?.()\n }\n\n #stopHeartbeat() {\n if (this.#heartbeatTimer) {\n clearInterval(this.#heartbeatTimer)\n this.#heartbeatTimer = undefined\n }\n }\n\n /**\n * Renew the acquired timestamp of the jobs currently in the pool so that\n * long-running handlers are not treated as stalled while they are still\n * running. Only jobs still active in the adapter are renewed.\n */\n async #renewActiveJobs(queues: string[]): Promise<void> {\n // Guard against overlapping runs if a renewal takes longer than the interval.\n if (this.#renewingJobs || !this.#pool || this.#pool.isEmpty()) {\n return\n }\n\n this.#renewingJobs = true\n\n try {\n const jobIdsByQueue = this.#pool.activeJobIdsByQueue()\n\n for (const queue of queues) {\n const jobIds = jobIdsByQueue.get(queue)\n\n if (!jobIds || jobIds.length === 0) {\n continue\n }\n\n try {\n await this.#wrapInternal(() => this.#adapter.renewJobs(queue, jobIds))\n } catch (error) {\n // A failed heartbeat must never crash the worker; the job will simply\n // be considered stalled if renewals keep failing.\n debug('worker %s: failed to renew jobs on queue %s: %O', this.#id, queue, error)\n }\n }\n } finally {\n this.#renewingJobs = false\n }\n }\n\n #setupGracefulShutdown() {\n if (!this.#gracefulShutdown) {\n return\n }\n\n this.#shutdownHandler = async () => {\n debug('received shutdown signal, stopping worker...')\n\n if (this.#onShutdownSignal) {\n await this.#onShutdownSignal()\n }\n\n await this.stop()\n }\n\n process.on('SIGINT', this.#shutdownHandler)\n process.on('SIGTERM', this.#shutdownHandler)\n }\n\n #removeShutdownHandlers() {\n if (this.#shutdownHandler) {\n process.off('SIGINT', this.#shutdownHandler)\n process.off('SIGTERM', this.#shutdownHandler)\n this.#shutdownHandler = undefined\n }\n }\n\n /**\n * Dispatch any due scheduled jobs.\n *\n * Claims due schedules from the adapter and dispatches the corresponding\n * jobs to their configured queues.\n */\n async #dispatchDueSchedules(): Promise<void> {\n // Keep claiming due schedules until there are none left\n while (true) {\n const schedule = await this.#wrapInternal(() => this.#adapter.claimDueSchedule())\n\n if (!schedule) {\n break\n }\n\n debug(\n 'worker %s: dispatching scheduled job %s (schedule: %s, runCount: %d)',\n this.#id,\n schedule.name,\n schedule.id,\n schedule.runCount + 1\n )\n\n // Get the job class to determine the target queue\n const JobClass = Locator.get(schedule.name)\n const queue = JobClass?.options?.queue ?? 'default'\n\n const jobData = {\n id: randomUUID(),\n name: schedule.name,\n payload: schedule.payload,\n attempts: 0,\n priority: JobClass?.options?.priority,\n }\n\n const message: JobDispatchMessage = { jobs: [jobData], queue }\n await dispatchChannel.tracePromise(async () => {\n await this.#wrapInternal(() => this.#adapter.pushOn(queue, jobData))\n }, message)\n }\n }\n}\n","import type { AcquiredJob } from './contracts/adapter.js'\n\n/**\n * Entry representing an active job in the pool.\n */\ninterface PoolEntry {\n /** Promise that resolves when the job completes */\n promise: Promise<void>\n /** The acquired job data */\n job: AcquiredJob\n /** The queue this job came from */\n queue: string\n}\n\n/**\n * Manages concurrent job execution with a fixed pool size.\n *\n * The pool tracks running jobs and returns the first one to complete,\n * allowing maximum throughput regardless of individual job duration:\n *\n * ```\n * Job A: ████████████████████░░░░░░░░░░ (slow - 10s)\n * Job B: ████ done (fast - 100ms) ← returns first\n * Job C: ████████████░░░░░░░░░░░░░░░░░░ (medium - 2s)\n * ↑\n * Slot freed, new job can start immediately\n * ```\n *\n * Key insight: slow jobs don't block the pool. As soon as any job\n * completes, its slot becomes available for new work.\n */\nexport class JobPool {\n #activeJobs = new Map<string, PoolEntry>()\n\n /** Number of currently running jobs */\n get size() {\n return this.#activeJobs.size\n }\n\n /**\n * Check if the pool has no running jobs.\n *\n * @returns True if no jobs are running\n */\n isEmpty() {\n return this.#activeJobs.size === 0\n }\n\n /**\n * Check if the pool can accept more jobs.\n *\n * @param concurrency - Maximum number of concurrent jobs\n * @returns True if there's room for more jobs\n */\n hasCapacity(concurrency: number) {\n return this.#activeJobs.size < concurrency\n }\n\n /**\n * Add a job to the pool.\n *\n * @param job - The acquired job data\n * @param queue - The queue the job came from\n * @param promise - Promise that resolves when the job completes\n */\n add(job: AcquiredJob, queue: string, promise: Promise<void>) {\n this.#activeJobs.set(job.id, { promise, job, queue })\n }\n\n /**\n * Get the ids of all currently running jobs, grouped by the queue they\n * came from.\n *\n * Used by the worker heartbeat to renew the acquired timestamp of in-flight\n * jobs so long-running handlers are not mistaken for stalled jobs.\n *\n * @returns A map of queue name to the job ids running for that queue\n */\n activeJobIdsByQueue(): Map<string, string[]> {\n const byQueue = new Map<string, string[]>()\n\n for (const { job, queue } of this.#activeJobs.values()) {\n const ids = byQueue.get(queue)\n if (ids) {\n ids.push(job.id)\n } else {\n byQueue.set(queue, [job.id])\n }\n }\n\n return byQueue\n }\n\n /**\n * Wait for the next job to complete and return it.\n *\n * Uses `Promise.race()` internally, so the fastest job wins.\n * The completed job is removed from the pool.\n *\n * @returns The first job to complete (success or failure)\n */\n async waitForNextCompletion(): Promise<PoolEntry> {\n const completedJobId = await Promise.race(\n [...this.#activeJobs.entries()].map(async ([id, { promise }]) => {\n try {\n await promise\n } catch {\n // Errors are handled in Worker#execute\n }\n return id\n })\n )\n\n const completed = this.#activeJobs.get(completedJobId)!\n this.#activeJobs.delete(completedJobId)\n\n return completed\n }\n\n /**\n * Wait for all running jobs to complete.\n *\n * Used during graceful shutdown to ensure no jobs are abandoned.\n * Clears the pool after all jobs finish.\n */\n async drain(): Promise<void> {\n const promises = [...this.#activeJobs.values()].map(async ({ promise }) => {\n try {\n await promise\n } catch {\n // Errors are handled in Worker#execute\n }\n })\n\n await Promise.all(promises)\n this.#activeJobs.clear()\n }\n}\n","import { QueueManager } from './queue_manager.js'\nimport { JobDispatcher } from './job_dispatcher.js'\nimport type { ScheduleData, ScheduleListOptions, ScheduleStatus } from './types/main.js'\n\n/**\n * Represents a persisted job schedule.\n *\n * Use `Schedule.find()` or `Schedule.list()` to retrieve schedules,\n * then use instance methods to manage them.\n *\n * @example\n * ```typescript\n * const schedule = await Schedule.find('cleanup-daily')\n * if (schedule) {\n * await schedule.pause()\n * // Later...\n * await schedule.resume()\n * }\n *\n * // List all active schedules\n * const activeSchedules = await Schedule.list({ status: 'active' })\n * ```\n */\nexport class Schedule {\n readonly #data: ScheduleData\n\n constructor(data: ScheduleData) {\n this.#data = data\n }\n\n get id(): string {\n return this.#data.id\n }\n\n get name(): string {\n return this.#data.name\n }\n\n get payload(): unknown {\n return this.#data.payload\n }\n\n get cronExpression(): string | null {\n return this.#data.cronExpression\n }\n\n get everyMs(): number | null {\n return this.#data.everyMs\n }\n\n get timezone(): string {\n return this.#data.timezone\n }\n\n get from(): Date | null {\n return this.#data.from\n }\n\n get to(): Date | null {\n return this.#data.to\n }\n\n get limit(): number | null {\n return this.#data.limit\n }\n\n get runCount(): number {\n return this.#data.runCount\n }\n\n get nextRunAt(): Date | null {\n return this.#data.nextRunAt\n }\n\n get lastRunAt(): Date | null {\n return this.#data.lastRunAt\n }\n\n get status(): ScheduleStatus {\n return this.#data.status\n }\n\n get createdAt(): Date {\n return this.#data.createdAt\n }\n\n /**\n * Find a schedule by ID.\n *\n * @param id - The schedule ID\n * @returns The schedule instance, or null if not found\n */\n static async find(id: string): Promise<Schedule | null> {\n const adapter = QueueManager.use()\n const data = await adapter.getSchedule(id)\n\n if (!data) return null\n\n return new Schedule(data)\n }\n\n /**\n * List all schedules matching the given options.\n *\n * @param options - Optional filters for listing\n * @returns Array of schedule instances\n */\n static async list(options?: ScheduleListOptions): Promise<Schedule[]> {\n const adapter = QueueManager.use()\n const schedules = await adapter.listSchedules(options)\n\n return schedules.map((data) => new Schedule(data))\n }\n\n /**\n * Pause this schedule.\n * No jobs will be dispatched while paused.\n */\n async pause(): Promise<void> {\n const adapter = QueueManager.use()\n await adapter.updateSchedule(this.#data.id, { status: 'paused' })\n this.#data.status = 'paused'\n }\n\n /**\n * Resume this schedule.\n * Jobs will be dispatched according to the schedule.\n */\n async resume(): Promise<void> {\n const adapter = QueueManager.use()\n await adapter.updateSchedule(this.#data.id, { status: 'active' })\n this.#data.status = 'active'\n }\n\n /**\n * Delete this schedule permanently.\n */\n async delete(): Promise<void> {\n const adapter = QueueManager.use()\n await adapter.deleteSchedule(this.#data.id)\n }\n\n /**\n * Trigger immediate execution of this schedule's job.\n * Also updates runCount and lastRunAt.\n *\n * If the schedule has reached its limit, the job will not be dispatched.\n *\n * @param payload - Optional custom payload for the job\n */\n async trigger(payload?: any): Promise<void> {\n // Check if limit is reached\n if (this.#data.limit !== null && this.#data.runCount >= this.#data.limit) {\n return\n }\n\n const adapter = QueueManager.use()\n\n // Dispatch the job\n const dispatcher = new JobDispatcher(this.#data.name, payload ?? this.#data.payload)\n await dispatcher.run()\n\n // Update run metadata\n const now = new Date()\n const newRunCount = this.#data.runCount + 1\n\n await adapter.updateSchedule(this.#data.id, {\n runCount: newRunCount,\n lastRunAt: now,\n })\n\n this.#data.runCount = newRunCount\n this.#data.lastRunAt = now\n }\n}\n","import type { Knex } from 'knex'\n\nexport class QueueSchemaService {\n #connection: Knex\n\n constructor(connection: Knex) {\n this.#connection = connection\n }\n\n /**\n * Creates the jobs table with the default schema.\n * The optional callback allows adding custom columns.\n */\n async createJobsTable(\n tableName: string = 'queue_jobs',\n extend?: (table: Knex.CreateTableBuilder) => void\n ): Promise<void> {\n await this.#connection.schema.createTable(tableName, (table) => {\n table.string('id', 255).notNullable()\n table.string('queue', 255).notNullable()\n table.enu('status', ['pending', 'active', 'delayed', 'completed', 'failed']).notNullable()\n table.text('data').notNullable()\n table.bigint('score').unsigned().nullable()\n table.string('worker_id', 255).nullable()\n table.bigint('acquired_at').unsigned().nullable()\n table.bigint('execute_at').unsigned().nullable()\n table.bigint('finished_at').unsigned().nullable()\n table.text('error').nullable()\n table.string('dedup_id', 510).nullable()\n table.bigint('dedup_at').unsigned().nullable()\n table.bigint('dedup_ttl').unsigned().nullable()\n table.primary(['id', 'queue'])\n table.index(['queue', 'status', 'score'])\n table.index(['queue', 'status', 'execute_at'])\n table.index(['queue', 'status', 'finished_at'])\n table.index(['queue', 'dedup_id'])\n\n extend?.(table)\n })\n\n await this.#createDedupActiveUniqueIndex(tableName)\n }\n\n /**\n * Idempotent migration: adds dedup columns (dedup_id, dedup_at, dedup_ttl)\n * and a (queue, dedup_id) index to an existing jobs table.\n *\n * Safe to run multiple times. Uses hasColumn checks so it won't fail on re-runs.\n * For large Postgres tables, consider pausing workers during the run.\n */\n async addDedupColumns(tableName: string = 'queue_jobs'): Promise<void> {\n const hasDedupId = await this.#connection.schema.hasColumn(tableName, 'dedup_id')\n const hasDedupAt = await this.#connection.schema.hasColumn(tableName, 'dedup_at')\n const hasDedupTtl = await this.#connection.schema.hasColumn(tableName, 'dedup_ttl')\n\n if (!hasDedupId || !hasDedupAt || !hasDedupTtl) {\n await this.#connection.schema.alterTable(tableName, (table) => {\n if (!hasDedupId) table.string('dedup_id', 510).nullable()\n if (!hasDedupAt) table.bigint('dedup_at').unsigned().nullable()\n if (!hasDedupTtl) table.bigint('dedup_ttl').unsigned().nullable()\n })\n }\n\n if (!hasDedupId) {\n await this.#connection.schema.alterTable(tableName, (table) => {\n table.index(['queue', 'dedup_id'])\n })\n }\n\n await this.#createDedupActiveUniqueIndex(tableName)\n }\n\n /**\n * Partial unique index on (queue, dedup_id) for active dedup slots.\n * Prevents two concurrent inserts with the same dedup_id from both succeeding.\n * Only PG and SQLite support partial unique indexes; MySQL is skipped.\n */\n async #createDedupActiveUniqueIndex(tableName: string): Promise<void> {\n const client = this.#connection.client.config.client\n if (client !== 'pg' && client !== 'better-sqlite3' && client !== 'sqlite3') return\n\n const indexName = `${tableName}_dedup_active_uidx`\n await this.#connection.raw(\n `CREATE UNIQUE INDEX IF NOT EXISTS ?? ON ?? (\"queue\", \"dedup_id\") ` +\n `WHERE \"dedup_id\" IS NOT NULL AND \"status\" IN ('pending', 'delayed')`,\n [indexName, tableName]\n )\n }\n\n /**\n * Creates the schedules table with the default schema.\n * The optional callback allows adding custom columns.\n */\n async createSchedulesTable(\n tableName: string = 'queue_schedules',\n extend?: (table: Knex.CreateTableBuilder) => void\n ): Promise<void> {\n await this.#connection.schema.createTable(tableName, (table) => {\n table.string('id', 255).primary()\n table.string('status', 50).notNullable().defaultTo('active')\n table.string('name', 255).notNullable()\n table.text('payload').notNullable()\n table.string('cron_expression', 255).nullable()\n table.bigint('every_ms').unsigned().nullable()\n table.string('timezone', 100).notNullable().defaultTo('UTC')\n table.timestamp('from_date').nullable()\n table.timestamp('to_date').nullable()\n table.integer('run_limit').unsigned().nullable()\n table.integer('run_count').unsigned().notNullable().defaultTo(0)\n table.timestamp('next_run_at').nullable()\n table.timestamp('last_run_at').nullable()\n table.timestamp('created_at').notNullable().defaultTo(this.#connection.fn.now())\n table.index(['status', 'next_run_at'])\n\n extend?.(table)\n })\n }\n\n /**\n * Drops the jobs table if it exists.\n */\n async dropJobsTable(tableName: string = 'queue_jobs'): Promise<void> {\n await this.#connection.schema.dropTableIfExists(tableName)\n }\n\n /**\n * Drops the schedules table if it exists.\n */\n async dropSchedulesTable(tableName: string = 'queue_schedules'): Promise<void> {\n await this.#connection.schema.dropTableIfExists(tableName)\n }\n}\n","import type { BackoffConfig, Duration } from '../types/main.js'\nimport * as errors from '../exceptions.js'\nimport { parse } from '../utils.js'\nimport { RuntimeException } from '@poppinss/utils/exception'\nimport { assertUnreachable } from '@poppinss/utils/assert'\n\n/**\n * Calculates retry delays using configurable strategies.\n *\n * Supports three built-in strategies:\n * - `exponential`: Delay doubles each attempt (1s, 2s, 4s, 8s, ...)\n * - `linear`: Delay increases linearly (5s, 10s, 15s, 20s, ...)\n * - `fixed`: Same delay every time (10s, 10s, 10s, ...)\n *\n * All strategies support:\n * - `maxDelay`: Cap the maximum delay\n * - `jitter`: Add randomness to prevent thundering herd\n *\n * @example\n * ```typescript\n * const strategy = new BackoffStrategy({\n * strategy: 'exponential',\n * baseDelay: '1s',\n * maxDelay: '5m',\n * multiplier: 2,\n * jitter: true,\n * })\n *\n * strategy.calculateDelay(1) // ~1000ms\n * strategy.calculateDelay(2) // ~2000ms\n * strategy.calculateDelay(3) // ~4000ms\n * ```\n */\nexport class BackoffStrategy {\n readonly #config: BackoffConfig\n\n /**\n * Create a new backoff strategy.\n *\n * @param config - Backoff configuration\n * @throws {E_INVALID_BASE_DELAY} If baseDelay is not positive\n * @throws {E_INVALID_MAX_DELAY} If maxDelay is invalid\n * @throws {E_INVALID_MULTIPLIER} If multiplier is invalid\n */\n constructor(config: BackoffConfig) {\n this.#config = config\n this.#validateConfig()\n }\n\n /**\n * Calculate the delay for a given attempt number.\n *\n * @param attempt - The attempt number (1-based)\n * @returns Delay in milliseconds\n * @throws {RuntimeException} If attempt is less than 1\n *\n * @example\n * ```typescript\n * // Exponential: 1s, 2s, 4s, 8s, 16s, ...\n * strategy.calculateDelay(1) // 1000\n * strategy.calculateDelay(2) // 2000\n * strategy.calculateDelay(3) // 4000\n * ```\n */\n calculateDelay(attempt: number): number {\n if (attempt < 1) {\n throw new RuntimeException('Attempt number must be >= 1')\n }\n\n const baseDelayMs = parse(this.#config.baseDelay)\n const maxDelayMs = this.#config.maxDelay ? parse(this.#config.maxDelay) : Infinity\n const multiplier = this.#config.multiplier ?? 2\n\n let delay: number\n\n switch (this.#config.strategy) {\n case 'exponential':\n delay = baseDelayMs * Math.pow(multiplier, attempt - 1)\n break\n case 'linear':\n delay = baseDelayMs * attempt\n break\n case 'fixed':\n delay = baseDelayMs\n break\n default:\n assertUnreachable(this.#config.strategy)\n }\n\n // Apply max delay limit\n delay = Math.min(delay, maxDelayMs)\n\n if (this.#config.jitter) {\n delay = this.#applyJitter(delay)\n }\n\n return Math.floor(delay)\n }\n\n /**\n * Get the Date when the next retry should occur.\n *\n * @param attempt - The attempt number (1-based)\n * @returns Date for the next retry\n *\n * @example\n * ```typescript\n * const nextRetry = strategy.getNextRetryAt(3)\n * console.log(`Retry at: ${nextRetry.toISOString()}`)\n * ```\n */\n getNextRetryAt(attempt: number): Date {\n const delay = this.calculateDelay(attempt)\n return new Date(Date.now() + delay)\n }\n\n /**\n * Get a frozen copy of the configuration.\n *\n * @returns Readonly configuration object\n */\n getConfig(): Readonly<BackoffConfig> {\n return Object.freeze({ ...this.#config })\n }\n\n #validateConfig() {\n const baseDelayMs = parse(this.#config.baseDelay)\n\n if (baseDelayMs <= 0) {\n throw new errors.E_INVALID_BASE_DELAY([\n 'Base delay must be a positive integer greater than zero',\n ])\n }\n\n if (this.#config.maxDelay) {\n const maxDelayMs = parse(this.#config.maxDelay)\n\n if (maxDelayMs <= 0) {\n throw new errors.E_INVALID_MAX_DELAY([\n 'Max delay must be a positive integer greater than zero',\n ])\n }\n\n if (maxDelayMs <= baseDelayMs) {\n throw new errors.E_INVALID_MAX_DELAY(['Max delay should be greater than base delay'])\n }\n }\n\n if (this.#config.multiplier !== undefined) {\n if (this.#config.multiplier <= 0) {\n throw new errors.E_INVALID_MULTIPLIER([\n 'Multiplier must be a positive number greater than zero',\n ])\n }\n\n if (this.#config.strategy === 'exponential' && this.#config.multiplier < 1) {\n throw new errors.E_INVALID_MULTIPLIER(['Exponential strategy multiplier should be >= 1'])\n }\n }\n }\n\n #applyJitter(delay: number): number {\n const jitterRange = delay * 0.25\n const jitter = (Math.random() - 0.5) * 2 * jitterRange\n\n return Math.max(0, delay + jitter)\n }\n}\n\n/**\n * Create an exponential backoff strategy factory.\n *\n * Delay doubles with each attempt: 1s → 2s → 4s → 8s → ...\n *\n * Default config:\n * - baseDelay: 1s\n * - maxDelay: 5m\n * - multiplier: 2\n * - jitter: true\n *\n * @param config - Optional overrides for default config\n * @returns Factory function for creating BackoffStrategy instances\n *\n * @example\n * ```typescript\n * const config = {\n * retry: {\n * maxRetries: 5,\n * backoff: exponentialBackoff({ baseDelay: '500ms', maxDelay: '1m' }),\n * },\n * }\n * ```\n */\nexport function exponentialBackoff(config?: Partial<Omit<BackoffConfig, 'strategy'>>) {\n return () =>\n new BackoffStrategy({\n strategy: 'exponential',\n baseDelay: '1s',\n maxDelay: '5m',\n multiplier: 2,\n jitter: true,\n ...config,\n })\n}\n\n/**\n * Create a linear backoff strategy factory.\n *\n * Delay increases linearly: 5s → 10s → 15s → 20s → ...\n *\n * Default config:\n * - baseDelay: 5s\n * - maxDelay: 2m\n *\n * @param config - Optional overrides for default config\n * @returns Factory function for creating BackoffStrategy instances\n *\n * @example\n * ```typescript\n * const config = {\n * retry: {\n * maxRetries: 3,\n * backoff: linearBackoff({ baseDelay: '10s' }),\n * },\n * }\n * ```\n */\nexport function linearBackoff(config?: Partial<Omit<BackoffConfig, 'strategy'>>) {\n return () =>\n new BackoffStrategy({\n strategy: 'linear',\n baseDelay: '5s',\n maxDelay: '2m',\n ...config,\n })\n}\n\n/**\n * Create a fixed delay backoff strategy factory.\n *\n * Same delay every time: 10s → 10s → 10s → ...\n *\n * @param delay - The fixed delay (default: '10s')\n * @returns Factory function for creating BackoffStrategy instances\n *\n * @example\n * ```typescript\n * const config = {\n * retry: {\n * maxRetries: 3,\n * backoff: fixedBackoff('30s'),\n * },\n * }\n * ```\n */\nexport function fixedBackoff(delay: Duration = '10s') {\n return () =>\n new BackoffStrategy({\n strategy: 'fixed',\n baseDelay: delay,\n })\n}\n\n/**\n * Create a custom backoff strategy factory.\n *\n * Use this when you need full control over the configuration.\n *\n * @param config - Complete backoff configuration\n * @returns Factory function for creating BackoffStrategy instances\n *\n * @example\n * ```typescript\n * const config = {\n * retry: {\n * maxRetries: 5,\n * backoff: customBackoff({\n * strategy: 'exponential',\n * baseDelay: '100ms',\n * maxDelay: '30s',\n * multiplier: 3,\n * jitter: false,\n * }),\n * },\n * }\n * ```\n */\nexport function customBackoff(config: BackoffConfig) {\n return () => new BackoffStrategy(config)\n}\n"],"mappings":";;;;;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