@nathapp/nestjs-queue 3.2.1 → 3.3.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/AGENTS.md +142 -0
- package/CLAUDE.md +18 -0
- package/GEMINI.md +140 -0
- package/README.md +97 -0
- package/codex.md +140 -0
- package/dist/module/queue.provider.js +31 -11
- package/dist/module/queue.provider.js.map +1 -1
- package/dist/provider/bullmq/bullmq.provider.js +19 -12
- package/dist/provider/bullmq/bullmq.provider.js.map +1 -1
- package/dist/provider/kafka/kafka.provider.js +42 -14
- package/dist/provider/kafka/kafka.provider.js.map +1 -1
- package/dist/provider/rabbitmq/rabbitmq.provider.js +31 -7
- package/dist/provider/rabbitmq/rabbitmq.provider.js.map +1 -1
- package/package.json +5 -3
package/AGENTS.md
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# Agent Instructions
|
|
2
|
+
|
|
3
|
+
This file is auto-generated from `.nax/context.md`.
|
|
4
|
+
DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
|
|
5
|
+
|
|
6
|
+
These instructions apply to all AI coding agents in this project.
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## Project Metadata
|
|
11
|
+
|
|
12
|
+
> Auto-injected by `nax generate`
|
|
13
|
+
|
|
14
|
+
**Project:** `@nathapp/nestjs-queue`
|
|
15
|
+
|
|
16
|
+
**Language:** TypeScript
|
|
17
|
+
|
|
18
|
+
**Key dependencies:** @nestjs/testing, @types/jest, bullmq, ioredis, jest, ts-jest, typescript
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
# @nathapp/nestjs-queue
|
|
22
|
+
|
|
23
|
+
Multi-provider queue abstraction for NestJS (BullMQ, Kafka, RabbitMQ, Redis Pub/Sub).
|
|
24
|
+
|
|
25
|
+
## Commands
|
|
26
|
+
- Build: `bun run build` (from monorepo root)
|
|
27
|
+
- Test: `bun run --filter @nathapp/nestjs-queue test`
|
|
28
|
+
- E2E: `bun run --filter @nathapp/nestjs-queue test:e2e`
|
|
29
|
+
- Lint: `bun run lint`
|
|
30
|
+
|
|
31
|
+
## Architecture
|
|
32
|
+
- `lib/provider/` - Provider implementations (BullMQ, Kafka, RabbitMQ, Redis)
|
|
33
|
+
- `lib/interface/` - Core interfaces (IQueueProvider, IJob, etc.)
|
|
34
|
+
- `lib/explorer/` - ProcessorExplorer for decorator scanning
|
|
35
|
+
- `lib/utils/` - Shared utilities (errors, validation, idempotency)
|
|
36
|
+
|
|
37
|
+
## Style
|
|
38
|
+
- All providers must implement `IQueueProvider` interface
|
|
39
|
+
- Use `QueueError` for domain errors with error codes
|
|
40
|
+
- Propagate `correlationId` through all job flows
|
|
41
|
+
- Clean up resources in `close()` with `ShutdownOptions`
|
|
42
|
+
|
|
43
|
+
## IMPORTANT
|
|
44
|
+
- Never break the `IQueueProvider` interface contract
|
|
45
|
+
- All new features must have unit tests
|
|
46
|
+
- E2E tests require Docker (docker-compose.e2e.yml)
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## 🔴 Queue Module Safety Checklist
|
|
51
|
+
|
|
52
|
+
**Always verify these when modifying queue code:**
|
|
53
|
+
|
|
54
|
+
### Memory Leaks
|
|
55
|
+
- [ ] All Maps/Sets cleared in `close()` method
|
|
56
|
+
- [ ] All event listeners removed on destroy (`removeAllListeners`)
|
|
57
|
+
- [ ] Timer/interval cleanup (`clearInterval`, `clearTimeout`)
|
|
58
|
+
- [ ] No unbounded caches (add TTL or max size)
|
|
59
|
+
- [ ] Health check doesn't create persistent resources
|
|
60
|
+
|
|
61
|
+
### Race Conditions
|
|
62
|
+
- [ ] Single worker per queue (ProcessorExplorer routing pattern)
|
|
63
|
+
- [ ] No duplicate worker registration (throw WORKER_EXISTS)
|
|
64
|
+
- [ ] Idempotency store lock before processing
|
|
65
|
+
- [ ] Lock renewal for long-running jobs (> lockTtl)
|
|
66
|
+
|
|
67
|
+
### Duplicate Job Prevention
|
|
68
|
+
- [ ] Idempotency store configured for production
|
|
69
|
+
- [ ] Original job ID preserved across retries (x-original-job-id)
|
|
70
|
+
- [ ] Consumer group / prefetch configured correctly
|
|
71
|
+
- [ ] Deduplication key includes partition+offset (Kafka)
|
|
72
|
+
|
|
73
|
+
### Job Loss on Restart
|
|
74
|
+
- [ ] Avoid in-memory delayed jobs (use broker-native delays)
|
|
75
|
+
- [ ] DelayedJobScheduler.shutdown({ executeImmediately: true })
|
|
76
|
+
- [ ] Kubernetes terminationGracePeriodSeconds >= shutdown timeout
|
|
77
|
+
- [ ] Ack AFTER successful retry add (RabbitMQ)
|
|
78
|
+
- [ ] Graceful shutdown: close workers → events → queues
|
|
79
|
+
|
|
80
|
+
### Security
|
|
81
|
+
- [ ] Sanitize correlationId (alphanumeric, hyphen, underscore only)
|
|
82
|
+
- [ ] Validate job structure before processing
|
|
83
|
+
- [ ] No credentials in URLs/logs
|
|
84
|
+
- [ ] Sanitize error messages before DLQ/logs
|
|
85
|
+
|
|
86
|
+
### Testing
|
|
87
|
+
- [ ] Reset circuit breaker in `beforeEach` for isolation
|
|
88
|
+
- [ ] Unique queue names per test to avoid WORKER_EXISTS
|
|
89
|
+
- [ ] Wait for worker ready before adding jobs
|
|
90
|
+
- [ ] Account for async processing in assertions
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## Circuit Breaker Notes
|
|
95
|
+
- State persists across tests (call `processorExplorer.resetCircuitBreaker()`)
|
|
96
|
+
- Reset timeout affects test timing (use 10s+ for reliable tests)
|
|
97
|
+
- OPEN state re-throws error to trigger provider retry
|
|
98
|
+
- Non-failure errors (per `isFailure`) count as successes for recovery
|
|
99
|
+
|
|
100
|
+
---
|
|
101
|
+
|
|
102
|
+
## Quick Reference
|
|
103
|
+
|
|
104
|
+
```typescript
|
|
105
|
+
// Producer-only mode (no ProcessorExplorer, just QueueService)
|
|
106
|
+
// Sync
|
|
107
|
+
QueueModule.forProducer({
|
|
108
|
+
provider: QueueProviderType.BULLMQ,
|
|
109
|
+
options: { connection: { host: 'redis', port: 6379 } },
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
// Async
|
|
113
|
+
QueueModule.forProducerAsync({
|
|
114
|
+
useFactory: (config: ConfigService) => ({
|
|
115
|
+
provider: QueueProviderType.BULLMQ,
|
|
116
|
+
options: { connection: config.get('redis') },
|
|
117
|
+
}),
|
|
118
|
+
inject: [ConfigService],
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
// Idempotency pattern (all providers)
|
|
122
|
+
const canProcess = await store.markProcessing(job.id, lockTtl);
|
|
123
|
+
if (!canProcess) return; // Skip duplicate
|
|
124
|
+
try {
|
|
125
|
+
await process(job);
|
|
126
|
+
await store.markComplete(job.id, completedTtl);
|
|
127
|
+
} catch (e) {
|
|
128
|
+
await store.releaseLock(job.id); // Allow retry
|
|
129
|
+
throw e;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Safe retry pattern (RabbitMQ)
|
|
133
|
+
await this.add(queueName, job.name, data, retryOpts); // Add FIRST
|
|
134
|
+
channel.ack(msg); // Ack AFTER successful add
|
|
135
|
+
|
|
136
|
+
// Cleanup pattern (close method)
|
|
137
|
+
await Promise.all(workers.map(w => w.close()));
|
|
138
|
+
workers.clear();
|
|
139
|
+
events.clear();
|
|
140
|
+
queues.clear();
|
|
141
|
+
listeners.clear();
|
|
142
|
+
```
|
package/CLAUDE.md
CHANGED
|
@@ -1,3 +1,21 @@
|
|
|
1
|
+
# Project Context
|
|
2
|
+
|
|
3
|
+
This file is auto-generated from `.nax/context.md`.
|
|
4
|
+
DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Project Metadata
|
|
9
|
+
|
|
10
|
+
> Auto-injected by `nax generate`
|
|
11
|
+
|
|
12
|
+
**Project:** `@nathapp/nestjs-queue`
|
|
13
|
+
|
|
14
|
+
**Language:** TypeScript
|
|
15
|
+
|
|
16
|
+
**Key dependencies:** @nestjs/testing, @types/jest, bullmq, ioredis, jest, ts-jest, typescript
|
|
17
|
+
|
|
18
|
+
---
|
|
1
19
|
# @nathapp/nestjs-queue
|
|
2
20
|
|
|
3
21
|
Multi-provider queue abstraction for NestJS (BullMQ, Kafka, RabbitMQ, Redis Pub/Sub).
|
package/GEMINI.md
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# Gemini CLI Context
|
|
2
|
+
|
|
3
|
+
This file is auto-generated from `.nax/context.md`.
|
|
4
|
+
DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Project Metadata
|
|
9
|
+
|
|
10
|
+
> Auto-injected by `nax generate`
|
|
11
|
+
|
|
12
|
+
**Project:** `@nathapp/nestjs-queue`
|
|
13
|
+
|
|
14
|
+
**Language:** TypeScript
|
|
15
|
+
|
|
16
|
+
**Key dependencies:** @nestjs/testing, @types/jest, bullmq, ioredis, jest, ts-jest, typescript
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
# @nathapp/nestjs-queue
|
|
20
|
+
|
|
21
|
+
Multi-provider queue abstraction for NestJS (BullMQ, Kafka, RabbitMQ, Redis Pub/Sub).
|
|
22
|
+
|
|
23
|
+
## Commands
|
|
24
|
+
- Build: `bun run build` (from monorepo root)
|
|
25
|
+
- Test: `bun run --filter @nathapp/nestjs-queue test`
|
|
26
|
+
- E2E: `bun run --filter @nathapp/nestjs-queue test:e2e`
|
|
27
|
+
- Lint: `bun run lint`
|
|
28
|
+
|
|
29
|
+
## Architecture
|
|
30
|
+
- `lib/provider/` - Provider implementations (BullMQ, Kafka, RabbitMQ, Redis)
|
|
31
|
+
- `lib/interface/` - Core interfaces (IQueueProvider, IJob, etc.)
|
|
32
|
+
- `lib/explorer/` - ProcessorExplorer for decorator scanning
|
|
33
|
+
- `lib/utils/` - Shared utilities (errors, validation, idempotency)
|
|
34
|
+
|
|
35
|
+
## Style
|
|
36
|
+
- All providers must implement `IQueueProvider` interface
|
|
37
|
+
- Use `QueueError` for domain errors with error codes
|
|
38
|
+
- Propagate `correlationId` through all job flows
|
|
39
|
+
- Clean up resources in `close()` with `ShutdownOptions`
|
|
40
|
+
|
|
41
|
+
## IMPORTANT
|
|
42
|
+
- Never break the `IQueueProvider` interface contract
|
|
43
|
+
- All new features must have unit tests
|
|
44
|
+
- E2E tests require Docker (docker-compose.e2e.yml)
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## 🔴 Queue Module Safety Checklist
|
|
49
|
+
|
|
50
|
+
**Always verify these when modifying queue code:**
|
|
51
|
+
|
|
52
|
+
### Memory Leaks
|
|
53
|
+
- [ ] All Maps/Sets cleared in `close()` method
|
|
54
|
+
- [ ] All event listeners removed on destroy (`removeAllListeners`)
|
|
55
|
+
- [ ] Timer/interval cleanup (`clearInterval`, `clearTimeout`)
|
|
56
|
+
- [ ] No unbounded caches (add TTL or max size)
|
|
57
|
+
- [ ] Health check doesn't create persistent resources
|
|
58
|
+
|
|
59
|
+
### Race Conditions
|
|
60
|
+
- [ ] Single worker per queue (ProcessorExplorer routing pattern)
|
|
61
|
+
- [ ] No duplicate worker registration (throw WORKER_EXISTS)
|
|
62
|
+
- [ ] Idempotency store lock before processing
|
|
63
|
+
- [ ] Lock renewal for long-running jobs (> lockTtl)
|
|
64
|
+
|
|
65
|
+
### Duplicate Job Prevention
|
|
66
|
+
- [ ] Idempotency store configured for production
|
|
67
|
+
- [ ] Original job ID preserved across retries (x-original-job-id)
|
|
68
|
+
- [ ] Consumer group / prefetch configured correctly
|
|
69
|
+
- [ ] Deduplication key includes partition+offset (Kafka)
|
|
70
|
+
|
|
71
|
+
### Job Loss on Restart
|
|
72
|
+
- [ ] Avoid in-memory delayed jobs (use broker-native delays)
|
|
73
|
+
- [ ] DelayedJobScheduler.shutdown({ executeImmediately: true })
|
|
74
|
+
- [ ] Kubernetes terminationGracePeriodSeconds >= shutdown timeout
|
|
75
|
+
- [ ] Ack AFTER successful retry add (RabbitMQ)
|
|
76
|
+
- [ ] Graceful shutdown: close workers → events → queues
|
|
77
|
+
|
|
78
|
+
### Security
|
|
79
|
+
- [ ] Sanitize correlationId (alphanumeric, hyphen, underscore only)
|
|
80
|
+
- [ ] Validate job structure before processing
|
|
81
|
+
- [ ] No credentials in URLs/logs
|
|
82
|
+
- [ ] Sanitize error messages before DLQ/logs
|
|
83
|
+
|
|
84
|
+
### Testing
|
|
85
|
+
- [ ] Reset circuit breaker in `beforeEach` for isolation
|
|
86
|
+
- [ ] Unique queue names per test to avoid WORKER_EXISTS
|
|
87
|
+
- [ ] Wait for worker ready before adding jobs
|
|
88
|
+
- [ ] Account for async processing in assertions
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## Circuit Breaker Notes
|
|
93
|
+
- State persists across tests (call `processorExplorer.resetCircuitBreaker()`)
|
|
94
|
+
- Reset timeout affects test timing (use 10s+ for reliable tests)
|
|
95
|
+
- OPEN state re-throws error to trigger provider retry
|
|
96
|
+
- Non-failure errors (per `isFailure`) count as successes for recovery
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
## Quick Reference
|
|
101
|
+
|
|
102
|
+
```typescript
|
|
103
|
+
// Producer-only mode (no ProcessorExplorer, just QueueService)
|
|
104
|
+
// Sync
|
|
105
|
+
QueueModule.forProducer({
|
|
106
|
+
provider: QueueProviderType.BULLMQ,
|
|
107
|
+
options: { connection: { host: 'redis', port: 6379 } },
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
// Async
|
|
111
|
+
QueueModule.forProducerAsync({
|
|
112
|
+
useFactory: (config: ConfigService) => ({
|
|
113
|
+
provider: QueueProviderType.BULLMQ,
|
|
114
|
+
options: { connection: config.get('redis') },
|
|
115
|
+
}),
|
|
116
|
+
inject: [ConfigService],
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
// Idempotency pattern (all providers)
|
|
120
|
+
const canProcess = await store.markProcessing(job.id, lockTtl);
|
|
121
|
+
if (!canProcess) return; // Skip duplicate
|
|
122
|
+
try {
|
|
123
|
+
await process(job);
|
|
124
|
+
await store.markComplete(job.id, completedTtl);
|
|
125
|
+
} catch (e) {
|
|
126
|
+
await store.releaseLock(job.id); // Allow retry
|
|
127
|
+
throw e;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Safe retry pattern (RabbitMQ)
|
|
131
|
+
await this.add(queueName, job.name, data, retryOpts); // Add FIRST
|
|
132
|
+
channel.ack(msg); // Ack AFTER successful add
|
|
133
|
+
|
|
134
|
+
// Cleanup pattern (close method)
|
|
135
|
+
await Promise.all(workers.map(w => w.close()));
|
|
136
|
+
workers.clear();
|
|
137
|
+
events.clear();
|
|
138
|
+
queues.clear();
|
|
139
|
+
listeners.clear();
|
|
140
|
+
```
|
package/README.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# @nathapp/nestjs-queue
|
|
2
|
+
|
|
3
|
+
Multi-provider queue abstraction for NestJS — BullMQ, Kafka, and RabbitMQ
|
|
4
|
+
behind one `IQueueProvider` interface, with decorator-based processors,
|
|
5
|
+
idempotency, circuit breaking, and delayed-job scheduling.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @nathapp/nestjs-queue
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Install the client library for whichever provider you use (e.g. `bullmq` +
|
|
14
|
+
`ioredis`, `kafkajs`, or `amqplib`) as a peer dependency. This package is part
|
|
15
|
+
of the `@nathapp/nestjs-*` peer-layer stack and builds on
|
|
16
|
+
`@nathapp/nestjs-common`.
|
|
17
|
+
|
|
18
|
+
## What it provides
|
|
19
|
+
|
|
20
|
+
- `QueueModule` — `register()` / `registerAsync()` for full processing mode
|
|
21
|
+
(wires `QueueService` + `ProcessorExplorer` for `@Processor`/`@Process`
|
|
22
|
+
decorators); `forProducer()` / `forProducerAsync()` for producer-only mode
|
|
23
|
+
(just `QueueService`, no decorator scanning).
|
|
24
|
+
- `QueueService` — `add`, `addBulk`, `process`, `getJob`, `getJobs`,
|
|
25
|
+
`removeJob`, `pause`, `resume`, and cleanup methods, delegating to the
|
|
26
|
+
configured `IQueueProvider`.
|
|
27
|
+
- `QueueProviderType` enum — `BULLMQ`, `KAFKA`, `RABBITMQ`, `CUSTOM`.
|
|
28
|
+
- Decorators — `@Processor(queueName | options)` (class) and
|
|
29
|
+
`@Process(name? | options)` (method) to declare job handlers;
|
|
30
|
+
`@OnQueueEvent`, `@BatchProcess` for event hooks and batch processing.
|
|
31
|
+
- Interfaces — `IJob<T>`, `JobOptions`, `IQueueProvider`,
|
|
32
|
+
`QueueModuleOptions`, `QueueModuleAsyncOptions`, `HealthCheckResult`,
|
|
33
|
+
`IdempotencyStoreOptions`.
|
|
34
|
+
- Utilities — `DelayedJobScheduler`, `QueueError`, `ShutdownOptions`,
|
|
35
|
+
sanitization/validation helpers, an `InMemoryIdempotencyStore` (under
|
|
36
|
+
`store`), and a Redis-backed idempotency store (under `utils`).
|
|
37
|
+
- Circuit breaking — `QueueModuleOptions.circuitBreaker` (global) and
|
|
38
|
+
`JobOptions.circuitBreaker` (per-processor, via `@Processor`) accept a
|
|
39
|
+
circuit-breaker config object to guard against cascading failures. The
|
|
40
|
+
breaker implementation and its option/state/metrics types are internal
|
|
41
|
+
and not part of the package's exported surface.
|
|
42
|
+
|
|
43
|
+
Provider implementations (BullMQ/Kafka/RabbitMQ) are lazy-loaded internally
|
|
44
|
+
and are not part of the package's static export surface — select one via
|
|
45
|
+
`provider: QueueProviderType.<X>` in the module options.
|
|
46
|
+
|
|
47
|
+
## Usage
|
|
48
|
+
|
|
49
|
+
Register a queue and declare a processor:
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
import { Module } from '@nestjs/common';
|
|
53
|
+
import { QueueModule, Processor, Process, IJob } from '@nathapp/nestjs-queue';
|
|
54
|
+
import { QueueProviderType } from '@nathapp/nestjs-queue';
|
|
55
|
+
|
|
56
|
+
@Module({
|
|
57
|
+
imports: [
|
|
58
|
+
QueueModule.register({
|
|
59
|
+
provider: QueueProviderType.BULLMQ,
|
|
60
|
+
options: { connection: { host: 'redis', port: 6379 } },
|
|
61
|
+
}),
|
|
62
|
+
],
|
|
63
|
+
providers: [EmailProcessor],
|
|
64
|
+
})
|
|
65
|
+
export class AppModule {}
|
|
66
|
+
|
|
67
|
+
@Processor('email-queue')
|
|
68
|
+
export class EmailProcessor {
|
|
69
|
+
@Process('send')
|
|
70
|
+
async handleSend(job: IJob<{ to: string }>) {
|
|
71
|
+
// ... send email
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
To only enqueue jobs (no local processing), use producer-only mode:
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
QueueModule.forProducer({
|
|
80
|
+
provider: QueueProviderType.BULLMQ,
|
|
81
|
+
options: { connection: { host: 'redis', port: 6379 } },
|
|
82
|
+
});
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
```typescript
|
|
86
|
+
import { Injectable } from '@nestjs/common';
|
|
87
|
+
import { QueueService } from '@nathapp/nestjs-queue';
|
|
88
|
+
|
|
89
|
+
@Injectable()
|
|
90
|
+
export class EmailQueueClient {
|
|
91
|
+
constructor(private readonly queue: QueueService) {}
|
|
92
|
+
|
|
93
|
+
enqueue(to: string) {
|
|
94
|
+
return this.queue.add('email-queue', 'send', { to });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
```
|
package/codex.md
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# Codex Instructions
|
|
2
|
+
|
|
3
|
+
This file is auto-generated from `.nax/context.md`.
|
|
4
|
+
DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Project Metadata
|
|
9
|
+
|
|
10
|
+
> Auto-injected by `nax generate`
|
|
11
|
+
|
|
12
|
+
**Project:** `@nathapp/nestjs-queue`
|
|
13
|
+
|
|
14
|
+
**Language:** TypeScript
|
|
15
|
+
|
|
16
|
+
**Key dependencies:** @nestjs/testing, @types/jest, bullmq, ioredis, jest, ts-jest, typescript
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
# @nathapp/nestjs-queue
|
|
20
|
+
|
|
21
|
+
Multi-provider queue abstraction for NestJS (BullMQ, Kafka, RabbitMQ, Redis Pub/Sub).
|
|
22
|
+
|
|
23
|
+
## Commands
|
|
24
|
+
- Build: `bun run build` (from monorepo root)
|
|
25
|
+
- Test: `bun run --filter @nathapp/nestjs-queue test`
|
|
26
|
+
- E2E: `bun run --filter @nathapp/nestjs-queue test:e2e`
|
|
27
|
+
- Lint: `bun run lint`
|
|
28
|
+
|
|
29
|
+
## Architecture
|
|
30
|
+
- `lib/provider/` - Provider implementations (BullMQ, Kafka, RabbitMQ, Redis)
|
|
31
|
+
- `lib/interface/` - Core interfaces (IQueueProvider, IJob, etc.)
|
|
32
|
+
- `lib/explorer/` - ProcessorExplorer for decorator scanning
|
|
33
|
+
- `lib/utils/` - Shared utilities (errors, validation, idempotency)
|
|
34
|
+
|
|
35
|
+
## Style
|
|
36
|
+
- All providers must implement `IQueueProvider` interface
|
|
37
|
+
- Use `QueueError` for domain errors with error codes
|
|
38
|
+
- Propagate `correlationId` through all job flows
|
|
39
|
+
- Clean up resources in `close()` with `ShutdownOptions`
|
|
40
|
+
|
|
41
|
+
## IMPORTANT
|
|
42
|
+
- Never break the `IQueueProvider` interface contract
|
|
43
|
+
- All new features must have unit tests
|
|
44
|
+
- E2E tests require Docker (docker-compose.e2e.yml)
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## 🔴 Queue Module Safety Checklist
|
|
49
|
+
|
|
50
|
+
**Always verify these when modifying queue code:**
|
|
51
|
+
|
|
52
|
+
### Memory Leaks
|
|
53
|
+
- [ ] All Maps/Sets cleared in `close()` method
|
|
54
|
+
- [ ] All event listeners removed on destroy (`removeAllListeners`)
|
|
55
|
+
- [ ] Timer/interval cleanup (`clearInterval`, `clearTimeout`)
|
|
56
|
+
- [ ] No unbounded caches (add TTL or max size)
|
|
57
|
+
- [ ] Health check doesn't create persistent resources
|
|
58
|
+
|
|
59
|
+
### Race Conditions
|
|
60
|
+
- [ ] Single worker per queue (ProcessorExplorer routing pattern)
|
|
61
|
+
- [ ] No duplicate worker registration (throw WORKER_EXISTS)
|
|
62
|
+
- [ ] Idempotency store lock before processing
|
|
63
|
+
- [ ] Lock renewal for long-running jobs (> lockTtl)
|
|
64
|
+
|
|
65
|
+
### Duplicate Job Prevention
|
|
66
|
+
- [ ] Idempotency store configured for production
|
|
67
|
+
- [ ] Original job ID preserved across retries (x-original-job-id)
|
|
68
|
+
- [ ] Consumer group / prefetch configured correctly
|
|
69
|
+
- [ ] Deduplication key includes partition+offset (Kafka)
|
|
70
|
+
|
|
71
|
+
### Job Loss on Restart
|
|
72
|
+
- [ ] Avoid in-memory delayed jobs (use broker-native delays)
|
|
73
|
+
- [ ] DelayedJobScheduler.shutdown({ executeImmediately: true })
|
|
74
|
+
- [ ] Kubernetes terminationGracePeriodSeconds >= shutdown timeout
|
|
75
|
+
- [ ] Ack AFTER successful retry add (RabbitMQ)
|
|
76
|
+
- [ ] Graceful shutdown: close workers → events → queues
|
|
77
|
+
|
|
78
|
+
### Security
|
|
79
|
+
- [ ] Sanitize correlationId (alphanumeric, hyphen, underscore only)
|
|
80
|
+
- [ ] Validate job structure before processing
|
|
81
|
+
- [ ] No credentials in URLs/logs
|
|
82
|
+
- [ ] Sanitize error messages before DLQ/logs
|
|
83
|
+
|
|
84
|
+
### Testing
|
|
85
|
+
- [ ] Reset circuit breaker in `beforeEach` for isolation
|
|
86
|
+
- [ ] Unique queue names per test to avoid WORKER_EXISTS
|
|
87
|
+
- [ ] Wait for worker ready before adding jobs
|
|
88
|
+
- [ ] Account for async processing in assertions
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## Circuit Breaker Notes
|
|
93
|
+
- State persists across tests (call `processorExplorer.resetCircuitBreaker()`)
|
|
94
|
+
- Reset timeout affects test timing (use 10s+ for reliable tests)
|
|
95
|
+
- OPEN state re-throws error to trigger provider retry
|
|
96
|
+
- Non-failure errors (per `isFailure`) count as successes for recovery
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
## Quick Reference
|
|
101
|
+
|
|
102
|
+
```typescript
|
|
103
|
+
// Producer-only mode (no ProcessorExplorer, just QueueService)
|
|
104
|
+
// Sync
|
|
105
|
+
QueueModule.forProducer({
|
|
106
|
+
provider: QueueProviderType.BULLMQ,
|
|
107
|
+
options: { connection: { host: 'redis', port: 6379 } },
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
// Async
|
|
111
|
+
QueueModule.forProducerAsync({
|
|
112
|
+
useFactory: (config: ConfigService) => ({
|
|
113
|
+
provider: QueueProviderType.BULLMQ,
|
|
114
|
+
options: { connection: config.get('redis') },
|
|
115
|
+
}),
|
|
116
|
+
inject: [ConfigService],
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
// Idempotency pattern (all providers)
|
|
120
|
+
const canProcess = await store.markProcessing(job.id, lockTtl);
|
|
121
|
+
if (!canProcess) return; // Skip duplicate
|
|
122
|
+
try {
|
|
123
|
+
await process(job);
|
|
124
|
+
await store.markComplete(job.id, completedTtl);
|
|
125
|
+
} catch (e) {
|
|
126
|
+
await store.releaseLock(job.id); // Allow retry
|
|
127
|
+
throw e;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Safe retry pattern (RabbitMQ)
|
|
131
|
+
await this.add(queueName, job.name, data, retryOpts); // Add FIRST
|
|
132
|
+
channel.ack(msg); // Ack AFTER successful add
|
|
133
|
+
|
|
134
|
+
// Cleanup pattern (close method)
|
|
135
|
+
await Promise.all(workers.map(w => w.close()));
|
|
136
|
+
workers.clear();
|
|
137
|
+
events.clear();
|
|
138
|
+
queues.clear();
|
|
139
|
+
listeners.clear();
|
|
140
|
+
```
|
|
@@ -1,32 +1,52 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.createQueueProvider = createQueueProvider;
|
|
4
|
+
const common_1 = require("@nestjs/common");
|
|
4
5
|
const queue_constant_1 = require("../constant/queue.constant");
|
|
5
6
|
const provider_enum_1 = require("../enum/provider.enum");
|
|
6
7
|
const queue_module_definition_1 = require("./queue.module-definition");
|
|
7
8
|
const in_memory_idempotency_store_1 = require("../store/in-memory-idempotency.store");
|
|
9
|
+
const logger = new common_1.Logger('QueueProviderFactory');
|
|
8
10
|
function createQueueProvider() {
|
|
9
11
|
return {
|
|
10
12
|
provide: queue_constant_1.QUEUE_PROVIDER,
|
|
11
13
|
useFactory: async (options) => {
|
|
12
14
|
if (options.useInMemoryIdempotency) {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
+
if (options.provider === provider_enum_1.QueueProviderType.BULLMQ) {
|
|
16
|
+
logger.warn('useInMemoryIdempotency is not supported for BullMQ; rely on Redis-backed jobId deduplication instead. Ignoring the flag.');
|
|
17
|
+
}
|
|
18
|
+
else {
|
|
19
|
+
const providerOptions = options.options;
|
|
20
|
+
let resolved = { ...providerOptions };
|
|
15
21
|
if (!providerOptions.idempotency) {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
22
|
+
resolved = {
|
|
23
|
+
...resolved,
|
|
24
|
+
idempotency: {
|
|
25
|
+
enabled: true,
|
|
26
|
+
store: new in_memory_idempotency_store_1.InMemoryIdempotencyStore(),
|
|
27
|
+
lockTtl: 30000,
|
|
28
|
+
completedTtl: 3600000,
|
|
29
|
+
},
|
|
21
30
|
};
|
|
22
31
|
}
|
|
23
32
|
else if (!providerOptions.idempotency.store) {
|
|
24
|
-
|
|
25
|
-
...
|
|
26
|
-
|
|
27
|
-
|
|
33
|
+
resolved = {
|
|
34
|
+
...resolved,
|
|
35
|
+
idempotency: {
|
|
36
|
+
...providerOptions.idempotency,
|
|
37
|
+
enabled: true,
|
|
38
|
+
store: new in_memory_idempotency_store_1.InMemoryIdempotencyStore(),
|
|
39
|
+
},
|
|
28
40
|
};
|
|
29
41
|
}
|
|
42
|
+
if (options.provider === provider_enum_1.QueueProviderType.KAFKA) {
|
|
43
|
+
const { KafkaQueueProvider } = await Promise.resolve().then(() => require('../provider/kafka/kafka.provider'));
|
|
44
|
+
return new KafkaQueueProvider(resolved);
|
|
45
|
+
}
|
|
46
|
+
if (options.provider === provider_enum_1.QueueProviderType.RABBITMQ) {
|
|
47
|
+
const { RabbitMQQueueProvider } = await Promise.resolve().then(() => require('../provider/rabbitmq/rabbitmq.provider'));
|
|
48
|
+
return new RabbitMQQueueProvider(resolved);
|
|
49
|
+
}
|
|
30
50
|
}
|
|
31
51
|
}
|
|
32
52
|
switch (options.provider) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queue.provider.js","sourceRoot":"","sources":["../../lib/module/queue.provider.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"queue.provider.js","sourceRoot":"","sources":["../../lib/module/queue.provider.ts"],"names":[],"mappings":";;AAkBA,kDA+EC;AAjGD,2CAAkD;AAClD,+DAA4D;AAC5D,yDAA0D;AAQ1D,uEAAiE;AACjE,sFAAgF;AAEhF,MAAM,MAAM,GAAG,IAAI,eAAM,CAAC,sBAAsB,CAAC,CAAC;AAKlD,SAAgB,mBAAmB;IACjC,OAAO;QACL,OAAO,EAAE,+BAAc;QACvB,UAAU,EAAE,KAAK,EAAE,OAA2B,EAA0B,EAAE;YAExE,IAAI,OAAO,CAAC,sBAAsB,EAAE,CAAC;gBACnC,IAAI,OAAO,CAAC,QAAQ,KAAK,iCAAiB,CAAC,MAAM,EAAE,CAAC;oBAGlD,MAAM,CAAC,IAAI,CACT,0HAA0H,CAC3H,CAAC;gBACJ,CAAC;qBAAM,CAAC;oBACN,MAA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