@igniter-js/jobs 0.1.13 → 0.1.14

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.
Files changed (40) hide show
  1. package/AGENTS.md +117 -243
  2. package/README.md +311 -153
  3. package/dist/{adapter-CXZxomI9.d.mts → adapter-Cax_40HW.d.mts} +27 -6
  4. package/dist/{adapter-CXZxomI9.d.ts → adapter-Cax_40HW.d.ts} +27 -6
  5. package/dist/adapters/bun.d.mts +93 -0
  6. package/dist/adapters/bun.d.ts +93 -0
  7. package/dist/adapters/bun.js +914 -0
  8. package/dist/adapters/bun.js.map +1 -0
  9. package/dist/adapters/bun.mjs +912 -0
  10. package/dist/adapters/bun.mjs.map +1 -0
  11. package/dist/adapters/{memory.adapter.d.ts → mock.d.mts} +1 -3
  12. package/dist/adapters/{memory.adapter.d.mts → mock.d.ts} +1 -3
  13. package/dist/adapters/{memory.adapter.js → mock.js} +58 -25
  14. package/dist/adapters/mock.js.map +1 -0
  15. package/dist/adapters/{memory.adapter.mjs → mock.mjs} +58 -25
  16. package/dist/adapters/mock.mjs.map +1 -0
  17. package/dist/adapters/{bullmq.adapter.d.ts → node.d.mts} +1 -3
  18. package/dist/adapters/{bullmq.adapter.d.mts → node.d.ts} +1 -3
  19. package/dist/adapters/{bullmq.adapter.js → node.js} +117 -40
  20. package/dist/adapters/node.js.map +1 -0
  21. package/dist/adapters/{bullmq.adapter.mjs → node.mjs} +117 -40
  22. package/dist/adapters/node.mjs.map +1 -0
  23. package/dist/index.d.mts +17 -21
  24. package/dist/index.d.ts +17 -21
  25. package/dist/index.js +20 -1854
  26. package/dist/index.js.map +1 -1
  27. package/dist/index.mjs +21 -1852
  28. package/dist/index.mjs.map +1 -1
  29. package/package.json +28 -40
  30. package/CHANGELOG.md +0 -13
  31. package/dist/adapters/bullmq.adapter.js.map +0 -1
  32. package/dist/adapters/bullmq.adapter.mjs.map +0 -1
  33. package/dist/adapters/index.d.mts +0 -143
  34. package/dist/adapters/index.d.ts +0 -143
  35. package/dist/adapters/index.js +0 -1891
  36. package/dist/adapters/index.js.map +0 -1
  37. package/dist/adapters/index.mjs +0 -1887
  38. package/dist/adapters/index.mjs.map +0 -1
  39. package/dist/adapters/memory.adapter.js.map +0 -1
  40. package/dist/adapters/memory.adapter.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,12 +1,6 @@
1
1
  import { IgniterError } from '@igniter-js/common';
2
- import { createBullMQAdapter } from '@igniter-js/adapter-bullmq';
3
2
 
4
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
5
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6
- }) : x)(function(x) {
7
- if (typeof require !== "undefined") return require.apply(this, arguments);
8
- throw Error('Dynamic require of "' + x + '" is not supported');
9
- });
3
+ // src/errors/jobs.error.ts
10
4
  var IGNITER_JOBS_ERROR_CODES = {
11
5
  JOBS_ADAPTER_REQUIRED: "JOBS_ADAPTER_REQUIRED",
12
6
  JOBS_SERVICE_REQUIRED: "JOBS_SERVICE_REQUIRED",
@@ -412,7 +406,8 @@ var IgniterJobsManager = class _IgniterJobsManager {
412
406
  return {
413
407
  create: () => new IgniterWorkerBuilder({
414
408
  adapter: this.adapter,
415
- allowedQueues: Object.keys(this.config.queues)
409
+ allowedQueues: Object.keys(this.config.queues),
410
+ state: this.config.workerDefaults
416
411
  })
417
412
  };
418
413
  }
@@ -463,7 +458,11 @@ var IgniterJobsManager = class _IgniterJobsManager {
463
458
  this.adapter.registerJob(
464
459
  queueName,
465
460
  jobName,
466
- this.wrapJobDefinition(queueName, jobName, def)
461
+ this.wrapJobDefinition(
462
+ queueName,
463
+ jobName,
464
+ this.getEffectiveJobDefinition(queueName, jobName, def)
465
+ )
467
466
  );
468
467
  }
469
468
  for (const [cronName, cron] of Object.entries(
@@ -555,8 +554,6 @@ var IgniterJobsManager = class _IgniterJobsManager {
555
554
  remove: () => self.adapter.removeManyJobs(ids, queueName)
556
555
  };
557
556
  },
558
- pause: () => self.adapter.pauseJobType(queueName, jobName),
559
- resume: () => self.adapter.resumeJobType(queueName, jobName),
560
557
  async subscribe(handler) {
561
558
  const channel = self.buildEventsChannel();
562
559
  return self.adapter.subscribeEvent(channel, async (event) => {
@@ -646,7 +643,7 @@ var IgniterJobsManager = class _IgniterJobsManager {
646
643
  "ctx.job.id": jobId,
647
644
  "ctx.job.name": jobName,
648
645
  "ctx.job.queue": queueName,
649
- "ctx.job.scheduledAt": params.runAt?.toISOString?.() ?? null,
646
+ "ctx.job.scheduledAt": params.at?.toISOString() ?? null,
650
647
  "ctx.job.cron": params.cron ?? null
651
648
  });
652
649
  return jobId;
@@ -910,7 +907,17 @@ var IgniterJobsManager = class _IgniterJobsManager {
910
907
  */
911
908
  getJobDefinition(queueName, jobName) {
912
909
  const queue = this.config.queues[queueName];
913
- return queue?.jobs?.[jobName];
910
+ const definition = queue?.jobs?.[jobName];
911
+ return definition ? this.getEffectiveJobDefinition(queueName, jobName, definition) : void 0;
912
+ }
913
+ getEffectiveJobDefinition(queueName, jobName, definition) {
914
+ const queue = this.config.queues[queueName];
915
+ return {
916
+ ...this.config.queueDefaults,
917
+ ...queue?.defaultJobOptions,
918
+ ...definition,
919
+ name: jobName
920
+ };
914
921
  }
915
922
  /**
916
923
  * Resolves the effective scope for a job operation.
@@ -1338,1845 +1345,7 @@ var IgniterJobsBuilder = class _IgniterJobsBuilder {
1338
1345
  var IgniterJobs = {
1339
1346
  create: IgniterJobsBuilder.create
1340
1347
  };
1341
- function toDateArray(values) {
1342
- if (!values) return void 0;
1343
- return values.map((v) => v instanceof Date ? v : new Date(v));
1344
- }
1345
- var IgniterJobsBullMQAdapter = class _IgniterJobsBullMQAdapter {
1346
- constructor(options) {
1347
- this.subscribers = /* @__PURE__ */ new Map();
1348
- this.coreAdapter = null;
1349
- this.coreExecutor = null;
1350
- this.executorDirty = true;
1351
- this.jobsByQueue = /* @__PURE__ */ new Map();
1352
- this.cronsByQueue = /* @__PURE__ */ new Map();
1353
- this.redis = options.redis;
1354
- this.publisher = this.redis;
1355
- this.subscriber = this.redis.duplicate();
1356
- this.client = { redis: this.redis };
1357
- this.subscriber.on("message", (channel, message) => {
1358
- const set = this.subscribers.get(channel);
1359
- if (!set || set.size === 0) return;
1360
- let payload = message;
1361
- try {
1362
- payload = JSON.parse(message);
1363
- } catch {
1364
- }
1365
- for (const handler of set) handler(payload);
1366
- });
1367
- this.queues = {
1368
- list: async () => this.listQueues(),
1369
- get: async (name) => this.getQueueInfo(name),
1370
- getJobCounts: async (name) => this.getQueueJobCounts(name),
1371
- getJobs: async (name, filter) => {
1372
- const full = this.toCoreQueueName(name);
1373
- return this.core().queues.getJobs(full, filter);
1374
- },
1375
- pause: async (name) => this.pauseQueue(name),
1376
- resume: async (name) => this.resumeQueue(name),
1377
- isPaused: async (name) => {
1378
- const full = this.toCoreQueueName(name);
1379
- return this.core().queues.isPaused(full);
1380
- },
1381
- drain: async (name) => this.drainQueue(name),
1382
- clean: async (name, options2) => this.cleanQueue(name, options2),
1383
- obliterate: async (name, options2) => this.obliterateQueue(name, options2)
1384
- };
1385
- }
1386
- static create(options) {
1387
- return new _IgniterJobsBullMQAdapter(options);
1388
- }
1389
- registerJob(queueName, jobName, definition) {
1390
- const map = this.jobsByQueue.get(queueName) ?? /* @__PURE__ */ new Map();
1391
- if (map.has(jobName)) {
1392
- throw new IgniterJobsError({
1393
- code: "JOBS_DUPLICATE_JOB",
1394
- message: `Job "${jobName}" is already registered in queue "${queueName}".`
1395
- });
1396
- }
1397
- map.set(jobName, definition);
1398
- this.jobsByQueue.set(queueName, map);
1399
- this.executorDirty = true;
1400
- }
1401
- registerCron(queueName, cronName, definition) {
1402
- const map = this.cronsByQueue.get(queueName) ?? /* @__PURE__ */ new Map();
1403
- if (map.has(cronName)) {
1404
- throw new IgniterJobsError({
1405
- code: "JOBS_INVALID_CRON",
1406
- message: `Cron "${cronName}" is already registered in queue "${queueName}".`
1407
- });
1408
- }
1409
- map.set(cronName, definition);
1410
- this.cronsByQueue.set(queueName, map);
1411
- this.executorDirty = true;
1412
- }
1413
- async dispatch(params) {
1414
- const executor = await this.executor();
1415
- const namespace = executor[params.queue];
1416
- if (!namespace) {
1417
- throw new IgniterJobsError({
1418
- code: "JOBS_QUEUE_NOT_FOUND",
1419
- message: `Queue "${params.queue}" is not registered in the adapter.`
1420
- });
1421
- }
1422
- return namespace.enqueue({
1423
- task: params.jobName,
1424
- input: params.input,
1425
- jobId: params.jobId,
1426
- delay: params.delay,
1427
- priority: params.priority,
1428
- attempts: params.attempts,
1429
- metadata: params.metadata,
1430
- removeOnComplete: params.removeOnComplete,
1431
- removeOnFail: params.removeOnFail,
1432
- limiter: params.limiter
1433
- });
1434
- }
1435
- async schedule(params) {
1436
- const executor = await this.executor();
1437
- const namespace = executor[params.queue];
1438
- if (!namespace) {
1439
- throw new IgniterJobsError({
1440
- code: "JOBS_QUEUE_NOT_FOUND",
1441
- message: `Queue "${params.queue}" is not registered in the adapter.`
1442
- });
1443
- }
1444
- const schedule = {
1445
- jobId: params.jobId,
1446
- delay: params.delay,
1447
- priority: params.priority,
1448
- attempts: params.attempts,
1449
- metadata: params.metadata,
1450
- removeOnComplete: params.removeOnComplete,
1451
- removeOnFail: params.removeOnFail,
1452
- limiter: params.limiter,
1453
- at: params.at,
1454
- repeat: params.cron || params.every || params.maxExecutions || params.skipWeekends || params.onlyBusinessHours || params.businessHours || params.onlyWeekdays || params.skipDates ? {
1455
- cron: params.cron,
1456
- every: params.every,
1457
- times: params.maxExecutions,
1458
- skipWeekends: params.skipWeekends,
1459
- onlyBusinessHours: params.onlyBusinessHours,
1460
- businessHours: params.businessHours,
1461
- onlyWeekdays: params.onlyWeekdays,
1462
- skipDates: toDateArray(params.skipDates)
1463
- } : void 0
1464
- };
1465
- return namespace.schedule({
1466
- task: params.jobName,
1467
- input: params.input,
1468
- ...schedule
1469
- });
1470
- }
1471
- async getJob(jobId, queue) {
1472
- const result = await this.core().job.get(jobId, queue ? this.toCoreQueueName(queue) : void 0);
1473
- return result ? this.mapJob(result, queue) : null;
1474
- }
1475
- async getJobState(jobId, queue) {
1476
- const state = await this.core().job.getState(jobId, queue ? this.toCoreQueueName(queue) : void 0);
1477
- return state;
1478
- }
1479
- async getJobLogs(jobId, queue) {
1480
- const logs = await this.core().job.getLogs(jobId, queue ? this.toCoreQueueName(queue) : void 0);
1481
- return logs;
1482
- }
1483
- async getJobProgress(jobId, queue) {
1484
- return this.core().job.getProgress(jobId, queue ? this.toCoreQueueName(queue) : void 0);
1485
- }
1486
- async retryJob(jobId, queue) {
1487
- await this.core().job.retry(jobId, queue ? this.toCoreQueueName(queue) : void 0);
1488
- }
1489
- async removeJob(jobId, queue) {
1490
- await this.core().job.remove(jobId, queue ? this.toCoreQueueName(queue) : void 0);
1491
- }
1492
- async promoteJob(jobId, queue) {
1493
- await this.core().job.promote(jobId, queue ? this.toCoreQueueName(queue) : void 0);
1494
- }
1495
- async moveJobToFailed(jobId, reason, queue) {
1496
- await this.core().job.moveToFailed(jobId, reason, queue ? this.toCoreQueueName(queue) : void 0);
1497
- }
1498
- async retryManyJobs(jobIds, queue) {
1499
- await this.core().job.retryMany(jobIds, queue ? this.toCoreQueueName(queue) : void 0);
1500
- }
1501
- async removeManyJobs(jobIds, queue) {
1502
- await this.core().job.removeMany(jobIds, queue ? this.toCoreQueueName(queue) : void 0);
1503
- }
1504
- async getQueueInfo(queue) {
1505
- const info = await this.core().queues.get(this.toCoreQueueName(queue));
1506
- if (!info) return null;
1507
- return this.mapQueueInfo(info);
1508
- }
1509
- async getQueueJobCounts(queue) {
1510
- const counts = await this.core().queues.getJobCounts(this.toCoreQueueName(queue));
1511
- return counts;
1512
- }
1513
- async listQueues() {
1514
- const list = await this.core().queues.list();
1515
- return list.map((q) => this.mapQueueInfo(q));
1516
- }
1517
- async pauseQueue(queue) {
1518
- await this.core().queues.pause(this.toCoreQueueName(queue));
1519
- }
1520
- async resumeQueue(queue) {
1521
- await this.core().queues.resume(this.toCoreQueueName(queue));
1522
- }
1523
- async drainQueue(queue) {
1524
- return this.core().queues.drain(this.toCoreQueueName(queue));
1525
- }
1526
- async cleanQueue(queue, options) {
1527
- return this.core().queues.clean(this.toCoreQueueName(queue), options);
1528
- }
1529
- async obliterateQueue(queue, options) {
1530
- await this.core().queues.obliterate(this.toCoreQueueName(queue), options);
1531
- }
1532
- async retryAllInQueue(queue) {
1533
- const jobs = await this.core().queues.getJobs(this.toCoreQueueName(queue), { status: ["failed"], limit: 1e3 });
1534
- await Promise.all(jobs.map((j) => this.core().job.retry(j.id, this.toCoreQueueName(queue))));
1535
- return jobs.length;
1536
- }
1537
- async pauseJobType(queue, jobName) {
1538
- throw new IgniterJobsError({
1539
- code: "JOBS_QUEUE_OPERATION_FAILED",
1540
- message: "BullMQ backend does not support pausing a single job type; pause the queue or adjust worker filters."
1541
- });
1542
- }
1543
- async resumeJobType(queue, jobName) {
1544
- throw new IgniterJobsError({
1545
- code: "JOBS_QUEUE_OPERATION_FAILED",
1546
- message: "BullMQ backend does not support resuming a single job type; resume the queue or adjust worker filters."
1547
- });
1548
- }
1549
- async searchJobs(filter) {
1550
- const queue = filter?.queue;
1551
- const status = filter?.status;
1552
- const limit = filter?.limit ?? 100;
1553
- const offset = filter?.offset ?? 0;
1554
- if (queue) {
1555
- const jobs = await this.core().queues.getJobs(this.toCoreQueueName(queue), { status, limit, offset });
1556
- return jobs.map((j) => this.mapJob(j, queue));
1557
- }
1558
- const queues = await this.listQueues();
1559
- const results = [];
1560
- for (const q of queues) {
1561
- const jobs = await this.core().queues.getJobs(this.toCoreQueueName(q.name), { status, limit, offset });
1562
- results.push(...jobs.map((j) => this.mapJob(j, q.name)));
1563
- if (results.length >= limit) break;
1564
- }
1565
- return results.slice(0, limit);
1566
- }
1567
- async searchQueues(filter) {
1568
- const all = await this.listQueues();
1569
- const name = filter?.name;
1570
- const isPaused = filter?.isPaused;
1571
- return all.filter((q) => name ? q.name.includes(name) : true).filter((q) => typeof isPaused === "boolean" ? q.isPaused === isPaused : true);
1572
- }
1573
- async searchWorkers(filter) {
1574
- const queue = filter?.queue;
1575
- const isRunning = filter?.isRunning;
1576
- const all = Array.from(this.core().getWorkers().values());
1577
- return all.filter((w) => {
1578
- if (!queue) return true;
1579
- const coreQueue = this.toCoreQueueName(queue);
1580
- const queues = w.config?.queues ?? [w.queueName];
1581
- return Array.isArray(queues) ? queues.includes(coreQueue) : false;
1582
- }).filter((w) => typeof isRunning === "boolean" ? isRunning ? w.isRunning() : !w.isRunning() : true).map((w) => this.mapWorker(w));
1583
- }
1584
- async createWorker(config) {
1585
- await this.executor();
1586
- const queuesSource = config.queues?.length ? config.queues : Array.from(/* @__PURE__ */ new Set([...this.jobsByQueue.keys(), ...this.cronsByQueue.keys()]));
1587
- const queues = queuesSource.map((q) => this.toCoreQueueName(q));
1588
- const coreConfig = {
1589
- queues,
1590
- concurrency: config.concurrency ?? 1,
1591
- limiter: config.limiter,
1592
- onActive: config.handlers?.onActive,
1593
- onSuccess: config.handlers?.onSuccess,
1594
- onFailure: config.handlers?.onFailure,
1595
- onIdle: config.handlers?.onIdle
1596
- };
1597
- const handle = await this.core().worker(coreConfig);
1598
- return this.mapWorker(handle);
1599
- }
1600
- getWorkers() {
1601
- const out = /* @__PURE__ */ new Map();
1602
- for (const [id, handle] of this.core().getWorkers()) out.set(id, this.mapWorker(handle));
1603
- return out;
1604
- }
1605
- async publishEvent(channel, payload) {
1606
- await this.publisher.publish(channel, JSON.stringify(payload));
1607
- }
1608
- async subscribeEvent(channel, handler) {
1609
- const set = this.subscribers.get(channel) ?? /* @__PURE__ */ new Set();
1610
- const wrapped = (payload) => void handler(payload);
1611
- set.add(wrapped);
1612
- this.subscribers.set(channel, set);
1613
- if (set.size === 1) {
1614
- await this.subscriber.subscribe(channel);
1615
- }
1616
- return async () => {
1617
- const current = this.subscribers.get(channel);
1618
- if (!current) return;
1619
- current.delete(wrapped);
1620
- if (current.size === 0) {
1621
- this.subscribers.delete(channel);
1622
- await this.subscriber.unsubscribe(channel);
1623
- }
1624
- };
1625
- }
1626
- async shutdown() {
1627
- await this.subscriber.quit();
1628
- }
1629
- core() {
1630
- if (!this.coreAdapter) {
1631
- this.coreAdapter = createBullMQAdapter({
1632
- store: { client: this.redis }
1633
- });
1634
- }
1635
- return this.coreAdapter;
1636
- }
1637
- async executor() {
1638
- if (!this.executorDirty && this.coreExecutor) return this.coreExecutor;
1639
- const routers = {};
1640
- const flattened = {};
1641
- const allQueues = /* @__PURE__ */ new Set([...this.jobsByQueue.keys(), ...this.cronsByQueue.keys()]);
1642
- for (const queueName of allQueues) {
1643
- const coreJobs = {};
1644
- const jobs = this.jobsByQueue.get(queueName);
1645
- if (jobs) {
1646
- for (const [jobName, def] of jobs.entries()) {
1647
- const queue = def.queue ? `${queueName}.${def.queue}` : queueName;
1648
- const fullQueue = IgniterJobsPrefix.buildQueueName(queue);
1649
- coreJobs[jobName] = this.toCoreJobDefinition(queueName, jobName, def, fullQueue);
1650
- }
1651
- }
1652
- const crons = this.cronsByQueue.get(queueName);
1653
- if (crons) {
1654
- for (const [cronName, def] of crons.entries()) {
1655
- const fullQueue = IgniterJobsPrefix.buildQueueName(queueName);
1656
- coreJobs[cronName] = this.toCoreCronJobDefinition(queueName, cronName, def, fullQueue);
1657
- }
1658
- }
1659
- if (Object.keys(coreJobs).length === 0) continue;
1660
- routers[queueName] = this.core().router({
1661
- jobs: coreJobs,
1662
- namespace: queueName
1663
- });
1664
- for (const [jobName, def] of Object.entries(coreJobs)) {
1665
- flattened[`${queueName}.${jobName}`] = def;
1666
- }
1667
- }
1668
- await this.core().bulkRegister(flattened);
1669
- this.coreExecutor = this.core().merge(routers);
1670
- this.executorDirty = false;
1671
- return this.coreExecutor;
1672
- }
1673
- toCoreQueueName(queueName) {
1674
- return IgniterJobsPrefix.buildQueueName(queueName);
1675
- }
1676
- mapQueueInfo(info) {
1677
- return {
1678
- name: this.fromCoreQueueName(info.name),
1679
- isPaused: info.isPaused,
1680
- jobCounts: info.jobCounts
1681
- };
1682
- }
1683
- fromCoreQueueName(full) {
1684
- const prefix = `${IgniterJobsPrefix.BASE_PREFIX}:`;
1685
- return full.startsWith(prefix) ? full.slice(prefix.length) : full;
1686
- }
1687
- mapJob(job, queue) {
1688
- const q = queue ?? this.fromCoreQueueName(job.metadata?.queue ?? job.queueName ?? "");
1689
- const scope = job.metadata?.__igniter_jobs_scope;
1690
- return {
1691
- id: job.id,
1692
- name: job.name,
1693
- queue: q,
1694
- status: job.status,
1695
- input: job.payload,
1696
- result: job.result,
1697
- error: job.error,
1698
- progress: 0,
1699
- attemptsMade: job.attemptsMade ?? 0,
1700
- priority: job.priority ?? 0,
1701
- createdAt: job.createdAt,
1702
- startedAt: job.processedAt,
1703
- completedAt: job.completedAt,
1704
- metadata: job.metadata,
1705
- scope
1706
- };
1707
- }
1708
- mapWorker(handle) {
1709
- const queues = handle.config?.queues ?? [handle.queueName];
1710
- return {
1711
- id: handle.id,
1712
- queues: queues.map((q) => this.fromCoreQueueName(q)),
1713
- pause: () => handle.pause(),
1714
- resume: () => handle.resume(),
1715
- close: () => handle.close(),
1716
- isRunning: () => handle.isRunning(),
1717
- isPaused: () => handle.isPaused(),
1718
- isClosed: () => handle.isClosed(),
1719
- getMetrics: async () => handle.getMetrics()
1720
- };
1721
- }
1722
- toCoreJobDefinition(queueName, jobName, def, fullQueueName) {
1723
- const handler = async (ctx) => {
1724
- return def.handler({
1725
- input: ctx.input,
1726
- context: ctx.context,
1727
- job: {
1728
- id: ctx.job.id,
1729
- name: jobName,
1730
- queue: queueName,
1731
- attemptsMade: ctx.job.attemptsMade,
1732
- createdAt: ctx.job.createdAt,
1733
- metadata: ctx.job.metadata
1734
- },
1735
- scope: ctx.job.metadata?.__igniter_jobs_scope
1736
- });
1737
- };
1738
- return {
1739
- name: jobName,
1740
- input: def.input,
1741
- handler,
1742
- queue: { name: fullQueueName },
1743
- attempts: def.attempts,
1744
- priority: def.priority,
1745
- delay: def.delay,
1746
- removeOnComplete: def.removeOnComplete,
1747
- removeOnFail: def.removeOnFail,
1748
- metadata: def.metadata,
1749
- limiter: def.limiter,
1750
- onStart: def.onStart,
1751
- onSuccess: def.onSuccess,
1752
- onFailure: def.onFailure,
1753
- onProgress: def.onProgress
1754
- };
1755
- }
1756
- toCoreCronJobDefinition(queueName, cronName, def, fullQueueName) {
1757
- const handler = async (ctx) => {
1758
- return def.handler({
1759
- context: ctx.context,
1760
- job: {
1761
- id: ctx.job.id,
1762
- name: cronName,
1763
- queue: queueName,
1764
- attemptsMade: ctx.job.attemptsMade,
1765
- createdAt: ctx.job.createdAt,
1766
- metadata: ctx.job.metadata
1767
- },
1768
- scope: ctx.job.metadata?.__igniter_jobs_scope
1769
- });
1770
- };
1771
- return {
1772
- name: cronName,
1773
- handler,
1774
- queue: { name: fullQueueName },
1775
- repeat: {
1776
- cron: def.cron,
1777
- tz: def.tz,
1778
- limit: def.maxExecutions,
1779
- startDate: def.startDate,
1780
- endDate: def.endDate
1781
- },
1782
- metadata: def.onlyBusinessHours || def.skipWeekends || def.businessHours || def.onlyWeekdays || def.skipDates || def.startDate && def.endDate ? {
1783
- advancedScheduling: {
1784
- onlyBusinessHours: def.onlyBusinessHours,
1785
- skipWeekends: def.skipWeekends,
1786
- businessHours: def.businessHours,
1787
- skipDates: toDateArray(def.skipDates),
1788
- onlyWeekdays: def.onlyWeekdays,
1789
- between: def.startDate && def.endDate ? [def.startDate, def.endDate] : void 0
1790
- }
1791
- } : void 0
1792
- };
1793
- }
1794
- };
1795
-
1796
- // src/utils/id-generator.ts
1797
- var IgniterJobsIdGenerator = class {
1798
- /**
1799
- * Generates a unique identifier with a prefix.
1800
- *
1801
- * @example
1802
- * ```typescript
1803
- * const jobId = IgniterJobsIdGenerator.generate('job')
1804
- * ```
1805
- */
1806
- static generate(prefix) {
1807
- const now = Date.now().toString(36);
1808
- const random = Math.random().toString(36).slice(2, 8);
1809
- return `${prefix}_${now}_${random}`;
1810
- }
1811
- };
1812
-
1813
- // src/adapters/memory.adapter.ts
1814
- var IgniterJobsMemoryAdapter = class _IgniterJobsMemoryAdapter {
1815
- constructor() {
1816
- this.client = {
1817
- type: "memory"
1818
- };
1819
- this.jobsById = /* @__PURE__ */ new Map();
1820
- this.jobsByQueue = /* @__PURE__ */ new Map();
1821
- this.registeredJobs = /* @__PURE__ */ new Map();
1822
- this.registeredCrons = /* @__PURE__ */ new Map();
1823
- this.workers = /* @__PURE__ */ new Map();
1824
- this.subscribers = /* @__PURE__ */ new Map();
1825
- this.queues = {
1826
- list: async () => this.listQueues(),
1827
- get: async (name) => this.getQueueInfo(name),
1828
- getJobCounts: async (name) => this.getQueueJobCounts(name),
1829
- getJobs: async (name, filter) => {
1830
- const statuses = filter?.status;
1831
- const limit = filter?.limit ?? 100;
1832
- const offset = filter?.offset ?? 0;
1833
- const results = await this.searchJobs({
1834
- queue: name,
1835
- status: statuses,
1836
- limit,
1837
- offset
1838
- });
1839
- return results;
1840
- },
1841
- pause: async (name) => this.pauseQueue(name),
1842
- resume: async (name) => this.resumeQueue(name),
1843
- isPaused: async (name) => {
1844
- const info = await this.getQueueInfo(name);
1845
- return info?.isPaused ?? false;
1846
- },
1847
- drain: async (name) => this.drainQueue(name),
1848
- clean: async (name, options) => this.cleanQueue(name, options),
1849
- obliterate: async (name, options) => this.obliterateQueue(name, options)
1850
- };
1851
- this.pausedQueues = /* @__PURE__ */ new Set();
1852
- }
1853
- static create() {
1854
- return new _IgniterJobsMemoryAdapter();
1855
- }
1856
- registerJob(queueName, jobName, definition) {
1857
- const queueJobs = this.registeredJobs.get(queueName) ?? /* @__PURE__ */ new Map();
1858
- if (queueJobs.has(jobName)) {
1859
- throw new IgniterJobsError({
1860
- code: "JOBS_DUPLICATE_JOB",
1861
- message: `Job "${jobName}" already registered for queue "${queueName}".`
1862
- });
1863
- }
1864
- queueJobs.set(jobName, definition);
1865
- this.registeredJobs.set(queueName, queueJobs);
1866
- }
1867
- registerCron(queueName, cronName, definition) {
1868
- const queueCrons = this.registeredCrons.get(queueName) ?? /* @__PURE__ */ new Map();
1869
- if (queueCrons.has(cronName)) {
1870
- throw new IgniterJobsError({
1871
- code: "JOBS_INVALID_CRON",
1872
- message: `Cron "${cronName}" already registered for queue "${queueName}".`
1873
- });
1874
- }
1875
- queueCrons.set(cronName, definition);
1876
- this.registeredCrons.set(queueName, queueCrons);
1877
- }
1878
- async dispatch(params) {
1879
- const jobId = params.jobId ?? IgniterJobsIdGenerator.generate("job");
1880
- const maxAttempts = params.attempts ?? 1;
1881
- const metadata = params.metadata ?? {};
1882
- const job = {
1883
- id: jobId,
1884
- name: params.jobName,
1885
- queue: params.queue,
1886
- input: params.input,
1887
- status: this.pausedQueues.has(params.queue) ? "paused" : params.delay && params.delay > 0 ? "delayed" : "waiting",
1888
- progress: 0,
1889
- attemptsMade: 0,
1890
- maxAttempts,
1891
- priority: params.priority ?? 0,
1892
- createdAt: /* @__PURE__ */ new Date(),
1893
- metadata,
1894
- scope: params.scope,
1895
- logs: []
1896
- };
1897
- this.jobsById.set(jobId, job);
1898
- const queueList = this.jobsByQueue.get(params.queue) ?? [];
1899
- queueList.push(jobId);
1900
- this.jobsByQueue.set(params.queue, queueList);
1901
- if (params.delay && params.delay > 0) {
1902
- setTimeout(() => {
1903
- const stored = this.jobsById.get(jobId);
1904
- if (!stored) return;
1905
- if (!this.pausedQueues.has(params.queue)) stored.status = "waiting";
1906
- void this.kickWorkers(params.queue);
1907
- }, params.delay);
1908
- return jobId;
1909
- }
1910
- void this.kickWorkers(params.queue);
1911
- return jobId;
1912
- }
1913
- async schedule(params) {
1914
- if (params.at) {
1915
- const delay = params.at.getTime() - Date.now();
1916
- if (delay <= 0) {
1917
- throw new IgniterJobsError({
1918
- code: "JOBS_INVALID_SCHEDULE",
1919
- message: "Scheduled time must be in the future."
1920
- });
1921
- }
1922
- return this.dispatch({ ...params, delay });
1923
- }
1924
- if (params.cron || params.every) {
1925
- return this.dispatch({ ...params, delay: params.delay ?? 0 });
1926
- }
1927
- return this.dispatch(params);
1928
- }
1929
- async getJob(jobId, queue) {
1930
- const job = this.jobsById.get(jobId);
1931
- if (!job) return null;
1932
- if (queue && job.queue !== queue) return null;
1933
- return this.toSearchResult(job);
1934
- }
1935
- async getJobState(jobId, queue) {
1936
- const job = this.jobsById.get(jobId);
1937
- if (!job) return null;
1938
- if (queue && job.queue !== queue) return null;
1939
- return job.status;
1940
- }
1941
- async getJobLogs(jobId, queue) {
1942
- const job = this.jobsById.get(jobId);
1943
- if (!job) return [];
1944
- if (queue && job.queue !== queue) return [];
1945
- return job.logs;
1946
- }
1947
- async getJobProgress(jobId, queue) {
1948
- const job = this.jobsById.get(jobId);
1949
- if (!job) return 0;
1950
- if (queue && job.queue !== queue) return 0;
1951
- return job.progress;
1952
- }
1953
- async retryJob(jobId, queue) {
1954
- const job = this.jobsById.get(jobId);
1955
- if (!job) {
1956
- throw new IgniterJobsError({
1957
- code: "JOBS_NOT_FOUND",
1958
- message: `Job "${jobId}" not found.`
1959
- });
1960
- }
1961
- if (queue && job.queue !== queue) {
1962
- throw new IgniterJobsError({
1963
- code: "JOBS_NOT_FOUND",
1964
- message: `Job "${jobId}" not found in queue "${queue}".`
1965
- });
1966
- }
1967
- job.status = "waiting";
1968
- job.error = void 0;
1969
- job.completedAt = void 0;
1970
- job.progress = 0;
1971
- void this.kickWorkers(job.queue);
1972
- }
1973
- async removeJob(jobId, queue) {
1974
- const job = this.jobsById.get(jobId);
1975
- if (!job) return;
1976
- if (queue && job.queue !== queue) return;
1977
- this.jobsById.delete(jobId);
1978
- const list = this.jobsByQueue.get(job.queue);
1979
- if (list)
1980
- this.jobsByQueue.set(
1981
- job.queue,
1982
- list.filter((id) => id !== jobId)
1983
- );
1984
- }
1985
- async promoteJob(jobId, queue) {
1986
- const job = this.jobsById.get(jobId);
1987
- if (!job) {
1988
- throw new IgniterJobsError({
1989
- code: "JOBS_NOT_FOUND",
1990
- message: `Job "${jobId}" not found.`
1991
- });
1992
- }
1993
- if (queue && job.queue !== queue) {
1994
- throw new IgniterJobsError({
1995
- code: "JOBS_NOT_FOUND",
1996
- message: `Job "${jobId}" not found in queue "${queue}".`
1997
- });
1998
- }
1999
- if (job.status === "delayed" || job.status === "paused") {
2000
- job.status = this.pausedQueues.has(job.queue) ? "paused" : "waiting";
2001
- void this.kickWorkers(job.queue);
2002
- }
2003
- }
2004
- async moveJobToFailed(jobId, reason, queue) {
2005
- const job = this.jobsById.get(jobId);
2006
- if (!job) {
2007
- throw new IgniterJobsError({
2008
- code: "JOBS_NOT_FOUND",
2009
- message: `Job "${jobId}" not found.`
2010
- });
2011
- }
2012
- if (queue && job.queue !== queue) {
2013
- throw new IgniterJobsError({
2014
- code: "JOBS_NOT_FOUND",
2015
- message: `Job "${jobId}" not found in queue "${queue}".`
2016
- });
2017
- }
2018
- job.status = "failed";
2019
- job.error = reason;
2020
- job.completedAt = /* @__PURE__ */ new Date();
2021
- }
2022
- async retryManyJobs(jobIds, queue) {
2023
- await Promise.all(jobIds.map((id) => this.retryJob(id, queue)));
2024
- }
2025
- async removeManyJobs(jobIds, queue) {
2026
- await Promise.all(jobIds.map((id) => this.removeJob(id, queue)));
2027
- }
2028
- async getQueueInfo(queue) {
2029
- const counts = await this.getQueueJobCounts(queue);
2030
- return {
2031
- name: queue,
2032
- isPaused: this.pausedQueues.has(queue),
2033
- jobCounts: counts
2034
- };
2035
- }
2036
- async getQueueJobCounts(queue) {
2037
- const jobIds = this.jobsByQueue.get(queue) ?? [];
2038
- const counts = {
2039
- waiting: 0,
2040
- active: 0,
2041
- completed: 0,
2042
- failed: 0,
2043
- delayed: 0,
2044
- paused: 0
2045
- };
2046
- for (const id of jobIds) {
2047
- const job = this.jobsById.get(id);
2048
- if (!job) continue;
2049
- if (job.status in counts) {
2050
- counts[job.status]++;
2051
- }
2052
- }
2053
- return counts;
2054
- }
2055
- async listQueues() {
2056
- const queues = Array.from(
2057
- /* @__PURE__ */ new Set([
2058
- ...this.jobsByQueue.keys(),
2059
- ...this.registeredJobs.keys(),
2060
- ...this.registeredCrons.keys()
2061
- ])
2062
- );
2063
- const result = [];
2064
- for (const q of queues) {
2065
- result.push(await this.getQueueInfo(q));
2066
- }
2067
- return result;
2068
- }
2069
- async pauseQueue(queue) {
2070
- this.pausedQueues.add(queue);
2071
- const jobIds = this.jobsByQueue.get(queue) ?? [];
2072
- for (const id of jobIds) {
2073
- const job = this.jobsById.get(id);
2074
- if (!job) continue;
2075
- if (job.status === "waiting") job.status = "paused";
2076
- }
2077
- }
2078
- async resumeQueue(queue) {
2079
- this.pausedQueues.delete(queue);
2080
- const jobIds = this.jobsByQueue.get(queue) ?? [];
2081
- for (const id of jobIds) {
2082
- const job = this.jobsById.get(id);
2083
- if (!job) continue;
2084
- if (job.status === "paused") job.status = "waiting";
2085
- }
2086
- void this.kickWorkers(queue);
2087
- }
2088
- async drainQueue(queue) {
2089
- const jobIds = this.jobsByQueue.get(queue) ?? [];
2090
- let removed = 0;
2091
- for (const id of jobIds) {
2092
- const job = this.jobsById.get(id);
2093
- if (!job) continue;
2094
- if (job.status === "waiting" || job.status === "paused") {
2095
- this.jobsById.delete(id);
2096
- removed++;
2097
- }
2098
- }
2099
- this.jobsByQueue.set(
2100
- queue,
2101
- jobIds.filter((id) => this.jobsById.has(id))
2102
- );
2103
- return removed;
2104
- }
2105
- async cleanQueue(queue, options) {
2106
- const statuses = Array.isArray(options.status) ? options.status : [options.status];
2107
- const olderThan = options.olderThan ?? 0;
2108
- const limit = options.limit ?? Number.POSITIVE_INFINITY;
2109
- const jobIds = this.jobsByQueue.get(queue) ?? [];
2110
- const now = Date.now();
2111
- let cleaned = 0;
2112
- for (const id of [...jobIds]) {
2113
- if (cleaned >= limit) break;
2114
- const job = this.jobsById.get(id);
2115
- if (!job) continue;
2116
- if (!statuses.includes(job.status)) continue;
2117
- const ageMs = now - job.createdAt.getTime();
2118
- if (ageMs < olderThan) continue;
2119
- this.jobsById.delete(id);
2120
- cleaned++;
2121
- }
2122
- this.jobsByQueue.set(
2123
- queue,
2124
- jobIds.filter((id) => this.jobsById.has(id))
2125
- );
2126
- return cleaned;
2127
- }
2128
- async obliterateQueue(queue, options) {
2129
- const jobIds = this.jobsByQueue.get(queue) ?? [];
2130
- for (const id of jobIds) this.jobsById.delete(id);
2131
- this.jobsByQueue.delete(queue);
2132
- this.registeredJobs.delete(queue);
2133
- this.registeredCrons.delete(queue);
2134
- this.pausedQueues.delete(queue);
2135
- }
2136
- async retryAllInQueue(queue) {
2137
- const jobIds = this.jobsByQueue.get(queue) ?? [];
2138
- let retried = 0;
2139
- for (const id of jobIds) {
2140
- const job = this.jobsById.get(id);
2141
- if (!job) continue;
2142
- if (job.status === "failed") {
2143
- await this.retryJob(id, queue);
2144
- retried++;
2145
- }
2146
- }
2147
- return retried;
2148
- }
2149
- async pauseJobType(queue, jobName) {
2150
- const jobIds = this.jobsByQueue.get(queue) ?? [];
2151
- for (const id of jobIds) {
2152
- const job = this.jobsById.get(id);
2153
- if (!job) continue;
2154
- if (job.name === jobName && job.status === "waiting")
2155
- job.status = "paused";
2156
- }
2157
- }
2158
- async resumeJobType(queue, jobName) {
2159
- const jobIds = this.jobsByQueue.get(queue) ?? [];
2160
- for (const id of jobIds) {
2161
- const job = this.jobsById.get(id);
2162
- if (!job) continue;
2163
- if (job.name === jobName && job.status === "paused")
2164
- job.status = "waiting";
2165
- }
2166
- void this.kickWorkers(queue);
2167
- }
2168
- async searchJobs(filter) {
2169
- const queue = filter?.queue;
2170
- const statuses = filter?.status;
2171
- const limit = filter?.limit ?? 100;
2172
- const offset = filter?.offset ?? 0;
2173
- const all = Array.from(this.jobsById.values()).filter((j) => queue ? j.queue === queue : true).filter((j) => statuses ? statuses.includes(j.status) : true).sort(
2174
- (a, b) => b.priority - a.priority || a.createdAt.getTime() - b.createdAt.getTime()
2175
- );
2176
- return all.slice(offset, offset + limit).map((j) => this.toSearchResult(j));
2177
- }
2178
- async searchQueues(filter) {
2179
- const name = filter?.name;
2180
- const isPaused = filter?.isPaused;
2181
- const all = await this.listQueues();
2182
- return all.filter((q) => name ? q.name.includes(name) : true).filter(
2183
- (q) => typeof isPaused === "boolean" ? q.isPaused === isPaused : true
2184
- );
2185
- }
2186
- async searchWorkers(filter) {
2187
- const queue = filter?.queue;
2188
- const isRunning = filter?.isRunning;
2189
- return Array.from(this.workers.values()).filter((w) => queue ? w.queues.includes(queue) : true).filter(
2190
- (w) => typeof isRunning === "boolean" ? isRunning ? !w.closed : w.closed : true
2191
- ).map((w) => this.toWorkerHandle(w));
2192
- }
2193
- async createWorker(config) {
2194
- const workerId = IgniterJobsIdGenerator.generate("worker");
2195
- const state = {
2196
- id: workerId,
2197
- queues: config.queues ?? [],
2198
- concurrency: config.concurrency ?? 1,
2199
- paused: false,
2200
- closed: false,
2201
- startedAt: /* @__PURE__ */ new Date(),
2202
- metrics: { processed: 0, failed: 0, totalDuration: 0 },
2203
- handlers: config.handlers
2204
- };
2205
- this.workers.set(workerId, state);
2206
- for (const q of state.queues) void this.kickWorkers(q);
2207
- return this.toWorkerHandle(state);
2208
- }
2209
- getWorkers() {
2210
- const out = /* @__PURE__ */ new Map();
2211
- for (const [id, state] of this.workers)
2212
- out.set(id, this.toWorkerHandle(state));
2213
- return out;
2214
- }
2215
- async publishEvent(channel, payload) {
2216
- const handlers = this.subscribers.get(channel);
2217
- if (!handlers) return;
2218
- await Promise.all(Array.from(handlers).map(async (h) => h(payload)));
2219
- }
2220
- async subscribeEvent(channel, handler) {
2221
- const set = this.subscribers.get(channel) ?? /* @__PURE__ */ new Set();
2222
- set.add(handler);
2223
- this.subscribers.set(channel, set);
2224
- return async () => {
2225
- const current = this.subscribers.get(channel);
2226
- if (!current) return;
2227
- current.delete(handler);
2228
- if (current.size === 0) this.subscribers.delete(channel);
2229
- };
2230
- }
2231
- async shutdown() {
2232
- this.workers.clear();
2233
- this.subscribers.clear();
2234
- }
2235
- toSearchResult(job) {
2236
- return {
2237
- id: job.id,
2238
- name: job.name,
2239
- queue: job.queue,
2240
- status: job.status,
2241
- input: job.input,
2242
- result: job.result,
2243
- error: job.error,
2244
- progress: job.progress,
2245
- attemptsMade: job.attemptsMade,
2246
- priority: job.priority,
2247
- createdAt: job.createdAt,
2248
- startedAt: job.startedAt,
2249
- completedAt: job.completedAt,
2250
- metadata: job.metadata,
2251
- scope: job.scope
2252
- };
2253
- }
2254
- toWorkerHandle(worker) {
2255
- return {
2256
- id: worker.id,
2257
- queues: worker.queues,
2258
- pause: async () => {
2259
- worker.paused = true;
2260
- },
2261
- resume: async () => {
2262
- worker.paused = false;
2263
- for (const q of worker.queues) void this.kickWorkers(q);
2264
- },
2265
- close: async () => {
2266
- worker.closed = true;
2267
- },
2268
- isRunning: () => !worker.closed && !worker.paused,
2269
- isPaused: () => worker.paused,
2270
- isClosed: () => worker.closed,
2271
- getMetrics: async () => this.toWorkerMetrics(worker)
2272
- };
2273
- }
2274
- toWorkerMetrics(worker) {
2275
- const uptime = Date.now() - worker.startedAt.getTime();
2276
- const processed = worker.metrics.processed;
2277
- return {
2278
- processed,
2279
- failed: worker.metrics.failed,
2280
- avgDuration: processed > 0 ? worker.metrics.totalDuration / processed : 0,
2281
- concurrency: worker.concurrency,
2282
- uptime
2283
- };
2284
- }
2285
- async kickWorkers(queue) {
2286
- if (this.pausedQueues.has(queue)) return;
2287
- const relevant = Array.from(this.workers.values()).filter(
2288
- (w) => !w.closed && !w.paused && (w.queues.length === 0 || w.queues.includes(queue))
2289
- );
2290
- if (relevant.length === 0) return;
2291
- for (const w of relevant) {
2292
- void this.processLoop(w, queue);
2293
- }
2294
- }
2295
- async processLoop(worker, queue) {
2296
- if (worker.closed || worker.paused) return;
2297
- const concurrency = Math.max(1, worker.concurrency);
2298
- const running = worker.__running;
2299
- const currentRunning = running ?? 0;
2300
- if (currentRunning >= concurrency) return;
2301
- worker.__running = currentRunning + 1;
2302
- try {
2303
- const next = this.nextJob(queue);
2304
- if (!next) return;
2305
- await this.processJob(worker, next);
2306
- } finally {
2307
- worker.__running = worker.__running - 1;
2308
- if (this.nextJob(queue)) void this.processLoop(worker, queue);
2309
- else if (worker.handlers?.onIdle) await worker.handlers.onIdle();
2310
- }
2311
- }
2312
- nextJob(queue) {
2313
- const ids = this.jobsByQueue.get(queue) ?? [];
2314
- const candidates = ids.map((id) => this.jobsById.get(id)).filter((j) => Boolean(j)).filter((j) => j.status === "waiting").sort(
2315
- (a, b) => b.priority - a.priority || a.createdAt.getTime() - b.createdAt.getTime()
2316
- );
2317
- return candidates[0] ?? null;
2318
- }
2319
- async processJob(worker, job) {
2320
- if (this.pausedQueues.has(job.queue)) {
2321
- job.status = "paused";
2322
- return;
2323
- }
2324
- job.status = "active";
2325
- job.startedAt = /* @__PURE__ */ new Date();
2326
- job.attemptsMade += 1;
2327
- job.logs.push({
2328
- timestamp: /* @__PURE__ */ new Date(),
2329
- level: "info",
2330
- message: "Job started"
2331
- });
2332
- if (worker.handlers?.onActive)
2333
- await worker.handlers.onActive({ job: this.toSearchResult(job) });
2334
- const start = Date.now();
2335
- try {
2336
- const definition = this.registeredJobs.get(job.queue)?.get(job.name);
2337
- if (!definition) {
2338
- throw new IgniterJobsError({
2339
- code: "JOBS_NOT_REGISTERED",
2340
- message: `Job "${job.name}" is not registered for queue "${job.queue}".`
2341
- });
2342
- }
2343
- if (definition.onStart) {
2344
- await definition.onStart({
2345
- input: job.input,
2346
- context: {},
2347
- job: {
2348
- id: job.id,
2349
- name: job.name,
2350
- queue: job.queue,
2351
- attemptsMade: job.attemptsMade,
2352
- metadata: job.metadata
2353
- },
2354
- scope: job.scope,
2355
- startedAt: job.startedAt
2356
- });
2357
- }
2358
- const result = await definition.handler({
2359
- input: job.input,
2360
- context: {},
2361
- job: {
2362
- id: job.id,
2363
- name: job.name,
2364
- queue: job.queue,
2365
- attemptsMade: job.attemptsMade,
2366
- metadata: job.metadata
2367
- },
2368
- scope: job.scope
2369
- });
2370
- const duration = Date.now() - start;
2371
- job.status = "completed";
2372
- job.completedAt = /* @__PURE__ */ new Date();
2373
- job.result = result;
2374
- job.progress = 100;
2375
- job.logs.push({
2376
- timestamp: /* @__PURE__ */ new Date(),
2377
- level: "info",
2378
- message: `Job completed in ${duration}ms`
2379
- });
2380
- worker.metrics.processed += 1;
2381
- worker.metrics.totalDuration += duration;
2382
- if (definition.onSuccess) {
2383
- await definition.onSuccess({
2384
- input: job.input,
2385
- context: {},
2386
- job: {
2387
- id: job.id,
2388
- name: job.name,
2389
- queue: job.queue,
2390
- attemptsMade: job.attemptsMade,
2391
- metadata: job.metadata
2392
- },
2393
- scope: job.scope,
2394
- result,
2395
- duration
2396
- });
2397
- }
2398
- if (worker.handlers?.onSuccess)
2399
- await worker.handlers.onSuccess({
2400
- job: this.toSearchResult(job),
2401
- result
2402
- });
2403
- } catch (error) {
2404
- job.error = error?.message ?? String(error);
2405
- job.logs.push({
2406
- timestamp: /* @__PURE__ */ new Date(),
2407
- level: "error",
2408
- message: job.error ?? "Unknown error"
2409
- });
2410
- const isFinalAttempt = job.attemptsMade >= job.maxAttempts;
2411
- if (isFinalAttempt) {
2412
- job.status = "failed";
2413
- job.completedAt = /* @__PURE__ */ new Date();
2414
- worker.metrics.failed += 1;
2415
- const definition = this.registeredJobs.get(job.queue)?.get(job.name);
2416
- if (definition?.onFailure) {
2417
- await definition.onFailure({
2418
- input: job.input,
2419
- context: {},
2420
- job: {
2421
- id: job.id,
2422
- name: job.name,
2423
- queue: job.queue,
2424
- attemptsMade: job.attemptsMade,
2425
- metadata: job.metadata
2426
- },
2427
- scope: job.scope,
2428
- error,
2429
- isFinalAttempt: true
2430
- });
2431
- }
2432
- if (worker.handlers?.onFailure)
2433
- await worker.handlers.onFailure({
2434
- job: this.toSearchResult(job),
2435
- error
2436
- });
2437
- } else {
2438
- job.status = "waiting";
2439
- void this.kickWorkers(job.queue);
2440
- }
2441
- }
2442
- }
2443
- };
2444
-
2445
- // src/adapters/sqlite.adapter.ts
2446
- var IgniterJobsSQLiteAdapter = class _IgniterJobsSQLiteAdapter {
2447
- constructor(options) {
2448
- this.registeredJobs = /* @__PURE__ */ new Map();
2449
- this.registeredCrons = /* @__PURE__ */ new Map();
2450
- this.workers = /* @__PURE__ */ new Map();
2451
- this.subscribers = /* @__PURE__ */ new Map();
2452
- this.pausedQueues = /* @__PURE__ */ new Set();
2453
- this.queues = {
2454
- list: async () => this.listQueues(),
2455
- get: async (name) => this.getQueueInfo(name),
2456
- getJobCounts: async (name) => this.getQueueJobCounts(name),
2457
- getJobs: async (name, filter) => {
2458
- const statuses = filter?.status;
2459
- const limit = filter?.limit ?? 100;
2460
- const offset = filter?.offset ?? 0;
2461
- const results = await this.searchJobs({
2462
- queue: name,
2463
- status: statuses,
2464
- limit,
2465
- offset
2466
- });
2467
- return results;
2468
- },
2469
- pause: async (name) => this.pauseQueue(name),
2470
- resume: async (name) => this.resumeQueue(name),
2471
- isPaused: async (name) => {
2472
- const info = await this.getQueueInfo(name);
2473
- return info?.isPaused ?? false;
2474
- },
2475
- drain: async (name) => this.drainQueue(name),
2476
- clean: async (name, options) => this.cleanQueue(name, options),
2477
- obliterate: async (name, options) => this.obliterateQueue(name, options)
2478
- };
2479
- this.options = {
2480
- path: options.path,
2481
- pollingInterval: options.pollingInterval ?? 500,
2482
- enableWAL: options.enableWAL ?? true
2483
- };
2484
- this.client = {
2485
- type: "sqlite",
2486
- path: this.options.path
2487
- };
2488
- const Database = __require("better-sqlite3");
2489
- this.db = new Database(this.options.path);
2490
- this.initializeSchema();
2491
- }
2492
- /**
2493
- * Creates a new SQLite adapter instance.
2494
- *
2495
- * @param options - Configuration options
2496
- * @returns A new adapter instance
2497
- *
2498
- * @example
2499
- * ```ts
2500
- * // File-based database (persistent)
2501
- * const adapter = IgniterJobsSQLiteAdapter.create({
2502
- * path: './data/jobs.sqlite'
2503
- * });
2504
- *
2505
- * // In-memory database (for testing)
2506
- * const testAdapter = IgniterJobsSQLiteAdapter.create({
2507
- * path: ':memory:'
2508
- * });
2509
- * ```
2510
- */
2511
- static create(options) {
2512
- return new _IgniterJobsSQLiteAdapter(options);
2513
- }
2514
- initializeSchema() {
2515
- if (this.options.enableWAL) {
2516
- this.db.exec("PRAGMA journal_mode = WAL;");
2517
- }
2518
- this.db.exec(`
2519
- CREATE TABLE IF NOT EXISTS jobs (
2520
- id TEXT PRIMARY KEY,
2521
- name TEXT NOT NULL,
2522
- queue TEXT NOT NULL,
2523
- input TEXT NOT NULL,
2524
- status TEXT NOT NULL DEFAULT 'waiting',
2525
- progress REAL NOT NULL DEFAULT 0,
2526
- attempts_made INTEGER NOT NULL DEFAULT 0,
2527
- max_attempts INTEGER NOT NULL DEFAULT 1,
2528
- priority INTEGER NOT NULL DEFAULT 0,
2529
- created_at TEXT NOT NULL,
2530
- started_at TEXT,
2531
- completed_at TEXT,
2532
- scheduled_at TEXT,
2533
- result TEXT,
2534
- error TEXT,
2535
- metadata TEXT,
2536
- scope TEXT
2537
- );
2538
-
2539
- CREATE INDEX IF NOT EXISTS idx_jobs_queue_status ON jobs(queue, status);
2540
- CREATE INDEX IF NOT EXISTS idx_jobs_status ON jobs(status);
2541
- CREATE INDEX IF NOT EXISTS idx_jobs_scheduled_at ON jobs(scheduled_at);
2542
- CREATE INDEX IF NOT EXISTS idx_jobs_priority ON jobs(priority DESC, created_at ASC);
2543
- `);
2544
- this.db.exec(`
2545
- CREATE TABLE IF NOT EXISTS job_logs (
2546
- id INTEGER PRIMARY KEY AUTOINCREMENT,
2547
- job_id TEXT NOT NULL,
2548
- timestamp TEXT NOT NULL,
2549
- level TEXT NOT NULL,
2550
- message TEXT NOT NULL,
2551
- FOREIGN KEY (job_id) REFERENCES jobs(id) ON DELETE CASCADE
2552
- );
2553
-
2554
- CREATE INDEX IF NOT EXISTS idx_job_logs_job_id ON job_logs(job_id);
2555
- `);
2556
- this.db.exec(`
2557
- CREATE TABLE IF NOT EXISTS paused_queues (
2558
- name TEXT PRIMARY KEY
2559
- );
2560
- `);
2561
- const pausedRows = this.db.prepare(
2562
- "SELECT name FROM paused_queues"
2563
- ).all();
2564
- for (const row of pausedRows) {
2565
- this.pausedQueues.add(row.name);
2566
- }
2567
- }
2568
- registerJob(queueName, jobName, definition) {
2569
- const queueJobs = this.registeredJobs.get(queueName) ?? /* @__PURE__ */ new Map();
2570
- if (queueJobs.has(jobName)) {
2571
- throw new IgniterJobsError({
2572
- code: "JOBS_DUPLICATE_JOB",
2573
- message: `Job "${jobName}" already registered for queue "${queueName}".`
2574
- });
2575
- }
2576
- queueJobs.set(jobName, definition);
2577
- this.registeredJobs.set(queueName, queueJobs);
2578
- }
2579
- registerCron(queueName, cronName, definition) {
2580
- const queueCrons = this.registeredCrons.get(queueName) ?? /* @__PURE__ */ new Map();
2581
- if (queueCrons.has(cronName)) {
2582
- throw new IgniterJobsError({
2583
- code: "JOBS_INVALID_CRON",
2584
- message: `Cron "${cronName}" already registered for queue "${queueName}".`
2585
- });
2586
- }
2587
- queueCrons.set(cronName, definition);
2588
- this.registeredCrons.set(queueName, queueCrons);
2589
- }
2590
- async dispatch(params) {
2591
- const jobId = params.jobId ?? IgniterJobsIdGenerator.generate("job");
2592
- const maxAttempts = params.attempts ?? 1;
2593
- const now = /* @__PURE__ */ new Date();
2594
- let status = "waiting";
2595
- let scheduledAt = null;
2596
- if (this.pausedQueues.has(params.queue)) {
2597
- status = "paused";
2598
- } else if (params.delay && params.delay > 0) {
2599
- status = "delayed";
2600
- scheduledAt = new Date(now.getTime() + params.delay);
2601
- }
2602
- const stmt = this.db.prepare(`
2603
- INSERT INTO jobs (
2604
- id, name, queue, input, status, progress, attempts_made, max_attempts,
2605
- priority, created_at, scheduled_at, metadata, scope
2606
- ) VALUES (?, ?, ?, ?, ?, 0, 0, ?, ?, ?, ?, ?, ?)
2607
- `);
2608
- stmt.run(
2609
- jobId,
2610
- params.jobName,
2611
- params.queue,
2612
- JSON.stringify(params.input ?? {}),
2613
- status,
2614
- maxAttempts,
2615
- params.priority ?? 0,
2616
- now.toISOString(),
2617
- scheduledAt?.toISOString() ?? null,
2618
- params.metadata ? JSON.stringify(params.metadata) : null,
2619
- params.scope ? JSON.stringify(params.scope) : null
2620
- );
2621
- if (params.delay && params.delay > 0) {
2622
- setTimeout(() => {
2623
- this.promoteDelayedJob(jobId, params.queue);
2624
- }, params.delay);
2625
- }
2626
- return jobId;
2627
- }
2628
- promoteDelayedJob(jobId, queue) {
2629
- if (this.pausedQueues.has(queue)) return;
2630
- const stmt = this.db.prepare(`
2631
- UPDATE jobs SET status = 'waiting', scheduled_at = NULL
2632
- WHERE id = ? AND status = 'delayed'
2633
- `);
2634
- stmt.run(jobId);
2635
- }
2636
- async schedule(params) {
2637
- if (params.at) {
2638
- const delay = params.at.getTime() - Date.now();
2639
- if (delay <= 0) {
2640
- throw new IgniterJobsError({
2641
- code: "JOBS_INVALID_SCHEDULE",
2642
- message: "Scheduled time must be in the future."
2643
- });
2644
- }
2645
- return this.dispatch({ ...params, delay });
2646
- }
2647
- if (params.cron || params.every) {
2648
- return this.dispatch({ ...params, delay: params.delay ?? 0 });
2649
- }
2650
- return this.dispatch(params);
2651
- }
2652
- async getJob(jobId, queue) {
2653
- let sql = "SELECT * FROM jobs WHERE id = ?";
2654
- const params = [jobId];
2655
- if (queue) {
2656
- sql += " AND queue = ?";
2657
- params.push(queue);
2658
- }
2659
- const row = this.db.prepare(sql).get(...params);
2660
- if (!row) return null;
2661
- return this.rowToSearchResult(row);
2662
- }
2663
- async getJobState(jobId, queue) {
2664
- let sql = "SELECT status FROM jobs WHERE id = ?";
2665
- const params = [jobId];
2666
- if (queue) {
2667
- sql += " AND queue = ?";
2668
- params.push(queue);
2669
- }
2670
- const row = this.db.prepare(sql).get(...params);
2671
- return row?.status ?? null;
2672
- }
2673
- async getJobLogs(jobId, queue) {
2674
- if (queue) {
2675
- const job = await this.getJob(jobId, queue);
2676
- if (!job) return [];
2677
- }
2678
- const rows = this.db.prepare("SELECT * FROM job_logs WHERE job_id = ? ORDER BY timestamp ASC").all(jobId);
2679
- return rows.map((row) => ({
2680
- timestamp: new Date(row.timestamp),
2681
- level: row.level,
2682
- message: row.message
2683
- }));
2684
- }
2685
- async getJobProgress(jobId, queue) {
2686
- let sql = "SELECT progress FROM jobs WHERE id = ?";
2687
- const params = [jobId];
2688
- if (queue) {
2689
- sql += " AND queue = ?";
2690
- params.push(queue);
2691
- }
2692
- const row = this.db.prepare(sql).get(...params);
2693
- return row?.progress ?? 0;
2694
- }
2695
- async retryJob(jobId, queue) {
2696
- let sql = "SELECT id FROM jobs WHERE id = ?";
2697
- const checkParams = [jobId];
2698
- if (queue) {
2699
- sql += " AND queue = ?";
2700
- checkParams.push(queue);
2701
- }
2702
- const exists = this.db.prepare(sql).get(...checkParams);
2703
- if (!exists) {
2704
- throw new IgniterJobsError({
2705
- code: "JOBS_NOT_FOUND",
2706
- message: `Job "${jobId}" not found${queue ? ` in queue "${queue}"` : ""}.`
2707
- });
2708
- }
2709
- let updateSql = "UPDATE jobs SET status = 'waiting', error = NULL, completed_at = NULL, progress = 0 WHERE id = ?";
2710
- const updateParams = [jobId];
2711
- if (queue) {
2712
- updateSql = updateSql.replace("WHERE id = ?", "WHERE id = ? AND queue = ?");
2713
- updateParams.push(queue);
2714
- }
2715
- this.db.prepare(updateSql).run(...updateParams);
2716
- }
2717
- async removeJob(jobId, queue) {
2718
- let sql = "DELETE FROM jobs WHERE id = ?";
2719
- const params = [jobId];
2720
- if (queue) {
2721
- sql += " AND queue = ?";
2722
- params.push(queue);
2723
- }
2724
- this.db.prepare(sql).run(...params);
2725
- }
2726
- async promoteJob(jobId, queue) {
2727
- let sql = "SELECT id, status, queue FROM jobs WHERE id = ?";
2728
- const checkParams = [jobId];
2729
- if (queue) {
2730
- sql += " AND queue = ?";
2731
- checkParams.push(queue);
2732
- }
2733
- const row = this.db.prepare(sql).get(...checkParams);
2734
- if (!row) {
2735
- throw new IgniterJobsError({
2736
- code: "JOBS_NOT_FOUND",
2737
- message: `Job "${jobId}" not found${queue ? ` in queue "${queue}"` : ""}.`
2738
- });
2739
- }
2740
- if (row.status === "delayed" || row.status === "paused") {
2741
- const newStatus = this.pausedQueues.has(row.queue) ? "paused" : "waiting";
2742
- this.db.prepare("UPDATE jobs SET status = ?, scheduled_at = NULL WHERE id = ?").run(newStatus, jobId);
2743
- }
2744
- }
2745
- async moveJobToFailed(jobId, reason, queue) {
2746
- let sql = "SELECT id FROM jobs WHERE id = ?";
2747
- const checkParams = [jobId];
2748
- if (queue) {
2749
- sql += " AND queue = ?";
2750
- checkParams.push(queue);
2751
- }
2752
- const exists = this.db.prepare(sql).get(...checkParams);
2753
- if (!exists) {
2754
- throw new IgniterJobsError({
2755
- code: "JOBS_NOT_FOUND",
2756
- message: `Job "${jobId}" not found${queue ? ` in queue "${queue}"` : ""}.`
2757
- });
2758
- }
2759
- this.db.prepare(`
2760
- UPDATE jobs SET status = 'failed', error = ?, completed_at = ?
2761
- WHERE id = ?
2762
- `).run(reason, (/* @__PURE__ */ new Date()).toISOString(), jobId);
2763
- }
2764
- async retryManyJobs(jobIds, queue) {
2765
- await Promise.all(jobIds.map((id) => this.retryJob(id, queue)));
2766
- }
2767
- async removeManyJobs(jobIds, queue) {
2768
- await Promise.all(jobIds.map((id) => this.removeJob(id, queue)));
2769
- }
2770
- async getQueueInfo(queue) {
2771
- const counts = await this.getQueueJobCounts(queue);
2772
- return {
2773
- name: queue,
2774
- isPaused: this.pausedQueues.has(queue),
2775
- jobCounts: counts
2776
- };
2777
- }
2778
- async getQueueJobCounts(queue) {
2779
- const counts = {
2780
- waiting: 0,
2781
- active: 0,
2782
- completed: 0,
2783
- failed: 0,
2784
- delayed: 0,
2785
- paused: 0
2786
- };
2787
- const rows = this.db.prepare(
2788
- "SELECT status, COUNT(*) as count FROM jobs WHERE queue = ? GROUP BY status"
2789
- ).all(queue);
2790
- for (const row of rows) {
2791
- if (row.status in counts) {
2792
- counts[row.status] = row.count;
2793
- }
2794
- }
2795
- return counts;
2796
- }
2797
- async listQueues() {
2798
- const jobQueues = this.db.prepare("SELECT DISTINCT queue FROM jobs").all().map((r) => r.queue);
2799
- const allQueues = /* @__PURE__ */ new Set([
2800
- ...jobQueues,
2801
- ...this.registeredJobs.keys(),
2802
- ...this.registeredCrons.keys()
2803
- ]);
2804
- const result = [];
2805
- for (const q of allQueues) {
2806
- const info = await this.getQueueInfo(q);
2807
- if (info) result.push(info);
2808
- }
2809
- return result;
2810
- }
2811
- async pauseQueue(queue) {
2812
- this.pausedQueues.add(queue);
2813
- this.db.prepare("INSERT OR IGNORE INTO paused_queues (name) VALUES (?)").run(queue);
2814
- this.db.prepare(
2815
- "UPDATE jobs SET status = 'paused' WHERE queue = ? AND status = 'waiting'"
2816
- ).run(queue);
2817
- }
2818
- async resumeQueue(queue) {
2819
- this.pausedQueues.delete(queue);
2820
- this.db.prepare("DELETE FROM paused_queues WHERE name = ?").run(queue);
2821
- this.db.prepare(
2822
- "UPDATE jobs SET status = 'waiting' WHERE queue = ? AND status = 'paused'"
2823
- ).run(queue);
2824
- }
2825
- async drainQueue(queue) {
2826
- const result = this.db.prepare(
2827
- "DELETE FROM jobs WHERE queue = ? AND status IN ('waiting', 'paused')"
2828
- ).run(queue);
2829
- return result.changes;
2830
- }
2831
- async cleanQueue(queue, options) {
2832
- const statuses = Array.isArray(options.status) ? options.status : [options.status];
2833
- const olderThan = options.olderThan ?? 0;
2834
- const limit = options.limit ?? Number.POSITIVE_INFINITY;
2835
- const cutoffTime = new Date(Date.now() - olderThan).toISOString();
2836
- const statusPlaceholders = statuses.map(() => "?").join(", ");
2837
- let sql = `
2838
- DELETE FROM jobs WHERE id IN (
2839
- SELECT id FROM jobs
2840
- WHERE queue = ? AND status IN (${statusPlaceholders}) AND created_at < ?
2841
- ORDER BY created_at ASC
2842
- LIMIT ?
2843
- )
2844
- `;
2845
- const result = this.db.prepare(sql).run(
2846
- queue,
2847
- ...statuses,
2848
- cutoffTime,
2849
- limit === Number.POSITIVE_INFINITY ? -1 : limit
2850
- );
2851
- return result.changes;
2852
- }
2853
- async obliterateQueue(queue, _options) {
2854
- this.db.prepare("DELETE FROM jobs WHERE queue = ?").run(queue);
2855
- this.registeredJobs.delete(queue);
2856
- this.registeredCrons.delete(queue);
2857
- this.pausedQueues.delete(queue);
2858
- this.db.prepare("DELETE FROM paused_queues WHERE name = ?").run(queue);
2859
- }
2860
- async retryAllInQueue(queue) {
2861
- const result = this.db.prepare(`
2862
- UPDATE jobs SET status = 'waiting', error = NULL, completed_at = NULL, progress = 0
2863
- WHERE queue = ? AND status = 'failed'
2864
- `).run(queue);
2865
- return result.changes;
2866
- }
2867
- async pauseJobType(queue, jobName) {
2868
- this.db.prepare(
2869
- "UPDATE jobs SET status = 'paused' WHERE queue = ? AND name = ? AND status = 'waiting'"
2870
- ).run(queue, jobName);
2871
- }
2872
- async resumeJobType(queue, jobName) {
2873
- this.db.prepare(
2874
- "UPDATE jobs SET status = 'waiting' WHERE queue = ? AND name = ? AND status = 'paused'"
2875
- ).run(queue, jobName);
2876
- }
2877
- async searchJobs(filter) {
2878
- const queue = filter?.queue;
2879
- const statuses = filter?.status;
2880
- const limit = filter?.limit ?? 100;
2881
- const offset = filter?.offset ?? 0;
2882
- let sql = "SELECT * FROM jobs WHERE 1=1";
2883
- const params = [];
2884
- if (queue) {
2885
- sql += " AND queue = ?";
2886
- params.push(queue);
2887
- }
2888
- if (statuses && statuses.length > 0) {
2889
- const placeholders = statuses.map(() => "?").join(", ");
2890
- sql += ` AND status IN (${placeholders})`;
2891
- params.push(...statuses);
2892
- }
2893
- sql += " ORDER BY priority DESC, created_at ASC LIMIT ? OFFSET ?";
2894
- params.push(limit, offset);
2895
- const rows = this.db.prepare(sql).all(...params);
2896
- return rows.map((row) => this.rowToSearchResult(row));
2897
- }
2898
- async searchQueues(filter) {
2899
- const name = filter?.name;
2900
- const isPaused = filter?.isPaused;
2901
- const all = await this.listQueues();
2902
- return all.filter((q) => name ? q.name.includes(name) : true).filter(
2903
- (q) => typeof isPaused === "boolean" ? q.isPaused === isPaused : true
2904
- );
2905
- }
2906
- async searchWorkers(filter) {
2907
- const queue = filter?.queue;
2908
- const isRunning = filter?.isRunning;
2909
- return Array.from(this.workers.values()).filter((w) => queue ? w.queues.includes(queue) : true).filter(
2910
- (w) => typeof isRunning === "boolean" ? isRunning ? !w.closed : w.closed : true
2911
- ).map((w) => this.toWorkerHandle(w));
2912
- }
2913
- async createWorker(config) {
2914
- const workerId = IgniterJobsIdGenerator.generate("worker");
2915
- const state = {
2916
- id: workerId,
2917
- queues: config.queues ?? [],
2918
- concurrency: config.concurrency ?? 1,
2919
- paused: false,
2920
- closed: false,
2921
- startedAt: /* @__PURE__ */ new Date(),
2922
- metrics: { processed: 0, failed: 0, totalDuration: 0 },
2923
- handlers: config.handlers,
2924
- activeJobs: 0
2925
- };
2926
- this.workers.set(workerId, state);
2927
- this.startPollingLoop(state);
2928
- return this.toWorkerHandle(state);
2929
- }
2930
- getWorkers() {
2931
- const out = /* @__PURE__ */ new Map();
2932
- for (const [id, state] of this.workers) {
2933
- out.set(id, this.toWorkerHandle(state));
2934
- }
2935
- return out;
2936
- }
2937
- async publishEvent(channel, payload) {
2938
- const handlers = this.subscribers.get(channel);
2939
- if (!handlers) return;
2940
- await Promise.all(Array.from(handlers).map(async (h) => h(payload)));
2941
- }
2942
- async subscribeEvent(channel, handler) {
2943
- const set = this.subscribers.get(channel) ?? /* @__PURE__ */ new Set();
2944
- set.add(handler);
2945
- this.subscribers.set(channel, set);
2946
- return async () => {
2947
- const current = this.subscribers.get(channel);
2948
- if (!current) return;
2949
- current.delete(handler);
2950
- if (current.size === 0) this.subscribers.delete(channel);
2951
- };
2952
- }
2953
- async shutdown() {
2954
- for (const worker of this.workers.values()) {
2955
- worker.closed = true;
2956
- if (worker.pollingTimer) {
2957
- clearInterval(worker.pollingTimer);
2958
- }
2959
- }
2960
- this.workers.clear();
2961
- this.subscribers.clear();
2962
- this.db.close();
2963
- }
2964
- // ─────────────────────────────────────────────────────────────────────────────
2965
- // Private helpers
2966
- // ─────────────────────────────────────────────────────────────────────────────
2967
- rowToSearchResult(row) {
2968
- return {
2969
- id: row.id,
2970
- name: row.name,
2971
- queue: row.queue,
2972
- status: row.status,
2973
- input: JSON.parse(row.input),
2974
- result: row.result ? JSON.parse(row.result) : void 0,
2975
- error: row.error ?? void 0,
2976
- progress: row.progress,
2977
- attemptsMade: row.attempts_made,
2978
- priority: row.priority,
2979
- createdAt: new Date(row.created_at),
2980
- startedAt: row.started_at ? new Date(row.started_at) : void 0,
2981
- completedAt: row.completed_at ? new Date(row.completed_at) : void 0,
2982
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
2983
- scope: row.scope ? JSON.parse(row.scope) : void 0
2984
- };
2985
- }
2986
- toWorkerHandle(worker) {
2987
- return {
2988
- id: worker.id,
2989
- queues: worker.queues,
2990
- pause: async () => {
2991
- worker.paused = true;
2992
- },
2993
- resume: async () => {
2994
- worker.paused = false;
2995
- },
2996
- close: async () => {
2997
- worker.closed = true;
2998
- if (worker.pollingTimer) {
2999
- clearInterval(worker.pollingTimer);
3000
- }
3001
- },
3002
- isRunning: () => !worker.closed && !worker.paused,
3003
- isPaused: () => worker.paused,
3004
- isClosed: () => worker.closed,
3005
- getMetrics: async () => this.toWorkerMetrics(worker)
3006
- };
3007
- }
3008
- toWorkerMetrics(worker) {
3009
- const uptime = Date.now() - worker.startedAt.getTime();
3010
- const processed = worker.metrics.processed;
3011
- return {
3012
- processed,
3013
- failed: worker.metrics.failed,
3014
- avgDuration: processed > 0 ? worker.metrics.totalDuration / processed : 0,
3015
- concurrency: worker.concurrency,
3016
- uptime
3017
- };
3018
- }
3019
- startPollingLoop(worker) {
3020
- const poll = () => {
3021
- if (worker.closed || worker.paused) return;
3022
- void this.processNextJobs(worker);
3023
- };
3024
- poll();
3025
- worker.pollingTimer = setInterval(poll, this.options.pollingInterval);
3026
- }
3027
- async processNextJobs(worker) {
3028
- if (worker.closed || worker.paused) return;
3029
- const availableSlots = worker.concurrency - worker.activeJobs;
3030
- if (availableSlots <= 0) return;
3031
- const queueFilter = worker.queues.length > 0 ? `queue IN (${worker.queues.map(() => "?").join(", ")})` : "1=1";
3032
- const params = worker.queues.length > 0 ? [...worker.queues, availableSlots] : [availableSlots];
3033
- const rows = this.db.prepare(`
3034
- SELECT * FROM jobs
3035
- WHERE status = 'waiting' AND ${queueFilter}
3036
- ORDER BY priority DESC, created_at ASC
3037
- LIMIT ?
3038
- `).all(...params);
3039
- for (const row of rows) {
3040
- if (worker.closed || worker.paused) break;
3041
- if (worker.activeJobs >= worker.concurrency) break;
3042
- const claimed = this.db.prepare(`
3043
- UPDATE jobs SET status = 'active', started_at = ?
3044
- WHERE id = ? AND status = 'waiting'
3045
- `).run((/* @__PURE__ */ new Date()).toISOString(), row.id);
3046
- if (claimed.changes === 0) continue;
3047
- worker.activeJobs++;
3048
- void this.processJob(worker, row.id).finally(() => {
3049
- worker.activeJobs--;
3050
- if (worker.handlers?.onIdle && worker.activeJobs === 0) {
3051
- void worker.handlers.onIdle();
3052
- }
3053
- });
3054
- }
3055
- }
3056
- async processJob(worker, jobId) {
3057
- const row = this.db.prepare("SELECT * FROM jobs WHERE id = ?").get(jobId);
3058
- if (!row) return;
3059
- const job = this.rowToSearchResult(row);
3060
- this.addJobLog(jobId, "info", "Job started");
3061
- if (worker.handlers?.onActive) {
3062
- await worker.handlers.onActive({ job });
3063
- }
3064
- const start = Date.now();
3065
- try {
3066
- const definition = this.registeredJobs.get(row.queue)?.get(row.name);
3067
- if (!definition) {
3068
- throw new IgniterJobsError({
3069
- code: "JOBS_NOT_REGISTERED",
3070
- message: `Job "${row.name}" is not registered for queue "${row.queue}".`
3071
- });
3072
- }
3073
- this.db.prepare("UPDATE jobs SET attempts_made = attempts_made + 1 WHERE id = ?").run(jobId);
3074
- if (definition.onStart) {
3075
- await definition.onStart({
3076
- input: job.input,
3077
- context: {},
3078
- job: {
3079
- id: job.id,
3080
- name: job.name,
3081
- queue: job.queue,
3082
- attemptsMade: job.attemptsMade + 1,
3083
- metadata: job.metadata
3084
- },
3085
- scope: job.scope,
3086
- startedAt: /* @__PURE__ */ new Date()
3087
- });
3088
- }
3089
- const result = await definition.handler({
3090
- input: job.input,
3091
- context: {},
3092
- job: {
3093
- id: job.id,
3094
- name: job.name,
3095
- queue: job.queue,
3096
- attemptsMade: job.attemptsMade + 1,
3097
- metadata: job.metadata
3098
- },
3099
- scope: job.scope
3100
- });
3101
- const duration = Date.now() - start;
3102
- this.db.prepare(`
3103
- UPDATE jobs SET status = 'completed', completed_at = ?, result = ?, progress = 100
3104
- WHERE id = ?
3105
- `).run((/* @__PURE__ */ new Date()).toISOString(), JSON.stringify(result), jobId);
3106
- this.addJobLog(jobId, "info", `Job completed in ${duration}ms`);
3107
- worker.metrics.processed++;
3108
- worker.metrics.totalDuration += duration;
3109
- if (definition.onSuccess) {
3110
- await definition.onSuccess({
3111
- input: job.input,
3112
- context: {},
3113
- job: {
3114
- id: job.id,
3115
- name: job.name,
3116
- queue: job.queue,
3117
- attemptsMade: job.attemptsMade + 1,
3118
- metadata: job.metadata
3119
- },
3120
- scope: job.scope,
3121
- result,
3122
- duration
3123
- });
3124
- }
3125
- if (worker.handlers?.onSuccess) {
3126
- const updatedJob = await this.getJob(jobId);
3127
- if (updatedJob) {
3128
- await worker.handlers.onSuccess({ job: updatedJob, result });
3129
- }
3130
- }
3131
- } catch (error) {
3132
- const errorMessage = error?.message ?? String(error);
3133
- this.addJobLog(jobId, "error", errorMessage);
3134
- const current = this.db.prepare(
3135
- "SELECT attempts_made, max_attempts FROM jobs WHERE id = ?"
3136
- ).get(jobId);
3137
- const isFinalAttempt = (current?.attempts_made ?? 0) >= (current?.max_attempts ?? 1);
3138
- if (isFinalAttempt) {
3139
- this.db.prepare(`
3140
- UPDATE jobs SET status = 'failed', error = ?, completed_at = ?
3141
- WHERE id = ?
3142
- `).run(errorMessage, (/* @__PURE__ */ new Date()).toISOString(), jobId);
3143
- worker.metrics.failed++;
3144
- const definition = this.registeredJobs.get(row.queue)?.get(row.name);
3145
- if (definition?.onFailure) {
3146
- await definition.onFailure({
3147
- input: job.input,
3148
- context: {},
3149
- job: {
3150
- id: job.id,
3151
- name: job.name,
3152
- queue: job.queue,
3153
- attemptsMade: current?.attempts_made ?? 1,
3154
- metadata: job.metadata
3155
- },
3156
- scope: job.scope,
3157
- error,
3158
- isFinalAttempt: true
3159
- });
3160
- }
3161
- if (worker.handlers?.onFailure) {
3162
- const updatedJob = await this.getJob(jobId);
3163
- if (updatedJob) {
3164
- await worker.handlers.onFailure({ job: updatedJob, error });
3165
- }
3166
- }
3167
- } else {
3168
- this.db.prepare("UPDATE jobs SET status = 'waiting' WHERE id = ?").run(jobId);
3169
- }
3170
- }
3171
- }
3172
- addJobLog(jobId, level, message) {
3173
- this.db.prepare(`
3174
- INSERT INTO job_logs (job_id, timestamp, level, message)
3175
- VALUES (?, ?, ?, ?)
3176
- `).run(jobId, (/* @__PURE__ */ new Date()).toISOString(), level, message);
3177
- }
3178
- };
3179
1348
 
3180
- export { IGNITER_JOBS_ERROR_CODES, IgniterJobs, IgniterJobsBuilder, IgniterJobsBullMQAdapter, IgniterJobsError, IgniterJobsManager, IgniterJobsMemoryAdapter, IgniterJobsSQLiteAdapter, IgniterQueue, IgniterQueueBuilder, IgniterWorkerBuilder };
1349
+ export { IGNITER_JOBS_ERROR_CODES, IgniterJobs, IgniterJobsBuilder, IgniterJobsError, IgniterJobsManager, IgniterQueue, IgniterQueueBuilder, IgniterWorkerBuilder };
3181
1350
  //# sourceMappingURL=index.mjs.map
3182
1351
  //# sourceMappingURL=index.mjs.map