@nathapp/nestjs-queue 2.1.0-rc.1
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/CLAUDE.md +106 -0
- package/TODO.md +44 -0
- package/dist/constant/index.d.ts +1 -0
- package/dist/constant/index.js +18 -0
- package/dist/constant/index.js.map +1 -0
- package/dist/constant/queue.constant.d.ts +6 -0
- package/dist/constant/queue.constant.js +10 -0
- package/dist/constant/queue.constant.js.map +1 -0
- package/dist/decorator/index.d.ts +3 -0
- package/dist/decorator/index.js +20 -0
- package/dist/decorator/index.js.map +1 -0
- package/dist/decorator/on-queue-event.decorator.d.ts +6 -0
- package/dist/decorator/on-queue-event.decorator.js +18 -0
- package/dist/decorator/on-queue-event.decorator.js.map +1 -0
- package/dist/decorator/process.decorator.d.ts +5 -0
- package/dist/decorator/process.decorator.js +18 -0
- package/dist/decorator/process.decorator.js.map +1 -0
- package/dist/decorator/processor.decorator.d.ts +5 -0
- package/dist/decorator/processor.decorator.js +12 -0
- package/dist/decorator/processor.decorator.js.map +1 -0
- package/dist/enum/index.d.ts +3 -0
- package/dist/enum/index.js +20 -0
- package/dist/enum/index.js.map +1 -0
- package/dist/enum/job-status.enum.d.ts +8 -0
- package/dist/enum/job-status.enum.js +13 -0
- package/dist/enum/job-status.enum.js.map +1 -0
- package/dist/enum/provider.enum.d.ts +7 -0
- package/dist/enum/provider.enum.js +12 -0
- package/dist/enum/provider.enum.js.map +1 -0
- package/dist/enum/queue-event.enum.d.ts +11 -0
- package/dist/enum/queue-event.enum.js +16 -0
- package/dist/enum/queue-event.enum.js.map +1 -0
- package/dist/explorer/index.d.ts +1 -0
- package/dist/explorer/index.js +18 -0
- package/dist/explorer/index.js.map +1 -0
- package/dist/explorer/processor.explorer.d.ts +25 -0
- package/dist/explorer/processor.explorer.js +241 -0
- package/dist/explorer/processor.explorer.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -0
- package/dist/interface/circuit-breaker.interface.d.ts +21 -0
- package/dist/interface/circuit-breaker.interface.js +10 -0
- package/dist/interface/circuit-breaker.interface.js.map +1 -0
- package/dist/interface/health.interface.d.ts +12 -0
- package/dist/interface/health.interface.js +3 -0
- package/dist/interface/health.interface.js.map +1 -0
- package/dist/interface/idempotency-store.interface.d.ts +14 -0
- package/dist/interface/idempotency-store.interface.js +3 -0
- package/dist/interface/idempotency-store.interface.js.map +1 -0
- package/dist/interface/index.d.ts +5 -0
- package/dist/interface/index.js +22 -0
- package/dist/interface/index.js.map +1 -0
- package/dist/interface/job.interface.d.ts +56 -0
- package/dist/interface/job.interface.js +3 -0
- package/dist/interface/job.interface.js.map +1 -0
- package/dist/interface/metrics.interface.d.ts +12 -0
- package/dist/interface/metrics.interface.js +3 -0
- package/dist/interface/metrics.interface.js.map +1 -0
- package/dist/interface/queue-options.interface.d.ts +84 -0
- package/dist/interface/queue-options.interface.js +3 -0
- package/dist/interface/queue-options.interface.js.map +1 -0
- package/dist/interface/queue-provider.interface.d.ts +55 -0
- package/dist/interface/queue-provider.interface.js +7 -0
- package/dist/interface/queue-provider.interface.js.map +1 -0
- package/dist/module/index.d.ts +3 -0
- package/dist/module/index.js +20 -0
- package/dist/module/index.js.map +1 -0
- package/dist/module/queue.module-definition.d.ts +2 -0
- package/dist/module/queue.module-definition.js +11 -0
- package/dist/module/queue.module-definition.js.map +1 -0
- package/dist/module/queue.module.d.ts +3 -0
- package/dist/module/queue.module.js +26 -0
- package/dist/module/queue.module.js.map +1 -0
- package/dist/module/queue.provider.d.ts +2 -0
- package/dist/module/queue.provider.js +57 -0
- package/dist/module/queue.provider.js.map +1 -0
- package/dist/provider/bullmq/bullmq.options.d.ts +12 -0
- package/dist/provider/bullmq/bullmq.options.js +3 -0
- package/dist/provider/bullmq/bullmq.options.js.map +1 -0
- package/dist/provider/bullmq/bullmq.provider.d.ts +52 -0
- package/dist/provider/bullmq/bullmq.provider.js +476 -0
- package/dist/provider/bullmq/bullmq.provider.js.map +1 -0
- package/dist/provider/bullmq/index.d.ts +1 -0
- package/dist/provider/bullmq/index.js +18 -0
- package/dist/provider/bullmq/index.js.map +1 -0
- package/dist/provider/index.d.ts +4 -0
- package/dist/provider/index.js +21 -0
- package/dist/provider/index.js.map +1 -0
- package/dist/provider/kafka/index.d.ts +1 -0
- package/dist/provider/kafka/index.js +18 -0
- package/dist/provider/kafka/index.js.map +1 -0
- package/dist/provider/kafka/kafka.provider.d.ts +59 -0
- package/dist/provider/kafka/kafka.provider.js +598 -0
- package/dist/provider/kafka/kafka.provider.js.map +1 -0
- package/dist/provider/rabbitmq/index.d.ts +1 -0
- package/dist/provider/rabbitmq/index.js +18 -0
- package/dist/provider/rabbitmq/index.js.map +1 -0
- package/dist/provider/rabbitmq/rabbitmq.provider.d.ts +48 -0
- package/dist/provider/rabbitmq/rabbitmq.provider.js +498 -0
- package/dist/provider/rabbitmq/rabbitmq.provider.js.map +1 -0
- package/dist/provider/redis-pubsub/index.d.ts +1 -0
- package/dist/provider/redis-pubsub/index.js +18 -0
- package/dist/provider/redis-pubsub/index.js.map +1 -0
- package/dist/provider/redis-pubsub/redis-pubsub.provider.d.ts +40 -0
- package/dist/provider/redis-pubsub/redis-pubsub.provider.js +226 -0
- package/dist/provider/redis-pubsub/redis-pubsub.provider.js.map +1 -0
- package/dist/service/index.d.ts +1 -0
- package/dist/service/index.js +18 -0
- package/dist/service/index.js.map +1 -0
- package/dist/service/queue.service.d.ts +36 -0
- package/dist/service/queue.service.js +89 -0
- package/dist/service/queue.service.js.map +1 -0
- package/dist/store/in-memory-idempotency.store.d.ts +15 -0
- package/dist/store/in-memory-idempotency.store.js +84 -0
- package/dist/store/in-memory-idempotency.store.js.map +1 -0
- package/dist/store/index.d.ts +1 -0
- package/dist/store/index.js +6 -0
- package/dist/store/index.js.map +1 -0
- package/dist/utils/circuit-breaker.d.ts +30 -0
- package/dist/utils/circuit-breaker.js +133 -0
- package/dist/utils/circuit-breaker.js.map +1 -0
- package/dist/utils/delayed-scheduler.d.ts +16 -0
- package/dist/utils/delayed-scheduler.js +100 -0
- package/dist/utils/delayed-scheduler.js.map +1 -0
- package/dist/utils/errors.d.ts +23 -0
- package/dist/utils/errors.js +85 -0
- package/dist/utils/errors.js.map +1 -0
- package/dist/utils/index.d.ts +5 -0
- package/dist/utils/index.js +22 -0
- package/dist/utils/index.js.map +1 -0
- package/dist/utils/lock-renewal.d.ts +14 -0
- package/dist/utils/lock-renewal.js +61 -0
- package/dist/utils/lock-renewal.js.map +1 -0
- package/dist/utils/redis-idempotency-store.d.ts +21 -0
- package/dist/utils/redis-idempotency-store.js +88 -0
- package/dist/utils/redis-idempotency-store.js.map +1 -0
- package/dist/utils/sanitize.d.ts +3 -0
- package/dist/utils/sanitize.js +55 -0
- package/dist/utils/sanitize.js.map +1 -0
- package/dist/utils/validation.d.ts +8 -0
- package/dist/utils/validation.js +60 -0
- package/dist/utils/validation.js.map +1 -0
- package/docker-compose.e2e.yml +69 -0
- package/docs/FINAL_CODE_REVIEW.md +328 -0
- package/docs/IMPLEMENTATION_PLAN.md +748 -0
- package/docs/archive/CIRCUIT_BREAKER_PLAN.md +35 -0
- package/docs/archive/CODE_REVIEW.md +596 -0
- package/docs/archive/CODE_REVIEW_V2.md +1081 -0
- package/docs/archive/CODE_REVIEW_V3.md +402 -0
- package/docs/archive/IMPLEMENTATION_PLAN.md +505 -0
- package/docs/archive/IMPLEMENTATION_PLAN_BUGFIX.md +428 -0
- package/package.json +70 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Implementation Plan: Circuit Breaker for `@nathapp/nestjs-queue`
|
|
2
|
+
|
|
3
|
+
## 1. Overview
|
|
4
|
+
The circuit breaker pattern prevents cascading failures when downstream services are unhealthy. It implements three states:
|
|
5
|
+
- **CLOSED**: Normal operation.
|
|
6
|
+
- **OPEN**: Fast-failing, rejecting calls after threshold reached.
|
|
7
|
+
- **HALF_OPEN**: Probing after reset timeout.
|
|
8
|
+
|
|
9
|
+
## 2. Interface Design
|
|
10
|
+
- **`CircuitBreakerOptions`**: `enabled`, `failureThreshold`, `successThreshold`, `resetTimeoutMs`, `windowMs`, `isFailure`, `onStateChange`.
|
|
11
|
+
- **`ProcessorOptions`**: Extend with `circuitBreaker`.
|
|
12
|
+
- **`QueueModuleOptions`**: Extend with global default `circuitBreaker`.
|
|
13
|
+
|
|
14
|
+
## 3. Core Implementation
|
|
15
|
+
- **`CircuitBreaker` class**: Manages states per queue using a sliding window for failures.
|
|
16
|
+
- **`CircuitBreakerOpenError`**: Custom error thrown when the circuit is OPEN.
|
|
17
|
+
|
|
18
|
+
## 4. Integration
|
|
19
|
+
- **`ProcessorExplorer`**: Wrap `routerHandler` with a circuit breaker guard.
|
|
20
|
+
- **`Processor` Decorator**: Allow per-processor configuration.
|
|
21
|
+
- **`QueueMetrics`**: Add `circuitBreakerStateChange` and `circuitBreakerRejection`.
|
|
22
|
+
|
|
23
|
+
## 5. File Changes
|
|
24
|
+
- `lib/interface/circuit-breaker.interface.ts` (New)
|
|
25
|
+
- `lib/utils/circuit-breaker.ts` (New)
|
|
26
|
+
- `lib/interface/job.interface.ts`
|
|
27
|
+
- `lib/interface/queue-options.interface.ts`
|
|
28
|
+
- `lib/interface/metrics.interface.ts`
|
|
29
|
+
- `lib/explorer/processor.explorer.ts`
|
|
30
|
+
- `lib/decorator/processor.decorator.ts`
|
|
31
|
+
- `test/circuit-breaker.spec.ts` (New)
|
|
32
|
+
- `test/e2e/circuit-breaker.e2e-spec.ts` (New)
|
|
33
|
+
|
|
34
|
+
## 6. Task
|
|
35
|
+
Implement the circuit breaker pattern as described in the plan. Ensure 100% test coverage for the new utility and verify integration via E2E tests.
|
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
# @nathapp/nestjs-queue - Code Review
|
|
2
|
+
|
|
3
|
+
**Date:** 2026-02-08
|
|
4
|
+
**Reviewer:** Sabrina (AI Assistant)
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Executive Summary
|
|
9
|
+
|
|
10
|
+
Deep analysis of the nestjs-queue package revealed **8 bugs**, **6 security concerns**, and **12 enhancement opportunities**. The most critical issues are in the BullMQ provider (causing test failures) and RabbitMQ retry logic (race condition).
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## 🐛 BUGS
|
|
15
|
+
|
|
16
|
+
### 1. **BullMQ: Lua Script Error from Undefined Options** ⚠️ CRITICAL
|
|
17
|
+
|
|
18
|
+
**File:** `lib/provider/bullmq/bullmq.provider.ts` (lines 65-80)
|
|
19
|
+
|
|
20
|
+
**Problem:** The `mapJobOptions` function returns undefined values which BullMQ passes to Redis Lua scripts, causing:
|
|
21
|
+
```
|
|
22
|
+
ERR Lua redis lib command arguments must be strings or integers
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
**Root Cause:**
|
|
26
|
+
```typescript
|
|
27
|
+
private mapJobOptions(opts?: JobOptions): any {
|
|
28
|
+
if (!opts) return {};
|
|
29
|
+
return {
|
|
30
|
+
delay: opts.delay, // undefined passed to Redis
|
|
31
|
+
attempts: opts.attempts, // undefined passed to Redis
|
|
32
|
+
backoff: opts.backoff, // undefined passed to Redis
|
|
33
|
+
// ... all undefined values included
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
**Fix:**
|
|
39
|
+
```typescript
|
|
40
|
+
private mapJobOptions(opts?: JobOptions): any {
|
|
41
|
+
if (!opts) return {};
|
|
42
|
+
|
|
43
|
+
const result: Record<string, any> = {};
|
|
44
|
+
|
|
45
|
+
if (opts.delay !== undefined) result.delay = opts.delay;
|
|
46
|
+
if (opts.attempts !== undefined) result.attempts = opts.attempts;
|
|
47
|
+
if (opts.backoff !== undefined) result.backoff = opts.backoff;
|
|
48
|
+
if (opts.priority !== undefined) result.priority = opts.priority;
|
|
49
|
+
if (opts.removeOnComplete !== undefined) result.removeOnComplete = opts.removeOnComplete;
|
|
50
|
+
if (opts.removeOnFail !== undefined) result.removeOnFail = opts.removeOnFail;
|
|
51
|
+
if (opts.jobId !== undefined) result.jobId = opts.jobId;
|
|
52
|
+
|
|
53
|
+
if (opts.repeat) {
|
|
54
|
+
result.repeat = {};
|
|
55
|
+
if (opts.repeat.pattern !== undefined) result.repeat.pattern = opts.repeat.pattern;
|
|
56
|
+
if (opts.repeat.every !== undefined) result.repeat.every = opts.repeat.every;
|
|
57
|
+
if (opts.repeat.limit !== undefined) result.repeat.limit = opts.repeat.limit;
|
|
58
|
+
if (opts.repeat.startDate !== undefined) result.repeat.startDate = opts.repeat.startDate;
|
|
59
|
+
if (opts.repeat.endDate !== undefined) result.repeat.endDate = opts.repeat.endDate;
|
|
60
|
+
if (opts.repeat.tz !== undefined) result.repeat.tz = opts.repeat.tz;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return result;
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
### 2. **RabbitMQ: Retry Race Condition** ⚠️ HIGH
|
|
70
|
+
|
|
71
|
+
**File:** `lib/provider/rabbitmq/rabbitmq.provider.ts` (lines 178-192)
|
|
72
|
+
|
|
73
|
+
**Problem:** When a job fails and needs retry:
|
|
74
|
+
1. `channel.nack()` is called immediately
|
|
75
|
+
2. `setTimeout` schedules re-add
|
|
76
|
+
3. If connection drops between nack and re-add, job is lost
|
|
77
|
+
|
|
78
|
+
**Current Code:**
|
|
79
|
+
```typescript
|
|
80
|
+
// Reject without requeue, then re-publish with delay
|
|
81
|
+
channel.nack(msg, false, false);
|
|
82
|
+
|
|
83
|
+
const delay = this.calculateBackoff(job);
|
|
84
|
+
|
|
85
|
+
// Race condition: connection could drop here
|
|
86
|
+
setTimeout(async () => {
|
|
87
|
+
await this.add(queueName, job.name, job.data, {...});
|
|
88
|
+
}, delay);
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
**Fix:**
|
|
92
|
+
```typescript
|
|
93
|
+
// Re-add FIRST, then nack
|
|
94
|
+
const delay = this.calculateBackoff(job);
|
|
95
|
+
|
|
96
|
+
try {
|
|
97
|
+
// Update job with incremented attempts before re-adding
|
|
98
|
+
const retryJob = {
|
|
99
|
+
...job,
|
|
100
|
+
attemptsMade: job.attemptsMade + 1,
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
await this.add(queueName, retryJob.name, retryJob.data, {
|
|
104
|
+
...retryJob.opts,
|
|
105
|
+
jobId: retryJob.id,
|
|
106
|
+
delay,
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
// Only ack after successful re-add
|
|
110
|
+
channel.ack(msg);
|
|
111
|
+
} catch (retryError) {
|
|
112
|
+
// If re-add fails, nack to requeue original message
|
|
113
|
+
channel.nack(msg, false, true);
|
|
114
|
+
this.logger.error(`Failed to reschedule retry: ${retryError.message}`);
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
### 3. **RabbitMQ: Event Listener Cross-Contamination** ⚠️ HIGH
|
|
121
|
+
|
|
122
|
+
**File:** `lib/provider/rabbitmq/rabbitmq.provider.ts` (lines 80-95)
|
|
123
|
+
|
|
124
|
+
**Problem:** Event listeners registered on a queue receive ALL job events, not just the ones they're interested in. This caused test failures:
|
|
125
|
+
```
|
|
126
|
+
Expected: { "processed": true }
|
|
127
|
+
Received: { "processed": 1770517735011 } // timestamp from different test
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
**Fix:** Add job correlation to events:
|
|
131
|
+
```typescript
|
|
132
|
+
on(
|
|
133
|
+
queueName: string,
|
|
134
|
+
event: QueueEvent,
|
|
135
|
+
callback: (job: IJob, result?: any) => void,
|
|
136
|
+
jobFilter?: { name?: string; id?: string },
|
|
137
|
+
): void {
|
|
138
|
+
// Store filter with callback
|
|
139
|
+
const wrappedCallback = (job: IJob, result?: any) => {
|
|
140
|
+
if (jobFilter?.name && job.name !== jobFilter.name) return;
|
|
141
|
+
if (jobFilter?.id && job.id !== jobFilter.id) return;
|
|
142
|
+
callback(job, result);
|
|
143
|
+
};
|
|
144
|
+
// ... rest of registration
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
---
|
|
149
|
+
|
|
150
|
+
### 4. **Kafka: Delayed Job Duplication** ⚠️ MEDIUM
|
|
151
|
+
|
|
152
|
+
**File:** `lib/provider/kafka/kafka.provider.ts` (lines 168-178)
|
|
153
|
+
|
|
154
|
+
**Problem:** When processing a delayed job that's not ready:
|
|
155
|
+
```typescript
|
|
156
|
+
if (processAfter && parseInt(processAfter) > Date.now()) {
|
|
157
|
+
const delay = parseInt(processAfter) - Date.now();
|
|
158
|
+
await this.add(queueName, job.name, job.data, {..., delay});
|
|
159
|
+
return; // Original message still committed!
|
|
160
|
+
}
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
This creates a DUPLICATE message every time the job is consumed before its time.
|
|
164
|
+
|
|
165
|
+
**Fix:** Use proper delay mechanism or track processed message IDs:
|
|
166
|
+
```typescript
|
|
167
|
+
// Option 1: Skip without re-adding (let Kafka re-deliver)
|
|
168
|
+
if (processAfter && parseInt(processAfter) > Date.now()) {
|
|
169
|
+
// Pause consumer briefly, then resume
|
|
170
|
+
await consumer.pause([{ topic: queueName }]);
|
|
171
|
+
const delay = Math.min(parseInt(processAfter) - Date.now(), 5000);
|
|
172
|
+
setTimeout(() => consumer.resume([{ topic: queueName }]), delay);
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Option 2: Use a separate delay topic pattern
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
---
|
|
180
|
+
|
|
181
|
+
### 5. **BullMQ: Missing Worker Error Recovery** ⚠️ MEDIUM
|
|
182
|
+
|
|
183
|
+
**File:** `lib/provider/bullmq/bullmq.provider.ts` (lines 155-157)
|
|
184
|
+
|
|
185
|
+
**Problem:** Worker errors are only logged, not recovered:
|
|
186
|
+
```typescript
|
|
187
|
+
worker.on('error', (error) => {
|
|
188
|
+
this.logger.error(`Worker error: ${error.message}`);
|
|
189
|
+
});
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
**Fix:** Implement error recovery:
|
|
193
|
+
```typescript
|
|
194
|
+
worker.on('error', (error) => {
|
|
195
|
+
this.logger.error(`Worker error: ${error.message}`);
|
|
196
|
+
|
|
197
|
+
// Emit to event listeners
|
|
198
|
+
this.emitLocalEvent(queueName, QueueEvent.ERROR, null, error);
|
|
199
|
+
|
|
200
|
+
// Attempt recovery for connection errors
|
|
201
|
+
if (error.message.includes('ECONNREFUSED') || error.message.includes('ECONNRESET')) {
|
|
202
|
+
this.logger.warn(`Attempting worker recovery for ${queueName}...`);
|
|
203
|
+
// Worker will auto-reconnect in most cases
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
---
|
|
209
|
+
|
|
210
|
+
### 6. **ProcessorExplorer: Swallowed Async Errors** ⚠️ MEDIUM
|
|
211
|
+
|
|
212
|
+
**File:** `lib/explorer/processor.explorer.ts` (line 45)
|
|
213
|
+
|
|
214
|
+
**Problem:** `explore()` doesn't handle async errors properly:
|
|
215
|
+
```typescript
|
|
216
|
+
async onModuleInit(): Promise<void> {
|
|
217
|
+
await this.explore(); // If this throws, app may be in bad state
|
|
218
|
+
}
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
**Fix:**
|
|
222
|
+
```typescript
|
|
223
|
+
async onModuleInit(): Promise<void> {
|
|
224
|
+
try {
|
|
225
|
+
await this.explore();
|
|
226
|
+
} catch (error) {
|
|
227
|
+
this.logger.error(`Failed to explore processors: ${error.message}`);
|
|
228
|
+
throw error; // Re-throw to fail module init
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
---
|
|
234
|
+
|
|
235
|
+
### 7. **Redis Pub/Sub: Subscriber Memory Leak** ⚠️ LOW
|
|
236
|
+
|
|
237
|
+
**File:** `lib/provider/redis-pubsub/redis-pubsub.provider.ts`
|
|
238
|
+
|
|
239
|
+
**Problem:** `pause()` unsubscribes but keeps the Redis connection. Multiple pause/resume cycles create connection objects that aren't cleaned up.
|
|
240
|
+
|
|
241
|
+
---
|
|
242
|
+
|
|
243
|
+
### 8. **All Providers: Missing Job ID Validation** ⚠️ LOW
|
|
244
|
+
|
|
245
|
+
**Problem:** Custom `jobId` values are not validated:
|
|
246
|
+
```typescript
|
|
247
|
+
const job = await queueService.add('queue', 'job', data, {
|
|
248
|
+
jobId: '../../etc/passwd', // Could cause issues in some storage backends
|
|
249
|
+
});
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
**Fix:** Validate job IDs:
|
|
253
|
+
```typescript
|
|
254
|
+
private validateJobId(id: string): void {
|
|
255
|
+
if (!/^[a-zA-Z0-9_-]{1,256}$/.test(id)) {
|
|
256
|
+
throw new Error('Invalid job ID format');
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
---
|
|
262
|
+
|
|
263
|
+
## 🔒 SECURITY ISSUES
|
|
264
|
+
|
|
265
|
+
### 1. **No Input Validation on Job Data** ⚠️ HIGH
|
|
266
|
+
|
|
267
|
+
**Problem:** Job data is serialized directly without validation:
|
|
268
|
+
```typescript
|
|
269
|
+
await channel.sendToQueue(queueName, Buffer.from(JSON.stringify(job)), ...);
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
Malicious payloads could cause:
|
|
273
|
+
- Prototype pollution during JSON.parse
|
|
274
|
+
- Denial of service from large payloads
|
|
275
|
+
- Injection attacks if data is used in queries
|
|
276
|
+
|
|
277
|
+
**Recommendation:**
|
|
278
|
+
```typescript
|
|
279
|
+
// Add validation before processing
|
|
280
|
+
import { validateOrReject, IsString, MaxLength } from 'class-validator';
|
|
281
|
+
|
|
282
|
+
interface JobDataConstraints {
|
|
283
|
+
maxPayloadSize: number; // e.g., 1MB
|
|
284
|
+
allowedTypes: string[];
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
private async validateJobData<T>(data: T, constraints?: JobDataConstraints): Promise<void> {
|
|
288
|
+
const serialized = JSON.stringify(data);
|
|
289
|
+
if (constraints?.maxPayloadSize && serialized.length > constraints.maxPayloadSize) {
|
|
290
|
+
throw new Error(`Job payload exceeds max size of ${constraints.maxPayloadSize} bytes`);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
---
|
|
296
|
+
|
|
297
|
+
### 2. **Credentials in Plain Text** ⚠️ HIGH
|
|
298
|
+
|
|
299
|
+
**Problem:** All providers accept passwords as plain strings:
|
|
300
|
+
```typescript
|
|
301
|
+
export interface BullMQConnectionOptions {
|
|
302
|
+
password?: string; // Plain text
|
|
303
|
+
}
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
**Recommendation:** Support secret providers:
|
|
307
|
+
```typescript
|
|
308
|
+
export interface BullMQConnectionOptions {
|
|
309
|
+
password?: string | (() => Promise<string>); // Support async secret fetch
|
|
310
|
+
passwordFromEnv?: string; // e.g., 'REDIS_PASSWORD'
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// In provider:
|
|
314
|
+
private async getPassword(): Promise<string | undefined> {
|
|
315
|
+
if (typeof this.options.connection.password === 'function') {
|
|
316
|
+
return this.options.connection.password();
|
|
317
|
+
}
|
|
318
|
+
if (this.options.connection.passwordFromEnv) {
|
|
319
|
+
return process.env[this.options.connection.passwordFromEnv];
|
|
320
|
+
}
|
|
321
|
+
return this.options.connection.password;
|
|
322
|
+
}
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
---
|
|
326
|
+
|
|
327
|
+
### 3. **Kafka SASL Credentials Logged on Error** ⚠️ MEDIUM
|
|
328
|
+
|
|
329
|
+
**File:** `lib/provider/kafka/kafka.provider.ts`
|
|
330
|
+
|
|
331
|
+
**Problem:** Error messages might include connection details:
|
|
332
|
+
```typescript
|
|
333
|
+
this.connection.on('connectFailed', (params: { err?: Error }) => {
|
|
334
|
+
this.logger.error(`RabbitMQ connection failed: ${params.err?.message || 'unknown'}`);
|
|
335
|
+
// Error message might contain password
|
|
336
|
+
});
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
**Recommendation:** Sanitize error messages:
|
|
340
|
+
```typescript
|
|
341
|
+
private sanitizeError(message: string): string {
|
|
342
|
+
return message.replace(/password=\S+/gi, 'password=***');
|
|
343
|
+
}
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
---
|
|
347
|
+
|
|
348
|
+
### 4. **No Job Encryption for Sensitive Data** ⚠️ MEDIUM
|
|
349
|
+
|
|
350
|
+
**Problem:** Job data is stored/transmitted in plain text. Sensitive data (PII, tokens) is exposed.
|
|
351
|
+
|
|
352
|
+
**Recommendation:** Add optional encryption layer:
|
|
353
|
+
```typescript
|
|
354
|
+
export interface QueueModuleOptions {
|
|
355
|
+
encryption?: {
|
|
356
|
+
enabled: boolean;
|
|
357
|
+
algorithm: 'aes-256-gcm';
|
|
358
|
+
keyProvider: () => Promise<Buffer>;
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
---
|
|
364
|
+
|
|
365
|
+
### 5. **No Rate Limiting at Add Level** ⚠️ LOW
|
|
366
|
+
|
|
367
|
+
**Problem:** No protection against queue flooding:
|
|
368
|
+
```typescript
|
|
369
|
+
// Attacker could call this in a loop
|
|
370
|
+
for (let i = 0; i < 1000000; i++) {
|
|
371
|
+
await queueService.add('queue', 'job', { malicious: true });
|
|
372
|
+
}
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
**Recommendation:** Add rate limiting option:
|
|
376
|
+
```typescript
|
|
377
|
+
export interface QueueModuleOptions {
|
|
378
|
+
rateLimits?: {
|
|
379
|
+
addPerSecond?: number;
|
|
380
|
+
addBurstSize?: number;
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
---
|
|
386
|
+
|
|
387
|
+
### 6. **Missing Dead Letter Queue Security** ⚠️ LOW
|
|
388
|
+
|
|
389
|
+
**Problem:** Failed jobs with sensitive data go to DLQ without encryption or TTL.
|
|
390
|
+
|
|
391
|
+
**Recommendation:** Auto-expire DLQ messages and encrypt sensitive fields.
|
|
392
|
+
|
|
393
|
+
---
|
|
394
|
+
|
|
395
|
+
## 🚀 ENHANCEMENT SUGGESTIONS
|
|
396
|
+
|
|
397
|
+
### 1. **Add Circuit Breaker Pattern**
|
|
398
|
+
|
|
399
|
+
```typescript
|
|
400
|
+
import CircuitBreaker from 'opossum';
|
|
401
|
+
|
|
402
|
+
export interface QueueModuleOptions {
|
|
403
|
+
circuitBreaker?: {
|
|
404
|
+
enabled: boolean;
|
|
405
|
+
timeout: number;
|
|
406
|
+
errorThresholdPercentage: number;
|
|
407
|
+
resetTimeout: number;
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
### 2. **Add Prometheus Metrics**
|
|
413
|
+
|
|
414
|
+
```typescript
|
|
415
|
+
import { Counter, Histogram, Gauge } from 'prom-client';
|
|
416
|
+
|
|
417
|
+
const jobsProcessed = new Counter({
|
|
418
|
+
name: 'queue_jobs_processed_total',
|
|
419
|
+
help: 'Total jobs processed',
|
|
420
|
+
labelNames: ['queue', 'status'],
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
const jobDuration = new Histogram({
|
|
424
|
+
name: 'queue_job_duration_seconds',
|
|
425
|
+
help: 'Job processing duration',
|
|
426
|
+
labelNames: ['queue', 'job_name'],
|
|
427
|
+
});
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
### 3. **Add Health Checks**
|
|
431
|
+
|
|
432
|
+
```typescript
|
|
433
|
+
@Injectable()
|
|
434
|
+
export class QueueHealthIndicator extends HealthIndicator {
|
|
435
|
+
async isHealthy(key: string): Promise<HealthIndicatorResult> {
|
|
436
|
+
const isHealthy = await this.provider.ping();
|
|
437
|
+
return this.getStatus(key, isHealthy);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
### 4. **Add Job Middleware/Interceptors**
|
|
443
|
+
|
|
444
|
+
```typescript
|
|
445
|
+
export interface JobMiddleware<T = any> {
|
|
446
|
+
before?(job: IJob<T>): Promise<IJob<T>>;
|
|
447
|
+
after?(job: IJob<T>, result: any): Promise<void>;
|
|
448
|
+
onError?(job: IJob<T>, error: Error): Promise<void>;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
@Processor({ queueName: 'emails', middleware: [LoggingMiddleware, ValidationMiddleware] })
|
|
452
|
+
```
|
|
453
|
+
|
|
454
|
+
### 5. **Better TypeScript Generics**
|
|
455
|
+
|
|
456
|
+
```typescript
|
|
457
|
+
// Current: weak typing
|
|
458
|
+
async add<T>(queueName: string, ...): Promise<IJob<T>>
|
|
459
|
+
|
|
460
|
+
// Enhanced: strong typing with job registry
|
|
461
|
+
interface JobRegistry {
|
|
462
|
+
'email-queue': { send: EmailPayload; verify: VerifyPayload };
|
|
463
|
+
'notification-queue': { push: PushPayload };
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
async add<Q extends keyof JobRegistry, J extends keyof JobRegistry[Q]>(
|
|
467
|
+
queueName: Q,
|
|
468
|
+
jobName: J,
|
|
469
|
+
data: JobRegistry[Q][J],
|
|
470
|
+
): Promise<IJob<JobRegistry[Q][J]>>
|
|
471
|
+
```
|
|
472
|
+
|
|
473
|
+
### 6. **Add Batch Processing Improvements**
|
|
474
|
+
|
|
475
|
+
```typescript
|
|
476
|
+
async addBatch<T>(
|
|
477
|
+
queueName: string,
|
|
478
|
+
jobs: Array<{ name: string; data: T; opts?: JobOptions }>,
|
|
479
|
+
options?: {
|
|
480
|
+
chunkSize?: number; // Split into chunks
|
|
481
|
+
parallel?: boolean; // Add chunks in parallel
|
|
482
|
+
stopOnError?: boolean; // Stop batch on first error
|
|
483
|
+
onProgress?: (completed: number, total: number) => void;
|
|
484
|
+
},
|
|
485
|
+
): Promise<BatchResult<T>>
|
|
486
|
+
```
|
|
487
|
+
|
|
488
|
+
### 7. **Add Job Scheduling with Cron**
|
|
489
|
+
|
|
490
|
+
```typescript
|
|
491
|
+
@Processor({ queueName: 'scheduled' })
|
|
492
|
+
export class ScheduledProcessor {
|
|
493
|
+
@Process()
|
|
494
|
+
@Cron('0 9 * * *', { timezone: 'UTC' }) // Every day at 9 AM
|
|
495
|
+
async dailyReport() {
|
|
496
|
+
// ...
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
```
|
|
500
|
+
|
|
501
|
+
### 8. **Add Graceful Shutdown with Drain**
|
|
502
|
+
|
|
503
|
+
```typescript
|
|
504
|
+
async onModuleDestroy(): Promise<void> {
|
|
505
|
+
this.logger.log('Starting graceful shutdown...');
|
|
506
|
+
|
|
507
|
+
// 1. Stop accepting new jobs
|
|
508
|
+
await this.provider.pauseAll();
|
|
509
|
+
|
|
510
|
+
// 2. Wait for in-flight jobs
|
|
511
|
+
const timeout = this.options.shutdownTimeout || 30000;
|
|
512
|
+
await this.provider.drain(timeout);
|
|
513
|
+
|
|
514
|
+
// 3. Close connections
|
|
515
|
+
await this.provider.close();
|
|
516
|
+
}
|
|
517
|
+
```
|
|
518
|
+
|
|
519
|
+
### 9. **Add Job Deduplication**
|
|
520
|
+
|
|
521
|
+
```typescript
|
|
522
|
+
export interface JobOptions {
|
|
523
|
+
dedupe?: {
|
|
524
|
+
enabled: boolean;
|
|
525
|
+
key?: string | ((data: any) => string); // Custom dedup key
|
|
526
|
+
ttl?: number; // How long to remember seen jobs
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
### 10. **Add Priority Queues Support**
|
|
532
|
+
|
|
533
|
+
```typescript
|
|
534
|
+
// Separate queues by priority with dedicated workers
|
|
535
|
+
@Processor({
|
|
536
|
+
queueName: 'notifications',
|
|
537
|
+
priorityQueues: ['high', 'normal', 'low'],
|
|
538
|
+
priorityWeights: { high: 10, normal: 5, low: 1 },
|
|
539
|
+
})
|
|
540
|
+
```
|
|
541
|
+
|
|
542
|
+
### 11. **Add Flow/Workflow Support**
|
|
543
|
+
|
|
544
|
+
```typescript
|
|
545
|
+
// Define job dependencies (like BullMQ flows)
|
|
546
|
+
const workflow = await queueService.addFlow({
|
|
547
|
+
name: 'order-processing',
|
|
548
|
+
children: [
|
|
549
|
+
{ name: 'validate-order', data: orderData },
|
|
550
|
+
{ name: 'charge-payment', data: paymentData, dependsOn: ['validate-order'] },
|
|
551
|
+
{ name: 'send-confirmation', data: emailData, dependsOn: ['charge-payment'] },
|
|
552
|
+
],
|
|
553
|
+
});
|
|
554
|
+
```
|
|
555
|
+
|
|
556
|
+
### 12. **Add OpenTelemetry Tracing**
|
|
557
|
+
|
|
558
|
+
```typescript
|
|
559
|
+
import { trace, context, SpanKind } from '@opentelemetry/api';
|
|
560
|
+
|
|
561
|
+
// Auto-instrument job processing with traces
|
|
562
|
+
const span = tracer.startSpan(`queue.process.${job.name}`, {
|
|
563
|
+
kind: SpanKind.CONSUMER,
|
|
564
|
+
attributes: {
|
|
565
|
+
'queue.name': queueName,
|
|
566
|
+
'job.id': job.id,
|
|
567
|
+
'job.name': job.name,
|
|
568
|
+
},
|
|
569
|
+
});
|
|
570
|
+
```
|
|
571
|
+
|
|
572
|
+
---
|
|
573
|
+
|
|
574
|
+
## 📋 Priority Matrix
|
|
575
|
+
|
|
576
|
+
| Issue | Severity | Effort | Priority |
|
|
577
|
+
|-------|----------|--------|----------|
|
|
578
|
+
| BullMQ Lua Script Error | Critical | Low | P0 |
|
|
579
|
+
| RabbitMQ Retry Race Condition | High | Medium | P0 |
|
|
580
|
+
| RabbitMQ Event Cross-Contamination | High | Medium | P1 |
|
|
581
|
+
| Input Validation | High | Medium | P1 |
|
|
582
|
+
| Kafka Delayed Job Duplication | Medium | Medium | P1 |
|
|
583
|
+
| Credentials Security | High | Low | P1 |
|
|
584
|
+
| Add Prometheus Metrics | Enhancement | Medium | P2 |
|
|
585
|
+
| Add Health Checks | Enhancement | Low | P2 |
|
|
586
|
+
| Add Circuit Breaker | Enhancement | Medium | P2 |
|
|
587
|
+
| Add Job Middleware | Enhancement | High | P3 |
|
|
588
|
+
|
|
589
|
+
---
|
|
590
|
+
|
|
591
|
+
## Next Steps
|
|
592
|
+
|
|
593
|
+
1. **Immediate:** Fix BullMQ `mapJobOptions` to filter undefined values
|
|
594
|
+
2. **This Sprint:** Fix RabbitMQ retry race condition and event isolation
|
|
595
|
+
3. **Backlog:** Add security enhancements (validation, encryption options)
|
|
596
|
+
4. **Future:** Implement observability (metrics, tracing, health checks)
|