@leoribeiroweb/nest-queue 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,9 @@
1
1
  # @leoribeiroweb/nest-queue
2
2
 
3
3
  BullMQ wiring for a NestJS service: the dual-mode Redis connection as BullMQ
4
- options, the worker lifecycle every processor repeats, deterministic job ids,
5
- and a queue health indicator.
4
+ options, the worker lifecycle every processor repeats, the producer-side queue
5
+ host every queue wrapper repeats, deterministic job ids, and a queue health
6
+ indicator.
6
7
 
7
8
  This package is part of the shared framework behind my own services. It is
8
9
  published publicly so builds need no registry credentials, but it is **not an
@@ -76,6 +77,119 @@ without a live Redis, and its disabled path, failure handler and bounded close
76
77
  would all be verified by inspection only. Pass `bullWorkerFactory` in
77
78
  production.
78
79
 
80
+ ### Worker options and event handlers
81
+
82
+ All three are optional; leaving them unset keeps the behavior above exactly.
83
+
84
+ ```ts
85
+ super({
86
+ name: NFSE_EMAIL_QUEUE,
87
+ source: configService,
88
+ logger: createLogger(NfseEmailProcessor.name),
89
+ createWorker: bullWorkerFactory,
90
+ workerOptions: limiter ? { limiter } : undefined,
91
+ onFailed: (job, error) => this.onJobFailed(job, error),
92
+ onActive: (job) => this.onJobActive(job),
93
+ });
94
+ ```
95
+
96
+ An arrow that reads `this` is legal in the `super(...)` arguments: it runs only
97
+ when BullMQ emits, long after the constructor returned.
98
+
99
+ - `workerOptions` is passed through to the BullMQ `Worker` (`limiter`,
100
+ `lockDuration`, `stalledInterval`, ...). The host's `connection` always wins;
101
+ a top-level `concurrency` wins over `workerOptions.concurrency`.
102
+ - `onFailed(job, error)` runs on every failed attempt, **after** the host's own
103
+ `<name>-job-failed` line. `job` is `undefined` when BullMQ cannot tie the
104
+ failure to a job.
105
+ - `onActive(job)` runs when a job becomes active. Without it no `active`
106
+ listener is registered.
107
+
108
+ A handler may be async. A throw or a rejection is logged as
109
+ `<name>-failed-handler-error` / `<name>-active-handler-error` and never reaches
110
+ BullMQ's emitter, where a throwing listener would be re-emitted as `'error'`
111
+ and a rejection would go unhandled.
112
+
113
+ ### Log types
114
+
115
+ `logTypes` renames any line the host emits; a key left out keeps its default.
116
+
117
+ | Key | Default | Level |
118
+ | --- | --- | --- |
119
+ | `disabled` | `<name>-worker-disabled` | warn |
120
+ | `jobFailed` | `<name>-job-failed` (meta `jobId`); `null` drops the line | error |
121
+ | `workerError` | `<name>-worker-error` | error |
122
+ | `closeFailed` | `<name>-worker-close-failed` | error / warn |
123
+ | `failedHandlerError` | `<name>-failed-handler-error` | error |
124
+ | `activeHandlerError` | `<name>-active-handler-error` | error |
125
+
126
+ It exists so a service moving an existing processor onto the host keeps the
127
+ log types its alerts read. `jobFailed: null` is for a processor whose
128
+ `onFailed` already logs the failure its own way. `workerError` can be renamed
129
+ but not dropped: without that listener BullMQ prints a raw `console.error`.
130
+
131
+ ```ts
132
+ logTypes: { disabled: 'nfse-zip-disabled', jobFailed: null, closeFailed: 'nfse-zip-worker-close-failed' },
133
+ ```
134
+
135
+ ## Queue host
136
+
137
+ The producer side every queue wrapper repeats: build the queue when Redis is
138
+ configured, stay `null` and no-op when it is not, address each job through a
139
+ deterministic id, close inside a deadline.
140
+
141
+ ```ts
142
+ @Injectable()
143
+ export class NfseQueue extends BullQueueHost<NfseJobData> {
144
+ constructor(configService: ConfigService) {
145
+ super({
146
+ name: NFSE_QUEUE, // 'nfse-emission'
147
+ logPrefix: 'nfse', // log types nfse-queue-ready, nfse-enqueue-skipped, ...
148
+ source: configService,
149
+ logger: createLogger(NfseQueue.name),
150
+ createQueue: bullQueueFactory,
151
+ queueOptions: {
152
+ defaultJobOptions: { attempts: 5, backoff: { type: 'exponential', delay: 30_000 } },
153
+ },
154
+ jobName: 'emit',
155
+ jobId: nfseJobId,
156
+ jobData: (emissionId) => ({ emissionId }),
157
+ keyLogField: 'emissionId',
158
+ });
159
+ }
160
+ }
161
+ ```
162
+
163
+ | Member | Without Redis | With Redis |
164
+ | --- | --- | --- |
165
+ | constructor | warns `<prefix>-queue-disabled` | builds the queue, logs `<prefix>-queue-ready` |
166
+ | `isConfigured()` | `false` | `true` |
167
+ | `enqueue(key, jobOptions?)` | warns `<prefix>-enqueue-skipped` with `{ [keyLogField]: key }`, resolves | `add(jobName, jobData(key), { ...jobOptions, jobId: jobId(key) })` |
168
+ | `removeJob(key)` | no-op | `remove(jobId(key))` |
169
+ | `hasLiveJob(key)` | `false` | `isLiveJobState(getJobState(jobId(key)))` |
170
+ | `onApplicationShutdown()` | no-op | `close()` through `runShutdownStep`, `<prefix>-queue-close-failed` |
171
+
172
+ `<prefix>` is `logPrefix ?? name`. The queue closes in `onApplicationShutdown`
173
+ (phase 4), not `onModuleDestroy`: producers are reached from HTTP handlers and
174
+ from workers that drain in phase 1, and an earlier close would race both. The
175
+ deadline defaults to `SHUTDOWN_STEP_TIMEOUT_MS` (`closeTimeoutMs` overrides it).
176
+
177
+ A subclass that needs more than these reaches the queue as `this.queue`. To
178
+ type it as the real BullMQ queue (for `getJob`), pass it as the second type
179
+ parameter: `class NfseZipQueue extends BullQueueHost<NfseZipJobData, Queue<NfseZipJobData>>`.
180
+ A queue that must remove a parked job before every add overrides `enqueue`:
181
+
182
+ ```ts
183
+ override async enqueue(competencia: string): Promise<void> {
184
+ await this.removeJob(competencia);
185
+ await super.enqueue(competencia);
186
+ }
187
+ ```
188
+
189
+ `isLiveJobState(state)` is exported on its own: `active`, `waiting`,
190
+ `waiting-children`, `delayed` and `prioritized` are live; `completed`, `failed`
191
+ and `unknown` need a `removeJob` before the next `enqueue`.
192
+
79
193
  ## Deterministic job ids
80
194
 
81
195
  ```ts
@@ -108,10 +222,16 @@ which *lost* `REDIS_HOST` belongs on the configuration, not on this probe.
108
222
 
109
223
  ## Requirements
110
224
 
111
- Node `>=20.11.0`. Peer dependencies: `@leoribeiroweb/nest-core` ^0.4,
225
+ Node `>=20.11.0`. Peer dependencies: `@leoribeiroweb/nest-core`,
112
226
  `@leoribeiroweb/nest-redis` ^0.1, `@nestjs/common` ^11, `@nestjs/terminus` ^11,
113
227
  `bullmq` `^5 || ^6`, `reflect-metadata` ^0.2.
114
228
 
229
+ The accepted `@leoribeiroweb/nest-core` range is the one in the `peerDependencies`
230
+ of this package's `package.json` (`npm view @leoribeiroweb/nest-queue@<version>
231
+ peerDependencies` for a published version). It has moved with every core minor,
232
+ so read it there rather than from this page, and bump `nest-core` and
233
+ `nest-queue` in the same change.
234
+
115
235
  Both BullMQ majors are exercised in CI: the lockfile installs 6, which the live
116
236
  services run, and a separate job installs the floor of the range and re-runs
117
237
  the suite.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export { createBullConnection } from './connection/bull-connection';
2
2
  export { createQueueHealthIndicator, type HealthProbeQueue, type QueueHealthIndicatorOptions, } from './health/queue-health';
3
+ export { BullQueueHost, bullQueueFactory, type BullQueueHostOptions, type BullQueueOptions, type HostedQueue, type QueueFactory, type QueueHostLogger, } from './queue/bull-queue-host';
3
4
  export { deterministicJobId } from './queue/job-id';
4
- export { BullWorkerHost, bullWorkerFactory, DEFAULT_WORKER_CONCURRENCY, type BullWorkerHostOptions, type QueueWorker, type WorkerFactory, type WorkerHostLogger, type WorkerProcessor, } from './worker/bull-worker-host';
5
+ export { isLiveJobState } from './queue/live-job-state';
6
+ export { BullWorkerHost, bullWorkerFactory, DEFAULT_WORKER_CONCURRENCY, type BullWorkerHostOptions, type BullWorkerOptions, type QueueWorker, type WorkerActiveHandler, type WorkerFactory, type WorkerFailedHandler, type WorkerHostLogger, type WorkerLogTypes, type WorkerProcessor, } from './worker/bull-worker-host';
package/dist/index.js CHANGED
@@ -1,12 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DEFAULT_WORKER_CONCURRENCY = exports.bullWorkerFactory = exports.BullWorkerHost = exports.deterministicJobId = exports.createQueueHealthIndicator = exports.createBullConnection = void 0;
3
+ exports.DEFAULT_WORKER_CONCURRENCY = exports.bullWorkerFactory = exports.BullWorkerHost = exports.isLiveJobState = exports.deterministicJobId = exports.bullQueueFactory = exports.BullQueueHost = exports.createQueueHealthIndicator = exports.createBullConnection = void 0;
4
4
  var bull_connection_1 = require("./connection/bull-connection");
5
5
  Object.defineProperty(exports, "createBullConnection", { enumerable: true, get: function () { return bull_connection_1.createBullConnection; } });
6
6
  var queue_health_1 = require("./health/queue-health");
7
7
  Object.defineProperty(exports, "createQueueHealthIndicator", { enumerable: true, get: function () { return queue_health_1.createQueueHealthIndicator; } });
8
+ var bull_queue_host_1 = require("./queue/bull-queue-host");
9
+ Object.defineProperty(exports, "BullQueueHost", { enumerable: true, get: function () { return bull_queue_host_1.BullQueueHost; } });
10
+ Object.defineProperty(exports, "bullQueueFactory", { enumerable: true, get: function () { return bull_queue_host_1.bullQueueFactory; } });
8
11
  var job_id_1 = require("./queue/job-id");
9
12
  Object.defineProperty(exports, "deterministicJobId", { enumerable: true, get: function () { return job_id_1.deterministicJobId; } });
13
+ var live_job_state_1 = require("./queue/live-job-state");
14
+ Object.defineProperty(exports, "isLiveJobState", { enumerable: true, get: function () { return live_job_state_1.isLiveJobState; } });
10
15
  var bull_worker_host_1 = require("./worker/bull-worker-host");
11
16
  Object.defineProperty(exports, "BullWorkerHost", { enumerable: true, get: function () { return bull_worker_host_1.BullWorkerHost; } });
12
17
  Object.defineProperty(exports, "bullWorkerFactory", { enumerable: true, get: function () { return bull_worker_host_1.bullWorkerFactory; } });
@@ -0,0 +1,111 @@
1
+ import type { OnApplicationShutdown } from '@nestjs/common';
2
+ import { type ShutdownPhaseLogger } from '@leoribeiroweb/nest-core';
3
+ import type { RedisConfigSource } from '@leoribeiroweb/nest-redis';
4
+ import { Queue, type JobsOptions, type QueueOptions } from 'bullmq';
5
+ /**
6
+ * What the host needs from a queue. BullMQ's `Queue<T>` satisfies it for any
7
+ * concrete `T`; a subclass that needs more (`getJob`, for a status read)
8
+ * passes the real `Queue<T>` as the second type parameter of
9
+ * {@link BullQueueHost} and reaches it through `this.queue`.
10
+ *
11
+ * It is the default of that parameter, rather than `Queue<T>`, because BullMQ
12
+ * derives its `add` payload type through conditional types that TypeScript
13
+ * cannot resolve while `T` is still generic.
14
+ */
15
+ export interface HostedQueue<T> {
16
+ add(name: string, data: T, opts?: JobsOptions): Promise<unknown>;
17
+ remove(jobId: string): Promise<unknown>;
18
+ getJobState(jobId: string): Promise<string>;
19
+ close(): Promise<void>;
20
+ }
21
+ /**
22
+ * How a queue gets built. A collaborator rather than a hard-coded
23
+ * `new Queue(...)` for the same reason as `WorkerFactory`: BullMQ connects on
24
+ * construction, and every branch of the host should be testable without a
25
+ * Redis. Pass {@link bullQueueFactory} in production.
26
+ */
27
+ export type QueueFactory<T, Q extends HostedQueue<T> = HostedQueue<T>> = (name: string, options: QueueOptions) => Q;
28
+ /** The production factory: a real BullMQ `Queue`. */
29
+ export declare function bullQueueFactory<T>(name: string, options: QueueOptions): Queue<T>;
30
+ /** The logging surface a queue host needs — the structured logger's, narrowed. */
31
+ export type QueueHostLogger = ShutdownPhaseLogger;
32
+ /**
33
+ * Queue options passed through to BullMQ (`defaultJobOptions`, `prefix`, ...).
34
+ * `connection` is not one of them: the host builds it from `source`.
35
+ */
36
+ export type BullQueueOptions = Omit<QueueOptions, 'connection'>;
37
+ export interface BullQueueHostOptions<T, Q extends HostedQueue<T> = HostedQueue<T>> {
38
+ /** The BullMQ queue name. */
39
+ name: string;
40
+ /**
41
+ * The prefix of every log type this host emits. Defaults to `name`. Exists
42
+ * because a queue's name and its log types often differ: `nfse-api`'s
43
+ * `nfse-emission` queue logs `nfse-queue-*`.
44
+ */
45
+ logPrefix?: string;
46
+ /** Where to read the Redis configuration. */
47
+ source: RedisConfigSource;
48
+ logger: QueueHostLogger;
49
+ createQueue: QueueFactory<T, Q>;
50
+ /** Passed through to the BullMQ `Queue`. Unset: the queue gets only `{ connection }`. */
51
+ queueOptions?: BullQueueOptions;
52
+ /** The BullMQ job name every `enqueue` uses. */
53
+ jobName: string;
54
+ /**
55
+ * The deterministic job id of a key — usually a `deterministicJobId` call.
56
+ * `enqueue`, `removeJob` and `hasLiveJob` all address the job through it,
57
+ * which is what makes a second `enqueue` of the same key a no-op.
58
+ */
59
+ jobId: (key: string) => string;
60
+ /** The job payload for a key. */
61
+ jobData: (key: string) => T;
62
+ /** The meta field naming the key on `<prefix>-enqueue-skipped`. Defaults to `'key'`. */
63
+ keyLogField?: string;
64
+ /** How long `close()` may hold shutdown. Defaults to `SHUTDOWN_STEP_TIMEOUT_MS`. */
65
+ closeTimeoutMs?: number;
66
+ }
67
+ /**
68
+ * The producer side of a BullMQ queue, keyed by a value that is unique per
69
+ * unit of work: build the queue if Redis is configured, stay `null` and no-op
70
+ * if it is not, address every job through its deterministic id, and close
71
+ * inside a deadline.
72
+ *
73
+ * The queue is built in the constructor, so it exists before any other
74
+ * provider's `onModuleInit` can enqueue. It closes in `onApplicationShutdown`
75
+ * — phase 4, after the HTTP drain — because producers are reached from HTTP
76
+ * handlers and from workers that drain in phase 1; closing in
77
+ * `onModuleDestroy` would race both (`nfse-api#546`).
78
+ *
79
+ * Log types, with `<prefix>` = `logPrefix ?? name`: `<prefix>-queue-ready`
80
+ * (info), `<prefix>-queue-disabled` (warn), `<prefix>-enqueue-skipped` (warn)
81
+ * and `<prefix>-queue-close-failed` (error or warn).
82
+ */
83
+ export declare class BullQueueHost<T, Q extends HostedQueue<T> = HostedQueue<T>> implements OnApplicationShutdown {
84
+ protected readonly options: BullQueueHostOptions<T, Q>;
85
+ /** The BullMQ queue, or `null` when Redis is not configured. */
86
+ protected readonly queue: Q | null;
87
+ private readonly logPrefix;
88
+ constructor(options: BullQueueHostOptions<T, Q>);
89
+ isConfigured(): boolean;
90
+ /**
91
+ * Add the job for `key` under its deterministic id. Without Redis, logs
92
+ * `<prefix>-enqueue-skipped` and resolves: the work stays where a repair
93
+ * sweep can find it, and the caller is not failed for an optional backend.
94
+ * `jobOptions` are merged per call; they cannot replace the job id.
95
+ */
96
+ enqueue(key: string, jobOptions?: Omit<JobsOptions, 'jobId'>): Promise<void>;
97
+ /**
98
+ * Remove the job BullMQ holds for `key`, typically one parked in the failed
99
+ * set: it occupies the deterministic id and would make the next `enqueue` a
100
+ * silent no-op. BullMQ leaves a locked (active) job alone. No-op without
101
+ * Redis.
102
+ */
103
+ removeJob(key: string): Promise<void>;
104
+ /**
105
+ * Whether BullMQ still holds a job for `key` that will be processed on its
106
+ * own (see `isLiveJobState`). `false` without Redis, so a repair sweep falls
107
+ * through to the no-op `enqueue` rather than treating everything as healthy.
108
+ */
109
+ hasLiveJob(key: string): Promise<boolean>;
110
+ onApplicationShutdown(): Promise<void>;
111
+ }
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BullQueueHost = void 0;
4
+ exports.bullQueueFactory = bullQueueFactory;
5
+ const nest_core_1 = require("@leoribeiroweb/nest-core");
6
+ const bullmq_1 = require("bullmq");
7
+ const bull_connection_1 = require("../connection/bull-connection");
8
+ const live_job_state_1 = require("./live-job-state");
9
+ /** The production factory: a real BullMQ `Queue`. */
10
+ function bullQueueFactory(name, options) {
11
+ return new bullmq_1.Queue(name, options);
12
+ }
13
+ /**
14
+ * The producer side of a BullMQ queue, keyed by a value that is unique per
15
+ * unit of work: build the queue if Redis is configured, stay `null` and no-op
16
+ * if it is not, address every job through its deterministic id, and close
17
+ * inside a deadline.
18
+ *
19
+ * The queue is built in the constructor, so it exists before any other
20
+ * provider's `onModuleInit` can enqueue. It closes in `onApplicationShutdown`
21
+ * — phase 4, after the HTTP drain — because producers are reached from HTTP
22
+ * handlers and from workers that drain in phase 1; closing in
23
+ * `onModuleDestroy` would race both (`nfse-api#546`).
24
+ *
25
+ * Log types, with `<prefix>` = `logPrefix ?? name`: `<prefix>-queue-ready`
26
+ * (info), `<prefix>-queue-disabled` (warn), `<prefix>-enqueue-skipped` (warn)
27
+ * and `<prefix>-queue-close-failed` (error or warn).
28
+ */
29
+ class BullQueueHost {
30
+ constructor(options) {
31
+ this.options = options;
32
+ const { name, source, logger, createQueue, queueOptions } = options;
33
+ this.logPrefix = options.logPrefix ?? name;
34
+ const connection = (0, bull_connection_1.createBullConnection)(source);
35
+ if (connection === null) {
36
+ this.queue = null;
37
+ logger.warn(`${this.logPrefix}-queue-disabled`, `Redis not configured — the ${name} queue is disabled`);
38
+ return;
39
+ }
40
+ this.queue = createQueue(name, { ...queueOptions, connection });
41
+ logger.info(`${this.logPrefix}-queue-ready`, `The ${name} queue is configured`);
42
+ }
43
+ isConfigured() {
44
+ return this.queue !== null;
45
+ }
46
+ /**
47
+ * Add the job for `key` under its deterministic id. Without Redis, logs
48
+ * `<prefix>-enqueue-skipped` and resolves: the work stays where a repair
49
+ * sweep can find it, and the caller is not failed for an optional backend.
50
+ * `jobOptions` are merged per call; they cannot replace the job id.
51
+ */
52
+ async enqueue(key, jobOptions) {
53
+ const { name, logger, jobName, jobId, jobData, keyLogField } = this.options;
54
+ if (!this.queue) {
55
+ logger.warn(`${this.logPrefix}-enqueue-skipped`, `Redis not configured — the ${name} job was not enqueued`, { meta: { [keyLogField ?? 'key']: key } });
56
+ return;
57
+ }
58
+ await this.queue.add(jobName, jobData(key), { ...jobOptions, jobId: jobId(key) });
59
+ }
60
+ /**
61
+ * Remove the job BullMQ holds for `key`, typically one parked in the failed
62
+ * set: it occupies the deterministic id and would make the next `enqueue` a
63
+ * silent no-op. BullMQ leaves a locked (active) job alone. No-op without
64
+ * Redis.
65
+ */
66
+ async removeJob(key) {
67
+ if (!this.queue)
68
+ return;
69
+ await this.queue.remove(this.options.jobId(key));
70
+ }
71
+ /**
72
+ * Whether BullMQ still holds a job for `key` that will be processed on its
73
+ * own (see `isLiveJobState`). `false` without Redis, so a repair sweep falls
74
+ * through to the no-op `enqueue` rather than treating everything as healthy.
75
+ */
76
+ async hasLiveJob(key) {
77
+ if (!this.queue)
78
+ return false;
79
+ return (0, live_job_state_1.isLiveJobState)(await this.queue.getJobState(this.options.jobId(key)));
80
+ }
81
+ async onApplicationShutdown() {
82
+ await (0, nest_core_1.runShutdownStep)(this.options.logger, `${this.logPrefix}-queue-close-failed`, () => this.queue?.close(), this.options.closeTimeoutMs ?? nest_core_1.SHUTDOWN_STEP_TIMEOUT_MS);
83
+ }
84
+ }
85
+ exports.BullQueueHost = BullQueueHost;
@@ -0,0 +1,2 @@
1
+ /** `state` is what `Queue#getJobState()` returns: a `JobState` or `'unknown'`. */
2
+ export declare function isLiveJobState(state: string): boolean;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isLiveJobState = isLiveJobState;
4
+ /**
5
+ * The BullMQ states in which a job is still going to be processed on its own.
6
+ *
7
+ * Age is not evidence that a job is lost: a large backlog drains for hours,
8
+ * and every row still waiting its turn looks old. A repair sweep asks this
9
+ * instead. The complement is deliberately the set that needs repairing:
10
+ * `completed` and `failed` are terminal, and `Queue#getJobState` answers
11
+ * `'unknown'` both for an id BullMQ holds no job under and for a job sitting
12
+ * in no set at all. All three want `removeJob` then `enqueue` — a dead job
13
+ * still occupies its deterministic id, so a bare `enqueue` would be a silent
14
+ * no-op.
15
+ *
16
+ * Provenance: `nfse-api` `src/nfse/live-job-state.ts`.
17
+ */
18
+ const LIVE_JOB_STATES = new Set([
19
+ 'active',
20
+ 'waiting',
21
+ 'waiting-children',
22
+ 'delayed',
23
+ 'prioritized',
24
+ ]);
25
+ /** `state` is what `Queue#getJobState()` returns: a `JobState` or `'unknown'`. */
26
+ function isLiveJobState(state) {
27
+ return LIVE_JOB_STATES.has(state);
28
+ }
@@ -15,7 +15,22 @@ export interface QueueWorker {
15
15
  close(): Promise<void>;
16
16
  on(event: 'failed', listener: (job: unknown, error: Error) => void): unknown;
17
17
  on(event: 'error', listener: (error: Error) => void): unknown;
18
+ /** Registered only when the consumer passes `onActive`. */
19
+ on(event: 'active', listener: (job: unknown, prev: string) => void): unknown;
18
20
  }
21
+ /**
22
+ * A consumer's reaction to a failed attempt. `job` is `undefined` when BullMQ
23
+ * reports a failure it cannot tie to a job (a stalled job it could not load).
24
+ * May be async: a rejection is logged, never left unhandled.
25
+ */
26
+ export type WorkerFailedHandler<T> = (job: Job<T> | undefined, error: Error) => void | Promise<void>;
27
+ /** A consumer's reaction to a job becoming active. May be async. */
28
+ export type WorkerActiveHandler<T> = (job: Job<T>) => void | Promise<void>;
29
+ /**
30
+ * Worker options passed through to BullMQ, `limiter` included. `connection` is
31
+ * not one of them: the host builds it from `source`.
32
+ */
33
+ export type BullWorkerOptions = Omit<WorkerOptions, 'connection'>;
19
34
  export type WorkerProcessor<T> = (job: Job<T>) => Promise<void>;
20
35
  /**
21
36
  * How a worker gets built.
@@ -43,6 +58,60 @@ export interface BullWorkerHostOptions<T> {
43
58
  concurrency?: number;
44
59
  /** How long `close()` may hold shutdown. Defaults to the package budget. */
45
60
  closeTimeoutMs?: number;
61
+ /**
62
+ * Passed through to the BullMQ `Worker` (`limiter`, `lockDuration`,
63
+ * `stalledInterval`, ...). The host's `connection` always wins, and a
64
+ * top-level `concurrency` wins over `workerOptions.concurrency`. Unset: the
65
+ * worker gets exactly `{ connection, concurrency }`, as before.
66
+ */
67
+ workerOptions?: BullWorkerOptions;
68
+ /**
69
+ * Called on every failed attempt, after the host's own
70
+ * `<name>-job-failed` line (unless `logTypes.jobFailed` is `null`). A throw
71
+ * or a rejection is logged as `<name>-failed-handler-error` and never
72
+ * reaches BullMQ.
73
+ */
74
+ onFailed?: WorkerFailedHandler<T>;
75
+ /**
76
+ * Called when a job becomes active. Unset: no `active` listener is
77
+ * registered. A throw or a rejection is logged as
78
+ * `<name>-active-handler-error`.
79
+ */
80
+ onActive?: WorkerActiveHandler<T>;
81
+ /**
82
+ * Overrides for the log types the host emits, one per line. A key left out
83
+ * keeps its default (`<name>-...`, see {@link WorkerLogTypes}). Exists so a
84
+ * service moving an existing processor onto the host keeps every log type
85
+ * its alerts and dashboards read.
86
+ */
87
+ logTypes?: Partial<WorkerLogTypes>;
88
+ }
89
+ /**
90
+ * The log types a {@link BullWorkerHost} emits. Defaults, with `<name>` the
91
+ * queue name: `<name>-worker-disabled`, `<name>-job-failed`,
92
+ * `<name>-worker-error`, `<name>-worker-close-failed`,
93
+ * `<name>-failed-handler-error`, `<name>-active-handler-error`.
94
+ */
95
+ export interface WorkerLogTypes {
96
+ /** Warn: Redis is not configured, so the worker does not start. */
97
+ disabled: string;
98
+ /**
99
+ * Error: a job attempt failed, with `meta.jobId`. `null` drops the line, for
100
+ * a consumer whose `onFailed` already logs the failure its own way. The
101
+ * consumer's handler still runs.
102
+ */
103
+ jobFailed: string | null;
104
+ /**
105
+ * Error: the worker's connection failed. Not suppressible: without a
106
+ * listener, BullMQ ends the error in a raw `console.error` (D9).
107
+ */
108
+ workerError: string;
109
+ /** Error or warn: `close()` failed or outlived its deadline. */
110
+ closeFailed: string;
111
+ /** Error: the consumer's `onFailed` threw or rejected. */
112
+ failedHandlerError: string;
113
+ /** Error: the consumer's `onActive` threw or rejected. */
114
+ activeHandlerError: string;
46
115
  }
47
116
  export declare const DEFAULT_WORKER_CONCURRENCY = 1;
48
117
  /**
@@ -67,5 +136,11 @@ export declare abstract class BullWorkerHost<T> implements OnModuleInit, OnModul
67
136
  /** Process one delivered job. */
68
137
  protected abstract process(job: Job<T>): Promise<void>;
69
138
  onModuleInit(): void;
139
+ /**
140
+ * Run a consumer's event handler so that neither a throw nor a rejection
141
+ * escapes into BullMQ's emitter: an exception thrown from a listener would
142
+ * be re-emitted as `'error'`, and a rejected promise would go unhandled.
143
+ */
144
+ private callHandler;
70
145
  onModuleDestroy(): Promise<void>;
71
146
  }
@@ -9,6 +9,17 @@ const bull_connection_1 = require("../connection/bull-connection");
9
9
  function bullWorkerFactory(name, process, options) {
10
10
  return new bullmq_1.Worker(name, process, options);
11
11
  }
12
+ function resolveLogTypes(name, overrides = {}) {
13
+ return {
14
+ disabled: `${name}-worker-disabled`,
15
+ jobFailed: `${name}-job-failed`,
16
+ workerError: `${name}-worker-error`,
17
+ closeFailed: `${name}-worker-close-failed`,
18
+ failedHandlerError: `${name}-failed-handler-error`,
19
+ activeHandlerError: `${name}-active-handler-error`,
20
+ ...overrides,
21
+ };
22
+ }
12
23
  exports.DEFAULT_WORKER_CONCURRENCY = 1;
13
24
  /**
14
25
  * The lifecycle every BullMQ processor in these services repeats: start a
@@ -31,28 +42,64 @@ class BullWorkerHost {
31
42
  this.worker = null;
32
43
  }
33
44
  onModuleInit() {
34
- const { name, source, logger, createWorker, concurrency } = this.options;
45
+ const { name, source, logger, createWorker, concurrency, workerOptions, onFailed, onActive } = this.options;
46
+ const types = resolveLogTypes(name, this.options.logTypes);
35
47
  const connection = (0, bull_connection_1.createBullConnection)(source);
36
48
  if (connection === null) {
37
- logger.warn(`${name}-worker-disabled`, `Redis not configured — the ${name} worker will not consume`);
49
+ logger.warn(types.disabled, `Redis not configured — the ${name} worker will not consume`);
38
50
  return;
39
51
  }
40
52
  this.worker = createWorker(name, (job) => this.process(job), {
53
+ ...workerOptions,
41
54
  connection,
42
- concurrency: concurrency ?? exports.DEFAULT_WORKER_CONCURRENCY,
55
+ concurrency: concurrency ?? workerOptions?.concurrency ?? exports.DEFAULT_WORKER_CONCURRENCY,
43
56
  });
44
57
  this.worker.on('failed', (job, error) => {
45
- logger.error(`${name}-job-failed`, `A ${name} job failed`, {
46
- error,
47
- meta: { jobId: job?.id },
48
- });
58
+ if (types.jobFailed !== null) {
59
+ logger.error(types.jobFailed, `A ${name} job failed`, {
60
+ error,
61
+ meta: { jobId: job?.id },
62
+ });
63
+ }
64
+ if (onFailed) {
65
+ this.callHandler(types.failedHandlerError, 'failed', () => onFailed(job, error));
66
+ }
49
67
  });
50
68
  this.worker.on('error', (error) => {
51
- logger.error(`${name}-worker-error`, `The ${name} worker connection failed`, { error });
69
+ logger.error(types.workerError, `The ${name} worker connection failed`, { error });
52
70
  });
71
+ if (onActive) {
72
+ this.worker.on('active', (job) => {
73
+ this.callHandler(types.activeHandlerError, 'active', () => onActive(job));
74
+ });
75
+ }
76
+ }
77
+ /**
78
+ * Run a consumer's event handler so that neither a throw nor a rejection
79
+ * escapes into BullMQ's emitter: an exception thrown from a listener would
80
+ * be re-emitted as `'error'`, and a rejected promise would go unhandled.
81
+ */
82
+ callHandler(logType, event, handler) {
83
+ const report = (error) => {
84
+ try {
85
+ this.options.logger.error(logType, `The consumer's ${event} handler of ${this.options.name} failed`, { error });
86
+ }
87
+ catch {
88
+ // A logger that throws must not take the worker's listener down with it.
89
+ }
90
+ };
91
+ try {
92
+ const outcome = handler();
93
+ if (outcome && typeof outcome.then === 'function') {
94
+ outcome.then(undefined, report);
95
+ }
96
+ }
97
+ catch (error) {
98
+ report(error);
99
+ }
53
100
  }
54
101
  async onModuleDestroy() {
55
- await (0, nest_core_1.closeWorkerWithDeadline)(this.worker, this.options.logger, `${this.options.name}-worker-close-failed`, this.options.closeTimeoutMs ?? nest_core_1.WORKER_CLOSE_TIMEOUT_MS);
102
+ await (0, nest_core_1.closeWorkerWithDeadline)(this.worker, this.options.logger, resolveLogTypes(this.options.name, this.options.logTypes).closeFailed, this.options.closeTimeoutMs ?? nest_core_1.WORKER_CLOSE_TIMEOUT_MS);
56
103
  }
57
104
  }
58
105
  exports.BullWorkerHost = BullWorkerHost;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leoribeiroweb/nest-queue",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
4
4
  "description": "Shared BullMQ building blocks: the dual-mode Redis connection as BullMQ options, base queue and worker hosts, and a queue health indicator.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -35,8 +35,8 @@
35
35
  "prepublishOnly": "npm run build"
36
36
  },
37
37
  "peerDependencies": {
38
- "@leoribeiroweb/nest-core": "^0.8.0",
39
- "@leoribeiroweb/nest-redis": "^0.1.0",
38
+ "@leoribeiroweb/nest-core": ">=0.8.0 <1.0.0",
39
+ "@leoribeiroweb/nest-redis": ">=0.1.0 <1.0.0",
40
40
  "@nestjs/common": "^11",
41
41
  "@nestjs/terminus": "^11",
42
42
  "bullmq": "^5 || ^6",