@nathapp/nestjs-queue 4.0.1 → 4.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -0
- package/dist/decorator/processor.decorator.js.map +1 -1
- package/dist/explorer/processor.explorer.d.ts +1 -1
- package/dist/interface/queue-options.interface.d.ts +1 -0
- package/dist/provider/bullmq/bullmq.provider.d.ts +2 -0
- package/dist/provider/bullmq/bullmq.provider.js +108 -58
- package/dist/provider/bullmq/bullmq.provider.js.map +1 -1
- package/dist/provider/kafka/kafka.provider.d.ts +14 -4
- package/dist/provider/kafka/kafka.provider.js +584 -251
- package/dist/provider/kafka/kafka.provider.js.map +1 -1
- package/dist/provider/rabbitmq/rabbitmq.provider.d.ts +18 -3
- package/dist/provider/rabbitmq/rabbitmq.provider.js +442 -251
- package/dist/provider/rabbitmq/rabbitmq.provider.js.map +1 -1
- package/dist/service/queue.service.d.ts +1 -1
- package/dist/utils/batch-result.d.ts +3 -0
- package/dist/utils/batch-result.js +42 -0
- package/dist/utils/batch-result.js.map +1 -0
- package/dist/utils/delayed-scheduler.d.ts +5 -1
- package/dist/utils/delayed-scheduler.js +49 -18
- package/dist/utils/delayed-scheduler.js.map +1 -1
- package/dist/utils/errors.d.ts +3 -3
- package/dist/utils/named-processor-registry.d.ts +10 -0
- package/dist/utils/named-processor-registry.js +45 -0
- package/dist/utils/named-processor-registry.js.map +1 -0
- package/dist/utils/redis-idempotency-store.d.ts +4 -0
- package/dist/utils/redis-idempotency-store.js +55 -9
- package/dist/utils/redis-idempotency-store.js.map +1 -1
- package/dist/utils/sanitize.js +21 -9
- package/dist/utils/sanitize.js.map +1 -1
- package/dist/utils/validation.js +0 -2
- package/dist/utils/validation.js.map +1 -1
- package/package.json +5 -4
- package/tsconfig.test.json +16 -0
|
@@ -11,20 +11,16 @@ const sanitize_1 = require("../../utils/sanitize");
|
|
|
11
11
|
const delayed_scheduler_1 = require("../../utils/delayed-scheduler");
|
|
12
12
|
const lock_renewal_1 = require("../../utils/lock-renewal");
|
|
13
13
|
const uuid_1 = require("uuid");
|
|
14
|
+
const batch_result_1 = require("../../utils/batch-result");
|
|
15
|
+
const validation_1 = require("../../utils/validation");
|
|
16
|
+
const named_processor_registry_1 = require("../../utils/named-processor-registry");
|
|
14
17
|
let _amqpConnectionManager = null;
|
|
15
|
-
let _amqplib = null;
|
|
16
18
|
async function getAmqpConnectionManager() {
|
|
17
19
|
if (!_amqpConnectionManager) {
|
|
18
20
|
_amqpConnectionManager = await Promise.resolve().then(() => require('amqp-connection-manager'));
|
|
19
21
|
}
|
|
20
22
|
return _amqpConnectionManager;
|
|
21
23
|
}
|
|
22
|
-
async function getAmqplib() {
|
|
23
|
-
if (!_amqplib) {
|
|
24
|
-
_amqplib = await Promise.resolve().then(() => require('amqplib'));
|
|
25
|
-
}
|
|
26
|
-
return _amqplib;
|
|
27
|
-
}
|
|
28
24
|
class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
29
25
|
constructor(options) {
|
|
30
26
|
var _a;
|
|
@@ -35,9 +31,15 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
35
31
|
this.channels = new Map();
|
|
36
32
|
this.consumerTags = new Map();
|
|
37
33
|
this.eventListeners = new Map();
|
|
34
|
+
this.registry = new named_processor_registry_1.NamedProcessorRegistry();
|
|
35
|
+
this.consumerConcurrency = new Map();
|
|
38
36
|
this.isShuttingDown = false;
|
|
39
37
|
this.batchAccumulators = new Map();
|
|
40
38
|
this.batchTimers = new Map();
|
|
39
|
+
this.delayedDeliveries = new Map();
|
|
40
|
+
this.channelGenerations = new Map();
|
|
41
|
+
this.channelGenerationCounter = 0;
|
|
42
|
+
this.hasWarnedLowPrefetchRetention = false;
|
|
41
43
|
this.type = provider_enum_1.QueueProviderType.RABBITMQ;
|
|
42
44
|
this.metrics = options.metrics;
|
|
43
45
|
if (!((_a = options.idempotency) === null || _a === void 0 ? void 0 : _a.store)) {
|
|
@@ -63,19 +65,30 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
63
65
|
heartbeatIntervalInSeconds: 5,
|
|
64
66
|
reconnectTimeInSeconds: reconnectOptions.initialDelay ? reconnectOptions.initialDelay / 1000 : 5,
|
|
65
67
|
});
|
|
66
|
-
this.connection
|
|
67
|
-
this.logger.log('RabbitMQ connected');
|
|
68
|
-
});
|
|
69
|
-
this.connection.on('disconnect', (params) => {
|
|
70
|
-
var _a;
|
|
71
|
-
this.logger.warn(`RabbitMQ disconnected: ${((_a = params.err) === null || _a === void 0 ? void 0 : _a.message) || 'unknown'}`);
|
|
72
|
-
});
|
|
73
|
-
this.connection.on('connectFailed', (params) => {
|
|
74
|
-
var _a;
|
|
75
|
-
this.logger.error(`RabbitMQ connection failed: ${((_a = params.err) === null || _a === void 0 ? void 0 : _a.message) || 'unknown'}`);
|
|
76
|
-
});
|
|
68
|
+
this.registerConnectionHandlers(this.connection);
|
|
77
69
|
}
|
|
78
|
-
catch (
|
|
70
|
+
catch (_error) {
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
registerConnectionHandlers(connection) {
|
|
74
|
+
connection.on('connect', () => {
|
|
75
|
+
this.logger.log('RabbitMQ connected');
|
|
76
|
+
});
|
|
77
|
+
connection.on('disconnect', (params) => {
|
|
78
|
+
var _a;
|
|
79
|
+
this.logger.warn(`RabbitMQ disconnected: ${((_a = params.err) === null || _a === void 0 ? void 0 : _a.message) || 'unknown'}`);
|
|
80
|
+
this.invalidateChannelGenerations();
|
|
81
|
+
this.delayedDeliveries.clear();
|
|
82
|
+
});
|
|
83
|
+
connection.on('connectFailed', (params) => {
|
|
84
|
+
var _a;
|
|
85
|
+
this.logger.error(`RabbitMQ connection failed: ${((_a = params.err) === null || _a === void 0 ? void 0 : _a.message) || 'unknown'}`);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
invalidateChannelGenerations() {
|
|
89
|
+
this.channelGenerationCounter += 1;
|
|
90
|
+
for (const [name] of this.channels) {
|
|
91
|
+
this.channelGenerations.set(name, this.channelGenerationCounter);
|
|
79
92
|
}
|
|
80
93
|
}
|
|
81
94
|
async getConnection() {
|
|
@@ -86,17 +99,7 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
86
99
|
heartbeatIntervalInSeconds: 5,
|
|
87
100
|
reconnectTimeInSeconds: reconnectOptions.initialDelay ? reconnectOptions.initialDelay / 1000 : 5,
|
|
88
101
|
});
|
|
89
|
-
this.connection
|
|
90
|
-
this.logger.log('RabbitMQ connected');
|
|
91
|
-
});
|
|
92
|
-
this.connection.on('disconnect', (params) => {
|
|
93
|
-
var _a;
|
|
94
|
-
this.logger.warn(`RabbitMQ disconnected: ${((_a = params.err) === null || _a === void 0 ? void 0 : _a.message) || 'unknown'}`);
|
|
95
|
-
});
|
|
96
|
-
this.connection.on('connectFailed', (params) => {
|
|
97
|
-
var _a;
|
|
98
|
-
this.logger.error(`RabbitMQ connection failed: ${((_a = params.err) === null || _a === void 0 ? void 0 : _a.message) || 'unknown'}`);
|
|
99
|
-
});
|
|
102
|
+
this.registerConnectionHandlers(this.connection);
|
|
100
103
|
}
|
|
101
104
|
return this.connection;
|
|
102
105
|
}
|
|
@@ -107,6 +110,100 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
107
110
|
const originalId = headers['x-original-job-id'];
|
|
108
111
|
return originalId ? String(originalId) : job.id;
|
|
109
112
|
}
|
|
113
|
+
getDeliveryGroupKey(queueName, jobId) {
|
|
114
|
+
return `${queueName}\u0000${jobId}`;
|
|
115
|
+
}
|
|
116
|
+
warnIfLowPrefetchRetention() {
|
|
117
|
+
if (this.hasWarnedLowPrefetchRetention) {
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
const effectivePrefetch = this.options.prefetchCount || 1;
|
|
121
|
+
if (effectivePrefetch > 1) {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
this.hasWarnedLowPrefetchRetention = true;
|
|
125
|
+
this.logger.warn(`Delayed delivery retained with prefetchCount=${effectivePrefetch}. ` +
|
|
126
|
+
'Each retained (unacknowledged) delivery holds a prefetch slot, so this queue can be ' +
|
|
127
|
+
'head-of-line blocked until the delay elapses. Use a dedicated queue for delayed jobs, ' +
|
|
128
|
+
'raise prefetchCount, or use the broker-native delayed message exchange for long delays.');
|
|
129
|
+
}
|
|
130
|
+
isCurrentChannel(queueName, channel, channelGeneration) {
|
|
131
|
+
return (this.channels.get(queueName) === channel &&
|
|
132
|
+
this.channelGenerations.get(queueName) === channelGeneration);
|
|
133
|
+
}
|
|
134
|
+
buildRepublishHeaders(job, headers, idempotencyKey) {
|
|
135
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
136
|
+
const { 'x-process-after': _processAfter, 'x-delay': _delay, ...sourceHeaders } = headers;
|
|
137
|
+
return {
|
|
138
|
+
...(_a = job.opts) === null || _a === void 0 ? void 0 : _a.headers,
|
|
139
|
+
...sourceHeaders,
|
|
140
|
+
'x-original-job-id': idempotencyKey,
|
|
141
|
+
'x-attempts': String((_c = (_b = headers['x-attempts']) !== null && _b !== void 0 ? _b : job.attemptsMade) !== null && _c !== void 0 ? _c : 0),
|
|
142
|
+
'x-max-attempts': String((_f = (_d = headers['x-max-attempts']) !== null && _d !== void 0 ? _d : (_e = job.opts) === null || _e === void 0 ? void 0 : _e.attempts) !== null && _f !== void 0 ? _f : 1),
|
|
143
|
+
'x-correlation-id': job.correlationId
|
|
144
|
+
? String(job.correlationId)
|
|
145
|
+
: String((_g = headers['x-correlation-id']) !== null && _g !== void 0 ? _g : job.id),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
scheduleDelayedDelivery(queueName, job, delay, msg, headers, channel, channelGeneration) {
|
|
149
|
+
var _a, _b;
|
|
150
|
+
const groupKey = this.getDeliveryGroupKey(queueName, job.id);
|
|
151
|
+
const retained = { msg, channel, channelGeneration };
|
|
152
|
+
this.warnIfLowPrefetchRetention();
|
|
153
|
+
const existing = this.delayedDeliveries.get(groupKey);
|
|
154
|
+
if (existing) {
|
|
155
|
+
existing.deliveries.push(retained);
|
|
156
|
+
this.logger.debug(`Delayed job ${job.id} already scheduled; retained duplicate delivery`);
|
|
157
|
+
return 'scheduled';
|
|
158
|
+
}
|
|
159
|
+
const idempotencyKey = this.getIdempotencyKey(job, headers);
|
|
160
|
+
const republishOpts = {
|
|
161
|
+
...job.opts,
|
|
162
|
+
jobId: job.id,
|
|
163
|
+
delay: 0,
|
|
164
|
+
correlationId: (_a = job.correlationId) !== null && _a !== void 0 ? _a : (_b = job.opts) === null || _b === void 0 ? void 0 : _b.correlationId,
|
|
165
|
+
headers: this.buildRepublishHeaders(job, headers, idempotencyKey),
|
|
166
|
+
};
|
|
167
|
+
const scheduledJob = { ...job, opts: republishOpts };
|
|
168
|
+
this.delayedDeliveries.set(groupKey, {
|
|
169
|
+
queueName,
|
|
170
|
+
jobId: job.id,
|
|
171
|
+
settled: false,
|
|
172
|
+
deliveries: [retained],
|
|
173
|
+
});
|
|
174
|
+
const scheduled = this.delayedScheduler.schedule(queueName, scheduledJob, delay, (error) => this.settleDelayedDeliveryGroup(groupKey, error), groupKey);
|
|
175
|
+
if (scheduled) {
|
|
176
|
+
return 'scheduled';
|
|
177
|
+
}
|
|
178
|
+
this.delayedDeliveries.delete(groupKey);
|
|
179
|
+
return this.delayedScheduler.shuttingDown ? 'requeue' : 'process';
|
|
180
|
+
}
|
|
181
|
+
settleDelayedDeliveryGroup(groupKey, error) {
|
|
182
|
+
var _a;
|
|
183
|
+
const group = this.delayedDeliveries.get(groupKey);
|
|
184
|
+
if (!group || group.settled) {
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
group.settled = true;
|
|
188
|
+
this.delayedDeliveries.delete(groupKey);
|
|
189
|
+
for (const delivery of group.deliveries) {
|
|
190
|
+
if (!this.isCurrentChannel(group.queueName, delivery.channel, delivery.channelGeneration)) {
|
|
191
|
+
this.logger.warn(`Skipping settlement of retained delayed job ${group.jobId}: original channel is no longer current`);
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
try {
|
|
195
|
+
if (error) {
|
|
196
|
+
delivery.channel.nack(delivery.msg, false, true);
|
|
197
|
+
}
|
|
198
|
+
else {
|
|
199
|
+
delivery.channel.ack(delivery.msg);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
catch (settleError) {
|
|
203
|
+
this.logger.error(`Failed to settle retained delayed job ${group.jobId}: ${(_a = settleError === null || settleError === void 0 ? void 0 : settleError.message) !== null && _a !== void 0 ? _a : String(settleError)}`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
110
207
|
calculateBackoff(job) {
|
|
111
208
|
const opts = job.opts;
|
|
112
209
|
if (!(opts === null || opts === void 0 ? void 0 : opts.backoff)) {
|
|
@@ -140,7 +237,6 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
140
237
|
async getChannel(queueName) {
|
|
141
238
|
if (!this.channels.has(queueName)) {
|
|
142
239
|
const connection = await this.getConnection();
|
|
143
|
-
const amqp = await getAmqplib();
|
|
144
240
|
const queueOpts = this.options.queueOptions || {};
|
|
145
241
|
const dlqName = `${queueName}-dlq`;
|
|
146
242
|
const channel = connection.createChannel({
|
|
@@ -165,11 +261,16 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
165
261
|
},
|
|
166
262
|
});
|
|
167
263
|
this.channels.set(queueName, channel);
|
|
264
|
+
this.channelGenerationCounter += 1;
|
|
265
|
+
this.channelGenerations.set(queueName, this.channelGenerationCounter);
|
|
168
266
|
}
|
|
169
267
|
return this.channels.get(queueName);
|
|
170
268
|
}
|
|
171
269
|
async add(queueName, jobName, data, opts) {
|
|
172
|
-
var _a
|
|
270
|
+
var _a;
|
|
271
|
+
(0, validation_1.validateJobData)(data);
|
|
272
|
+
if (opts === null || opts === void 0 ? void 0 : opts.jobId)
|
|
273
|
+
(0, validation_1.validateJobId)(opts.jobId);
|
|
173
274
|
const channel = await this.getChannel(queueName);
|
|
174
275
|
const sanitizedCorrelationId = (0, errors_1.sanitizeCorrelationId)(opts === null || opts === void 0 ? void 0 : opts.correlationId);
|
|
175
276
|
const job = {
|
|
@@ -181,43 +282,22 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
181
282
|
attemptsMade: 0,
|
|
182
283
|
correlationId: sanitizedCorrelationId,
|
|
183
284
|
};
|
|
184
|
-
const messageOptions =
|
|
185
|
-
persistent: true,
|
|
186
|
-
messageId: job.id,
|
|
187
|
-
correlationId: sanitizedCorrelationId,
|
|
188
|
-
contentType: 'application/json',
|
|
189
|
-
headers: {
|
|
190
|
-
'x-job-name': jobName,
|
|
191
|
-
'x-job-id': job.id,
|
|
192
|
-
'x-correlation-id': sanitizedCorrelationId || job.id,
|
|
193
|
-
'x-original-job-id': ((_a = opts === null || opts === void 0 ? void 0 : opts.headers) === null || _a === void 0 ? void 0 : _a['x-original-job-id']) || (opts === null || opts === void 0 ? void 0 : opts.jobId) || job.id,
|
|
194
|
-
'x-attempts': job.attemptsMade || 0,
|
|
195
|
-
'x-max-attempts': (opts === null || opts === void 0 ? void 0 : opts.attempts) || 1,
|
|
196
|
-
'x-timestamp': job.timestamp,
|
|
197
|
-
...opts === null || opts === void 0 ? void 0 : opts.headers,
|
|
198
|
-
},
|
|
199
|
-
};
|
|
200
|
-
if ((opts === null || opts === void 0 ? void 0 : opts.priority) !== undefined) {
|
|
201
|
-
messageOptions.priority = opts.priority;
|
|
202
|
-
}
|
|
203
|
-
if (opts === null || opts === void 0 ? void 0 : opts.delay) {
|
|
204
|
-
if (this.options.useDelayedMessagePlugin) {
|
|
205
|
-
messageOptions.headers['x-delay'] = opts.delay;
|
|
206
|
-
}
|
|
207
|
-
else {
|
|
208
|
-
messageOptions.headers['x-process-after'] = Date.now() + opts.delay;
|
|
209
|
-
this.logger.warn('Delayed messages without plugin may not be accurate. Consider installing rabbitmq_delayed_message_exchange plugin.');
|
|
210
|
-
}
|
|
211
|
-
}
|
|
285
|
+
const messageOptions = this.buildPublishOptions(job);
|
|
212
286
|
await channel.sendToQueue(queueName, Buffer.from(JSON.stringify(job)), messageOptions);
|
|
213
287
|
this.logger.debug(`Job added: ${jobName} (${job.id}) to queue ${queueName}`);
|
|
214
|
-
(
|
|
288
|
+
(_a = this.metrics) === null || _a === void 0 ? void 0 : _a.jobAdded(queueName, jobName, job.id, {
|
|
215
289
|
delay: opts === null || opts === void 0 ? void 0 : opts.delay,
|
|
216
290
|
priority: opts === null || opts === void 0 ? void 0 : opts.priority,
|
|
217
291
|
});
|
|
218
292
|
return job;
|
|
219
293
|
}
|
|
220
294
|
async addBulk(queueName, jobs) {
|
|
295
|
+
var _a;
|
|
296
|
+
for (const j of jobs) {
|
|
297
|
+
(0, validation_1.validateJobData)(j.data);
|
|
298
|
+
if ((_a = j.opts) === null || _a === void 0 ? void 0 : _a.jobId)
|
|
299
|
+
(0, validation_1.validateJobId)(j.opts.jobId);
|
|
300
|
+
}
|
|
221
301
|
const channel = await this.getChannel(queueName);
|
|
222
302
|
const createdJobs = jobs.map((j) => {
|
|
223
303
|
var _a, _b;
|
|
@@ -232,35 +312,8 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
232
312
|
correlationId: sanitizedCorrelationId,
|
|
233
313
|
};
|
|
234
314
|
});
|
|
235
|
-
const publishPromises = createdJobs.map((job
|
|
236
|
-
|
|
237
|
-
const original = jobs[idx];
|
|
238
|
-
const messageOptions = {
|
|
239
|
-
persistent: true,
|
|
240
|
-
messageId: job.id,
|
|
241
|
-
correlationId: job.correlationId,
|
|
242
|
-
contentType: 'application/json',
|
|
243
|
-
headers: {
|
|
244
|
-
'x-job-name': job.name,
|
|
245
|
-
'x-job-id': job.id,
|
|
246
|
-
'x-correlation-id': job.correlationId || job.id,
|
|
247
|
-
'x-original-job-id': ((_a = original.opts) === null || _a === void 0 ? void 0 : _a.jobId) || job.id,
|
|
248
|
-
'x-attempts': 0,
|
|
249
|
-
'x-max-attempts': ((_b = original.opts) === null || _b === void 0 ? void 0 : _b.attempts) || 1,
|
|
250
|
-
'x-timestamp': job.timestamp,
|
|
251
|
-
},
|
|
252
|
-
};
|
|
253
|
-
if (((_c = original.opts) === null || _c === void 0 ? void 0 : _c.priority) !== undefined) {
|
|
254
|
-
messageOptions.priority = original.opts.priority;
|
|
255
|
-
}
|
|
256
|
-
if ((_d = original.opts) === null || _d === void 0 ? void 0 : _d.delay) {
|
|
257
|
-
if (this.options.useDelayedMessagePlugin) {
|
|
258
|
-
messageOptions.headers['x-delay'] = original.opts.delay;
|
|
259
|
-
}
|
|
260
|
-
else {
|
|
261
|
-
messageOptions.headers['x-process-after'] = Date.now() + original.opts.delay;
|
|
262
|
-
}
|
|
263
|
-
}
|
|
315
|
+
const publishPromises = createdJobs.map((job) => {
|
|
316
|
+
const messageOptions = this.buildPublishOptions(job);
|
|
264
317
|
return channel.sendToQueue(queueName, Buffer.from(JSON.stringify(job)), messageOptions);
|
|
265
318
|
});
|
|
266
319
|
await Promise.all(publishPromises);
|
|
@@ -275,137 +328,200 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
275
328
|
this.logger.debug(`${createdJobs.length} jobs added in bulk to queue ${queueName}`);
|
|
276
329
|
return createdJobs;
|
|
277
330
|
}
|
|
331
|
+
buildPublishOptions(job) {
|
|
332
|
+
var _a;
|
|
333
|
+
const opts = job.opts;
|
|
334
|
+
const headers = {
|
|
335
|
+
'x-job-name': job.name,
|
|
336
|
+
'x-job-id': job.id,
|
|
337
|
+
'x-correlation-id': job.correlationId || job.id,
|
|
338
|
+
'x-original-job-id': ((_a = opts === null || opts === void 0 ? void 0 : opts.headers) === null || _a === void 0 ? void 0 : _a['x-original-job-id']) || (opts === null || opts === void 0 ? void 0 : opts.jobId) || job.id,
|
|
339
|
+
'x-attempts': job.attemptsMade || 0,
|
|
340
|
+
'x-max-attempts': (opts === null || opts === void 0 ? void 0 : opts.attempts) || 1,
|
|
341
|
+
'x-timestamp': job.timestamp,
|
|
342
|
+
...opts === null || opts === void 0 ? void 0 : opts.headers,
|
|
343
|
+
};
|
|
344
|
+
if (opts === null || opts === void 0 ? void 0 : opts.delay) {
|
|
345
|
+
if (this.options.useDelayedMessagePlugin) {
|
|
346
|
+
headers['x-delay'] = opts.delay;
|
|
347
|
+
}
|
|
348
|
+
else {
|
|
349
|
+
headers['x-process-after'] = Date.now() + opts.delay;
|
|
350
|
+
this.logger.warn('Delayed messages without plugin may not be accurate. Consider installing rabbitmq_delayed_message_exchange plugin.');
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
return {
|
|
354
|
+
persistent: true,
|
|
355
|
+
messageId: job.id,
|
|
356
|
+
correlationId: job.correlationId,
|
|
357
|
+
contentType: 'application/json',
|
|
358
|
+
headers,
|
|
359
|
+
...((opts === null || opts === void 0 ? void 0 : opts.priority) !== undefined ? { priority: opts.priority } : {}),
|
|
360
|
+
};
|
|
361
|
+
}
|
|
278
362
|
async process(queueName, processor, options) {
|
|
279
|
-
var _a, _b, _c, _d, _e;
|
|
280
|
-
const
|
|
281
|
-
if (
|
|
363
|
+
var _a, _b, _c, _d, _e, _f;
|
|
364
|
+
const status = this.registry.register(queueName, options === null || options === void 0 ? void 0 : options.name, processor);
|
|
365
|
+
if (status === 'duplicate') {
|
|
366
|
+
const consumerKey = (options === null || options === void 0 ? void 0 : options.name) ? `${queueName}:${options.name}` : queueName;
|
|
282
367
|
this.logger.warn(`Consumer already exists for ${consumerKey}`);
|
|
283
368
|
return false;
|
|
284
369
|
}
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
370
|
+
if (status === 'added') {
|
|
371
|
+
const requestedConcurrency = (options === null || options === void 0 ? void 0 : options.concurrency) || 1;
|
|
372
|
+
const existingConcurrency = (_a = this.consumerConcurrency.get(queueName)) !== null && _a !== void 0 ? _a : 1;
|
|
373
|
+
if (requestedConcurrency !== existingConcurrency) {
|
|
374
|
+
this.logger.debug(`Consumer for queue ${queueName} already exists with concurrency ${existingConcurrency}; ` +
|
|
375
|
+
`ignoring requested concurrency ${requestedConcurrency} for named processor "${options === null || options === void 0 ? void 0 : options.name}".`);
|
|
376
|
+
}
|
|
377
|
+
return true;
|
|
378
|
+
}
|
|
379
|
+
const idempotencyStore = (_b = this.options.idempotency) === null || _b === void 0 ? void 0 : _b.store;
|
|
380
|
+
const lockTtl = (_d = (_c = this.options.idempotency) === null || _c === void 0 ? void 0 : _c.lockTtl) !== null && _d !== void 0 ? _d : 60000;
|
|
381
|
+
const completedTtl = (_f = (_e = this.options.idempotency) === null || _e === void 0 ? void 0 : _e.completedTtl) !== null && _f !== void 0 ? _f : 3600000;
|
|
382
|
+
if (this.options.noAck) {
|
|
383
|
+
this.logger.warn('QueueOptions.noAck is deprecated and ignored: manual acknowledgement is required for retry/DLQ correctness (M-13)');
|
|
384
|
+
}
|
|
385
|
+
let channel;
|
|
386
|
+
let consumerTag;
|
|
387
|
+
try {
|
|
388
|
+
channel = await this.getChannel(queueName);
|
|
389
|
+
({ consumerTag } = await channel.consume(queueName, async (msg) => {
|
|
390
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
391
|
+
if (!msg)
|
|
392
|
+
return;
|
|
393
|
+
let job;
|
|
309
394
|
try {
|
|
310
|
-
|
|
395
|
+
const parsed = JSON.parse(msg.content.toString());
|
|
396
|
+
(0, errors_1.validateJobStructure)(parsed);
|
|
397
|
+
job = parsed;
|
|
311
398
|
}
|
|
312
399
|
catch (error) {
|
|
313
|
-
this.logger.
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
if ((options === null || options === void 0 ? void 0 : options.name) && job.name !== options.name) {
|
|
317
|
-
channel.ack(msg);
|
|
318
|
-
return;
|
|
319
|
-
}
|
|
320
|
-
const idempotencyKey = idempotencyStore ? this.getIdempotencyKey(job, headers) : job.id;
|
|
321
|
-
if (idempotencyStore) {
|
|
322
|
-
const canProcess = await idempotencyStore.markProcessing(idempotencyKey, lockTtl);
|
|
323
|
-
if (!canProcess) {
|
|
400
|
+
this.logger.error(`Failed to parse or validate job message: ${error.message}`);
|
|
324
401
|
channel.ack(msg);
|
|
325
|
-
this.logger.debug(`Job ${job.id} skipped (idempotency check, original ID: ${idempotencyKey})`);
|
|
326
402
|
return;
|
|
327
403
|
}
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
const
|
|
332
|
-
if (
|
|
333
|
-
|
|
404
|
+
const headers = msg.properties.headers || {};
|
|
405
|
+
const attempts = parseInt(String(headers['x-attempts'] || '0'));
|
|
406
|
+
const maxAttempts = parseInt(String(headers['x-max-attempts'] || '1'));
|
|
407
|
+
const rawCorrelationId = headers['x-correlation-id'] || msg.properties.correlationId;
|
|
408
|
+
if (rawCorrelationId) {
|
|
409
|
+
try {
|
|
410
|
+
job.correlationId = (0, errors_1.sanitizeCorrelationId)(String(rawCorrelationId));
|
|
411
|
+
}
|
|
412
|
+
catch (error) {
|
|
413
|
+
this.logger.warn(`Invalid correlationId in message: ${error.message}`);
|
|
414
|
+
}
|
|
334
415
|
}
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
416
|
+
const handler = this.registry.resolve(queueName, job.name);
|
|
417
|
+
if (!handler) {
|
|
418
|
+
this.logger.warn(`No handler for job "${job.name}" on queue "${queueName}"`);
|
|
419
|
+
channel.ack(msg);
|
|
420
|
+
return;
|
|
339
421
|
}
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
422
|
+
const processAfter = headers['x-process-after'];
|
|
423
|
+
if (processAfter && parseInt(String(processAfter), 10) > Date.now()) {
|
|
424
|
+
const delay = parseInt(String(processAfter), 10) - Date.now();
|
|
425
|
+
const channelGeneration = (_a = this.channelGenerations.get(queueName)) !== null && _a !== void 0 ? _a : 0;
|
|
426
|
+
const outcome = this.scheduleDelayedDelivery(queueName, job, delay, msg, headers, channel, channelGeneration);
|
|
427
|
+
if (outcome === 'scheduled') {
|
|
428
|
+
this.logger.debug(`Delayed job scheduled locally: ${job.id}, delay: ${delay}ms`);
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
if (outcome === 'requeue') {
|
|
432
|
+
try {
|
|
433
|
+
channel.nack(msg, false, true);
|
|
434
|
+
}
|
|
435
|
+
catch (nackError) {
|
|
436
|
+
this.logger.error(`Failed to requeue delayed job ${job.id} during shutdown: ${(_b = nackError === null || nackError === void 0 ? void 0 : nackError.message) !== null && _b !== void 0 ? _b : String(nackError)}`);
|
|
437
|
+
}
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
355
440
|
}
|
|
356
|
-
const
|
|
357
|
-
(_b = this.metrics) === null || _b === void 0 ? void 0 : _b.jobCompleted(queueName, job.name, job.id, duration);
|
|
358
|
-
channel.ack(msg);
|
|
359
|
-
this.emitEvent(queueName, queue_event_enum_1.QueueEvent.COMPLETED, job, result);
|
|
360
|
-
this.logger.debug(`Job completed: ${job.name} (${job.id})`);
|
|
361
|
-
}
|
|
362
|
-
catch (error) {
|
|
363
|
-
job.attemptsMade = attempts + 1;
|
|
364
|
-
job.failedReason = (0, sanitize_1.sanitizeErrorMessage)(error instanceof Error ? error.message : String(error));
|
|
365
|
-
(_c = this.metrics) === null || _c === void 0 ? void 0 : _c.jobFailed(queueName, job.name, job.id, job.failedReason, job.attemptsMade);
|
|
441
|
+
const idempotencyKey = idempotencyStore ? this.getIdempotencyKey(job, headers) : job.id;
|
|
366
442
|
if (idempotencyStore) {
|
|
367
|
-
await idempotencyStore.
|
|
368
|
-
|
|
369
|
-
if (job.attemptsMade < maxAttempts) {
|
|
370
|
-
const delay = this.calculateBackoff(job);
|
|
371
|
-
(_d = this.metrics) === null || _d === void 0 ? void 0 : _d.jobRetried(queueName, job.name, job.id, job.attemptsMade + 1, delay);
|
|
372
|
-
try {
|
|
373
|
-
const retryJobOpts = {
|
|
374
|
-
...job.opts,
|
|
375
|
-
jobId: `${idempotencyKey}-retry-${job.attemptsMade + 1}`,
|
|
376
|
-
delay,
|
|
377
|
-
correlationId: job.correlationId,
|
|
378
|
-
headers: {
|
|
379
|
-
...(_e = job.opts) === null || _e === void 0 ? void 0 : _e.headers,
|
|
380
|
-
'x-original-job-id': idempotencyKey,
|
|
381
|
-
'x-retry-count': String(job.attemptsMade + 1),
|
|
382
|
-
},
|
|
383
|
-
};
|
|
384
|
-
await this.add(queueName, job.name, job.data, retryJobOpts);
|
|
443
|
+
const canProcess = await idempotencyStore.markProcessing(idempotencyKey, lockTtl);
|
|
444
|
+
if (!canProcess) {
|
|
385
445
|
channel.ack(msg);
|
|
386
|
-
this.logger.debug(`Job
|
|
446
|
+
this.logger.debug(`Job ${job.id} skipped (idempotency check, original ID: ${idempotencyKey})`);
|
|
447
|
+
return;
|
|
387
448
|
}
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
449
|
+
}
|
|
450
|
+
let lockRenewal;
|
|
451
|
+
if (idempotencyStore) {
|
|
452
|
+
lockRenewal = new lock_renewal_1.LockRenewal(idempotencyStore, idempotencyKey, lockTtl, Math.floor(lockTtl / 2));
|
|
453
|
+
lockRenewal.start();
|
|
454
|
+
}
|
|
455
|
+
try {
|
|
456
|
+
this.emitEvent(queueName, queue_event_enum_1.QueueEvent.ACTIVE, job);
|
|
457
|
+
(_c = this.metrics) === null || _c === void 0 ? void 0 : _c.jobStarted(queueName, job.name, job.id);
|
|
458
|
+
const startTime = Date.now();
|
|
459
|
+
const result = await handler(job);
|
|
460
|
+
job.returnvalue = result;
|
|
461
|
+
if (idempotencyStore) {
|
|
462
|
+
await idempotencyStore.markComplete(idempotencyKey, completedTtl);
|
|
391
463
|
}
|
|
464
|
+
const duration = Date.now() - startTime;
|
|
465
|
+
(_d = this.metrics) === null || _d === void 0 ? void 0 : _d.jobCompleted(queueName, job.name, job.id, duration);
|
|
466
|
+
channel.ack(msg);
|
|
467
|
+
this.emitEvent(queueName, queue_event_enum_1.QueueEvent.COMPLETED, job, result);
|
|
468
|
+
this.logger.debug(`Job completed: ${job.name} (${job.id})`);
|
|
392
469
|
}
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
this.
|
|
397
|
-
|
|
470
|
+
catch (error) {
|
|
471
|
+
job.attemptsMade = attempts + 1;
|
|
472
|
+
job.failedReason = (0, sanitize_1.sanitizeErrorMessage)(error instanceof Error ? error.message : String(error));
|
|
473
|
+
(_e = this.metrics) === null || _e === void 0 ? void 0 : _e.jobFailed(queueName, job.name, job.id, job.failedReason, job.attemptsMade);
|
|
474
|
+
if (idempotencyStore) {
|
|
475
|
+
await idempotencyStore.releaseLock(idempotencyKey);
|
|
476
|
+
}
|
|
477
|
+
if (job.attemptsMade < maxAttempts) {
|
|
478
|
+
const delay = this.calculateBackoff(job);
|
|
479
|
+
(_f = this.metrics) === null || _f === void 0 ? void 0 : _f.jobRetried(queueName, job.name, job.id, job.attemptsMade + 1, delay);
|
|
480
|
+
try {
|
|
481
|
+
const retryJobOpts = {
|
|
482
|
+
...job.opts,
|
|
483
|
+
jobId: `${idempotencyKey}-retry-${job.attemptsMade + 1}`,
|
|
484
|
+
delay,
|
|
485
|
+
correlationId: job.correlationId,
|
|
486
|
+
headers: {
|
|
487
|
+
...(_g = job.opts) === null || _g === void 0 ? void 0 : _g.headers,
|
|
488
|
+
'x-original-job-id': idempotencyKey,
|
|
489
|
+
'x-retry-count': String(job.attemptsMade + 1),
|
|
490
|
+
},
|
|
491
|
+
};
|
|
492
|
+
await this.add(queueName, job.name, job.data, retryJobOpts);
|
|
493
|
+
channel.ack(msg);
|
|
494
|
+
this.logger.debug(`Job retry scheduled: ${job.name} (${job.id}), attempt ${job.attemptsMade + 1}/${maxAttempts}, delay ${delay}ms`);
|
|
495
|
+
}
|
|
496
|
+
catch (retryError) {
|
|
497
|
+
this.logger.error(`Failed to schedule retry for job ${job.id}: ${retryError.message}`);
|
|
498
|
+
channel.nack(msg, false, true);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
else {
|
|
502
|
+
channel.nack(msg, false, false);
|
|
503
|
+
const sanitizedMessage = (0, sanitize_1.sanitizeErrorMessage)(error instanceof Error ? error.message : String(error));
|
|
504
|
+
this.emitEvent(queueName, queue_event_enum_1.QueueEvent.FAILED, job, new Error(sanitizedMessage));
|
|
505
|
+
this.logger.error(`Job failed permanently: ${job.name} (${job.id}): ${sanitizedMessage}`);
|
|
506
|
+
}
|
|
398
507
|
}
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
508
|
+
finally {
|
|
509
|
+
if (lockRenewal) {
|
|
510
|
+
lockRenewal.stop();
|
|
511
|
+
}
|
|
403
512
|
}
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
}
|
|
408
|
-
|
|
513
|
+
}, {
|
|
514
|
+
noAck: false,
|
|
515
|
+
}));
|
|
516
|
+
}
|
|
517
|
+
catch (error) {
|
|
518
|
+
this.consumerTags.delete(queueName);
|
|
519
|
+
this.consumerConcurrency.delete(queueName);
|
|
520
|
+
this.registry.removeQueue(queueName);
|
|
521
|
+
throw error;
|
|
522
|
+
}
|
|
523
|
+
this.consumerTags.set(queueName, consumerTag);
|
|
524
|
+
this.consumerConcurrency.set(queueName, (options === null || options === void 0 ? void 0 : options.concurrency) || 1);
|
|
409
525
|
this.logger.log(`Consumer started for queue: ${queueName}${(options === null || options === void 0 ? void 0 : options.name) ? ` (${options.name})` : ''}`);
|
|
410
526
|
return true;
|
|
411
527
|
}
|
|
@@ -425,7 +541,61 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
425
541
|
});
|
|
426
542
|
const accumulatorKey = queueName;
|
|
427
543
|
this.batchAccumulators.set(accumulatorKey, []);
|
|
544
|
+
const settleFailure = async (entry, error) => {
|
|
545
|
+
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
546
|
+
const { job, msg, headers, idempotencyKey } = entry;
|
|
547
|
+
const currentAttempts = (Number.parseInt(String((_b = (_a = headers['x-attempts']) !== null && _a !== void 0 ? _a : job.attemptsMade) !== null && _b !== void 0 ? _b : 0), 10) || 0) + 1;
|
|
548
|
+
const maxAttempts = Number.parseInt(String((_e = (_c = headers['x-max-attempts']) !== null && _c !== void 0 ? _c : (_d = job.opts) === null || _d === void 0 ? void 0 : _d.attempts) !== null && _e !== void 0 ? _e : 1), 10) || 1;
|
|
549
|
+
job.attemptsMade = currentAttempts;
|
|
550
|
+
job.failedReason = (0, sanitize_1.sanitizeErrorMessage)(error.message);
|
|
551
|
+
(_f = this.metrics) === null || _f === void 0 ? void 0 : _f.jobFailed(queueName, job.name, job.id, job.failedReason, currentAttempts);
|
|
552
|
+
try {
|
|
553
|
+
if (retryFailedIndividually && currentAttempts < maxAttempts) {
|
|
554
|
+
const delay = this.calculateBackoff(job);
|
|
555
|
+
(_g = this.metrics) === null || _g === void 0 ? void 0 : _g.jobRetried(queueName, job.name, job.id, currentAttempts, delay);
|
|
556
|
+
await this.add(queueName, job.name, job.data, {
|
|
557
|
+
...job.opts,
|
|
558
|
+
attempts: maxAttempts,
|
|
559
|
+
delay,
|
|
560
|
+
jobId: `${idempotencyKey}-retry-${currentAttempts}`,
|
|
561
|
+
correlationId: job.correlationId,
|
|
562
|
+
headers: {
|
|
563
|
+
...(_h = job.opts) === null || _h === void 0 ? void 0 : _h.headers,
|
|
564
|
+
...headers,
|
|
565
|
+
'x-original-job-id': idempotencyKey,
|
|
566
|
+
'x-attempts': String(currentAttempts),
|
|
567
|
+
'x-max-attempts': String(maxAttempts),
|
|
568
|
+
'x-retry-count': String(currentAttempts),
|
|
569
|
+
},
|
|
570
|
+
});
|
|
571
|
+
if (idempotencyStore)
|
|
572
|
+
await idempotencyStore.releaseLock(idempotencyKey);
|
|
573
|
+
channel.ack(msg);
|
|
574
|
+
entry.settled = true;
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
if (idempotencyStore)
|
|
578
|
+
await idempotencyStore.releaseLock(idempotencyKey);
|
|
579
|
+
channel.nack(msg, false, false);
|
|
580
|
+
entry.settled = true;
|
|
581
|
+
this.emitEvent(queueName, queue_event_enum_1.QueueEvent.FAILED, job, error);
|
|
582
|
+
}
|
|
583
|
+
catch (publishError) {
|
|
584
|
+
this.logger.error(`Failed to hand off batch job ${job.id}: ${publishError instanceof Error ? publishError.message : String(publishError)}`);
|
|
585
|
+
try {
|
|
586
|
+
if (idempotencyStore)
|
|
587
|
+
await idempotencyStore.releaseLock(idempotencyKey);
|
|
588
|
+
}
|
|
589
|
+
finally {
|
|
590
|
+
if (!entry.settled) {
|
|
591
|
+
channel.nack(msg, false, true);
|
|
592
|
+
entry.settled = true;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
};
|
|
428
597
|
const processBatchFn = async () => {
|
|
598
|
+
var _a;
|
|
429
599
|
const timer = this.batchTimers.get(accumulatorKey);
|
|
430
600
|
if (timer) {
|
|
431
601
|
clearTimeout(timer);
|
|
@@ -439,36 +609,31 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
439
609
|
const startTime = Date.now();
|
|
440
610
|
try {
|
|
441
611
|
const result = await processor(jobs, options || {});
|
|
612
|
+
const jobResults = (0, batch_result_1.validateBatchResults)(queueName, jobs, result);
|
|
442
613
|
for (let i = 0; i < batch.length; i++) {
|
|
443
|
-
const
|
|
444
|
-
const jobResult =
|
|
445
|
-
const job = jobs[i];
|
|
614
|
+
const entry = batch[i];
|
|
615
|
+
const jobResult = jobResults[i];
|
|
446
616
|
if (jobResult.success) {
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
}
|
|
454
|
-
else if (retryFailedIndividually && jobResult.error) {
|
|
455
|
-
channel.nack(msg, false, true);
|
|
456
|
-
if (idempotencyStore) {
|
|
457
|
-
const headers = msg.properties.headers || {};
|
|
458
|
-
const idempotencyKey = this.getIdempotencyKey(job, headers);
|
|
459
|
-
await idempotencyStore.releaseLock(idempotencyKey);
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
else if (!continueOnError && jobResult.error) {
|
|
463
|
-
channel.ack(msg);
|
|
464
|
-
if (idempotencyStore) {
|
|
465
|
-
const headers = msg.properties.headers || {};
|
|
466
|
-
const idempotencyKey = this.getIdempotencyKey(job, headers);
|
|
467
|
-
await idempotencyStore.releaseLock(idempotencyKey);
|
|
468
|
-
}
|
|
617
|
+
if (idempotencyStore)
|
|
618
|
+
await idempotencyStore.markComplete(entry.idempotencyKey, completedTtl);
|
|
619
|
+
channel.ack(entry.msg);
|
|
620
|
+
entry.settled = true;
|
|
621
|
+
(_a = this.metrics) === null || _a === void 0 ? void 0 : _a.jobCompleted(queueName, entry.job.name, entry.job.id, Date.now() - startTime);
|
|
622
|
+
this.emitEvent(queueName, queue_event_enum_1.QueueEvent.COMPLETED, entry.job, jobResult.result);
|
|
469
623
|
}
|
|
470
624
|
else {
|
|
471
|
-
|
|
625
|
+
await settleFailure(entry, jobResult.error);
|
|
626
|
+
if (!continueOnError) {
|
|
627
|
+
for (const remaining of batch.slice(i + 1)) {
|
|
628
|
+
if (remaining.settled)
|
|
629
|
+
continue;
|
|
630
|
+
if (idempotencyStore)
|
|
631
|
+
await idempotencyStore.releaseLock(remaining.idempotencyKey);
|
|
632
|
+
channel.nack(remaining.msg, false, true);
|
|
633
|
+
remaining.settled = true;
|
|
634
|
+
}
|
|
635
|
+
break;
|
|
636
|
+
}
|
|
472
637
|
}
|
|
473
638
|
}
|
|
474
639
|
const duration = Date.now() - startTime;
|
|
@@ -476,12 +641,15 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
476
641
|
}
|
|
477
642
|
catch (error) {
|
|
478
643
|
this.logger.error(`Batch processing failed: ${error.message}`);
|
|
479
|
-
|
|
480
|
-
|
|
644
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
645
|
+
for (const entry of batch) {
|
|
646
|
+
if (!entry.settled)
|
|
647
|
+
await settleFailure(entry, failure);
|
|
481
648
|
}
|
|
482
649
|
}
|
|
483
650
|
};
|
|
484
651
|
const { consumerTag } = await channel.consume(queueName, async (msg) => {
|
|
652
|
+
var _a, _b, _c, _d;
|
|
485
653
|
if (!msg)
|
|
486
654
|
return;
|
|
487
655
|
let job;
|
|
@@ -496,6 +664,7 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
496
664
|
return;
|
|
497
665
|
}
|
|
498
666
|
const headers = msg.properties.headers || {};
|
|
667
|
+
job.attemptsMade = Number.parseInt(String((_b = (_a = headers['x-attempts']) !== null && _a !== void 0 ? _a : job.attemptsMade) !== null && _b !== void 0 ? _b : 0), 10) || 0;
|
|
499
668
|
const rawCorrelationId = headers['x-correlation-id'] || msg.properties.correlationId;
|
|
500
669
|
if (rawCorrelationId) {
|
|
501
670
|
try {
|
|
@@ -505,31 +674,42 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
505
674
|
this.logger.warn(`Invalid correlationId in message: ${error.message}`);
|
|
506
675
|
}
|
|
507
676
|
}
|
|
677
|
+
const processAfter = headers['x-process-after'];
|
|
678
|
+
if (processAfter && parseInt(String(processAfter), 10) > Date.now()) {
|
|
679
|
+
const delay = parseInt(String(processAfter), 10) - Date.now();
|
|
680
|
+
const channelGeneration = (_c = this.channelGenerations.get(queueName)) !== null && _c !== void 0 ? _c : 0;
|
|
681
|
+
const outcome = this.scheduleDelayedDelivery(queueName, job, delay, msg, headers, channel, channelGeneration);
|
|
682
|
+
if (outcome === 'scheduled') {
|
|
683
|
+
this.logger.debug(`Delayed batch job scheduled locally: ${job.id}, delay: ${delay}ms`);
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
if (outcome === 'requeue') {
|
|
687
|
+
try {
|
|
688
|
+
channel.nack(msg, false, true);
|
|
689
|
+
}
|
|
690
|
+
catch (nackError) {
|
|
691
|
+
this.logger.error(`Failed to requeue delayed batch job ${job.id} during shutdown: ${(_d = nackError === null || nackError === void 0 ? void 0 : nackError.message) !== null && _d !== void 0 ? _d : String(nackError)}`);
|
|
692
|
+
}
|
|
693
|
+
return;
|
|
694
|
+
}
|
|
695
|
+
}
|
|
508
696
|
if (idempotencyStore) {
|
|
509
697
|
const idempotencyKey = this.getIdempotencyKey(job, headers);
|
|
510
698
|
const canProcess = await idempotencyStore.markProcessing(idempotencyKey, lockTtl);
|
|
511
699
|
if (!canProcess) {
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
const delay = parseInt(String(processAfter)) - Date.now();
|
|
520
|
-
const scheduled = this.delayedScheduler.schedule(queueName, job, delay);
|
|
521
|
-
if (scheduled) {
|
|
522
|
-
if (idempotencyStore) {
|
|
523
|
-
const idempotencyKey = this.getIdempotencyKey(job, headers);
|
|
524
|
-
await idempotencyStore.releaseLock(idempotencyKey);
|
|
700
|
+
if (await idempotencyStore.isProcessed(idempotencyKey)) {
|
|
701
|
+
channel.ack(msg);
|
|
702
|
+
this.logger.debug(`Completed duplicate ${job.id} acknowledged (idempotency key: ${idempotencyKey})`);
|
|
703
|
+
}
|
|
704
|
+
else {
|
|
705
|
+
channel.nack(msg, false, true);
|
|
706
|
+
this.logger.debug(`Active duplicate ${job.id} requeued (idempotency key: ${idempotencyKey})`);
|
|
525
707
|
}
|
|
526
|
-
channel.ack(msg);
|
|
527
|
-
this.logger.debug(`Delayed batch job scheduled locally: ${job.id}, delay: ${delay}ms`);
|
|
528
708
|
return;
|
|
529
709
|
}
|
|
530
710
|
}
|
|
531
711
|
const currentAccumulator = this.batchAccumulators.get(accumulatorKey) || [];
|
|
532
|
-
currentAccumulator.push({ job, msg });
|
|
712
|
+
currentAccumulator.push({ job, msg, headers, idempotencyKey: this.getIdempotencyKey(job, headers) });
|
|
533
713
|
if (currentAccumulator.length >= batchSize) {
|
|
534
714
|
await processBatchFn();
|
|
535
715
|
}
|
|
@@ -548,6 +728,12 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
548
728
|
this.logger.log(`Batch consumer started for queue: ${queueName} (batchSize: ${batchSize})`);
|
|
549
729
|
}
|
|
550
730
|
async addBatch(queueName, jobs, batchId) {
|
|
731
|
+
var _a;
|
|
732
|
+
for (const j of jobs) {
|
|
733
|
+
(0, validation_1.validateJobData)(j.data);
|
|
734
|
+
if ((_a = j.opts) === null || _a === void 0 ? void 0 : _a.jobId)
|
|
735
|
+
(0, validation_1.validateJobId)(j.opts.jobId);
|
|
736
|
+
}
|
|
551
737
|
const channel = await this.getChannel(queueName);
|
|
552
738
|
const createdJobs = jobs.map((j) => {
|
|
553
739
|
var _a, _b;
|
|
@@ -588,15 +774,15 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
588
774
|
this.logger.debug(`${createdJobs.length} jobs added to batch queue ${queueName}${batchId ? ` (batch: ${batchId})` : ''}`);
|
|
589
775
|
return createdJobs;
|
|
590
776
|
}
|
|
591
|
-
async getJob(
|
|
777
|
+
async getJob(_queueName, _jobId) {
|
|
592
778
|
this.logger.warn('getJob is not efficiently supported in RabbitMQ. Consider using a separate state store.');
|
|
593
779
|
return null;
|
|
594
780
|
}
|
|
595
|
-
async getJobs(queueName, status,
|
|
781
|
+
async getJobs(queueName, status, _start = 0, _end = 100) {
|
|
596
782
|
this.logger.warn('getJobs is not efficiently supported in RabbitMQ. Consider using a separate state store.');
|
|
597
783
|
return [];
|
|
598
784
|
}
|
|
599
|
-
async removeJob(
|
|
785
|
+
async removeJob(_queueName, _jobId) {
|
|
600
786
|
this.logger.warn('removeJob is not supported in RabbitMQ. Messages cannot be selectively deleted.');
|
|
601
787
|
}
|
|
602
788
|
async pause(queueName) {
|
|
@@ -661,6 +847,7 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
661
847
|
var _a, _b, _c, _d, _e, _f;
|
|
662
848
|
const timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : 30000;
|
|
663
849
|
const force = (_b = options.force) !== null && _b !== void 0 ? _b : false;
|
|
850
|
+
const deadline = Date.now() + timeout;
|
|
664
851
|
this.isShuttingDown = true;
|
|
665
852
|
this.logger.log(`Closing RabbitMQ connections (timeout: ${timeout}ms, force: ${force})...`);
|
|
666
853
|
for (const timer of this.batchTimers.values()) {
|
|
@@ -669,19 +856,20 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
669
856
|
this.batchTimers.clear();
|
|
670
857
|
this.batchAccumulators.clear();
|
|
671
858
|
try {
|
|
672
|
-
await this.delayedScheduler.shutdown({ executeImmediately: !force });
|
|
859
|
+
await (0, errors_1.withTimeout)(this.delayedScheduler.shutdown({ executeImmediately: !force }), Math.max(1, deadline - Date.now()), 'Delayed scheduler shutdown');
|
|
673
860
|
this.logger.debug('Delayed scheduler shutdown complete');
|
|
674
861
|
}
|
|
675
862
|
catch (error) {
|
|
676
863
|
this.logger.warn(`Failed to shutdown delayed scheduler: ${error.message}`);
|
|
677
864
|
}
|
|
865
|
+
this.delayedDeliveries.clear();
|
|
678
866
|
for (const [name, channel] of this.channels) {
|
|
679
867
|
try {
|
|
680
868
|
if (force) {
|
|
681
869
|
await channel.close();
|
|
682
870
|
}
|
|
683
871
|
else {
|
|
684
|
-
await (0, errors_1.withTimeout)(channel.close(),
|
|
872
|
+
await (0, errors_1.withTimeout)(channel.close(), Math.max(1, (deadline - Date.now()) / 2), `Channel ${name} close`);
|
|
685
873
|
}
|
|
686
874
|
this.logger.debug(`Channel closed: ${name}`);
|
|
687
875
|
}
|
|
@@ -690,7 +878,10 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
690
878
|
}
|
|
691
879
|
}
|
|
692
880
|
this.channels.clear();
|
|
881
|
+
this.channelGenerations.clear();
|
|
693
882
|
this.consumerTags.clear();
|
|
883
|
+
this.registry.clear();
|
|
884
|
+
this.consumerConcurrency.clear();
|
|
694
885
|
this.eventListeners.clear();
|
|
695
886
|
if (this.connection) {
|
|
696
887
|
try {
|
|
@@ -698,7 +889,7 @@ class RabbitMQQueueProvider extends queue_provider_interface_1.QueueProvider {
|
|
|
698
889
|
await this.connection.close();
|
|
699
890
|
}
|
|
700
891
|
else {
|
|
701
|
-
await (0, errors_1.withTimeout)(this.connection.close(),
|
|
892
|
+
await (0, errors_1.withTimeout)(this.connection.close(), Math.max(1, (deadline - Date.now()) / 2), 'Connection close');
|
|
702
893
|
}
|
|
703
894
|
this.logger.log('All RabbitMQ connections closed');
|
|
704
895
|
}
|