@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,1081 @@
|
|
|
1
|
+
# Code Review V2: Error Handling, Graceful Shutdown & Multi-Instance
|
|
2
|
+
|
|
3
|
+
## Executive Summary
|
|
4
|
+
|
|
5
|
+
This review addresses:
|
|
6
|
+
1. **Error Handling** - Proper try/catch, error propagation, and recovery
|
|
7
|
+
2. **Graceful Shutdown** - Clean resource cleanup with timeouts
|
|
8
|
+
3. **Retry/Delay Overhead** - Performance analysis for RabbitMQ and Kafka
|
|
9
|
+
4. **Multi-Instance Proof** - Preventing duplicate processing across pods
|
|
10
|
+
5. **Idempotency Store** - Abstract, pluggable idempotency for RabbitMQ *(NEW)*
|
|
11
|
+
6. **CorrelationId Handling** - Request tracing across job boundaries *(NEW)*
|
|
12
|
+
7. **Memory Leak Analysis** - Identified leaks and fixes *(NEW)*
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## 1. Error Handling Analysis
|
|
17
|
+
|
|
18
|
+
### Current State
|
|
19
|
+
|
|
20
|
+
#### BullMQ ✅ Good
|
|
21
|
+
- Worker errors are caught and logged
|
|
22
|
+
- Job failures emit proper events
|
|
23
|
+
- Connection errors handled by BullMQ internally
|
|
24
|
+
|
|
25
|
+
#### Kafka ⚠️ Needs Improvement
|
|
26
|
+
- No try/catch around consumer.connect()
|
|
27
|
+
- Admin operations can throw without cleanup
|
|
28
|
+
- Producer send failures not consistently handled
|
|
29
|
+
|
|
30
|
+
#### RabbitMQ ⚠️ Needs Improvement
|
|
31
|
+
- Channel errors can orphan connections
|
|
32
|
+
- No reconnection handling for channel failures
|
|
33
|
+
- Message parsing errors not isolated
|
|
34
|
+
|
|
35
|
+
### Recommended Fixes
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
// Pattern: Wrap all async operations with proper error handling
|
|
39
|
+
async add<T>(queueName: string, ...): Promise<IJob<T>> {
|
|
40
|
+
try {
|
|
41
|
+
// ... operation
|
|
42
|
+
} catch (error) {
|
|
43
|
+
this.logger.error(`Failed to add job to ${queueName}: ${error.message}`);
|
|
44
|
+
throw new QueueOperationError('ADD_FAILED', queueName, error);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## 2. Graceful Shutdown Analysis
|
|
52
|
+
|
|
53
|
+
### Current Issues
|
|
54
|
+
|
|
55
|
+
1. **No Shutdown Timeout** - `close()` can hang indefinitely if a connection is stuck
|
|
56
|
+
2. **No In-Flight Job Handling** - Jobs being processed during shutdown may be lost
|
|
57
|
+
3. **No Shutdown Signal Handling** - Missing SIGTERM/SIGINT hooks
|
|
58
|
+
|
|
59
|
+
### Recommended Implementation
|
|
60
|
+
|
|
61
|
+
```typescript
|
|
62
|
+
interface ShutdownOptions {
|
|
63
|
+
timeout?: number; // Max wait time (default: 30s)
|
|
64
|
+
drainQueues?: boolean; // Wait for in-flight jobs (default: true)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async close(options: ShutdownOptions = {}): Promise<void> {
|
|
68
|
+
const timeout = options.timeout ?? 30000;
|
|
69
|
+
const drainQueues = options.drainQueues ?? true;
|
|
70
|
+
|
|
71
|
+
// 1. Stop accepting new jobs
|
|
72
|
+
// 2. Wait for in-flight jobs (with timeout)
|
|
73
|
+
// 3. Close connections
|
|
74
|
+
// 4. Cleanup resources
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
## 3. Retry & Delayed Job Overhead
|
|
81
|
+
|
|
82
|
+
### RabbitMQ
|
|
83
|
+
|
|
84
|
+
#### Current Implementation
|
|
85
|
+
- **Retry**: Re-publish message with new headers, ack original
|
|
86
|
+
- **Delay**: Uses `x-delayed-message` exchange OR nack+requeue loop
|
|
87
|
+
|
|
88
|
+
#### Overhead Analysis
|
|
89
|
+
| Operation | Network Calls | Broker Load | Memory |
|
|
90
|
+
|-----------|--------------|-------------|--------|
|
|
91
|
+
| Retry | 2 (publish + ack) | Medium | Low |
|
|
92
|
+
| Delay (requeue) | N (loops until ready) | **HIGH** | Low |
|
|
93
|
+
| Delay (plugin) | 1 | Low | Medium |
|
|
94
|
+
|
|
95
|
+
#### Recommendation
|
|
96
|
+
⚠️ **Current delay implementation (nack+requeue) causes high overhead!**
|
|
97
|
+
|
|
98
|
+
**Solution**: Use RabbitMQ Delayed Message Exchange plugin OR implement local scheduling:
|
|
99
|
+
|
|
100
|
+
```typescript
|
|
101
|
+
// Option 1: Use delayed-message-exchange plugin (recommended)
|
|
102
|
+
// Requires: rabbitmq_delayed_message_exchange plugin
|
|
103
|
+
|
|
104
|
+
// Option 2: Local scheduler (no plugin required)
|
|
105
|
+
private delayedJobScheduler: Map<string, NodeJS.Timeout> = new Map();
|
|
106
|
+
|
|
107
|
+
async scheduleDelayedJob(queueName: string, job: IJob, delay: number) {
|
|
108
|
+
const timerId = setTimeout(async () => {
|
|
109
|
+
await this.add(queueName, job.name, job.data, { ...job.opts, delay: 0 });
|
|
110
|
+
this.delayedJobScheduler.delete(job.id);
|
|
111
|
+
}, delay);
|
|
112
|
+
this.delayedJobScheduler.set(job.id, timerId);
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Kafka
|
|
117
|
+
|
|
118
|
+
#### Current Implementation
|
|
119
|
+
- **Retry**: Re-publish message to same topic with delay header
|
|
120
|
+
- **Delay**: Poll message, check timestamp, re-publish if not ready
|
|
121
|
+
|
|
122
|
+
#### Overhead Analysis
|
|
123
|
+
| Operation | Network Calls | Broker Load | Memory |
|
|
124
|
+
|-----------|--------------|-------------|--------|
|
|
125
|
+
| Retry | 1 (publish) | Low | Low |
|
|
126
|
+
| Delay (requeue) | N (re-publish loops) | **HIGH** | Medium |
|
|
127
|
+
|
|
128
|
+
#### Recommendation
|
|
129
|
+
⚠️ **Current delay implementation causes message multiplication!**
|
|
130
|
+
|
|
131
|
+
**Solution**: Use local scheduler with deduplication:
|
|
132
|
+
|
|
133
|
+
```typescript
|
|
134
|
+
// Delayed job scheduler (in-memory, per instance)
|
|
135
|
+
private readonly delayedJobs: Map<string, {
|
|
136
|
+
job: IJob;
|
|
137
|
+
queueName: string;
|
|
138
|
+
executeAt: number;
|
|
139
|
+
timerId: NodeJS.Timeout;
|
|
140
|
+
}> = new Map();
|
|
141
|
+
|
|
142
|
+
async handleDelayedMessage(queueName: string, job: IJob, executeAt: number) {
|
|
143
|
+
const delay = executeAt - Date.now();
|
|
144
|
+
if (delay <= 0) return false; // Process immediately
|
|
145
|
+
|
|
146
|
+
// Don't re-queue, schedule locally
|
|
147
|
+
const timerId = setTimeout(async () => {
|
|
148
|
+
await this.add(queueName, job.name, job.data, job.opts);
|
|
149
|
+
this.delayedJobs.delete(job.id);
|
|
150
|
+
}, delay);
|
|
151
|
+
|
|
152
|
+
this.delayedJobs.set(job.id, { job, queueName, executeAt, timerId });
|
|
153
|
+
return true; // Job scheduled, don't process now
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
---
|
|
158
|
+
|
|
159
|
+
## 4. Multi-Instance Proof (Duplicate Prevention)
|
|
160
|
+
|
|
161
|
+
### BullMQ ✅ Native Support
|
|
162
|
+
- Uses Redis atomic operations
|
|
163
|
+
- Job locks prevent duplicate processing
|
|
164
|
+
- Built-in worker coordination
|
|
165
|
+
|
|
166
|
+
**No changes needed.**
|
|
167
|
+
|
|
168
|
+
### Kafka ✅ Native Support (with caveats)
|
|
169
|
+
- Consumer groups provide partition-based distribution
|
|
170
|
+
- Each partition assigned to exactly one consumer
|
|
171
|
+
- **Caveat**: Rebalancing during scaling can cause brief duplicates
|
|
172
|
+
|
|
173
|
+
**Recommendation**: Enable idempotent producer:
|
|
174
|
+
```typescript
|
|
175
|
+
this.producer = this.kafka.producer({
|
|
176
|
+
idempotent: true, // Prevents duplicate publishes
|
|
177
|
+
maxInFlightRequests: 5,
|
|
178
|
+
});
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
### RabbitMQ ⚠️ Needs Attention
|
|
182
|
+
- Competing consumers pattern works, BUT:
|
|
183
|
+
- **Manual ack + retry can cause duplicates** if pod crashes after re-publish but before ack
|
|
184
|
+
|
|
185
|
+
**Current Risk Scenario:**
|
|
186
|
+
1. Pod A processes job, fails, re-publishes retry
|
|
187
|
+
2. Pod A crashes before acking original
|
|
188
|
+
3. RabbitMQ redelivers original to Pod B
|
|
189
|
+
4. Now TWO copies of the job exist!
|
|
190
|
+
|
|
191
|
+
**Solution**: Idempotency key tracking (see Section 5)
|
|
192
|
+
|
|
193
|
+
---
|
|
194
|
+
|
|
195
|
+
## 5. Idempotency Store (NEW)
|
|
196
|
+
|
|
197
|
+
### Overview
|
|
198
|
+
|
|
199
|
+
The idempotency store is an **optional, abstract** component that prevents duplicate job processing in RabbitMQ edge cases (crash after retry publish, before ack).
|
|
200
|
+
|
|
201
|
+
### Interface Design
|
|
202
|
+
|
|
203
|
+
```typescript
|
|
204
|
+
// lib/interface/idempotency-store.interface.ts
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Abstract idempotency store interface
|
|
208
|
+
* Implementations can use Redis, PostgreSQL, DynamoDB, etc.
|
|
209
|
+
*/
|
|
210
|
+
export interface IdempotencyStore {
|
|
211
|
+
/**
|
|
212
|
+
* Mark a job as processing (returns false if already being processed)
|
|
213
|
+
* @param jobId - Unique job identifier
|
|
214
|
+
* @param ttl - Time-to-live in milliseconds
|
|
215
|
+
* @returns true if lock acquired, false if already processing
|
|
216
|
+
*/
|
|
217
|
+
markProcessing(jobId: string, ttl: number): Promise<boolean>;
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Mark a job as completed (removes processing lock, adds to completed set)
|
|
221
|
+
* @param jobId - Unique job identifier
|
|
222
|
+
* @param resultTtl - How long to remember completion (ms)
|
|
223
|
+
*/
|
|
224
|
+
markComplete(jobId: string, resultTtl?: number): Promise<void>;
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Check if a job was already processed
|
|
228
|
+
* @param jobId - Unique job identifier
|
|
229
|
+
*/
|
|
230
|
+
isProcessed(jobId: string): Promise<boolean>;
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Release a processing lock (for failed jobs that should retry)
|
|
234
|
+
* @param jobId - Unique job identifier
|
|
235
|
+
*/
|
|
236
|
+
releaseLock(jobId: string): Promise<void>;
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Close connections
|
|
240
|
+
*/
|
|
241
|
+
close(): Promise<void>;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Idempotency store options for module registration
|
|
246
|
+
*/
|
|
247
|
+
export interface IdempotencyStoreOptions {
|
|
248
|
+
/**
|
|
249
|
+
* Enable idempotency tracking
|
|
250
|
+
* @default false
|
|
251
|
+
*/
|
|
252
|
+
enabled: boolean;
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Default lock TTL in milliseconds
|
|
256
|
+
* @default 60000 (1 minute)
|
|
257
|
+
*/
|
|
258
|
+
lockTtl?: number;
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* How long to remember completed jobs (ms)
|
|
262
|
+
* @default 3600000 (1 hour)
|
|
263
|
+
*/
|
|
264
|
+
completedTtl?: number;
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Custom store implementation (for DI)
|
|
268
|
+
*/
|
|
269
|
+
store?: IdempotencyStore;
|
|
270
|
+
}
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
### Redis Implementation
|
|
274
|
+
|
|
275
|
+
```typescript
|
|
276
|
+
// lib/utils/redis-idempotency-store.ts
|
|
277
|
+
|
|
278
|
+
import { Logger } from '@nestjs/common';
|
|
279
|
+
import { Redis } from 'ioredis';
|
|
280
|
+
import { IdempotencyStore } from '../interface/idempotency-store.interface';
|
|
281
|
+
|
|
282
|
+
export interface RedisIdempotencyStoreOptions {
|
|
283
|
+
host: string;
|
|
284
|
+
port: number;
|
|
285
|
+
password?: string;
|
|
286
|
+
db?: number;
|
|
287
|
+
keyPrefix?: string;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export class RedisIdempotencyStore implements IdempotencyStore {
|
|
291
|
+
private readonly logger = new Logger(RedisIdempotencyStore.name);
|
|
292
|
+
private readonly redis: Redis;
|
|
293
|
+
private readonly keyPrefix: string;
|
|
294
|
+
|
|
295
|
+
constructor(options: RedisIdempotencyStoreOptions) {
|
|
296
|
+
this.redis = new Redis({
|
|
297
|
+
host: options.host,
|
|
298
|
+
port: options.port,
|
|
299
|
+
password: options.password,
|
|
300
|
+
db: options.db ?? 0,
|
|
301
|
+
maxRetriesPerRequest: null,
|
|
302
|
+
});
|
|
303
|
+
this.keyPrefix = options.keyPrefix ?? 'queue:idempotency:';
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
private processingKey(jobId: string): string {
|
|
307
|
+
return `${this.keyPrefix}processing:${jobId}`;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
private completedKey(jobId: string): string {
|
|
311
|
+
return `${this.keyPrefix}completed:${jobId}`;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async markProcessing(jobId: string, ttl: number): Promise<boolean> {
|
|
315
|
+
// Check if already completed first
|
|
316
|
+
const completed = await this.redis.get(this.completedKey(jobId));
|
|
317
|
+
if (completed) {
|
|
318
|
+
this.logger.debug(`Job ${jobId} already completed, skipping`);
|
|
319
|
+
return false;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// Try to acquire lock with NX (only if not exists)
|
|
323
|
+
const result = await this.redis.set(
|
|
324
|
+
this.processingKey(jobId),
|
|
325
|
+
Date.now().toString(),
|
|
326
|
+
'PX',
|
|
327
|
+
ttl,
|
|
328
|
+
'NX',
|
|
329
|
+
);
|
|
330
|
+
|
|
331
|
+
const acquired = result === 'OK';
|
|
332
|
+
if (!acquired) {
|
|
333
|
+
this.logger.debug(`Job ${jobId} already being processed by another worker`);
|
|
334
|
+
}
|
|
335
|
+
return acquired;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
async markComplete(jobId: string, resultTtl = 3600000): Promise<void> {
|
|
339
|
+
// Remove processing lock and add to completed set
|
|
340
|
+
const pipeline = this.redis.pipeline();
|
|
341
|
+
pipeline.del(this.processingKey(jobId));
|
|
342
|
+
pipeline.set(
|
|
343
|
+
this.completedKey(jobId),
|
|
344
|
+
Date.now().toString(),
|
|
345
|
+
'PX',
|
|
346
|
+
resultTtl,
|
|
347
|
+
);
|
|
348
|
+
await pipeline.exec();
|
|
349
|
+
this.logger.debug(`Job ${jobId} marked complete`);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
async isProcessed(jobId: string): Promise<boolean> {
|
|
353
|
+
const completed = await this.redis.get(this.completedKey(jobId));
|
|
354
|
+
return completed !== null;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
async releaseLock(jobId: string): Promise<void> {
|
|
358
|
+
await this.redis.del(this.processingKey(jobId));
|
|
359
|
+
this.logger.debug(`Released lock for job ${jobId}`);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
async close(): Promise<void> {
|
|
363
|
+
await this.redis.quit();
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
### Module Registration
|
|
369
|
+
|
|
370
|
+
```typescript
|
|
371
|
+
// Updated queue-options.interface.ts
|
|
372
|
+
|
|
373
|
+
import { IdempotencyStoreOptions } from './idempotency-store.interface';
|
|
374
|
+
|
|
375
|
+
export interface RabbitMQOptions {
|
|
376
|
+
urls: string[];
|
|
377
|
+
prefetchCount?: number;
|
|
378
|
+
noAck?: boolean;
|
|
379
|
+
queueOptions?: { /* ... */ };
|
|
380
|
+
useDelayedMessagePlugin?: boolean;
|
|
381
|
+
reconnect?: { /* ... */ };
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Idempotency store configuration (optional)
|
|
385
|
+
* Prevents duplicate processing in multi-instance deployments
|
|
386
|
+
*/
|
|
387
|
+
idempotency?: IdempotencyStoreOptions;
|
|
388
|
+
}
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
### Usage in RabbitMQ Provider
|
|
392
|
+
|
|
393
|
+
```typescript
|
|
394
|
+
// rabbitmq.provider.ts (updated process method)
|
|
395
|
+
|
|
396
|
+
async process<T>(
|
|
397
|
+
queueName: string,
|
|
398
|
+
processor: (job: IJob<T>) => Promise<any>,
|
|
399
|
+
options?: ProcessorOptions,
|
|
400
|
+
): Promise<void> {
|
|
401
|
+
const channel = await this.getChannel(queueName);
|
|
402
|
+
const idempotencyStore = this.options.idempotency?.store;
|
|
403
|
+
const lockTtl = this.options.idempotency?.lockTtl ?? 60000;
|
|
404
|
+
const completedTtl = this.options.idempotency?.completedTtl ?? 3600000;
|
|
405
|
+
|
|
406
|
+
await channel.consume(queueName, async (msg) => {
|
|
407
|
+
if (!msg) return;
|
|
408
|
+
|
|
409
|
+
const job: IJob<T> = JSON.parse(msg.content.toString());
|
|
410
|
+
const headers = msg.properties.headers || {};
|
|
411
|
+
|
|
412
|
+
// Extract correlationId from headers (see Section 6)
|
|
413
|
+
const correlationId = headers['x-correlation-id'] || job.id;
|
|
414
|
+
|
|
415
|
+
// Idempotency check (if store configured)
|
|
416
|
+
if (idempotencyStore) {
|
|
417
|
+
const canProcess = await idempotencyStore.markProcessing(job.id, lockTtl);
|
|
418
|
+
if (!canProcess) {
|
|
419
|
+
// Already being processed or completed
|
|
420
|
+
channel.ack(msg);
|
|
421
|
+
this.logger.debug(`Job ${job.id} skipped (idempotency check)`);
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
try {
|
|
427
|
+
this.emitEvent(queueName, QueueEvent.ACTIVE, job);
|
|
428
|
+
const result = await processor(job);
|
|
429
|
+
job.returnvalue = result;
|
|
430
|
+
|
|
431
|
+
// Mark complete in idempotency store
|
|
432
|
+
if (idempotencyStore) {
|
|
433
|
+
await idempotencyStore.markComplete(job.id, completedTtl);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
channel.ack(msg);
|
|
437
|
+
this.emitEvent(queueName, QueueEvent.COMPLETED, job, result);
|
|
438
|
+
} catch (error: any) {
|
|
439
|
+
job.attemptsMade++;
|
|
440
|
+
job.failedReason = error.message;
|
|
441
|
+
|
|
442
|
+
// Release idempotency lock for retry
|
|
443
|
+
if (idempotencyStore) {
|
|
444
|
+
await idempotencyStore.releaseLock(job.id);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// ... existing retry logic ...
|
|
448
|
+
}
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
### Module Registration Example
|
|
454
|
+
|
|
455
|
+
```typescript
|
|
456
|
+
// app.module.ts
|
|
457
|
+
|
|
458
|
+
import { QueueModule } from '@nathapp/nestjs-queue';
|
|
459
|
+
import { QueueProviderType } from '@nathapp/nestjs-queue/enum';
|
|
460
|
+
import { RedisIdempotencyStore } from '@nathapp/nestjs-queue/utils';
|
|
461
|
+
|
|
462
|
+
@Module({
|
|
463
|
+
imports: [
|
|
464
|
+
QueueModule.register({
|
|
465
|
+
provider: QueueProviderType.RABBITMQ,
|
|
466
|
+
options: {
|
|
467
|
+
urls: ['amqp://localhost:5672'],
|
|
468
|
+
prefetchCount: 1,
|
|
469
|
+
|
|
470
|
+
// Optional: Enable idempotency store
|
|
471
|
+
idempotency: {
|
|
472
|
+
enabled: true,
|
|
473
|
+
lockTtl: 60000, // 1 minute lock
|
|
474
|
+
completedTtl: 3600000, // Remember completed for 1 hour
|
|
475
|
+
store: new RedisIdempotencyStore({
|
|
476
|
+
host: 'localhost',
|
|
477
|
+
port: 6379,
|
|
478
|
+
}),
|
|
479
|
+
},
|
|
480
|
+
},
|
|
481
|
+
}),
|
|
482
|
+
],
|
|
483
|
+
})
|
|
484
|
+
export class AppModule {}
|
|
485
|
+
|
|
486
|
+
// Async registration with factory
|
|
487
|
+
@Module({
|
|
488
|
+
imports: [
|
|
489
|
+
QueueModule.registerAsync({
|
|
490
|
+
useFactory: (configService: ConfigService) => ({
|
|
491
|
+
provider: QueueProviderType.RABBITMQ,
|
|
492
|
+
options: {
|
|
493
|
+
urls: [configService.get('RABBITMQ_URL')],
|
|
494
|
+
idempotency: {
|
|
495
|
+
enabled: configService.get('ENABLE_IDEMPOTENCY', false),
|
|
496
|
+
store: new RedisIdempotencyStore({
|
|
497
|
+
host: configService.get('REDIS_HOST'),
|
|
498
|
+
port: configService.get('REDIS_PORT'),
|
|
499
|
+
}),
|
|
500
|
+
},
|
|
501
|
+
},
|
|
502
|
+
}),
|
|
503
|
+
inject: [ConfigService],
|
|
504
|
+
}),
|
|
505
|
+
],
|
|
506
|
+
})
|
|
507
|
+
export class AppModule {}
|
|
508
|
+
```
|
|
509
|
+
|
|
510
|
+
---
|
|
511
|
+
|
|
512
|
+
## 6. CorrelationId Handling (NEW)
|
|
513
|
+
|
|
514
|
+
### Overview
|
|
515
|
+
|
|
516
|
+
CorrelationId enables request tracing across job boundaries. When a job is created from an HTTP request, the correlationId propagates through retries and child jobs.
|
|
517
|
+
|
|
518
|
+
### Interface Updates
|
|
519
|
+
|
|
520
|
+
```typescript
|
|
521
|
+
// lib/interface/job.interface.ts (updated)
|
|
522
|
+
|
|
523
|
+
export interface JobOptions {
|
|
524
|
+
// ... existing options ...
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Correlation ID for request tracing
|
|
528
|
+
* Propagates through retries and child jobs
|
|
529
|
+
*/
|
|
530
|
+
correlationId?: string;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
export interface IJob<T = any> {
|
|
534
|
+
// ... existing fields ...
|
|
535
|
+
|
|
536
|
+
/**
|
|
537
|
+
* Correlation ID for request tracing
|
|
538
|
+
*/
|
|
539
|
+
correlationId?: string;
|
|
540
|
+
}
|
|
541
|
+
```
|
|
542
|
+
|
|
543
|
+
### Implementation in Providers
|
|
544
|
+
|
|
545
|
+
```typescript
|
|
546
|
+
// rabbitmq.provider.ts - add() method
|
|
547
|
+
|
|
548
|
+
async add<T>(
|
|
549
|
+
queueName: string,
|
|
550
|
+
jobName: string,
|
|
551
|
+
data: T,
|
|
552
|
+
opts?: JobOptions,
|
|
553
|
+
): Promise<IJob<T>> {
|
|
554
|
+
const channel = await this.getChannel(queueName);
|
|
555
|
+
|
|
556
|
+
const job: IJob<T> = {
|
|
557
|
+
id: opts?.jobId || this.generateJobId(),
|
|
558
|
+
name: jobName,
|
|
559
|
+
data,
|
|
560
|
+
opts,
|
|
561
|
+
timestamp: Date.now(),
|
|
562
|
+
attemptsMade: 0,
|
|
563
|
+
correlationId: opts?.correlationId, // ← Add correlationId
|
|
564
|
+
};
|
|
565
|
+
|
|
566
|
+
const messageOptions: amqp.Options.Publish = {
|
|
567
|
+
persistent: true,
|
|
568
|
+
messageId: job.id,
|
|
569
|
+
correlationId: opts?.correlationId, // ← AMQP native field
|
|
570
|
+
contentType: 'application/json',
|
|
571
|
+
headers: {
|
|
572
|
+
'x-job-name': jobName,
|
|
573
|
+
'x-job-id': job.id,
|
|
574
|
+
'x-correlation-id': opts?.correlationId || job.id, // ← Header for tracing
|
|
575
|
+
// ... other headers
|
|
576
|
+
},
|
|
577
|
+
};
|
|
578
|
+
|
|
579
|
+
await channel.sendToQueue(queueName, Buffer.from(JSON.stringify(job)), messageOptions);
|
|
580
|
+
return job;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// In process() - propagate correlationId on retry
|
|
584
|
+
if (job.attemptsMade < maxAttempts) {
|
|
585
|
+
const retryJobOpts: JobOptions = {
|
|
586
|
+
...job.opts,
|
|
587
|
+
jobId: `${job.id}-retry-${job.attemptsMade}`,
|
|
588
|
+
delay,
|
|
589
|
+
correlationId: job.correlationId, // ← Preserve across retries
|
|
590
|
+
};
|
|
591
|
+
await this.add(queueName, job.name, job.data, retryJobOpts);
|
|
592
|
+
}
|
|
593
|
+
```
|
|
594
|
+
|
|
595
|
+
### Usage with AsyncLocalStorage (NestJS)
|
|
596
|
+
|
|
597
|
+
```typescript
|
|
598
|
+
// correlation.middleware.ts
|
|
599
|
+
import { Injectable, NestMiddleware } from '@nestjs/common';
|
|
600
|
+
import { AsyncLocalStorage } from 'async_hooks';
|
|
601
|
+
import { v4 as uuidv4 } from 'uuid';
|
|
602
|
+
|
|
603
|
+
export const correlationStorage = new AsyncLocalStorage<{ correlationId: string }>();
|
|
604
|
+
|
|
605
|
+
@Injectable()
|
|
606
|
+
export class CorrelationMiddleware implements NestMiddleware {
|
|
607
|
+
use(req: any, res: any, next: () => void) {
|
|
608
|
+
const correlationId = req.headers['x-correlation-id'] || uuidv4();
|
|
609
|
+
correlationStorage.run({ correlationId }, next);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// job.service.ts - automatically attach correlationId
|
|
614
|
+
@Injectable()
|
|
615
|
+
export class JobService {
|
|
616
|
+
constructor(private readonly queueService: QueueService) {}
|
|
617
|
+
|
|
618
|
+
async createJob<T>(queueName: string, name: string, data: T): Promise<IJob<T>> {
|
|
619
|
+
const store = correlationStorage.getStore();
|
|
620
|
+
return this.queueService.add(queueName, name, data, {
|
|
621
|
+
correlationId: store?.correlationId,
|
|
622
|
+
});
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
```
|
|
626
|
+
|
|
627
|
+
---
|
|
628
|
+
|
|
629
|
+
## 7. Decorator Processor E2E Example (NEW)
|
|
630
|
+
|
|
631
|
+
### Complete Example with @Processor and @Process
|
|
632
|
+
|
|
633
|
+
```typescript
|
|
634
|
+
// test/e2e/decorator-processor.e2e-spec.ts
|
|
635
|
+
|
|
636
|
+
import { Test, TestingModule } from '@nestjs/testing';
|
|
637
|
+
import { INestApplication, Injectable } from '@nestjs/common';
|
|
638
|
+
import { QueueModule } from '../../lib/module/queue.module';
|
|
639
|
+
import { QueueService } from '../../lib/service/queue.service';
|
|
640
|
+
import { Processor, Process, OnQueueEvent } from '../../lib/decorator';
|
|
641
|
+
import { QueueProviderType } from '../../lib/enum/provider.enum';
|
|
642
|
+
import { QueueEvent } from '../../lib/enum/queue-event.enum';
|
|
643
|
+
import { IJob } from '../../lib/interface/job.interface';
|
|
644
|
+
|
|
645
|
+
// Test data interface
|
|
646
|
+
interface EmailJobData {
|
|
647
|
+
to: string;
|
|
648
|
+
subject: string;
|
|
649
|
+
body: string;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// Define the processor class with decorators
|
|
653
|
+
@Processor({ queueName: 'email-queue', concurrency: 2 })
|
|
654
|
+
@Injectable()
|
|
655
|
+
class EmailProcessor {
|
|
656
|
+
public processedJobs: IJob<EmailJobData>[] = [];
|
|
657
|
+
public completedJobs: IJob<EmailJobData>[] = [];
|
|
658
|
+
public failedJobs: IJob<EmailJobData>[] = [];
|
|
659
|
+
|
|
660
|
+
@Process('send')
|
|
661
|
+
async handleSendEmail(job: IJob<EmailJobData>): Promise<{ sent: boolean }> {
|
|
662
|
+
this.processedJobs.push(job);
|
|
663
|
+
|
|
664
|
+
// Simulate email sending
|
|
665
|
+
if (job.data.to.includes('fail')) {
|
|
666
|
+
throw new Error('Email delivery failed');
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
return { sent: true };
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
@Process('template')
|
|
673
|
+
async handleTemplateEmail(job: IJob<EmailJobData>): Promise<{ rendered: boolean }> {
|
|
674
|
+
this.processedJobs.push(job);
|
|
675
|
+
return { rendered: true };
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
@Process() // Default handler for unmatched job names
|
|
679
|
+
async handleDefault(job: IJob<any>): Promise<void> {
|
|
680
|
+
this.processedJobs.push(job);
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
@OnQueueEvent(QueueEvent.COMPLETED)
|
|
684
|
+
onCompleted(job: IJob<EmailJobData>, result: any): void {
|
|
685
|
+
this.completedJobs.push(job);
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
@OnQueueEvent(QueueEvent.FAILED)
|
|
689
|
+
onFailed(job: IJob<EmailJobData>, error: Error): void {
|
|
690
|
+
this.failedJobs.push(job);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
describe('Decorator Processor E2E', () => {
|
|
695
|
+
let app: INestApplication;
|
|
696
|
+
let queueService: QueueService;
|
|
697
|
+
let emailProcessor: EmailProcessor;
|
|
698
|
+
|
|
699
|
+
beforeAll(async () => {
|
|
700
|
+
const moduleFixture: TestingModule = await Test.createTestingModule({
|
|
701
|
+
imports: [
|
|
702
|
+
QueueModule.register({
|
|
703
|
+
isGlobal: true,
|
|
704
|
+
provider: QueueProviderType.BULLMQ,
|
|
705
|
+
options: {
|
|
706
|
+
connection: {
|
|
707
|
+
host: process.env.REDIS_HOST || 'localhost',
|
|
708
|
+
port: parseInt(process.env.REDIS_PORT || '6379'),
|
|
709
|
+
},
|
|
710
|
+
},
|
|
711
|
+
}),
|
|
712
|
+
],
|
|
713
|
+
providers: [EmailProcessor],
|
|
714
|
+
}).compile();
|
|
715
|
+
|
|
716
|
+
app = moduleFixture.createNestApplication();
|
|
717
|
+
await app.init();
|
|
718
|
+
|
|
719
|
+
queueService = app.get<QueueService>(QueueService);
|
|
720
|
+
emailProcessor = app.get<EmailProcessor>(EmailProcessor);
|
|
721
|
+
|
|
722
|
+
// Wait for processor discovery
|
|
723
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
724
|
+
});
|
|
725
|
+
|
|
726
|
+
afterAll(async () => {
|
|
727
|
+
await app?.close();
|
|
728
|
+
});
|
|
729
|
+
|
|
730
|
+
it('should process jobs with @Process("send") handler', async () => {
|
|
731
|
+
const job = await queueService.add<EmailJobData>('email-queue', 'send', {
|
|
732
|
+
to: 'test@example.com',
|
|
733
|
+
subject: 'Hello',
|
|
734
|
+
body: 'World',
|
|
735
|
+
});
|
|
736
|
+
|
|
737
|
+
// Wait for processing
|
|
738
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
739
|
+
|
|
740
|
+
expect(emailProcessor.processedJobs.length).toBeGreaterThan(0);
|
|
741
|
+
expect(emailProcessor.processedJobs.some((j) => j.id === job.id)).toBe(true);
|
|
742
|
+
});
|
|
743
|
+
|
|
744
|
+
it('should process jobs with @Process("template") handler', async () => {
|
|
745
|
+
const job = await queueService.add<EmailJobData>('email-queue', 'template', {
|
|
746
|
+
to: 'template@example.com',
|
|
747
|
+
subject: 'Template',
|
|
748
|
+
body: '{{ name }}',
|
|
749
|
+
});
|
|
750
|
+
|
|
751
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
752
|
+
|
|
753
|
+
const processed = emailProcessor.processedJobs.find((j) => j.id === job.id);
|
|
754
|
+
expect(processed).toBeDefined();
|
|
755
|
+
expect(processed?.name).toBe('template');
|
|
756
|
+
});
|
|
757
|
+
|
|
758
|
+
it('should use default handler for unknown job names', async () => {
|
|
759
|
+
const job = await queueService.add('email-queue', 'unknown-job', {
|
|
760
|
+
data: 'test',
|
|
761
|
+
});
|
|
762
|
+
|
|
763
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
764
|
+
|
|
765
|
+
expect(emailProcessor.processedJobs.some((j) => j.id === job.id)).toBe(true);
|
|
766
|
+
});
|
|
767
|
+
|
|
768
|
+
it('should trigger @OnQueueEvent(COMPLETED) on success', async () => {
|
|
769
|
+
const initialCount = emailProcessor.completedJobs.length;
|
|
770
|
+
|
|
771
|
+
await queueService.add<EmailJobData>('email-queue', 'send', {
|
|
772
|
+
to: 'success@example.com',
|
|
773
|
+
subject: 'Test',
|
|
774
|
+
body: 'Body',
|
|
775
|
+
});
|
|
776
|
+
|
|
777
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
778
|
+
|
|
779
|
+
expect(emailProcessor.completedJobs.length).toBeGreaterThan(initialCount);
|
|
780
|
+
});
|
|
781
|
+
|
|
782
|
+
it('should trigger @OnQueueEvent(FAILED) on error', async () => {
|
|
783
|
+
const initialCount = emailProcessor.failedJobs.length;
|
|
784
|
+
|
|
785
|
+
await queueService.add<EmailJobData>('email-queue', 'send', {
|
|
786
|
+
to: 'fail@example.com', // Contains 'fail' - triggers error
|
|
787
|
+
subject: 'Test',
|
|
788
|
+
body: 'Body',
|
|
789
|
+
});
|
|
790
|
+
|
|
791
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
792
|
+
|
|
793
|
+
expect(emailProcessor.failedJobs.length).toBeGreaterThan(initialCount);
|
|
794
|
+
});
|
|
795
|
+
|
|
796
|
+
it('should respect concurrency setting', async () => {
|
|
797
|
+
const startTimes: number[] = [];
|
|
798
|
+
const originalHandler = emailProcessor.handleSendEmail.bind(emailProcessor);
|
|
799
|
+
|
|
800
|
+
// Override to track timing
|
|
801
|
+
emailProcessor.handleSendEmail = async (job) => {
|
|
802
|
+
startTimes.push(Date.now());
|
|
803
|
+
await new Promise((r) => setTimeout(r, 500)); // Simulate work
|
|
804
|
+
return originalHandler(job);
|
|
805
|
+
};
|
|
806
|
+
|
|
807
|
+
// Add 4 jobs (concurrency is 2)
|
|
808
|
+
await Promise.all([
|
|
809
|
+
queueService.add('email-queue', 'send', { to: 'a@test.com', subject: '', body: '' }),
|
|
810
|
+
queueService.add('email-queue', 'send', { to: 'b@test.com', subject: '', body: '' }),
|
|
811
|
+
queueService.add('email-queue', 'send', { to: 'c@test.com', subject: '', body: '' }),
|
|
812
|
+
queueService.add('email-queue', 'send', { to: 'd@test.com', subject: '', body: '' }),
|
|
813
|
+
]);
|
|
814
|
+
|
|
815
|
+
await new Promise((r) => setTimeout(r, 2000));
|
|
816
|
+
|
|
817
|
+
// With concurrency=2, first 2 should start together, next 2 ~500ms later
|
|
818
|
+
expect(startTimes.length).toBe(4);
|
|
819
|
+
// Verify batching (first 2 within 100ms, next 2 after ~500ms)
|
|
820
|
+
expect(startTimes[1] - startTimes[0]).toBeLessThan(100);
|
|
821
|
+
expect(startTimes[2] - startTimes[0]).toBeGreaterThan(400);
|
|
822
|
+
});
|
|
823
|
+
});
|
|
824
|
+
```
|
|
825
|
+
|
|
826
|
+
### Processor with CorrelationId
|
|
827
|
+
|
|
828
|
+
```typescript
|
|
829
|
+
// Example: Processor that logs correlationId
|
|
830
|
+
|
|
831
|
+
@Processor({ queueName: 'audit-queue' })
|
|
832
|
+
@Injectable()
|
|
833
|
+
class AuditProcessor {
|
|
834
|
+
private readonly logger = new Logger(AuditProcessor.name);
|
|
835
|
+
|
|
836
|
+
@Process('log')
|
|
837
|
+
async handleAuditLog(job: IJob<{ action: string; userId: string }>): Promise<void> {
|
|
838
|
+
// Access correlationId from job
|
|
839
|
+
const correlationId = job.correlationId || job.opts?.correlationId || job.id;
|
|
840
|
+
|
|
841
|
+
this.logger.log(
|
|
842
|
+
`[${correlationId}] User ${job.data.userId} performed ${job.data.action}`,
|
|
843
|
+
);
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
```
|
|
847
|
+
|
|
848
|
+
---
|
|
849
|
+
|
|
850
|
+
## 8. Memory Leak Analysis (NEW)
|
|
851
|
+
|
|
852
|
+
### Identified Memory Leaks
|
|
853
|
+
|
|
854
|
+
#### 🔴 Critical: Kafka `processedDelayedJobs` Set Never Cleaned
|
|
855
|
+
|
|
856
|
+
**Location**: `kafka.provider.ts` lines 35-40
|
|
857
|
+
|
|
858
|
+
```typescript
|
|
859
|
+
// CURRENT (LEAKS)
|
|
860
|
+
private readonly processedDelayedJobs: Set<string> = new Set();
|
|
861
|
+
private readonly DELAYED_JOB_TTL_MS = 3600000; // TTL defined but never used!
|
|
862
|
+
```
|
|
863
|
+
|
|
864
|
+
**Problem**: The `processedDelayedJobs` Set grows unbounded. Although `DELAYED_JOB_TTL_MS` is defined, there's no cleanup logic. Over time, this Set accumulates all delayed job keys.
|
|
865
|
+
|
|
866
|
+
**Fix**:
|
|
867
|
+
|
|
868
|
+
```typescript
|
|
869
|
+
// lib/provider/kafka/kafka.provider.ts
|
|
870
|
+
|
|
871
|
+
/**
|
|
872
|
+
* Track delayed jobs with timestamps for cleanup
|
|
873
|
+
*/
|
|
874
|
+
private readonly processedDelayedJobs: Map<string, number> = new Map();
|
|
875
|
+
private readonly DELAYED_JOB_TTL_MS = 3600000; // 1 hour
|
|
876
|
+
private cleanupTimer: NodeJS.Timeout | null = null;
|
|
877
|
+
|
|
878
|
+
constructor(options: KafkaQueueOptions) {
|
|
879
|
+
super();
|
|
880
|
+
// ... existing code ...
|
|
881
|
+
|
|
882
|
+
// Start cleanup timer
|
|
883
|
+
this.cleanupTimer = setInterval(() => {
|
|
884
|
+
this.cleanupExpiredDelayedJobEntries();
|
|
885
|
+
}, 300000); // Run every 5 minutes
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
private cleanupExpiredDelayedJobEntries(): void {
|
|
889
|
+
const now = Date.now();
|
|
890
|
+
const expiredCount = 0;
|
|
891
|
+
|
|
892
|
+
for (const [key, timestamp] of this.processedDelayedJobs) {
|
|
893
|
+
if (now - timestamp > this.DELAYED_JOB_TTL_MS) {
|
|
894
|
+
this.processedDelayedJobs.delete(key);
|
|
895
|
+
expiredCount++;
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
if (expiredCount > 0) {
|
|
900
|
+
this.logger.debug(`Cleaned up ${expiredCount} expired delayed job entries`);
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
// Update process() to store timestamp
|
|
905
|
+
const delayKey = `${queueName}-${partition}-${message.offset}`;
|
|
906
|
+
this.processedDelayedJobs.set(delayKey, Date.now()); // Store with timestamp
|
|
907
|
+
|
|
908
|
+
// Update close() to clear timer
|
|
909
|
+
async close(options: ShutdownOptions = {}): Promise<void> {
|
|
910
|
+
// Clear cleanup timer
|
|
911
|
+
if (this.cleanupTimer) {
|
|
912
|
+
clearInterval(this.cleanupTimer);
|
|
913
|
+
this.cleanupTimer = null;
|
|
914
|
+
}
|
|
915
|
+
this.processedDelayedJobs.clear();
|
|
916
|
+
|
|
917
|
+
// ... existing close logic ...
|
|
918
|
+
}
|
|
919
|
+
```
|
|
920
|
+
|
|
921
|
+
#### 🟡 Medium: Event Listeners Never Removed
|
|
922
|
+
|
|
923
|
+
**Location**: All providers' `eventListeners` Map
|
|
924
|
+
|
|
925
|
+
```typescript
|
|
926
|
+
// CURRENT (POTENTIAL LEAK)
|
|
927
|
+
private readonly eventListeners: Map<string, Map<QueueEvent, Array<...>>> = new Map();
|
|
928
|
+
|
|
929
|
+
// on() adds listeners but there's no off() method
|
|
930
|
+
```
|
|
931
|
+
|
|
932
|
+
**Problem**: Event listeners accumulate if the same queue is registered multiple times (e.g., in tests or hot-reload scenarios).
|
|
933
|
+
|
|
934
|
+
**Fix**: Add `off()` and `removeAllListeners()` methods:
|
|
935
|
+
|
|
936
|
+
```typescript
|
|
937
|
+
// lib/interface/queue-provider.interface.ts
|
|
938
|
+
|
|
939
|
+
export interface IQueueProvider {
|
|
940
|
+
// ... existing methods ...
|
|
941
|
+
|
|
942
|
+
/**
|
|
943
|
+
* Remove a specific event listener
|
|
944
|
+
*/
|
|
945
|
+
off(
|
|
946
|
+
queueName: string,
|
|
947
|
+
event: QueueEvent,
|
|
948
|
+
callback: (job: IJob, result?: any) => void,
|
|
949
|
+
): void;
|
|
950
|
+
|
|
951
|
+
/**
|
|
952
|
+
* Remove all event listeners for a queue
|
|
953
|
+
*/
|
|
954
|
+
removeAllListeners(queueName: string): void;
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
// Implementation in each provider
|
|
958
|
+
off(
|
|
959
|
+
queueName: string,
|
|
960
|
+
event: QueueEvent,
|
|
961
|
+
callback: (job: IJob, result?: any) => void,
|
|
962
|
+
): void {
|
|
963
|
+
const queueListeners = this.eventListeners.get(queueName);
|
|
964
|
+
if (!queueListeners) return;
|
|
965
|
+
|
|
966
|
+
const listeners = queueListeners.get(event);
|
|
967
|
+
if (!listeners) return;
|
|
968
|
+
|
|
969
|
+
const index = listeners.indexOf(callback);
|
|
970
|
+
if (index > -1) {
|
|
971
|
+
listeners.splice(index, 1);
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
removeAllListeners(queueName: string): void {
|
|
976
|
+
this.eventListeners.delete(queueName);
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
// Update close() to clear all listeners
|
|
980
|
+
async close(options: ShutdownOptions = {}): Promise<void> {
|
|
981
|
+
// ... existing code ...
|
|
982
|
+
this.eventListeners.clear();
|
|
983
|
+
}
|
|
984
|
+
```
|
|
985
|
+
|
|
986
|
+
#### 🟢 Low: BullMQ QueueEvents Accumulation
|
|
987
|
+
|
|
988
|
+
**Location**: `bullmq.provider.ts` `on()` method
|
|
989
|
+
|
|
990
|
+
```typescript
|
|
991
|
+
// CURRENT
|
|
992
|
+
on(queueName: string, event: QueueEvent, callback: ...): void {
|
|
993
|
+
const queueEvents = this.getQueueEvents(queueName);
|
|
994
|
+
queueEvents.on(bullEvent as any, async ({ jobId, ... }) => {
|
|
995
|
+
// Creates closure that holds references
|
|
996
|
+
});
|
|
997
|
+
}
|
|
998
|
+
```
|
|
999
|
+
|
|
1000
|
+
**Problem**: Multiple calls to `on()` for the same event add multiple listeners. BullMQ's QueueEvents has a listener limit warning.
|
|
1001
|
+
|
|
1002
|
+
**Fix**: Track registered events to prevent duplicates:
|
|
1003
|
+
|
|
1004
|
+
```typescript
|
|
1005
|
+
private readonly registeredEvents: Map<string, Set<string>> = new Map();
|
|
1006
|
+
|
|
1007
|
+
on(queueName: string, event: QueueEvent, callback: ...): void {
|
|
1008
|
+
const eventKey = `${queueName}:${event}`;
|
|
1009
|
+
|
|
1010
|
+
if (!this.registeredEvents.has(queueName)) {
|
|
1011
|
+
this.registeredEvents.set(queueName, new Set());
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
const queueEvents = this.getQueueEvents(queueName);
|
|
1015
|
+
const bullEvent = this.mapEventToBullMQ(event);
|
|
1016
|
+
|
|
1017
|
+
// Store callback for later removal
|
|
1018
|
+
const wrappedCallback = async ({ jobId, returnvalue, failedReason }) => {
|
|
1019
|
+
// ... existing logic
|
|
1020
|
+
};
|
|
1021
|
+
|
|
1022
|
+
queueEvents.on(bullEvent as any, wrappedCallback);
|
|
1023
|
+
this.registeredEvents.get(queueName)!.add(eventKey);
|
|
1024
|
+
}
|
|
1025
|
+
```
|
|
1026
|
+
|
|
1027
|
+
### Summary Table
|
|
1028
|
+
|
|
1029
|
+
| Issue | Severity | Provider | Status |
|
|
1030
|
+
|-------|----------|----------|--------|
|
|
1031
|
+
| `processedDelayedJobs` never cleaned | 🔴 Critical | Kafka | Needs fix |
|
|
1032
|
+
| Event listeners never removed | 🟡 Medium | All | Needs fix |
|
|
1033
|
+
| QueueEvents listener accumulation | 🟢 Low | BullMQ | Recommended |
|
|
1034
|
+
| DelayedScheduler cleanup | ✅ OK | All | Properly handled |
|
|
1035
|
+
| Channel/Consumer cleanup on close | ✅ OK | All | Properly handled |
|
|
1036
|
+
|
|
1037
|
+
---
|
|
1038
|
+
|
|
1039
|
+
## Implementation Priority
|
|
1040
|
+
|
|
1041
|
+
### P0 - Critical (Implement Now)
|
|
1042
|
+
1. ✅ Error handling wrapper for all public methods
|
|
1043
|
+
2. ✅ Graceful shutdown with timeout
|
|
1044
|
+
3. ✅ RabbitMQ delayed job local scheduler (avoid nack loop)
|
|
1045
|
+
4. 🆕 **Kafka processedDelayedJobs cleanup** (memory leak)
|
|
1046
|
+
|
|
1047
|
+
### P1 - High (Implement Soon)
|
|
1048
|
+
1. ✅ Kafka delayed job local scheduler
|
|
1049
|
+
2. 🆕 RabbitMQ idempotency store integration
|
|
1050
|
+
3. 🆕 CorrelationId propagation
|
|
1051
|
+
4. 🆕 Event listener cleanup on close (memory leak)
|
|
1052
|
+
5. Shutdown signal handlers (SIGTERM/SIGINT)
|
|
1053
|
+
|
|
1054
|
+
### P2 - Medium (Future)
|
|
1055
|
+
1. Metrics/observability hooks
|
|
1056
|
+
2. Circuit breaker for downstream failures
|
|
1057
|
+
3. Rate limiting for producers
|
|
1058
|
+
4. `off()` method for event listeners
|
|
1059
|
+
|
|
1060
|
+
---
|
|
1061
|
+
|
|
1062
|
+
## Estimated Changes
|
|
1063
|
+
|
|
1064
|
+
| Provider | Lines Added | Lines Modified | Complexity |
|
|
1065
|
+
|----------|-------------|----------------|------------|
|
|
1066
|
+
| BullMQ | ~20 | ~30 | Low |
|
|
1067
|
+
| Kafka | ~120 | ~60 | Medium |
|
|
1068
|
+
| RabbitMQ | ~150 | ~70 | High |
|
|
1069
|
+
| Common (utils) | ~150 | 0 | Medium |
|
|
1070
|
+
| Interfaces | ~50 | ~20 | Low |
|
|
1071
|
+
|
|
1072
|
+
---
|
|
1073
|
+
|
|
1074
|
+
## Next Steps
|
|
1075
|
+
|
|
1076
|
+
1. **Immediate**: Fix Kafka `processedDelayedJobs` memory leak
|
|
1077
|
+
2. Implement `IdempotencyStore` interface and Redis implementation
|
|
1078
|
+
3. Add `correlationId` to `IJob` and propagate through providers
|
|
1079
|
+
4. Add `off()` and `removeAllListeners()` to providers
|
|
1080
|
+
5. Create decorator processor E2E tests
|
|
1081
|
+
6. Update module registration to accept idempotency store config
|