@seta-labs/nestjs-bullmq 0.0.0-stage → 0.1.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.
Files changed (41) hide show
  1. package/README.md +129 -2
  2. package/dist/bullmq.constants.d.ts +8 -0
  3. package/dist/bullmq.constants.js +9 -0
  4. package/dist/bullmq.constants.js.map +1 -0
  5. package/dist/events/job-events.service.d.ts +32 -0
  6. package/dist/events/job-events.service.js +117 -0
  7. package/dist/events/job-events.service.js.map +1 -0
  8. package/dist/events/queue-events.module.d.ts +9 -0
  9. package/dist/events/queue-events.module.js +28 -0
  10. package/dist/events/queue-events.module.js.map +1 -0
  11. package/dist/index.d.ts +8 -0
  12. package/dist/index.js +6 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/metrics/prometheus.util.d.ts +7 -0
  15. package/dist/metrics/prometheus.util.js +23 -0
  16. package/dist/metrics/prometheus.util.js.map +1 -0
  17. package/dist/metrics/queue-metrics.controller.d.ts +6 -0
  18. package/dist/metrics/queue-metrics.controller.js +49 -0
  19. package/dist/metrics/queue-metrics.controller.js.map +1 -0
  20. package/dist/metrics/queue-metrics.module.d.ts +10 -0
  21. package/dist/metrics/queue-metrics.module.js +42 -0
  22. package/dist/metrics/queue-metrics.module.js.map +1 -0
  23. package/dist/metrics/queue-metrics.service.d.ts +18 -0
  24. package/dist/metrics/queue-metrics.service.js +77 -0
  25. package/dist/metrics/queue-metrics.service.js.map +1 -0
  26. package/dist/queue-defaults.util.d.ts +14 -0
  27. package/dist/queue-defaults.util.js +26 -0
  28. package/dist/queue-defaults.util.js.map +1 -0
  29. package/dist/types/observed-worker.type.d.ts +12 -0
  30. package/dist/types/observed-worker.type.js +2 -0
  31. package/dist/types/observed-worker.type.js.map +1 -0
  32. package/dist/types/queue-events-options.type.d.ts +17 -0
  33. package/dist/types/queue-events-options.type.js +2 -0
  34. package/dist/types/queue-events-options.type.js.map +1 -0
  35. package/dist/types/queue-metrics-options.type.d.ts +13 -0
  36. package/dist/types/queue-metrics-options.type.js +2 -0
  37. package/dist/types/queue-metrics-options.type.js.map +1 -0
  38. package/dist/types/queue-snapshot.type.d.ts +11 -0
  39. package/dist/types/queue-snapshot.type.js +2 -0
  40. package/dist/types/queue-snapshot.type.js.map +1 -0
  41. package/package.json +49 -5
package/README.md CHANGED
@@ -1,3 +1,130 @@
1
- # Temporary Holding Version
1
+ # @seta-labs/nestjs-bullmq
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ BullMQ queues for NestJS apps, the same in every repository:
4
+
5
+ - `queueDefaults()` / `workerDefaults()`: the job and worker options of a queue that sets none;
6
+ - `QueueEventsModule`: one log line per job outcome and a per-minute summary per queue;
7
+ - `QueueMetricsModule`: `GET /metrics`, the queues in the Prometheus text format, read by the cluster's Alloy through a `PodMonitor`.
8
+
9
+ The app keeps creating its queues and workers as it does today (`new Queue`, `new Worker`, `@nestjs/bullmq`): the package hooks onto them.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pnpm add @seta-labs/nestjs-bullmq
15
+ ```
16
+
17
+ Peer dependencies: `@nestjs/common`, `@nestjs/core`, `@nestjs/swagger`, `bullmq` 6.
18
+
19
+ ## Options
20
+
21
+ ```ts
22
+ import { queueDefaults, workerDefaults } from '@seta-labs/nestjs-bullmq';
23
+
24
+ const queue = new Queue('emails', {
25
+ connection,
26
+ defaultJobOptions: queueDefaults({ attempts: 5 }),
27
+ });
28
+ const worker = new Worker('emails', process, workerDefaults({ connection, concurrency: 4 }));
29
+ ```
30
+
31
+ - `queueDefaults`: 3 attempts with exponential backoff from 1 s; completed jobs kept 1 day (at most 1,000), failed ones 7 days (at most 5,000). A field the app passes wins.
32
+ - `workerDefaults`: `metrics` on, one week of per-minute points. Without `metrics` the counters `/metrics` reads stay at 0, and the `JobEventsService` warns at `observe`.
33
+
34
+ A repository adopting the package keeps the values it already has: the defaults fill only what is unset.
35
+
36
+ ## Outcome logs
37
+
38
+ ```ts
39
+ // worker role module
40
+ QueueEventsModule.forRoot({
41
+ rescheduledErrors: ['BlockedError'], // lost, but the processor rescheduled them: warn, not error
42
+ stopMessage: 'Job stopped by user', // a stop asked by a person: an outcome, not a failure
43
+ subjectOf: (data) => ({ orderId: (data as OrderJob).orderId }),
44
+ }),
45
+
46
+ // where the worker is created
47
+ constructor(private readonly events: JobEventsService) {}
48
+ this.events.observe(worker);
49
+ ```
50
+
51
+ | Event | Level | Message |
52
+ | ---------------------------------------------- | ------- | ----------------------------------------------------------------------- |
53
+ | failed attempt, a retry follows | `warn` | `job attempt failed, retrying` |
54
+ | failed with no attempt left, rescheduled error | `warn` | `job failed, no retry left` |
55
+ | failed with no attempt left, any other error | `error` | `job failed, no retry left` |
56
+ | stopped by a person (`stopMessage`) | `info` | `job stopped by user` |
57
+ | stalled, requeued by BullMQ | `warn` | `job stalled, requeued` |
58
+ | worker connection error | `error` | `worker connection failed` |
59
+ | every minute, per queue that ran something | `info` | `queue jobs summary` (`queue`, `completed`, `retried`, `lost`, `maxMs`) |
60
+
61
+ `observe` attaches the `error` handler too: remove the app's own, or the line is logged twice. An `UnrecoverableError` is lost at its first attempt.
62
+
63
+ ## `/metrics`
64
+
65
+ ```ts
66
+ // the module of ONE headless role (scheduler, worker) served on its health port
67
+ QueueMetricsModule.forRoot({
68
+ connection: redisConnection(env),
69
+ queues: ['emails', 'reports'],
70
+ decorators: [Public()], // only with a global guard
71
+ }),
72
+ ```
73
+
74
+ | Series | Type | |
75
+ | ----------------------------------- | ------- | -------------------------------------------------------------------------------------------------------- |
76
+ | `bullmq_job_count{queue,state}` | gauge | jobs per state: `waiting`, `active`, `delayed`, `prioritized`, `waiting-children`, `completed`, `failed` |
77
+ | `bullmq_job_completed_total{queue}` | counter | jobs completed since the queue exists |
78
+ | `bullmq_job_failed_total{queue}` | counter | jobs failed with no attempt left (a retried attempt is not counted) |
79
+ | `bullmq_queue_paused{queue}` | gauge | `1` while the queue is paused |
80
+
81
+ - The counters live in Redis: the same whichever pod reads them, and they survive restarts. Serve `/metrics` from one role, and write the alerts with `max by`, so a second replica cannot double them.
82
+ - Never on a port an ingress publishes: the scrape needs no auth. A role without such a port (an app with the api pod only) gets one before it gets `/metrics`.
83
+ - Redis not answering within `timeoutMs` (default 5 s) is a 503: the scrape fails, `up` turns 0.
84
+ - `/metrics` is left out of the OpenAPI document and of the request log (`@seta-labs/nestjs-logging` ≥ 0.5.1 ignores it like the health probes).
85
+
86
+ ```yaml
87
+ # k8s/base/queue-metrics.yaml
88
+ apiVersion: monitoring.coreos.com/v1
89
+ kind: PodMonitor
90
+ metadata:
91
+ name: queue-metrics
92
+ labels:
93
+ app.kubernetes.io/name: my-app
94
+ app.kubernetes.io/component: metrics
95
+ app.kubernetes.io/part-of: my-app
96
+ spec:
97
+ selector:
98
+ matchLabels:
99
+ app.kubernetes.io/name: my-app
100
+ app.kubernetes.io/component: scheduler
101
+ podMetricsEndpoints:
102
+ - port: health # the named containerPort of HEALTH_PORT
103
+ path: /api/metrics # the app's global prefix, if any
104
+ interval: 60s
105
+ ```
106
+
107
+ ## Alerts
108
+
109
+ A `PrometheusRule` with `seta.io/alerts: 'true'` reaches the Grafana Cloud ruler through the alloy-ruler of seta-infra. Alert names carry their threshold.
110
+
111
+ ```yaml
112
+ - alert: QueueJobsFailingAbove5pct1h # severity: warning; 30pct1h with severity: critical
113
+ expr: |
114
+ max by (namespace, queue) (increase(bullmq_job_failed_total[1h])) / (max by (namespace, queue) (increase(bullmq_job_failed_total[1h])) + max by (namespace, queue) (increase(bullmq_job_completed_total[1h]))) > 0.05
115
+ and
116
+ max by (namespace, queue) (increase(bullmq_job_failed_total[1h])) >= 10
117
+ for: 15m
118
+ - alert: QueueStalled30m # jobs waiting, none running or completing, queue not paused
119
+ expr: |
120
+ max by (namespace, queue) (bullmq_job_count{state=~"waiting|prioritized"}) > 0
121
+ and
122
+ max by (namespace, queue) (bullmq_job_count{state="active"}) == 0
123
+ and
124
+ max by (namespace, queue) (increase(bullmq_job_completed_total[30m])) == 0
125
+ and
126
+ max by (namespace, queue) (bullmq_queue_paused) == 0
127
+ for: 15m
128
+ ```
129
+
130
+ The minimum of 10 failed jobs keeps a low-volume queue from crossing 5 % on one or two failures; tune it to the queue's volume. `QueueStalled30m` sees a queue nobody consumes (worker down, concurrency 0), not a job stuck while active.
@@ -0,0 +1,8 @@
1
+ export declare const QUEUE_EVENTS_OPTIONS: unique symbol;
2
+ export declare const QUEUE_METRICS_OPTIONS: unique symbol;
3
+ /** The `Queue` instances `/metrics` reads, one per configured name. */
4
+ export declare const QUEUE_METRICS_QUEUES: unique symbol;
5
+ export declare const DEFAULT_SUMMARY_INTERVAL_MS = 60000;
6
+ export declare const DEFAULT_METRICS_TIMEOUT_MS = 5000;
7
+ /** Prometheus text exposition format, version 0.0.4. */
8
+ export declare const PROMETHEUS_CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8";
@@ -0,0 +1,9 @@
1
+ export const QUEUE_EVENTS_OPTIONS = Symbol('QUEUE_EVENTS_OPTIONS');
2
+ export const QUEUE_METRICS_OPTIONS = Symbol('QUEUE_METRICS_OPTIONS');
3
+ /** The `Queue` instances `/metrics` reads, one per configured name. */
4
+ export const QUEUE_METRICS_QUEUES = Symbol('QUEUE_METRICS_QUEUES');
5
+ export const DEFAULT_SUMMARY_INTERVAL_MS = 60_000;
6
+ export const DEFAULT_METRICS_TIMEOUT_MS = 5_000;
7
+ /** Prometheus text exposition format, version 0.0.4. */
8
+ export const PROMETHEUS_CONTENT_TYPE = 'text/plain; version=0.0.4; charset=utf-8';
9
+ //# sourceMappingURL=bullmq.constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bullmq.constants.js","sourceRoot":"","sources":["../src/bullmq.constants.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,oBAAoB,GAAG,MAAM,CAAC,sBAAsB,CAAC,CAAC;AAEnE,MAAM,CAAC,MAAM,qBAAqB,GAAG,MAAM,CAAC,uBAAuB,CAAC,CAAC;AAErE,uEAAuE;AACvE,MAAM,CAAC,MAAM,oBAAoB,GAAG,MAAM,CAAC,sBAAsB,CAAC,CAAC;AAEnE,MAAM,CAAC,MAAM,2BAA2B,GAAG,MAAM,CAAC;AAElD,MAAM,CAAC,MAAM,0BAA0B,GAAG,KAAK,CAAC;AAEhD,wDAAwD;AACxD,MAAM,CAAC,MAAM,uBAAuB,GAAG,0CAA0C,CAAC"}
@@ -0,0 +1,32 @@
1
+ import { type OnModuleDestroy } from '@nestjs/common';
2
+ import type { ObservedWorker } from '../types/observed-worker.type.js';
3
+ import type { QueueEventsOptions } from '../types/queue-events-options.type.js';
4
+ /**
5
+ * Logs the outcome events of the BullMQ workers it observes, so a job that
6
+ * fails leaves a line whatever its processor caught, and sums up each queue
7
+ * once a minute so a queue that only succeeds is still visible.
8
+ */
9
+ export declare class JobEventsService implements OnModuleDestroy {
10
+ private readonly options;
11
+ private readonly logger;
12
+ private readonly tallies;
13
+ private readonly rescheduled;
14
+ private timer?;
15
+ constructor(options?: QueueEventsOptions);
16
+ /** Attaches the outcome, stall and connection handlers of one worker. */
17
+ observe(worker: ObservedWorker): void;
18
+ onModuleDestroy(): void;
19
+ private tallyOf;
20
+ private countCompleted;
21
+ /** One line per queue that ran something since the previous summary. */
22
+ private logSummaries;
23
+ /**
24
+ * One line per failed attempt. BullMQ emits `failed` on every attempt and
25
+ * sets `finishedOn` only when the job is lost (attempts spent,
26
+ * `UnrecoverableError`, a backoff that gives up): until then a retry
27
+ * follows (`warn`). A lost job is an `error` only when nothing redoes it:
28
+ * the errors the processor rescheduled are a `warn`. A stop asked by a
29
+ * person is an outcome, not a failure.
30
+ */
31
+ private logFailure;
32
+ }
@@ -0,0 +1,117 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ var JobEventsService_1;
14
+ import { Inject, Injectable, Logger, Optional } from '@nestjs/common';
15
+ import { DEFAULT_SUMMARY_INTERVAL_MS, QUEUE_EVENTS_OPTIONS } from '../bullmq.constants.js';
16
+ function emptyTally() {
17
+ return { completed: 0, retried: 0, lost: 0, maxMs: 0 };
18
+ }
19
+ /**
20
+ * Logs the outcome events of the BullMQ workers it observes, so a job that
21
+ * fails leaves a line whatever its processor caught, and sums up each queue
22
+ * once a minute so a queue that only succeeds is still visible.
23
+ */
24
+ let JobEventsService = JobEventsService_1 = class JobEventsService {
25
+ options;
26
+ logger = new Logger(JobEventsService_1.name);
27
+ tallies = new Map();
28
+ rescheduled;
29
+ timer;
30
+ constructor(options = {}) {
31
+ this.options = options;
32
+ this.rescheduled = new Set(options.rescheduledErrors ?? []);
33
+ }
34
+ /** Attaches the outcome, stall and connection handlers of one worker. */
35
+ observe(worker) {
36
+ if (!worker.opts.metrics)
37
+ this.logger.warn({ queue: worker.name }, 'worker without metrics: its completed and failed counters stay at 0');
38
+ this.tallies.set(worker.name, emptyTally());
39
+ worker.on('completed', (job) => this.countCompleted(worker.name, job));
40
+ worker.on('failed', (job, err) => this.logFailure(worker.name, job, err));
41
+ worker.on('stalled', (jobId) => this.logger.warn({ queue: worker.name, jobId }, 'job stalled, requeued'));
42
+ worker.on('error', (err) => this.logger.error({ err, queue: worker.name }, 'worker connection failed'));
43
+ this.timer ??= setInterval(() => this.logSummaries(), this.options.summaryIntervalMs ?? DEFAULT_SUMMARY_INTERVAL_MS).unref();
44
+ }
45
+ onModuleDestroy() {
46
+ clearInterval(this.timer);
47
+ this.timer = undefined;
48
+ this.logSummaries();
49
+ }
50
+ tallyOf(queue) {
51
+ let tally = this.tallies.get(queue);
52
+ if (!tally) {
53
+ tally = emptyTally();
54
+ this.tallies.set(queue, tally);
55
+ }
56
+ return tally;
57
+ }
58
+ countCompleted(queue, job) {
59
+ const tally = this.tallyOf(queue);
60
+ tally.completed += 1;
61
+ if (job.processedOn && job.finishedOn)
62
+ tally.maxMs = Math.max(tally.maxMs, job.finishedOn - job.processedOn);
63
+ }
64
+ /** One line per queue that ran something since the previous summary. */
65
+ logSummaries() {
66
+ for (const [queue, tally] of this.tallies) {
67
+ if (tally.completed + tally.retried + tally.lost === 0)
68
+ continue;
69
+ this.logger.log({ queue, ...tally }, 'queue jobs summary');
70
+ this.tallies.set(queue, emptyTally());
71
+ }
72
+ }
73
+ /**
74
+ * One line per failed attempt. BullMQ emits `failed` on every attempt and
75
+ * sets `finishedOn` only when the job is lost (attempts spent,
76
+ * `UnrecoverableError`, a backoff that gives up): until then a retry
77
+ * follows (`warn`). A lost job is an `error` only when nothing redoes it:
78
+ * the errors the processor rescheduled are a `warn`. A stop asked by a
79
+ * person is an outcome, not a failure.
80
+ */
81
+ logFailure(queue, job, err) {
82
+ const attempts = job?.opts.attempts ?? 1;
83
+ const attemptsMade = job?.attemptsMade ?? attempts;
84
+ const fields = {
85
+ queue,
86
+ jobId: job?.id,
87
+ attemptsMade,
88
+ attempts,
89
+ errorName: err.name,
90
+ ...(job ? this.options.subjectOf?.(job.data) : undefined),
91
+ };
92
+ if (this.options.stopMessage && err.message === this.options.stopMessage) {
93
+ this.logger.log(fields, 'job stopped by user');
94
+ return;
95
+ }
96
+ const tally = this.tallyOf(queue);
97
+ const isLost = !job || Boolean(job.finishedOn);
98
+ if (!isLost) {
99
+ tally.retried += 1;
100
+ this.logger.warn({ err, ...fields }, 'job attempt failed, retrying');
101
+ return;
102
+ }
103
+ tally.lost += 1;
104
+ if (this.rescheduled.has(err.name))
105
+ this.logger.warn({ err, ...fields }, 'job failed, no retry left');
106
+ else
107
+ this.logger.error({ err, ...fields }, 'job failed, no retry left');
108
+ }
109
+ };
110
+ JobEventsService = JobEventsService_1 = __decorate([
111
+ Injectable(),
112
+ __param(0, Optional()),
113
+ __param(0, Inject(QUEUE_EVENTS_OPTIONS)),
114
+ __metadata("design:paramtypes", [Object])
115
+ ], JobEventsService);
116
+ export { JobEventsService };
117
+ //# sourceMappingURL=job-events.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"job-events.service.js","sourceRoot":"","sources":["../../src/events/job-events.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAwB,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAG5F,OAAO,EAAE,2BAA2B,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAY3F,SAAS,UAAU;IACf,OAAO,EAAE,SAAS,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC;AAC3D,CAAC;AAED;;;;GAIG;AAEI,IAAM,gBAAgB,wBAAtB,MAAM,gBAAgB;IASJ;IARJ,MAAM,GAAG,IAAI,MAAM,CAAC,kBAAgB,CAAC,IAAI,CAAC,CAAC;IAC3C,OAAO,GAAG,IAAI,GAAG,EAAsB,CAAC;IACxC,WAAW,CAAsB;IAC1C,KAAK,CAAkB;IAE/B,YAGqB,UAA8B,EAAE;QAAhC,YAAO,GAAP,OAAO,CAAyB;QAEjD,IAAI,CAAC,WAAW,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,iBAAiB,IAAI,EAAE,CAAC,CAAC;IAChE,CAAC;IAED,yEAAyE;IACzE,OAAO,CAAC,MAAsB;QAC1B,IAAI,CAAC,MA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;IAC5E,CAAC;CACJ,CAAA;AAtGY,gBAAgB;IAD5B,UAAU,EAAE;IAQJ,WAAA,QAAQ,EAAE,CAAA;IACV,WAAA,MAAM,CAAC,oBAAoB,CAAC,CAAA;;GARxB,gBAAgB,CAsG5B"}
@@ -0,0 +1,9 @@
1
+ import { type DynamicModule } from '@nestjs/common';
2
+ import type { QueueEventsOptions } from '../types/queue-events-options.type.js';
3
+ /**
4
+ * `JobEventsService`, for the roles that run workers: pass each worker to
5
+ * `observe` right after creating it.
6
+ */
7
+ export declare class QueueEventsModule {
8
+ static forRoot(options?: QueueEventsOptions): DynamicModule;
9
+ }
@@ -0,0 +1,28 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var QueueEventsModule_1;
8
+ import { Module } from '@nestjs/common';
9
+ import { QUEUE_EVENTS_OPTIONS } from '../bullmq.constants.js';
10
+ import { JobEventsService } from './job-events.service.js';
11
+ /**
12
+ * `JobEventsService`, for the roles that run workers: pass each worker to
13
+ * `observe` right after creating it.
14
+ */
15
+ let QueueEventsModule = QueueEventsModule_1 = class QueueEventsModule {
16
+ static forRoot(options = {}) {
17
+ return {
18
+ module: QueueEventsModule_1,
19
+ providers: [{ provide: QUEUE_EVENTS_OPTIONS, useValue: options }, JobEventsService],
20
+ exports: [JobEventsService],
21
+ };
22
+ }
23
+ };
24
+ QueueEventsModule = QueueEventsModule_1 = __decorate([
25
+ Module({})
26
+ ], QueueEventsModule);
27
+ export { QueueEventsModule };
28
+ //# sourceMappingURL=queue-events.module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queue-events.module.js","sourceRoot":"","sources":["../../src/events/queue-events.module.ts"],"names":[],"mappings":";;;;;;;AAAA,OAAO,EAAsB,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAE5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAG9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAE3D;;;GAGG;AAEI,IAAM,iBAAiB,yBAAvB,MAAM,iBAAiB;IAC1B,MAAM,CAAC,OAAO,CAAC,UAA8B,EAAE;QAC3C,OAAO;YACH,MAAM,EAAE,mBAAiB;YACzB,SAAS,EAAE,CAAC,EAAE,OAAO,EAAE,oBAAoB,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,gBAAgB,CAAC;YACnF,OAAO,EAAE,CAAC,gBAAgB,CAAC;SAC9B,CAAC;IACN,CAAC;CACJ,CAAA;AARY,iBAAiB;IAD7B,MAAM,CAAC,EAAE,CAAC;GACE,iBAAiB,CAQ7B"}
@@ -0,0 +1,8 @@
1
+ export { JobEventsService } from './events/job-events.service.js';
2
+ export { QueueEventsModule } from './events/queue-events.module.js';
3
+ export { QueueMetricsModule } from './metrics/queue-metrics.module.js';
4
+ export { QueueMetricsService } from './metrics/queue-metrics.service.js';
5
+ export { queueDefaults, workerDefaults } from './queue-defaults.util.js';
6
+ export type { ObservedWorker } from './types/observed-worker.type.js';
7
+ export type { QueueEventsOptions } from './types/queue-events-options.type.js';
8
+ export type { QueueMetricsOptions } from './types/queue-metrics-options.type.js';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { JobEventsService } from './events/job-events.service.js';
2
+ export { QueueEventsModule } from './events/queue-events.module.js';
3
+ export { QueueMetricsModule } from './metrics/queue-metrics.module.js';
4
+ export { QueueMetricsService } from './metrics/queue-metrics.service.js';
5
+ export { queueDefaults, workerDefaults } from './queue-defaults.util.js';
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EAAE,kBAAkB,EAAE,MAAM,mCAAmC,CAAC;AACvE,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC"}
@@ -0,0 +1,7 @@
1
+ import type { QueueSnapshot } from '../types/queue-snapshot.type.js';
2
+ /**
3
+ * The queues in the Prometheus text format, one block per metric family:
4
+ * the names of BullMQ's own `exportPrometheusMetrics`, plus
5
+ * `bullmq_queue_paused`, which tells an idle queue from a paused one.
6
+ */
7
+ export declare function renderPrometheus(snapshots: QueueSnapshot[]): string;
@@ -0,0 +1,23 @@
1
+ /** Label value escaping of the text exposition format: backslash, quote, newline. */
2
+ function escapeLabel(value) {
3
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
4
+ }
5
+ function family(name, type, help, samples) {
6
+ return [`# HELP ${name} ${help}`, `# TYPE ${name} ${type}`, ...samples];
7
+ }
8
+ /**
9
+ * The queues in the Prometheus text format, one block per metric family:
10
+ * the names of BullMQ's own `exportPrometheusMetrics`, plus
11
+ * `bullmq_queue_paused`, which tells an idle queue from a paused one.
12
+ */
13
+ export function renderPrometheus(snapshots) {
14
+ const queue = (snapshot) => `queue="${escapeLabel(snapshot.name)}"`;
15
+ const lines = [
16
+ ...family('bullmq_job_count', 'gauge', 'Number of jobs in the queue by state', snapshots.flatMap((snapshot) => Object.entries(snapshot.counts).map(([state, count]) => `bullmq_job_count{${queue(snapshot)},state="${escapeLabel(state)}"} ${count}`))),
17
+ ...family('bullmq_job_completed_total', 'counter', 'Total number of completed jobs', snapshots.map((snapshot) => `bullmq_job_completed_total{${queue(snapshot)}} ${snapshot.completed}`)),
18
+ ...family('bullmq_job_failed_total', 'counter', 'Total number of jobs failed with no attempt left', snapshots.map((snapshot) => `bullmq_job_failed_total{${queue(snapshot)}} ${snapshot.failed}`)),
19
+ ...family('bullmq_queue_paused', 'gauge', 'Whether the queue is paused (1) or not (0)', snapshots.map((snapshot) => `bullmq_queue_paused{${queue(snapshot)}} ${snapshot.isPaused ? 1 : 0}`)),
20
+ ];
21
+ return `${lines.join('\n')}\n`;
22
+ }
23
+ //# sourceMappingURL=prometheus.util.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prometheus.util.js","sourceRoot":"","sources":["../../src/metrics/prometheus.util.ts"],"names":[],"mappings":"AAEA,qFAAqF;AACrF,SAAS,WAAW,CAAC,KAAa;IAC9B,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AACnF,CAAC;AAED,SAAS,MAAM,CACX,IAAY,EACZ,IAAyB,EACzB,IAAY,EACZ,OAAiB;IAEjB,OAAO,CAAC,UAAU,IAAI,IAAI,IAAI,EAAE,EAAE,UAAU,IAAI,IAAI,IAAI,EAAE,EAAE,GAAG,OAAO,CAAC,CAAC;AAC5E,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAAC,SAA0B;IACvD,MAAM,KAAK,GAAG,CAAC,QAAuB,EAAU,EAAE,CAAC,UAAU,WAAW,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC;IAC3F,MAAM,KAAK,GAAG;QACV,GAAG,MAAM,CACL,kBAAkB,EAClB,OAAO,EACP,sCAAsC,EACtC,SAAS,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE,CAC3B,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,GAAG,CAC/B,CAAC,CAAC,KAAK,EAAE,KAAK,CAAC,EAAE,EAAE,CACf,oBAAoB,KAAK,CAAC,QAAQ,CAAC,WAAW,WAAW,CAAC,KAAK,CAAC,MAAM,KAAK,EAAE,CACpF,CACJ,CACJ;QACD,GAAG,MAAM,CACL,4BAA4B,EAC5B,SAAS,EACT,gCAAgC,EAChC,SAAS,CAAC,GAAG,CACT,CAAC,QAAQ,EAAE,EAAE,CACT,8BAA8B,KAAK,CAAC,QAAQ,CAAC,KAAK,QAAQ,CAAC,SAAS,EAAE,CAC7E,CACJ;QACD,GAAG,MAAM,CACL,yBAAyB,EACzB,SAAS,EACT,kDAAkD,EAClD,SAAS,CAAC,GAAG,CACT,CAAC,QAAQ,EAAE,EAAE,CAAC,2BAA2B,KAAK,CAAC,QAAQ,CAAC,KAAK,QAAQ,CAAC,MAAM,EAAE,CACjF,CACJ;QACD,GAAG,MAAM,CACL,qBAAqB,EACrB,OAAO,EACP,4CAA4C,EAC5C,SAAS,CAAC,GAAG,CACT,CAAC,QAAQ,EAAE,EAAE,CACT,uBAAuB,KAAK,CAAC,QAAQ,CAAC,KAAK,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAC7E,CACJ;KACJ,CAAC;IACF,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;AACnC,CAAC"}
@@ -0,0 +1,6 @@
1
+ import { type Type } from '@nestjs/common';
2
+ /**
3
+ * Built per `forRoot` so the app's decorators (`Public()`) land on this app's
4
+ * controller only. Out of the OpenAPI contract: a scrape target, not an API.
5
+ */
6
+ export declare function createQueueMetricsController(decorators?: MethodDecorator[]): Type<unknown>;
@@ -0,0 +1,49 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { applyDecorators, Controller, Get, Header, Inject } from '@nestjs/common';
14
+ import { ApiExcludeController } from '@nestjs/swagger';
15
+ import { PROMETHEUS_CONTENT_TYPE } from '../bullmq.constants.js';
16
+ import { QueueMetricsService } from './queue-metrics.service.js';
17
+ /**
18
+ * Built per `forRoot` so the app's decorators (`Public()`) land on this app's
19
+ * controller only. Out of the OpenAPI contract: a scrape target, not an API.
20
+ */
21
+ export function createQueueMetricsController(decorators = []) {
22
+ const scrape = applyDecorators(...decorators);
23
+ let QueueMetricsController = class QueueMetricsController {
24
+ metrics;
25
+ constructor(metrics) {
26
+ this.metrics = metrics;
27
+ }
28
+ render() {
29
+ return this.metrics.render();
30
+ }
31
+ };
32
+ __decorate([
33
+ Get(),
34
+ scrape,
35
+ Header('Content-Type', PROMETHEUS_CONTENT_TYPE),
36
+ Header('Cache-Control', 'no-store'),
37
+ __metadata("design:type", Function),
38
+ __metadata("design:paramtypes", []),
39
+ __metadata("design:returntype", Promise)
40
+ ], QueueMetricsController.prototype, "render", null);
41
+ QueueMetricsController = __decorate([
42
+ ApiExcludeController(),
43
+ Controller('metrics'),
44
+ __param(0, Inject(QueueMetricsService)),
45
+ __metadata("design:paramtypes", [QueueMetricsService])
46
+ ], QueueMetricsController);
47
+ return QueueMetricsController;
48
+ }
49
+ //# sourceMappingURL=queue-metrics.controller.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queue-metrics.controller.js","sourceRoot":"","sources":["../../src/metrics/queue-metrics.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAa,MAAM,gBAAgB,CAAC;AAC7F,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAEvD,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAEjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAEjE;;;GAGG;AACH,MAAM,UAAU,4BAA4B,CAAC,aAAgC,EAAE;IAC3E,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,UAAU,CAAC,CAAC;IAE9C,IAEM,sBAAsB,GAF5B,MAEM,sBAAsB;QACkC;QAA1D,YAA0D,OAA4B;YAA5B,YAAO,GAAP,OAAO,CAAqB;QAAG,CAAC;QAM1F,MAAM;YACF,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;QACjC,CAAC;KACJ,CAAA;IAHG;QAJC,GAAG,EAAE;QACL,MAAM;QACN,MAAM,CAAC,cAAc,EAAE,uBAAuB,CAAC;QAC/C,MAAM,CAAC,eAAe,EAAE,UAAU,CAAC;;;;wDAGnC;IATC,sBAAsB;QAF3B,oBAAoB,EAAE;QACtB,UAAU,CAAC,SAAS,CAAC;QAEL,WAAA,MAAM,CAAC,mBAAmB,CAAC,CAAA;yCAA2B,mBAAmB;OADpF,sBAAsB,CAU3B;IAED,OAAO,sBAAsB,CAAC;AAClC,CAAC"}
@@ -0,0 +1,10 @@
1
+ import { type DynamicModule } from '@nestjs/common';
2
+ import type { QueueMetricsOptions } from '../types/queue-metrics-options.type.js';
3
+ /**
4
+ * `GET /metrics`: the configured queues in the Prometheus text format. Import
5
+ * it in a role whose port no ingress publishes (a headless role on its health
6
+ * port): the scrape needs no auth, so the route must not be public.
7
+ */
8
+ export declare class QueueMetricsModule {
9
+ static forRoot(options: QueueMetricsOptions): DynamicModule;
10
+ }
@@ -0,0 +1,42 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var QueueMetricsModule_1;
8
+ import { Module } from '@nestjs/common';
9
+ import { Queue } from 'bullmq';
10
+ import { QUEUE_METRICS_OPTIONS, QUEUE_METRICS_QUEUES } from '../bullmq.constants.js';
11
+ import { createQueueMetricsController } from './queue-metrics.controller.js';
12
+ import { QueueMetricsService } from './queue-metrics.service.js';
13
+ /**
14
+ * `GET /metrics`: the configured queues in the Prometheus text format. Import
15
+ * it in a role whose port no ingress publishes (a headless role on its health
16
+ * port): the scrape needs no auth, so the route must not be public.
17
+ */
18
+ let QueueMetricsModule = QueueMetricsModule_1 = class QueueMetricsModule {
19
+ static forRoot(options) {
20
+ return {
21
+ module: QueueMetricsModule_1,
22
+ controllers: [createQueueMetricsController(options.decorators)],
23
+ providers: [
24
+ { provide: QUEUE_METRICS_OPTIONS, useValue: options },
25
+ {
26
+ provide: QUEUE_METRICS_QUEUES,
27
+ useFactory: () => options.queues.map((name) => new Queue(name, {
28
+ connection: options.connection,
29
+ prefix: options.prefix,
30
+ })),
31
+ },
32
+ QueueMetricsService,
33
+ ],
34
+ exports: [QueueMetricsService],
35
+ };
36
+ }
37
+ };
38
+ QueueMetricsModule = QueueMetricsModule_1 = __decorate([
39
+ Module({})
40
+ ], QueueMetricsModule);
41
+ export { QueueMetricsModule };
42
+ //# sourceMappingURL=queue-metrics.module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queue-metrics.module.js","sourceRoot":"","sources":["../../src/metrics/queue-metrics.module.ts"],"names":[],"mappings":";;;;;;;AAAA,OAAO,EAAsB,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAE/B,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAGrF,OAAO,EAAE,4BAA4B,EAAE,MAAM,+BAA+B,CAAC;AAC7E,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAEjE;;;;GAIG;AAEI,IAAM,kBAAkB,0BAAxB,MAAM,kBAAkB;IAC3B,MAAM,CAAC,OAAO,CAAC,OAA4B;QACvC,OAAO;YACH,MAAM,EAAE,oBAAkB;YAC1B,WAAW,EAAE,CAAC,4BAA4B,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;YAC/D,SAAS,EAAE;gBACP,EAAE,OAAO,EAAE,qBAAqB,EAAE,QAAQ,EAAE,OAAO,EAAE;gBACrD;oBACI,OAAO,EAAE,oBAAoB;oBAC7B,UAAU,EAAE,GAAY,EAAE,CACtB,OAAO,CAAC,MAAM,CAAC,GAAG,CACd,CAAC,IAAI,EAAE,EAAE,CACL,IAAI,KAAK,CAAC,IAAI,EAAE;wBACZ,UAAU,EAAE,OAAO,CAAC,UAAU;wBAC9B,MAAM,EAAE,OAAO,CAAC,MAAM;qBACzB,CAAC,CACT;iBACR;gBACD,mBAAmB;aACtB;YACD,OAAO,EAAE,CAAC,mBAAmB,CAAC;SACjC,CAAC;IACN,CAAC;CACJ,CAAA;AAvBY,kBAAkB;IAD9B,MAAM,CAAC,EAAE,CAAC;GACE,kBAAkB,CAuB9B"}
@@ -0,0 +1,18 @@
1
+ import { type OnModuleDestroy } from '@nestjs/common';
2
+ import type { Queue } from 'bullmq';
3
+ import type { QueueMetricsOptions } from '../types/queue-metrics-options.type.js';
4
+ /** The calls `/metrics` makes on a queue. */
5
+ export type MetricsQueue = Pick<Queue, 'name' | 'getJobCounts' | 'getMetrics' | 'isPaused' | 'close'>;
6
+ /**
7
+ * Reads the configured queues for `/metrics`. The counters live in Redis and
8
+ * are the same whichever pod reads them.
9
+ */
10
+ export declare class QueueMetricsService implements OnModuleDestroy {
11
+ private readonly options;
12
+ private readonly queues;
13
+ private readonly logger;
14
+ constructor(options: QueueMetricsOptions, queues: MetricsQueue[]);
15
+ /** Every queue in the Prometheus text format; a 503 when Redis does not answer in time. */
16
+ render(): Promise<string>;
17
+ onModuleDestroy(): Promise<void>;
18
+ }
@@ -0,0 +1,77 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ var QueueMetricsService_1;
14
+ import { Inject, Injectable, Logger, ServiceUnavailableException, } from '@nestjs/common';
15
+ import { DEFAULT_METRICS_TIMEOUT_MS, QUEUE_METRICS_OPTIONS, QUEUE_METRICS_QUEUES, } from '../bullmq.constants.js';
16
+ import { renderPrometheus } from './prometheus.util.js';
17
+ async function snapshotOf(queue) {
18
+ const [counts, completed, failed, isPaused] = await Promise.all([
19
+ queue.getJobCounts(),
20
+ queue.getMetrics('completed', 0, 0),
21
+ queue.getMetrics('failed', 0, 0),
22
+ queue.isPaused(),
23
+ ]);
24
+ return {
25
+ name: queue.name,
26
+ counts,
27
+ completed: completed.meta.count,
28
+ failed: failed.meta.count,
29
+ isPaused,
30
+ };
31
+ }
32
+ /**
33
+ * Reads the configured queues for `/metrics`. The counters live in Redis and
34
+ * are the same whichever pod reads them.
35
+ */
36
+ let QueueMetricsService = QueueMetricsService_1 = class QueueMetricsService {
37
+ options;
38
+ queues;
39
+ logger = new Logger(QueueMetricsService_1.name);
40
+ constructor(options, queues) {
41
+ this.options = options;
42
+ this.queues = queues;
43
+ }
44
+ /** Every queue in the Prometheus text format; a 503 when Redis does not answer in time. */
45
+ async render() {
46
+ const timeoutMs = this.options.timeoutMs ?? DEFAULT_METRICS_TIMEOUT_MS;
47
+ let timer;
48
+ const timeout = new Promise((_, reject) => {
49
+ timer = setTimeout(() => reject(new Error(`queues not read within ${timeoutMs} ms`)), timeoutMs);
50
+ });
51
+ try {
52
+ const snapshots = await Promise.race([
53
+ Promise.all(this.queues.map(snapshotOf)),
54
+ timeout,
55
+ ]);
56
+ return renderPrometheus(snapshots);
57
+ }
58
+ catch (err) {
59
+ this.logger.warn({ err, queues: this.options.queues.length }, 'queue metrics not read');
60
+ throw new ServiceUnavailableException('Queue metrics unavailable');
61
+ }
62
+ finally {
63
+ clearTimeout(timer);
64
+ }
65
+ }
66
+ async onModuleDestroy() {
67
+ await Promise.all(this.queues.map((queue) => queue.close()));
68
+ }
69
+ };
70
+ QueueMetricsService = QueueMetricsService_1 = __decorate([
71
+ Injectable(),
72
+ __param(0, Inject(QUEUE_METRICS_OPTIONS)),
73
+ __param(1, Inject(QUEUE_METRICS_QUEUES)),
74
+ __metadata("design:paramtypes", [Object, Array])
75
+ ], QueueMetricsService);
76
+ export { QueueMetricsService };
77
+ //# sourceMappingURL=queue-metrics.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queue-metrics.service.js","sourceRoot":"","sources":["../../src/metrics/queue-metrics.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EACH,MAAM,EACN,UA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CACd,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,0BAA0B,SAAS,KAAK,CAAC,CAAC,EACjE,SAAS,CACZ,CAAC;QACN,CAAC,CAAC,CAAC;QACH,IAAI,CAAC;YACD,MAAM,SAAS,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC;gBACjC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;gBACxC,OAAO;aACV,CAAC,CAAC;YACH,OAAO,gBAAgB,CAAC,SAAS,CAAC,CAAC;QACvC,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACX,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,EAAE,wBAAwB,CAAC,CAAC;YACxF,MAAM,IAAI,2BAA2B,CAAC,2BAA2B,CAAC,CAAC;QACvE,CAAC;gBAAS,CAAC;YACP,YAAY,CAAC,KAAK,CAAC,CAAC;QACxB,CAAC;IACL,CAAC;IAED,KAAK,CAAC,eAAe;QACjB,MAAM,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;IACjE,CAAC;CACJ,CAAA;AAnCY,mBAAmB;IAD/B,UAAU,EAAE;IAKJ,WAAA,MAAM,CAAC,qBAAqB,CAAC,CAAA;IAC7B,WAAA,MAAM,CAAC,oBAAoB,CAAC,CAAA;;GALxB,mBAAmB,CAmC/B"}
@@ -0,0 +1,14 @@
1
+ import { type DefaultJobOptions, type WorkerOptions } from 'bullmq';
2
+ /**
3
+ * Job options of a queue without its own: 3 attempts, 1 s → 2 s → 4 s, the
4
+ * completed jobs kept 1 day (at most 1,000), the failed ones 7 days (at most
5
+ * 5,000) so a failure can still be read the next morning. A value the app
6
+ * passes wins, field by field.
7
+ */
8
+ export declare function queueDefaults(options?: DefaultJobOptions): DefaultJobOptions;
9
+ /**
10
+ * Worker options with the per-minute metrics on, one week of them: without
11
+ * them `bullmq_job_completed_total` and `bullmq_job_failed_total` stay at 0.
12
+ * A `metrics` the app passes wins.
13
+ */
14
+ export declare function workerDefaults(options: WorkerOptions): WorkerOptions;
@@ -0,0 +1,26 @@
1
+ import { MetricsTime } from 'bullmq';
2
+ const HOUR_S = 3_600;
3
+ /**
4
+ * Job options of a queue without its own: 3 attempts, 1 s → 2 s → 4 s, the
5
+ * completed jobs kept 1 day (at most 1,000), the failed ones 7 days (at most
6
+ * 5,000) so a failure can still be read the next morning. A value the app
7
+ * passes wins, field by field.
8
+ */
9
+ export function queueDefaults(options = {}) {
10
+ return {
11
+ attempts: 3,
12
+ backoff: { type: 'exponential', delay: 1_000 },
13
+ removeOnComplete: { age: 24 * HOUR_S, count: 1_000 },
14
+ removeOnFail: { age: 7 * 24 * HOUR_S, count: 5_000 },
15
+ ...options,
16
+ };
17
+ }
18
+ /**
19
+ * Worker options with the per-minute metrics on, one week of them: without
20
+ * them `bullmq_job_completed_total` and `bullmq_job_failed_total` stay at 0.
21
+ * A `metrics` the app passes wins.
22
+ */
23
+ export function workerDefaults(options) {
24
+ return { metrics: { maxDataPoints: MetricsTime.ONE_WEEK }, ...options };
25
+ }
26
+ //# sourceMappingURL=queue-defaults.util.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queue-defaults.util.js","sourceRoot":"","sources":["../src/queue-defaults.util.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0B,WAAW,EAAsB,MAAM,QAAQ,CAAC;AAEjF,MAAM,MAAM,GAAG,KAAK,CAAC;AAErB;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,UAA6B,EAAE;IACzD,OAAO;QACH,QAAQ,EAAE,CAAC;QACX,OAAO,EAAE,EAAE,IAAI,EAAE,aAAa,EAAE,KAAK,EAAE,KAAK,EAAE;QAC9C,gBAAgB,EAAE,EAAE,GAAG,EAAE,EAAE,GAAG,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE;QACpD,YAAY,EAAE,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,GAAG,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE;QACpD,GAAG,OAAO;KACb,CAAC;AACN,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,OAAsB;IACjD,OAAO,EAAE,OAAO,EAAE,EAAE,aAAa,EAAE,WAAW,CAAC,QAAQ,EAAE,EAAE,GAAG,OAAO,EAAE,CAAC;AAC5E,CAAC"}
@@ -0,0 +1,12 @@
1
+ import type { Job } from 'bullmq';
2
+ /** What the outcome events need of a BullMQ worker, whatever the data type of its jobs. */
3
+ export interface ObservedWorker {
4
+ readonly name: string;
5
+ readonly opts: {
6
+ readonly metrics?: unknown;
7
+ };
8
+ on(event: 'failed', listener: (job: Job | undefined, err: Error) => void): unknown;
9
+ on(event: 'completed', listener: (job: Job) => void): unknown;
10
+ on(event: 'stalled', listener: (jobId: string) => void): unknown;
11
+ on(event: 'error', listener: (err: Error) => void): unknown;
12
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=observed-worker.type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"observed-worker.type.js","sourceRoot":"","sources":["../../src/types/observed-worker.type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,17 @@
1
+ export interface QueueEventsOptions {
2
+ /**
3
+ * Error names of the lost jobs the processor already rescheduled itself:
4
+ * logged at `warn`, since nothing is lost for good. Every other lost job
5
+ * is an `error`.
6
+ */
7
+ rescheduledErrors?: string[];
8
+ /**
9
+ * Message of the error a processor throws to stop a job a person asked to
10
+ * stop: logged as an outcome at `info`, never counted as a failure.
11
+ */
12
+ stopMessage?: string;
13
+ /** Fields naming the resource of a job in its log lines, e.g. `{ orderId }`. */
14
+ subjectOf?: (data: unknown) => Record<string, unknown>;
15
+ /** How often each queue's outcomes are summed up in one line. Default `60_000`. */
16
+ summaryIntervalMs?: number;
17
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=queue-events-options.type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queue-events-options.type.js","sourceRoot":"","sources":["../../src/types/queue-events-options.type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,13 @@
1
+ import type { ConnectionOptions } from 'bullmq';
2
+ export interface QueueMetricsOptions {
3
+ /** Redis of the queues; an ioredis instance is shared by every queue read. */
4
+ connection: ConnectionOptions;
5
+ /** Names of the queues read by `/metrics`. */
6
+ queues: string[];
7
+ /** BullMQ key prefix of the queues. Default `bull`, BullMQ's own. */
8
+ prefix?: string;
9
+ /** Decorators applied to the route, e.g. the app's `Public()` when a global guard protects every route. */
10
+ decorators?: MethodDecorator[];
11
+ /** Time allowed to read every queue before the scrape fails with a 503. Default `5_000`. */
12
+ timeoutMs?: number;
13
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=queue-metrics-options.type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queue-metrics-options.type.js","sourceRoot":"","sources":["../../src/types/queue-metrics-options.type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,11 @@
1
+ /** What `/metrics` reads of one queue. */
2
+ export interface QueueSnapshot {
3
+ name: string;
4
+ /** Jobs per state, as `Queue.getJobCounts()` returns them. */
5
+ counts: Record<string, number>;
6
+ /** Jobs completed since the queue exists, from the workers' metrics. */
7
+ completed: number;
8
+ /** Jobs failed with no attempt left since the queue exists, from the workers' metrics. */
9
+ failed: number;
10
+ isPaused: boolean;
11
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=queue-snapshot.type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queue-snapshot.type.js","sourceRoot":"","sources":["../../src/types/queue-snapshot.type.ts"],"names":[],"mappings":""}
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
- "name": "@seta-labs/nestjs-bullmq",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@seta-labs/nestjs-bullmq",
3
+ "version": "0.1.0",
4
+ "description": "BullMQ queues for NestJS apps: default job and worker options, one log line per job outcome with a per-minute summary per queue, and the queue counters in the Prometheus format",
5
+ "license": "UNLICENSED",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Seta-Labs/node-common.git",
9
+ "directory": "packages/nestjs-bullmq"
10
+ },
11
+ "type": "module",
12
+ "main": "dist/index.js",
13
+ "types": "dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "scripts": {
27
+ "build": "tsc -p tsconfig.build.json",
28
+ "test": "vitest run",
29
+ "typecheck": "tsc -p tsconfig.json --noEmit"
30
+ },
31
+ "peerDependencies": {
32
+ "@nestjs/common": "^11.0.0 || ^12.0.0",
33
+ "@nestjs/core": "^11.0.0 || ^12.0.0",
34
+ "@nestjs/swagger": "^11.0.0 || ^12.0.0",
35
+ "bullmq": "^6.0.0"
36
+ },
37
+ "devDependencies": {
38
+ "@nestjs/common": "^12.3.2",
39
+ "@nestjs/core": "^12.3.2",
40
+ "@nestjs/platform-express": "^12.3.2",
41
+ "@nestjs/swagger": "^12.0.5",
42
+ "@nestjs/testing": "^12.6.3",
43
+ "@types/node": "^26.6.6",
44
+ "bullmq": "^6.7.2",
45
+ "reflect-metadata": "^0.2.2",
46
+ "rxjs": "^7.8.2",
47
+ "typescript": "^6.0.3",
48
+ "vitest": "^5.0.5"
49
+ }
50
+ }