@leoribeiroweb/nest-queue 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.
package/README.md ADDED
@@ -0,0 +1,117 @@
1
+ # @leoribeiroweb/nest-queue
2
+
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.
6
+
7
+ This package is part of the shared framework behind my own services. It is
8
+ published publicly so builds need no registry credentials, but it is **not an
9
+ open-source project**: there is no support commitment, and the API changes to
10
+ suit the services that consume it. Pin a major version.
11
+
12
+ ## Connection
13
+
14
+ ```ts
15
+ const connection = createBullConnection(configService);
16
+ if (connection === null) {
17
+ // Redis is not configured: the queue stays disabled and the service boots.
18
+ }
19
+ ```
20
+
21
+ It reads the same four variables as `@leoribeiroweb/nest-redis` — `REDIS_URL`,
22
+ or `REDIS_HOST`/`REDIS_PORT`/`REDIS_PASSWORD` — through the same resolver, so
23
+ the two packages cannot drift on what "configured" means.
24
+
25
+ Two BullMQ-specific overrides ride on top:
26
+
27
+ - `maxRetriesPerRequest: null`, which BullMQ requires — it blocks on its
28
+ connections and throws at construction with anything else.
29
+ - `enableOfflineQueue: true`, deliberately overriding the shared default. Plain
30
+ Redis traffic fails fast during an outage so a caller can degrade; a queue
31
+ command is work someone is waiting on, so dropping it mid-reconnect loses a
32
+ job rather than delaying a read.
33
+
34
+ It returns options rather than a client so BullMQ owns the connection
35
+ lifecycle: `Queue#close()` and `Worker#close()` are then enough to shut
36
+ everything down.
37
+
38
+ Whether that client is the *same* ioredis the rest of the process uses depends
39
+ on the major: **bullmq 6** declares `ioredis` as an optional peer and loads the
40
+ top-level copy, **bullmq 5** carries its own in `dependencies` and can end up
41
+ with a second. Both live services run 6; the range admits 5 for
42
+ `browser-worker`.
43
+
44
+ ## Worker host
45
+
46
+ ```ts
47
+ @Injectable()
48
+ export class NfseProcessor extends BullWorkerHost<NfseJobData> {
49
+ constructor(configService: ConfigService, private readonly emissions: EmissionService) {
50
+ super({
51
+ name: NFSE_QUEUE,
52
+ source: configService,
53
+ logger: createLogger(NfseProcessor.name),
54
+ createWorker: bullWorkerFactory,
55
+ });
56
+ }
57
+
58
+ protected async process(job: Job<NfseJobData>): Promise<void> {
59
+ await this.emissions.emit(job.data.emissionId);
60
+ }
61
+ }
62
+ ```
63
+
64
+ The host starts a worker in `onModuleInit` when Redis is configured, warns and
65
+ stays idle when it is not, reports failed jobs **and connection errors** — an
66
+ unlistened BullMQ `'error'` ends in a raw `console.error` that reaches no
67
+ structured sink — and closes in
68
+ `onModuleDestroy` inside `@leoribeiroweb/nest-core`'s shutdown budget — phase
69
+ 1, where a module stops consuming before the HTTP drain. **A service that adds
70
+ a Worker-owning module must re-derive its shutdown budget.**
71
+
72
+ `createWorker` is an explicit collaborator rather than a hard-coded
73
+ `new Worker(...)` because BullMQ's Worker opens a blocking Redis connection the
74
+ moment it is constructed: a host that built its own could not be exercised
75
+ without a live Redis, and its disabled path, failure handler and bounded close
76
+ would all be verified by inspection only. Pass `bullWorkerFactory` in
77
+ production.
78
+
79
+ ## Deterministic job ids
80
+
81
+ ```ts
82
+ await queue.add('emit', { emissionId }, { jobId: deterministicJobId('nfse', emissionId) });
83
+ ```
84
+
85
+ BullMQ refuses a second job with an id it already holds, so a redelivered
86
+ webhook, a double tap or a retried producer collapses into one job. The
87
+ namespace keeps two features that key on the same value apart. Sanitizing is
88
+ lossy (`a/b` and `a_b` both become `a_b`), so the source value must already be
89
+ unique.
90
+
91
+ ## Health
92
+
93
+ ```ts
94
+ HealthModule.forRoot({
95
+ indicators: [createQueueHealthIndicator({ name: 'nfse-queue', queue })],
96
+ });
97
+ ```
98
+
99
+ It pings Redis and reads the queue depths — a connection that is open but
100
+ cannot answer `LLEN` is not a working queue — and reports `down` rather than
101
+ throwing, so terminus returns a 503 naming the failing check instead of a 500
102
+ with a stack. It joins **readiness**, not liveness: an unreachable queue should
103
+ take the pod out of rotation, not restart a process that is still serving HTTP.
104
+
105
+ A `null` queue reports up, tagged `disabled`. Running without Redis is a
106
+ supported deployment shape; the check that catches a production deployment
107
+ which *lost* `REDIS_HOST` belongs on the configuration, not on this probe.
108
+
109
+ ## Requirements
110
+
111
+ Node `>=20.11.0`. Peer dependencies: `@leoribeiroweb/nest-core` ^0.4,
112
+ `@leoribeiroweb/nest-redis` ^0.1, `@nestjs/common` ^11, `@nestjs/terminus` ^11,
113
+ `bullmq` `^5 || ^6`, `reflect-metadata` ^0.2.
114
+
115
+ Both BullMQ majors are exercised in CI: the lockfile installs 6, which the live
116
+ services run, and a separate job installs the floor of the range and re-runs
117
+ the suite.
@@ -0,0 +1,35 @@
1
+ import { type RedisConfigSource, type RedisConnectionOptions } from '@leoribeiroweb/nest-redis';
2
+ /**
3
+ * BullMQ's connection options, which are **not** ioredis's.
4
+ *
5
+ * Since bullmq 6 the library declares its own `RedisOptions` rather than
6
+ * re-exporting ioredis's, and the two disagree on one property: ioredis types
7
+ * `retryStrategy` as `((times) => …) | null | undefined`, where `null` disables
8
+ * reconnection wholesale, while BullMQ accepts only the function. Narrowing it
9
+ * here is safe in both directions — every connection this module builds sets a
10
+ * function — and it is what makes the result assignable to `ConnectionOptions`
11
+ * under bullmq 5 and 6 alike, without a cast at the call site.
12
+ */
13
+ export type BullConnectionOptions = Omit<RedisConnectionOptions, 'retryStrategy'> & {
14
+ retryStrategy?: (times: number) => number | void | null;
15
+ };
16
+ /**
17
+ * BullMQ connection options, or `null` when Redis is not configured.
18
+ *
19
+ * Returns a plain options object rather than a pre-built client so BullMQ owns
20
+ * the connection lifecycle: it constructs, retries and closes the client
21
+ * itself, and `Queue#close()` / `Worker#close()` are then enough to shut
22
+ * everything down.
23
+ *
24
+ * Whether that client is the *same* ioredis the rest of the process uses
25
+ * depends on the major. **bullmq 6** declares `ioredis` as an optional peer
26
+ * dependency, so it lazily loads the top-level copy and there is one client
27
+ * library in the tree. **bullmq 5** carries `ioredis` in its own
28
+ * `dependencies`, so a consumer whose ioredis does not dedupe with BullMQ's can
29
+ * end up with two copies — same wire protocol, separate module state. Both live
30
+ * services run bullmq 6; the peer range still admits 5 for `browser-worker`.
31
+ *
32
+ * `null` is how a service without Redis stays bootable: its queues report
33
+ * `isConfigured() === false` and its workers never start.
34
+ */
35
+ export declare function createBullConnection(source: RedisConfigSource): BullConnectionOptions | null;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createBullConnection = createBullConnection;
4
+ const nest_redis_1 = require("@leoribeiroweb/nest-redis");
5
+ /**
6
+ * What BullMQ needs on top of the shared Redis defaults.
7
+ *
8
+ * `maxRetriesPerRequest: null` is not a preference: BullMQ blocks on its
9
+ * connections and throws at construction time with anything else.
10
+ *
11
+ * `enableOfflineQueue: true` deliberately overrides the shared default. Plain
12
+ * Redis traffic fails fast during an outage so a caller can degrade; a queue
13
+ * command is work someone is waiting on, so dropping it mid-reconnect loses a
14
+ * job instead of delaying a read.
15
+ */
16
+ const BULL_REQUIRED_OPTIONS = {
17
+ maxRetriesPerRequest: null,
18
+ enableOfflineQueue: true,
19
+ };
20
+ /**
21
+ * BullMQ connection options, or `null` when Redis is not configured.
22
+ *
23
+ * Returns a plain options object rather than a pre-built client so BullMQ owns
24
+ * the connection lifecycle: it constructs, retries and closes the client
25
+ * itself, and `Queue#close()` / `Worker#close()` are then enough to shut
26
+ * everything down.
27
+ *
28
+ * Whether that client is the *same* ioredis the rest of the process uses
29
+ * depends on the major. **bullmq 6** declares `ioredis` as an optional peer
30
+ * dependency, so it lazily loads the top-level copy and there is one client
31
+ * library in the tree. **bullmq 5** carries `ioredis` in its own
32
+ * `dependencies`, so a consumer whose ioredis does not dedupe with BullMQ's can
33
+ * end up with two copies — same wire protocol, separate module state. Both live
34
+ * services run bullmq 6; the peer range still admits 5 for `browser-worker`.
35
+ *
36
+ * `null` is how a service without Redis stays bootable: its queues report
37
+ * `isConfigured() === false` and its workers never start.
38
+ */
39
+ function createBullConnection(source) {
40
+ const settings = (0, nest_redis_1.resolveRedisConnection)(source);
41
+ if (settings === null)
42
+ return null;
43
+ return {
44
+ ...(0, nest_redis_1.buildRedisOptions)(settings, BULL_REQUIRED_OPTIONS),
45
+ // Restated rather than inherited so the property carries the narrow
46
+ // function type BullMQ's `RedisOptions` requires. Same strategy, same
47
+ // behaviour — see `redisRetryStrategy`.
48
+ retryStrategy: nest_redis_1.redisRetryStrategy,
49
+ };
50
+ }
@@ -0,0 +1,45 @@
1
+ import { type HealthCheckKind, type HealthIndicatorRegistration } from '@leoribeiroweb/nest-core';
2
+ /**
3
+ * The part of a BullMQ `Queue` a probe touches. Structural, so the indicator
4
+ * can be exercised without a live Redis — which is the only way "reports
5
+ * unhealthy when Redis is unreachable" is a tested claim rather than an
6
+ * inspected one.
7
+ */
8
+ export interface HealthProbeQueue {
9
+ /** BullMQ resolves its client lazily; the promise rejects when it cannot connect. */
10
+ readonly client: Promise<{
11
+ ping(): Promise<unknown>;
12
+ }>;
13
+ getWaitingCount(): Promise<number>;
14
+ getActiveCount(): Promise<number>;
15
+ getFailedCount(): Promise<number>;
16
+ }
17
+ export interface QueueHealthIndicatorOptions {
18
+ /** The key this check reports under, and the name a failure is attributed to. */
19
+ name: string;
20
+ /** The queue to probe, or `null` when the service runs without one. */
21
+ queue: HealthProbeQueue | null;
22
+ /** Which probes this check joins. Defaults to readiness only. */
23
+ kinds?: HealthCheckKind[];
24
+ }
25
+ /**
26
+ * A readiness check for one BullMQ queue.
27
+ *
28
+ * It pings Redis and reads the queue depths, because a connection that is open
29
+ * but cannot answer `LLEN` is not a working queue. Both are reported as
30
+ * `down` rather than thrown: terminus turns a `down` result into a 503 with
31
+ * the failing check named, and a thrown non-`HealthCheckError` would otherwise
32
+ * escape as a 500 with a stack.
33
+ *
34
+ * **Readiness, not liveness.** A queue that cannot be reached should take the
35
+ * pod out of rotation; it is not a reason to restart a process that is
36
+ * otherwise serving HTTP.
37
+ *
38
+ * A `null` queue reports **up**, tagged `disabled`. A service is allowed to
39
+ * run without Redis — that is what `createBullConnection` returning `null`
40
+ * means — so an un-configured queue is a deployment shape, not a fault. The
41
+ * trap is that a production deployment which lost `REDIS_HOST` reports healthy
42
+ * here; the check that catches that belongs on the configuration, not on this
43
+ * probe.
44
+ */
45
+ export declare function createQueueHealthIndicator({ name, queue, kinds, }: QueueHealthIndicatorOptions): HealthIndicatorRegistration;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createQueueHealthIndicator = createQueueHealthIndicator;
4
+ const nest_core_1 = require("@leoribeiroweb/nest-core");
5
+ /**
6
+ * A readiness check for one BullMQ queue.
7
+ *
8
+ * It pings Redis and reads the queue depths, because a connection that is open
9
+ * but cannot answer `LLEN` is not a working queue. Both are reported as
10
+ * `down` rather than thrown: terminus turns a `down` result into a 503 with
11
+ * the failing check named, and a thrown non-`HealthCheckError` would otherwise
12
+ * escape as a 500 with a stack.
13
+ *
14
+ * **Readiness, not liveness.** A queue that cannot be reached should take the
15
+ * pod out of rotation; it is not a reason to restart a process that is
16
+ * otherwise serving HTTP.
17
+ *
18
+ * A `null` queue reports **up**, tagged `disabled`. A service is allowed to
19
+ * run without Redis — that is what `createBullConnection` returning `null`
20
+ * means — so an un-configured queue is a deployment shape, not a fault. The
21
+ * trap is that a production deployment which lost `REDIS_HOST` reports healthy
22
+ * here; the check that catches that belongs on the configuration, not on this
23
+ * probe.
24
+ */
25
+ function createQueueHealthIndicator({ name, queue, kinds = ['readiness'], }) {
26
+ return {
27
+ name,
28
+ kinds,
29
+ check: async () => {
30
+ if (queue === null) {
31
+ return { [name]: { status: 'up', queue: 'disabled' } };
32
+ }
33
+ try {
34
+ const client = await queue.client;
35
+ await client.ping();
36
+ const [waiting, active, failed] = await Promise.all([
37
+ queue.getWaitingCount(),
38
+ queue.getActiveCount(),
39
+ queue.getFailedCount(),
40
+ ]);
41
+ return { [name]: { status: 'up', waiting, active, failed } };
42
+ }
43
+ catch (error) {
44
+ // describeError redacts: a connection failure commonly carries the
45
+ // credentials it failed to connect with, and this reaches /health/ready.
46
+ return { [name]: { status: 'down', message: (0, nest_core_1.describeError)(error) } };
47
+ }
48
+ },
49
+ };
50
+ }
@@ -0,0 +1,4 @@
1
+ export { createBullConnection } from './connection/bull-connection';
2
+ export { createQueueHealthIndicator, type HealthProbeQueue, type QueueHealthIndicatorOptions, } from './health/queue-health';
3
+ 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';
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_WORKER_CONCURRENCY = exports.bullWorkerFactory = exports.BullWorkerHost = exports.deterministicJobId = exports.createQueueHealthIndicator = exports.createBullConnection = void 0;
4
+ var bull_connection_1 = require("./connection/bull-connection");
5
+ Object.defineProperty(exports, "createBullConnection", { enumerable: true, get: function () { return bull_connection_1.createBullConnection; } });
6
+ var queue_health_1 = require("./health/queue-health");
7
+ Object.defineProperty(exports, "createQueueHealthIndicator", { enumerable: true, get: function () { return queue_health_1.createQueueHealthIndicator; } });
8
+ var job_id_1 = require("./queue/job-id");
9
+ Object.defineProperty(exports, "deterministicJobId", { enumerable: true, get: function () { return job_id_1.deterministicJobId; } });
10
+ var bull_worker_host_1 = require("./worker/bull-worker-host");
11
+ Object.defineProperty(exports, "BullWorkerHost", { enumerable: true, get: function () { return bull_worker_host_1.BullWorkerHost; } });
12
+ Object.defineProperty(exports, "bullWorkerFactory", { enumerable: true, get: function () { return bull_worker_host_1.bullWorkerFactory; } });
13
+ Object.defineProperty(exports, "DEFAULT_WORKER_CONCURRENCY", { enumerable: true, get: function () { return bull_worker_host_1.DEFAULT_WORKER_CONCURRENCY; } });
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Derive a stable job id from a value that is already unique per unit of work.
3
+ *
4
+ * This is the deduplication mechanism, not a cosmetic one: BullMQ refuses a
5
+ * second job with an id it already holds, so a redelivered webhook, a double
6
+ * tap or a retried producer collapses into the one job instead of running the
7
+ * work twice.
8
+ *
9
+ * Two restrictions, both load-bearing:
10
+ *
11
+ * 1. **The source value must already be unique.** Sanitizing is lossy — `a/b`
12
+ * and `a_b` both become `a_b` — so a value that is only unique in its
13
+ * punctuation is not safe to key on.
14
+ * 2. **Within one queue, no namespace may be another namespace plus `-`.**
15
+ * The separator is an ordinary legal character, so `('nfse', 'archive-X')`
16
+ * and `('nfse-archive', 'X')` produce the same id. BullMQ scopes job ids
17
+ * per queue (`bull:<queue>:<jobId>`), so this only bites when a single
18
+ * queue uses two such namespaces; the six live queues each use one.
19
+ *
20
+ * Dedup also lasts only as long as the job record does. With
21
+ * `removeOnComplete`, a replay that arrives after the job was reaped is a new
22
+ * job and the work runs again — the id collapses concurrent and in-flight
23
+ * duplicates, not a redelivery days later.
24
+ */
25
+ export declare function deterministicJobId(namespace: string, source: string): string;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deterministicJobId = deterministicJobId;
4
+ /** Everything outside this set is replaced: BullMQ rejects it in a custom job id. */
5
+ const UNSAFE_IN_JOB_ID = /[^a-zA-Z0-9_-]/g;
6
+ /**
7
+ * Derive a stable job id from a value that is already unique per unit of work.
8
+ *
9
+ * This is the deduplication mechanism, not a cosmetic one: BullMQ refuses a
10
+ * second job with an id it already holds, so a redelivered webhook, a double
11
+ * tap or a retried producer collapses into the one job instead of running the
12
+ * work twice.
13
+ *
14
+ * Two restrictions, both load-bearing:
15
+ *
16
+ * 1. **The source value must already be unique.** Sanitizing is lossy — `a/b`
17
+ * and `a_b` both become `a_b` — so a value that is only unique in its
18
+ * punctuation is not safe to key on.
19
+ * 2. **Within one queue, no namespace may be another namespace plus `-`.**
20
+ * The separator is an ordinary legal character, so `('nfse', 'archive-X')`
21
+ * and `('nfse-archive', 'X')` produce the same id. BullMQ scopes job ids
22
+ * per queue (`bull:<queue>:<jobId>`), so this only bites when a single
23
+ * queue uses two such namespaces; the six live queues each use one.
24
+ *
25
+ * Dedup also lasts only as long as the job record does. With
26
+ * `removeOnComplete`, a replay that arrives after the job was reaped is a new
27
+ * job and the work runs again — the id collapses concurrent and in-flight
28
+ * duplicates, not a redelivery days later.
29
+ */
30
+ function deterministicJobId(namespace, source) {
31
+ return `${namespace}-${source.replace(UNSAFE_IN_JOB_ID, '_')}`;
32
+ }
@@ -0,0 +1,71 @@
1
+ import type { OnModuleDestroy, OnModuleInit } from '@nestjs/common';
2
+ import { type ShutdownPhaseLogger } from '@leoribeiroweb/nest-core';
3
+ import type { RedisConfigSource } from '@leoribeiroweb/nest-redis';
4
+ import { Job, type WorkerOptions } from 'bullmq';
5
+ /**
6
+ * What the host needs from a worker: close it, and hear about both kinds of
7
+ * failure — a job that failed, and the connection underneath it.
8
+ *
9
+ * `'error'` is not optional. BullMQ's `emit` re-emits an unlistened error as
10
+ * `'error'`, which throws again on an EventEmitter with no listener, and ends
11
+ * in a raw `console.error` (`queue-base.js`). The process survives; the log
12
+ * line has no type, reaches no structured sink and alerts nobody.
13
+ */
14
+ export interface QueueWorker {
15
+ close(): Promise<void>;
16
+ on(event: 'failed', listener: (job: unknown, error: Error) => void): unknown;
17
+ on(event: 'error', listener: (error: Error) => void): unknown;
18
+ }
19
+ export type WorkerProcessor<T> = (job: Job<T>) => Promise<void>;
20
+ /**
21
+ * How a worker gets built.
22
+ *
23
+ * This is a constructor collaborator rather than a hard-coded `new Worker(...)`
24
+ * because BullMQ's Worker opens a **blocking** Redis connection the moment it
25
+ * is constructed. A host that built one itself could not be exercised without
26
+ * a live Redis, which would leave every branch below — the disabled path, the
27
+ * failure handler, the bounded close — verified by inspection only. Pass
28
+ * {@link bullWorkerFactory} in production.
29
+ */
30
+ export type WorkerFactory<T> = (name: string, process: WorkerProcessor<T>, options: WorkerOptions) => QueueWorker;
31
+ /** The production factory: a real BullMQ `Worker`. */
32
+ export declare function bullWorkerFactory<T>(name: string, process: WorkerProcessor<T>, options: WorkerOptions): QueueWorker;
33
+ /** The logging surface a host needs — the structured logger's, narrowed. */
34
+ export type WorkerHostLogger = ShutdownPhaseLogger;
35
+ export interface BullWorkerHostOptions<T> {
36
+ /** The queue name. Also the prefix of every log type this host emits. */
37
+ name: string;
38
+ /** Where to read the Redis configuration. */
39
+ source: RedisConfigSource;
40
+ logger: WorkerHostLogger;
41
+ createWorker: WorkerFactory<T>;
42
+ /** Jobs processed in parallel. Defaults to 1. */
43
+ concurrency?: number;
44
+ /** How long `close()` may hold shutdown. Defaults to the package budget. */
45
+ closeTimeoutMs?: number;
46
+ }
47
+ export declare const DEFAULT_WORKER_CONCURRENCY = 1;
48
+ /**
49
+ * The lifecycle every BullMQ processor in these services repeats: start a
50
+ * worker if Redis is configured, warn and stay idle if it is not, report
51
+ * failed jobs, and close inside the shutdown budget.
52
+ *
53
+ * The worker starts in `onModuleInit` and closes in `onModuleDestroy` — phase
54
+ * 1 of the shutdown sequence, where a module stops *consuming* before the HTTP
55
+ * drain. `@leoribeiroweb/nest-core`'s shutdown budget counts one
56
+ * `WORKER_CLOSE_TIMEOUT_MS` per Worker-owning **module**, so a service that
57
+ * adds one must re-derive its budget.
58
+ *
59
+ * Subclasses implement `process` and nothing else. A throw from `process` is
60
+ * BullMQ's business: it retries per the queue's `attempts`, and the `failed`
61
+ * handler here reports the outcome.
62
+ */
63
+ export declare abstract class BullWorkerHost<T> implements OnModuleInit, OnModuleDestroy {
64
+ protected readonly options: BullWorkerHostOptions<T>;
65
+ private worker;
66
+ constructor(options: BullWorkerHostOptions<T>);
67
+ /** Process one delivered job. */
68
+ protected abstract process(job: Job<T>): Promise<void>;
69
+ onModuleInit(): void;
70
+ onModuleDestroy(): Promise<void>;
71
+ }
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BullWorkerHost = exports.DEFAULT_WORKER_CONCURRENCY = void 0;
4
+ exports.bullWorkerFactory = bullWorkerFactory;
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
+ /** The production factory: a real BullMQ `Worker`. */
9
+ function bullWorkerFactory(name, process, options) {
10
+ return new bullmq_1.Worker(name, process, options);
11
+ }
12
+ exports.DEFAULT_WORKER_CONCURRENCY = 1;
13
+ /**
14
+ * The lifecycle every BullMQ processor in these services repeats: start a
15
+ * worker if Redis is configured, warn and stay idle if it is not, report
16
+ * failed jobs, and close inside the shutdown budget.
17
+ *
18
+ * The worker starts in `onModuleInit` and closes in `onModuleDestroy` — phase
19
+ * 1 of the shutdown sequence, where a module stops *consuming* before the HTTP
20
+ * drain. `@leoribeiroweb/nest-core`'s shutdown budget counts one
21
+ * `WORKER_CLOSE_TIMEOUT_MS` per Worker-owning **module**, so a service that
22
+ * adds one must re-derive its budget.
23
+ *
24
+ * Subclasses implement `process` and nothing else. A throw from `process` is
25
+ * BullMQ's business: it retries per the queue's `attempts`, and the `failed`
26
+ * handler here reports the outcome.
27
+ */
28
+ class BullWorkerHost {
29
+ constructor(options) {
30
+ this.options = options;
31
+ this.worker = null;
32
+ }
33
+ onModuleInit() {
34
+ const { name, source, logger, createWorker, concurrency } = this.options;
35
+ const connection = (0, bull_connection_1.createBullConnection)(source);
36
+ if (connection === null) {
37
+ logger.warn(`${name}-worker-disabled`, `Redis not configured — the ${name} worker will not consume`);
38
+ return;
39
+ }
40
+ this.worker = createWorker(name, (job) => this.process(job), {
41
+ connection,
42
+ concurrency: concurrency ?? exports.DEFAULT_WORKER_CONCURRENCY,
43
+ });
44
+ this.worker.on('failed', (job, error) => {
45
+ logger.error(`${name}-job-failed`, `A ${name} job failed`, {
46
+ error,
47
+ meta: { jobId: job?.id },
48
+ });
49
+ });
50
+ this.worker.on('error', (error) => {
51
+ logger.error(`${name}-worker-error`, `The ${name} worker connection failed`, { error });
52
+ });
53
+ }
54
+ 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);
56
+ }
57
+ }
58
+ exports.BullWorkerHost = BullWorkerHost;
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@leoribeiroweb/nest-queue",
3
+ "version": "0.1.0",
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
+ "license": "UNLICENSED",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/leoribeiro2/nest-core.git",
9
+ "directory": "packages/nest-queue"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/leoribeiro2/nest-core/issues"
13
+ },
14
+ "homepage": "https://github.com/leoribeiro2/nest-core#readme",
15
+ "main": "dist/index.js",
16
+ "types": "dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "engines": {
28
+ "node": ">=20.11.0"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "scripts": {
34
+ "build": "tsc -p tsconfig.build.json",
35
+ "prepublishOnly": "npm run build"
36
+ },
37
+ "peerDependencies": {
38
+ "@leoribeiroweb/nest-core": "^0.4.0",
39
+ "@leoribeiroweb/nest-redis": "^0.1.0",
40
+ "@nestjs/common": "^11",
41
+ "@nestjs/terminus": "^11",
42
+ "bullmq": "^5 || ^6",
43
+ "reflect-metadata": "^0.2"
44
+ },
45
+ "devDependencies": {
46
+ "@leoribeiroweb/nest-core": "*",
47
+ "@leoribeiroweb/nest-redis": "*",
48
+ "@nestjs/common": "^11.1.28",
49
+ "@nestjs/core": "^11.1.28",
50
+ "@nestjs/platform-express": "^11.2.5",
51
+ "@nestjs/terminus": "^11.1.1",
52
+ "@nestjs/testing": "^11.1.28",
53
+ "@types/supertest": "^6.0.3",
54
+ "bullmq": "^6.3.7",
55
+ "ioredis": "^6.0.0",
56
+ "reflect-metadata": "^0.2.2",
57
+ "supertest": "^7.2.2"
58
+ }
59
+ }