rxjs-rabbitmq 2.1.9 → 2.2.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/README.md +416 -65
- package/dist/rabbitmq-client.helper.d.ts +34 -2
- package/dist/rabbitmq-client.helper.js +262 -81
- package/dist/rabbitmq-client.helper.js.map +1 -1
- package/dist/types.d.ts +36 -10
- package/dist/utils.d.ts +4 -16
- package/dist/utils.js +12 -3
- package/dist/utils.js.map +1 -1
- package/package.json +2 -2
- package/src/rabbitmq-client.helper.ts +309 -95
- package/src/types.ts +38 -10
- package/src/utils.ts +13 -4
- package/test/rabbitmq-client.test.js +49 -0
|
@@ -19,6 +19,10 @@ const enums_1 = require("./enums");
|
|
|
19
19
|
Rabbit MQ - RxJS Powered
|
|
20
20
|
*/
|
|
21
21
|
class RabbitMQClient {
|
|
22
|
+
log(level, ...args) {
|
|
23
|
+
const handler = this.logger[level] || (() => undefined);
|
|
24
|
+
handler(...args);
|
|
25
|
+
}
|
|
22
26
|
get onReady() {
|
|
23
27
|
return this.isReadyStream.asObservable().pipe((0, rxjs_1.filter)((state) => !!state), (0, rxjs_1.take)(1));
|
|
24
28
|
}
|
|
@@ -32,10 +36,12 @@ class RabbitMQClient {
|
|
|
32
36
|
return this.messagesStream.asObservable();
|
|
33
37
|
}
|
|
34
38
|
constructor(clientInitConfig) {
|
|
39
|
+
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
35
40
|
this.isReady = false;
|
|
36
41
|
this.isReadyStream = new rxjs_1.BehaviorSubject(this.isReady);
|
|
37
42
|
this.connectionErrorStream = new rxjs_1.Subject();
|
|
38
43
|
this.connectionCloseStream = new rxjs_1.Subject();
|
|
44
|
+
this.reconnectAttempts = 0;
|
|
39
45
|
/*
|
|
40
46
|
Handle all messages from all queues on this client
|
|
41
47
|
*/
|
|
@@ -46,26 +52,81 @@ class RabbitMQClient {
|
|
|
46
52
|
this.bindings = [];
|
|
47
53
|
this.DEFAULT_LISTENER_TYPE = '__default';
|
|
48
54
|
this.queueListeners = {};
|
|
49
|
-
this.
|
|
50
|
-
this.
|
|
55
|
+
this.registeredQueueConsumers = [];
|
|
56
|
+
this.metrics = {
|
|
57
|
+
messagesReceived: 0,
|
|
58
|
+
messagesPublished: 0,
|
|
59
|
+
messagesAcked: 0,
|
|
60
|
+
messagesNacked: 0,
|
|
61
|
+
messagesRetried: 0,
|
|
62
|
+
rpcRequests: 0,
|
|
63
|
+
rpcResponses: 0,
|
|
64
|
+
reconnects: 0,
|
|
65
|
+
};
|
|
66
|
+
this.queueToEventHandleMapping = new Map();
|
|
67
|
+
this.queueToEventCallbackMapping = new Map();
|
|
51
68
|
this.clientInitConfig = clientInitConfig;
|
|
69
|
+
this.metricsEnabled = !!clientInitConfig.metrics;
|
|
70
|
+
this.logger = {
|
|
71
|
+
debug: (_b = (_a = clientInitConfig.logger) === null || _a === void 0 ? void 0 : _a.debug) !== null && _b !== void 0 ? _b : (() => undefined),
|
|
72
|
+
info: (_d = (_c = clientInitConfig.logger) === null || _c === void 0 ? void 0 : _c.info) !== null && _d !== void 0 ? _d : console.info.bind(console),
|
|
73
|
+
warn: (_f = (_e = clientInitConfig.logger) === null || _e === void 0 ? void 0 : _e.warn) !== null && _f !== void 0 ? _f : console.warn.bind(console),
|
|
74
|
+
error: (_h = (_g = clientInitConfig.logger) === null || _g === void 0 ? void 0 : _g.error) !== null && _h !== void 0 ? _h : console.error.bind(console),
|
|
75
|
+
};
|
|
52
76
|
!clientInitConfig.stopAutoInit && this.init();
|
|
53
77
|
}
|
|
78
|
+
static registerSerializer(contentType, serializer) {
|
|
79
|
+
return (0, utils_1.registerSerializer)(contentType, serializer);
|
|
80
|
+
}
|
|
81
|
+
getMetrics() {
|
|
82
|
+
return Object.assign({}, this.metrics);
|
|
83
|
+
}
|
|
84
|
+
resubscribeToRegisteredQueues() {
|
|
85
|
+
for (const { queue, options } of this.registeredQueueConsumers) {
|
|
86
|
+
if (this.queueListeners[queue]) {
|
|
87
|
+
this.queueListeners[queue].unsubscribe();
|
|
88
|
+
delete this.queueListeners[queue];
|
|
89
|
+
}
|
|
90
|
+
this.listenToQueue(queue, options);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
scheduleReconnect(reason) {
|
|
94
|
+
if (this.reconnectTimeout) {
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const retryAttempts = this.clientInitConfig.retryAttempts || 0;
|
|
98
|
+
if (retryAttempts > 0 && this.reconnectAttempts >= retryAttempts) {
|
|
99
|
+
this.log('error', `RabbitMQ reconnect attempts exhausted after ${retryAttempts} tries.`);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
this.isReady = false;
|
|
103
|
+
this.isReadyStream.next(false);
|
|
104
|
+
this.reconnectAttempts += 1;
|
|
105
|
+
this.metrics.reconnects += 1;
|
|
106
|
+
const retryDelay = this.clientInitConfig.retryDelay || 1000;
|
|
107
|
+
this.log('warn', `${reason}; reconnecting in ${retryDelay}ms (attempt ${this.reconnectAttempts}/${retryAttempts || '∞'})`);
|
|
108
|
+
this.reconnectTimeout = setTimeout(() => {
|
|
109
|
+
this.reconnectTimeout = undefined;
|
|
110
|
+
this.init().catch((error) => {
|
|
111
|
+
this.log('error', 'Reconnect failed', error);
|
|
112
|
+
});
|
|
113
|
+
}, retryDelay);
|
|
114
|
+
}
|
|
54
115
|
init() {
|
|
55
116
|
if (this.isReady) {
|
|
56
|
-
|
|
57
|
-
return;
|
|
117
|
+
this.log('info', 'Already initialized');
|
|
118
|
+
return Promise.resolve();
|
|
58
119
|
}
|
|
59
120
|
const { delayStart, connection_url, prefetch, queues, exchanges, bindings, pre_init_promises, post_init_promises } = this.clientInitConfig;
|
|
60
121
|
let retryAttempts = this.clientInitConfig.retryAttempts || 0;
|
|
61
122
|
const retryDelay = this.clientInitConfig.retryDelay || 0;
|
|
62
123
|
const init = () => {
|
|
63
124
|
// creating connection
|
|
64
|
-
|
|
125
|
+
this.log('info', 'Attempting connection to Rabbit MQ...');
|
|
65
126
|
return (0, amqplib_1.connect)(connection_url)
|
|
66
127
|
.then((connection) => {
|
|
67
128
|
this.connection = connection;
|
|
68
|
-
|
|
129
|
+
this.log('info', 'Connected to message server');
|
|
69
130
|
return this.connection.createChannel();
|
|
70
131
|
})
|
|
71
132
|
// creating channel
|
|
@@ -74,33 +135,33 @@ class RabbitMQClient {
|
|
|
74
135
|
if (prefetch) {
|
|
75
136
|
this.channel.prefetch(prefetch || 1);
|
|
76
137
|
}
|
|
77
|
-
|
|
138
|
+
this.log('info', 'Channel created on message server');
|
|
78
139
|
})
|
|
79
140
|
// assert to queues
|
|
80
141
|
.then(() => {
|
|
81
142
|
const promises = [];
|
|
82
143
|
for (const queueConfig of queues) {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
144
|
+
const queueListenersMap = new Map();
|
|
145
|
+
const queueCallbacksMap = new Map();
|
|
146
|
+
this.queueToEventHandleMapping.set(queueConfig.name, queueListenersMap);
|
|
147
|
+
this.queueToEventCallbackMapping.set(queueConfig.name, queueCallbacksMap);
|
|
87
148
|
// by default, create an observable stream on the queue for unidentified/null routing keys
|
|
88
|
-
queueListenersMap
|
|
149
|
+
queueListenersMap.set(this.DEFAULT_LISTENER_TYPE, new rxjs_1.ReplaySubject());
|
|
89
150
|
const useHandleMessageTypes = queueConfig.handleMessageTypes || [];
|
|
90
151
|
for (const messageType of useHandleMessageTypes) {
|
|
91
152
|
if (typeof messageType === 'string') {
|
|
92
|
-
queueListenersMap
|
|
153
|
+
queueListenersMap.set(messageType, new rxjs_1.ReplaySubject());
|
|
93
154
|
}
|
|
94
155
|
else {
|
|
95
156
|
const config = messageType;
|
|
96
|
-
queueCallbacksMap
|
|
157
|
+
queueCallbacksMap.set(config.messageName, config.callbackHandler);
|
|
97
158
|
}
|
|
98
159
|
}
|
|
99
160
|
promises.push(this.channel.assertQueue(queueConfig.name, queueConfig.options));
|
|
100
161
|
}
|
|
101
162
|
return Promise.all(promises).then((values) => {
|
|
102
163
|
this.queues = (0, utils_1.mapify)(values, 'queue');
|
|
103
|
-
|
|
164
|
+
this.log('info', 'queues created on channel');
|
|
104
165
|
});
|
|
105
166
|
})
|
|
106
167
|
// assert exchanges
|
|
@@ -108,7 +169,7 @@ class RabbitMQClient {
|
|
|
108
169
|
const promises = exchanges.map((config) => this.channel.assertExchange(config.name, config.type, config.options));
|
|
109
170
|
return Promise.all(promises).then(values => {
|
|
110
171
|
this.exchanges = (0, utils_1.mapify)(values, 'exchange');
|
|
111
|
-
|
|
172
|
+
this.log('info', 'exchanges created on channel');
|
|
112
173
|
});
|
|
113
174
|
})
|
|
114
175
|
// apply bindings
|
|
@@ -117,26 +178,32 @@ class RabbitMQClient {
|
|
|
117
178
|
// bind the exclusive queue to all the exchanges
|
|
118
179
|
// const exclusiveBindings = bindings.map((config) => this.channel.bindQueue(this.EXCLUSIVE_QUEUE, config.exchange, config.routingKey));
|
|
119
180
|
return Promise.all(promises).then(values => {
|
|
120
|
-
|
|
181
|
+
this.log('info', 'bindings created on channel');
|
|
121
182
|
});
|
|
122
183
|
})
|
|
123
184
|
.then(() => {
|
|
124
|
-
|
|
185
|
+
this.log('info', 'Client initialization complete; waiting for messages/events...');
|
|
125
186
|
// initialization complete; listen for connection issues to retry again
|
|
126
187
|
retryAttempts = this.clientInitConfig.retryAttempts;
|
|
127
188
|
this.connection.on("error", (err) => {
|
|
128
189
|
this.connectionErrorStream.next(err);
|
|
190
|
+
this.log('error', 'RabbitMQ connection error', err);
|
|
191
|
+
this.scheduleReconnect('RabbitMQ connection error');
|
|
129
192
|
});
|
|
130
193
|
this.connection.on("close", (err) => {
|
|
131
194
|
this.connectionCloseStream.next(err);
|
|
195
|
+
this.log('warn', 'RabbitMQ connection closed', err);
|
|
196
|
+
this.scheduleReconnect('RabbitMQ connection closed');
|
|
132
197
|
});
|
|
198
|
+
this.reconnectAttempts = 0;
|
|
133
199
|
this.isReady = true;
|
|
134
200
|
this.isReadyStream.next(true);
|
|
201
|
+
this.resubscribeToRegisteredQueues();
|
|
135
202
|
})
|
|
136
203
|
.catch((error) => {
|
|
137
|
-
|
|
204
|
+
this.log('error', 'connection error, retryAttempts:', retryAttempts, error);
|
|
138
205
|
if (retryAttempts === 0) {
|
|
139
|
-
|
|
206
|
+
this.log('error', 'all retry attemptys exhaused; exiting...');
|
|
140
207
|
throw error;
|
|
141
208
|
}
|
|
142
209
|
retryAttempts = retryAttempts - 1;
|
|
@@ -145,16 +212,16 @@ class RabbitMQClient {
|
|
|
145
212
|
};
|
|
146
213
|
return (0, utils_1.wait)(delayStart || 0)
|
|
147
214
|
.then(() => {
|
|
148
|
-
|
|
215
|
+
this.log('info', 'Running pre init promises...');
|
|
149
216
|
return Promise.all((pre_init_promises === null || pre_init_promises === void 0 ? void 0 : pre_init_promises.map(p => p instanceof Promise ? p : p())) || []).then(() => {
|
|
150
|
-
|
|
217
|
+
this.log('info', 'Done running pre init promises.');
|
|
151
218
|
});
|
|
152
219
|
})
|
|
153
220
|
.then(init)
|
|
154
221
|
.then(() => {
|
|
155
|
-
|
|
222
|
+
this.log('info', 'Running post init promises...');
|
|
156
223
|
return Promise.all((post_init_promises === null || post_init_promises === void 0 ? void 0 : post_init_promises.map(p => p instanceof Promise ? p : p())) || []).then(() => {
|
|
157
|
-
|
|
224
|
+
this.log('info', 'Done running post init promises.');
|
|
158
225
|
});
|
|
159
226
|
});
|
|
160
227
|
}
|
|
@@ -168,6 +235,7 @@ class RabbitMQClient {
|
|
|
168
235
|
return () => {
|
|
169
236
|
// callback
|
|
170
237
|
const handleCallback = (message) => {
|
|
238
|
+
var _a, _b;
|
|
171
239
|
if (!message) {
|
|
172
240
|
// console.log('Consumer cancelled by server');
|
|
173
241
|
// throw new Error('Consumer cancelled by server');
|
|
@@ -177,7 +245,11 @@ class RabbitMQClient {
|
|
|
177
245
|
// see if a listener was created for the routing key
|
|
178
246
|
const messageType = message.properties.type;
|
|
179
247
|
const useContentType = message.properties.contentType;
|
|
180
|
-
const
|
|
248
|
+
const serializer = (0, utils_1.getSerializer)(useContentType || 'application/octet-stream');
|
|
249
|
+
const useData = serializer ? serializer.deserialize(message.content) : message.content;
|
|
250
|
+
if (this.metricsEnabled) {
|
|
251
|
+
this.metrics.messagesReceived += 1;
|
|
252
|
+
}
|
|
181
253
|
const messageObj = {
|
|
182
254
|
data: useData,
|
|
183
255
|
message,
|
|
@@ -193,33 +265,38 @@ class RabbitMQClient {
|
|
|
193
265
|
// send message to queue stream
|
|
194
266
|
!!this.messagesStreamsByQueue[queue] && this.messagesStreamsByQueue[queue].next(messageObj);
|
|
195
267
|
// console.log(`Message on queue ${queue}:`, messageObj);
|
|
268
|
+
const queueListeners = (_a = this.queueToEventHandleMapping.get(queue)) !== null && _a !== void 0 ? _a : new Map();
|
|
269
|
+
const queueCallbacks = (_b = this.queueToEventCallbackMapping.get(queue)) !== null && _b !== void 0 ? _b : new Map();
|
|
196
270
|
if (!messageType) {
|
|
197
271
|
// no type key found, push to default stream
|
|
198
|
-
|
|
199
|
-
|
|
272
|
+
this.log('debug', `No message type found; pushing to default handler on queue ${queue}`);
|
|
273
|
+
const defaultListener = queueListeners.get(this.DEFAULT_LISTENER_TYPE);
|
|
274
|
+
defaultListener === null || defaultListener === void 0 ? void 0 : defaultListener.next(messageObj);
|
|
200
275
|
return;
|
|
201
276
|
}
|
|
202
|
-
|
|
277
|
+
const typeListener = queueListeners.get(messageType);
|
|
278
|
+
if (typeListener) {
|
|
203
279
|
// there is a registered listener for the type, push to that stream
|
|
204
|
-
|
|
205
|
-
|
|
280
|
+
this.log('debug', `message type handler found; pushing to ${messageType} handler on queue ${queue}`);
|
|
281
|
+
typeListener.next(messageObj);
|
|
206
282
|
}
|
|
207
|
-
else if (
|
|
283
|
+
else if (queueCallbacks.has(messageType)) {
|
|
208
284
|
// there is a registered listener for the type, push to that stream
|
|
209
|
-
|
|
210
|
-
const callbackHandler =
|
|
285
|
+
this.log('debug', `message type callback found; pushing to ${messageType} callback on queue ${queue}`);
|
|
286
|
+
const callbackHandler = queueCallbacks.get(messageType);
|
|
211
287
|
callbackHandler(messageObj);
|
|
212
288
|
}
|
|
213
289
|
else {
|
|
214
290
|
// no registered listener
|
|
215
291
|
if (this.clientInitConfig.autoAckUnhandledMessageTypes) {
|
|
216
|
-
|
|
292
|
+
this.log('debug', `No handler found for message type ${messageType} on queue ${queue}; auto acknowledging.`);
|
|
217
293
|
this.ack(message);
|
|
218
294
|
return;
|
|
219
295
|
}
|
|
220
296
|
else if (this.clientInitConfig.pushUnhandledMessageTypesToDefaultHandler) {
|
|
221
|
-
|
|
222
|
-
|
|
297
|
+
this.log('debug', `No handler found for message type ${messageType} on queue ${queue}; pushing to ${this.DEFAULT_LISTENER_TYPE} handler.`);
|
|
298
|
+
const defaultListener = queueListeners.get(this.DEFAULT_LISTENER_TYPE);
|
|
299
|
+
defaultListener === null || defaultListener === void 0 ? void 0 : defaultListener.next(messageObj);
|
|
223
300
|
return;
|
|
224
301
|
}
|
|
225
302
|
else {
|
|
@@ -233,10 +310,12 @@ class RabbitMQClient {
|
|
|
233
310
|
}
|
|
234
311
|
listenToQueue(queue, options) {
|
|
235
312
|
if (this.queueListeners[queue]) {
|
|
236
|
-
|
|
313
|
+
this.log('debug', `Already Registered messages/events listener for queue: ${queue}`);
|
|
237
314
|
return;
|
|
238
315
|
}
|
|
239
|
-
|
|
316
|
+
this.registeredQueueConsumers = this.registeredQueueConsumers.filter((entry) => entry.queue !== queue);
|
|
317
|
+
this.registeredQueueConsumers.push({ queue, options });
|
|
318
|
+
this.log('info', `Registering messages/events listener for queue: ${queue}`);
|
|
240
319
|
const startQueueListener = this.getQueueListener(queue, options);
|
|
241
320
|
this.messagesStreamsByQueue[queue] = new rxjs_1.Subject();
|
|
242
321
|
this.queueListeners[queue] = this.onReady.pipe((0, rxjs_1.tap)((readyState) => {
|
|
@@ -244,7 +323,7 @@ class RabbitMQClient {
|
|
|
244
323
|
}))
|
|
245
324
|
.subscribe({
|
|
246
325
|
next: (readyState) => {
|
|
247
|
-
|
|
326
|
+
this.log('info', `Registered: Now listening to messages/events on queue ${queue}...`);
|
|
248
327
|
}
|
|
249
328
|
});
|
|
250
329
|
}
|
|
@@ -253,14 +332,19 @@ class RabbitMQClient {
|
|
|
253
332
|
this.listenToQueue(queue, options);
|
|
254
333
|
const handle = (messageType) => {
|
|
255
334
|
return this.onReady.pipe((0, rxjs_1.mergeMap)((ready, index) => {
|
|
256
|
-
|
|
335
|
+
const queueListeners = this.queueToEventHandleMapping.get(queue);
|
|
336
|
+
if (!(queueListeners === null || queueListeners === void 0 ? void 0 : queueListeners.has(messageType))) {
|
|
257
337
|
throw new Error(`The provided routing key was not provided during initialization. Please add routing key "${messageType}" in the list of routing keys for the queue config in the constructor.`);
|
|
258
338
|
}
|
|
259
|
-
return
|
|
339
|
+
return queueListeners.get(messageType).asObservable();
|
|
260
340
|
}));
|
|
261
341
|
};
|
|
262
342
|
const handleDefault = () => {
|
|
263
|
-
return this.onReady.pipe((0, rxjs_1.mergeMap)((ready, index) =>
|
|
343
|
+
return this.onReady.pipe((0, rxjs_1.mergeMap)((ready, index) => {
|
|
344
|
+
var _a;
|
|
345
|
+
const queueListeners = this.queueToEventHandleMapping.get(queue);
|
|
346
|
+
return ((_a = queueListeners === null || queueListeners === void 0 ? void 0 : queueListeners.get(this.DEFAULT_LISTENER_TYPE)) !== null && _a !== void 0 ? _a : new rxjs_1.ReplaySubject()).asObservable();
|
|
347
|
+
}));
|
|
264
348
|
};
|
|
265
349
|
/**
|
|
266
350
|
Providing callback function approach
|
|
@@ -289,51 +373,149 @@ class RabbitMQClient {
|
|
|
289
373
|
}
|
|
290
374
|
ack(message) {
|
|
291
375
|
this.channel.ack(message);
|
|
292
|
-
|
|
376
|
+
if (this.metricsEnabled) {
|
|
377
|
+
this.metrics.messagesAcked += 1;
|
|
378
|
+
}
|
|
379
|
+
this.log('debug', 'Acknoledged rmq message.');
|
|
380
|
+
}
|
|
381
|
+
nack(message, requeue = true) {
|
|
382
|
+
if (!this.channel) {
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
this.channel.nack(message, false, requeue);
|
|
386
|
+
if (this.metricsEnabled) {
|
|
387
|
+
this.metrics.messagesNacked += 1;
|
|
388
|
+
}
|
|
389
|
+
this.log('debug', `Nacknowledged rmq message with requeue=${requeue}.`);
|
|
390
|
+
}
|
|
391
|
+
retryMessage(message, options = {}) {
|
|
392
|
+
const { delayMs = 0, requeue = true, queue = '' } = options;
|
|
393
|
+
const targetQueue = queue || message.fields.routingKey || '';
|
|
394
|
+
if (delayMs > 0) {
|
|
395
|
+
setTimeout(() => {
|
|
396
|
+
if (targetQueue) {
|
|
397
|
+
this.channel.sendToQueue(targetQueue, message.content, Object.assign({ persistent: true }, message.properties));
|
|
398
|
+
}
|
|
399
|
+
}, delayMs);
|
|
400
|
+
}
|
|
401
|
+
else if (targetQueue) {
|
|
402
|
+
this.channel.sendToQueue(targetQueue, message.content, Object.assign({ persistent: true }, message.properties));
|
|
403
|
+
}
|
|
404
|
+
this.nack(message, requeue);
|
|
405
|
+
if (this.metricsEnabled) {
|
|
406
|
+
this.metrics.messagesRetried += 1;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
deadLetter(message, reason, queue) {
|
|
410
|
+
const targetQueue = queue || `${message.fields.routingKey || 'dead-letter'}.dlq`;
|
|
411
|
+
const headers = Object.assign(Object.assign({}, (message.properties.headers || {})), { 'x-death-reason': reason });
|
|
412
|
+
this.channel.sendToQueue(targetQueue, message.content, Object.assign(Object.assign({}, message.properties), { headers, persistent: true }));
|
|
413
|
+
this.nack(message, false);
|
|
414
|
+
}
|
|
415
|
+
close() {
|
|
416
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
417
|
+
if (this.reconnectTimeout) {
|
|
418
|
+
clearTimeout(this.reconnectTimeout);
|
|
419
|
+
this.reconnectTimeout = undefined;
|
|
420
|
+
}
|
|
421
|
+
if (this.channel) {
|
|
422
|
+
yield this.channel.close();
|
|
423
|
+
}
|
|
424
|
+
if (this.connection) {
|
|
425
|
+
yield this.connection.close();
|
|
426
|
+
}
|
|
427
|
+
this.isReady = false;
|
|
428
|
+
this.isReadyStream.next(false);
|
|
429
|
+
this.log('info', 'RabbitMQ client closed.');
|
|
430
|
+
});
|
|
293
431
|
}
|
|
294
432
|
sendMessage(options) {
|
|
295
433
|
const send = () => {
|
|
296
434
|
const { data, publishOptions, queue } = options;
|
|
297
435
|
const useContentType = publishOptions.contentType || enums_1.ContentTypes.TEXT;
|
|
298
|
-
const
|
|
436
|
+
const serializer = (0, utils_1.getSerializer)(useContentType) || utils_1.SERIALIZERS[useContentType];
|
|
437
|
+
const useData = serializer
|
|
438
|
+
? serializer.serialize(data)
|
|
439
|
+
: Buffer.from(typeof data === 'string' ? data : JSON.stringify(data), 'utf8');
|
|
440
|
+
if (this.metricsEnabled) {
|
|
441
|
+
this.metrics.messagesPublished += 1;
|
|
442
|
+
}
|
|
299
443
|
this.channel.sendToQueue(queue, useData, Object.assign(Object.assign({}, publishOptions), { appId: publishOptions.appId }));
|
|
300
444
|
};
|
|
301
445
|
if (!this.isReady) {
|
|
302
|
-
|
|
446
|
+
this.log('debug', 'wait until ready to send message...');
|
|
303
447
|
(0, rxjs_1.firstValueFrom)(this.onReady).then((readyState) => {
|
|
304
|
-
|
|
448
|
+
this.log('debug', 'now ready to send message', { readyState });
|
|
305
449
|
send();
|
|
306
450
|
});
|
|
307
451
|
}
|
|
308
452
|
else {
|
|
309
|
-
|
|
453
|
+
this.log('debug', 'is ready to send message');
|
|
310
454
|
send();
|
|
311
455
|
}
|
|
312
456
|
}
|
|
313
|
-
getRpcMethods(temporaryRpcQueue, options) {
|
|
457
|
+
getRpcMethods(temporaryRpcQueue, options, autoAckOnReceiveReply, requestTimeoutMs) {
|
|
458
|
+
var _a;
|
|
314
459
|
const start_time = Date.now();
|
|
315
460
|
const consumerTag = (0, utils_1.uniqueValue)();
|
|
316
461
|
const correlationId = options.publishOptions.correlationId || (0, uuid_1.v4)();
|
|
462
|
+
const timeoutMs = (_a = requestTimeoutMs !== null && requestTimeoutMs !== void 0 ? requestTimeoutMs : this.clientInitConfig.rpcRequestTimeoutMs) !== null && _a !== void 0 ? _a : 30000;
|
|
317
463
|
const send = () => {
|
|
318
464
|
const { data, publishOptions, queue } = options;
|
|
319
465
|
const useContentType = publishOptions.contentType || enums_1.ContentTypes.TEXT;
|
|
320
|
-
const
|
|
466
|
+
const serializer = (0, utils_1.getSerializer)(useContentType) || utils_1.SERIALIZERS[useContentType];
|
|
467
|
+
const useData = serializer
|
|
468
|
+
? serializer.serialize(data)
|
|
469
|
+
: Buffer.from(typeof data === 'string' ? data : JSON.stringify(data), 'utf8');
|
|
470
|
+
if (this.metricsEnabled) {
|
|
471
|
+
this.metrics.rpcRequests += 1;
|
|
472
|
+
}
|
|
321
473
|
this.channel.sendToQueue(queue, useData, Object.assign(Object.assign({}, publishOptions), { correlationId, replyTo: temporaryRpcQueue, appId: publishOptions.appId }));
|
|
322
474
|
};
|
|
323
475
|
const watch = () => {
|
|
324
476
|
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
|
|
325
|
-
|
|
477
|
+
let settled = false;
|
|
478
|
+
let timeoutHandle;
|
|
479
|
+
const cleanup = () => __awaiter(this, void 0, void 0, function* () {
|
|
480
|
+
if (timeoutHandle) {
|
|
481
|
+
clearTimeout(timeoutHandle);
|
|
482
|
+
}
|
|
483
|
+
try {
|
|
484
|
+
yield this.channel.cancel(consumerTag);
|
|
485
|
+
}
|
|
486
|
+
catch (error) {
|
|
487
|
+
this.log('debug', 'Ignoring cancel failure for RPC consumer', { consumerTag, error });
|
|
488
|
+
}
|
|
489
|
+
});
|
|
490
|
+
timeoutHandle = setTimeout(() => __awaiter(this, void 0, void 0, function* () {
|
|
491
|
+
if (settled) {
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
settled = true;
|
|
495
|
+
yield cleanup();
|
|
496
|
+
reject(new Error(`RabbitMQ request timed out after ${timeoutMs}ms for correlationId ${correlationId}`));
|
|
497
|
+
}), timeoutMs);
|
|
498
|
+
this.log('debug', 'request/rpc sent; awaiting response...', { correlationId, consumerTag, temporaryRpcQueue });
|
|
326
499
|
const replyHandler = (message) => {
|
|
327
|
-
|
|
500
|
+
if (!message || settled) {
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
this.log('debug', 'Received reply.', { message });
|
|
328
504
|
const correlationIdMatch = message.properties.correlationId == correlationId;
|
|
329
505
|
const isReplyToRequest = !!message && correlationIdMatch;
|
|
330
|
-
|
|
506
|
+
this.log('debug', { isReplyToRequest, consumerTag, correlationIdMatch, requestCorrelationId: correlationId, responseCorrelationId: message.properties.correlationId });
|
|
331
507
|
if (isReplyToRequest) {
|
|
508
|
+
settled = true;
|
|
509
|
+
void cleanup();
|
|
332
510
|
const useContentType = message.properties.contentType;
|
|
333
|
-
const
|
|
511
|
+
const serializer = (0, utils_1.getSerializer)(useContentType || 'application/octet-stream') || utils_1.SERIALIZERS[useContentType || 'application/octet-stream'];
|
|
512
|
+
const useData = serializer ? serializer.deserialize(message.content) : message.content;
|
|
513
|
+
if (this.metricsEnabled) {
|
|
514
|
+
this.metrics.rpcResponses += 1;
|
|
515
|
+
}
|
|
334
516
|
const messageObj = {
|
|
335
517
|
data: useData,
|
|
336
|
-
message
|
|
518
|
+
message,
|
|
337
519
|
ack: () => {
|
|
338
520
|
this.ack(message);
|
|
339
521
|
},
|
|
@@ -344,18 +526,11 @@ class RabbitMQClient {
|
|
|
344
526
|
const end_time = Date.now();
|
|
345
527
|
const total_time = (end_time - start_time) / 1000;
|
|
346
528
|
const time_in_seconds = total_time.toFixed();
|
|
347
|
-
|
|
529
|
+
this.log('debug', 'received response from request/rpc:', { start_time, end_time, total_time, time_in_seconds, messageObj, options });
|
|
530
|
+
if (autoAckOnReceiveReply) {
|
|
531
|
+
this.ack(message);
|
|
532
|
+
}
|
|
348
533
|
resolve(messageObj);
|
|
349
|
-
// this.channel.cancel(consumerTag).then(() => {
|
|
350
|
-
// console.log(`removed consumer via consumerTag; deleting temporary queue ${temporaryRpcQueue}...`);
|
|
351
|
-
// this.channel.deleteQueue(temporaryRpcQueue, { ifEmpty: true, ifUnused: true })
|
|
352
|
-
// .then(() => {
|
|
353
|
-
// console.log(`temp queue deleted: ${temporaryRpcQueue}`);
|
|
354
|
-
// })
|
|
355
|
-
// .catch((error) => {
|
|
356
|
-
// console.log(`could not delete temp queue ${temporaryRpcQueue}`);
|
|
357
|
-
// });
|
|
358
|
-
// });
|
|
359
534
|
}
|
|
360
535
|
};
|
|
361
536
|
this.channel.consume(temporaryRpcQueue, replyHandler, { consumerTag });
|
|
@@ -363,32 +538,32 @@ class RabbitMQClient {
|
|
|
363
538
|
};
|
|
364
539
|
return { watch, send };
|
|
365
540
|
}
|
|
366
|
-
sendRequest(options) {
|
|
367
|
-
|
|
541
|
+
sendRequest(options, autoAckOnReceiveReply = true, timeoutMs) {
|
|
542
|
+
this.log('debug', 'sendRequest:', options);
|
|
368
543
|
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
|
|
369
544
|
const temporaryRpcQueue = (0, uuid_1.v1)();
|
|
370
545
|
const newQueue = yield this.channel.assertQueue(temporaryRpcQueue, { exclusive: true, durable: false, autoDelete: true }).then((response) => {
|
|
371
|
-
|
|
546
|
+
this.log('debug', `Created temp queue ${temporaryRpcQueue} for client.`);
|
|
372
547
|
return response;
|
|
373
548
|
});
|
|
374
|
-
const rpc = this.getRpcMethods(temporaryRpcQueue, options);
|
|
549
|
+
const rpc = this.getRpcMethods(temporaryRpcQueue, options, autoAckOnReceiveReply, timeoutMs);
|
|
375
550
|
if (!this.isReady) {
|
|
376
|
-
|
|
551
|
+
this.log('debug', 'waiting until ready to send request');
|
|
377
552
|
(0, rxjs_1.firstValueFrom)(this.onReady).then((readyState) => {
|
|
378
|
-
|
|
553
|
+
this.log('debug', 'now ready and watching temp queue', { readyState });
|
|
379
554
|
rpc.watch().then((message) => {
|
|
380
555
|
resolve(message);
|
|
381
|
-
}); // first listen on the reply queue
|
|
382
|
-
|
|
556
|
+
}).catch(reject); // first listen on the reply queue
|
|
557
|
+
this.log('debug', 'sending request');
|
|
383
558
|
rpc.send(); // then send the rpc/rmq message
|
|
384
|
-
});
|
|
559
|
+
}).catch(reject);
|
|
385
560
|
}
|
|
386
561
|
else {
|
|
387
|
-
|
|
562
|
+
this.log('debug', 'now ready and watching temp queue');
|
|
388
563
|
rpc.watch().then((message) => {
|
|
389
564
|
resolve(message);
|
|
390
|
-
}); // first listen on the reply queue
|
|
391
|
-
|
|
565
|
+
}).catch(reject); // first listen on the reply queue
|
|
566
|
+
this.log('debug', 'sending request');
|
|
392
567
|
rpc.send(); // then send the rpc/rmq message
|
|
393
568
|
}
|
|
394
569
|
}));
|
|
@@ -397,20 +572,26 @@ class RabbitMQClient {
|
|
|
397
572
|
const publish = () => {
|
|
398
573
|
const { data, routingKey, publishOptions, exchange } = options;
|
|
399
574
|
const useContentType = publishOptions.contentType || enums_1.ContentTypes.TEXT;
|
|
400
|
-
const
|
|
575
|
+
const serializer = (0, utils_1.getSerializer)(useContentType) || utils_1.SERIALIZERS[useContentType];
|
|
576
|
+
const useData = serializer
|
|
577
|
+
? serializer.serialize(data)
|
|
578
|
+
: Buffer.from(typeof data === 'string' ? data : JSON.stringify(data), 'utf8');
|
|
579
|
+
if (this.metricsEnabled) {
|
|
580
|
+
this.metrics.messagesPublished += 1;
|
|
581
|
+
}
|
|
401
582
|
this.channel.publish(exchange, routingKey || '', useData, Object.assign(Object.assign({}, publishOptions), { appId: publishOptions.appId }));
|
|
402
583
|
};
|
|
403
584
|
if (!this.isReady) {
|
|
404
|
-
|
|
585
|
+
this.log('debug', 'wait until ready to publish event');
|
|
405
586
|
this.onReady.subscribe({
|
|
406
587
|
next: () => {
|
|
407
|
-
|
|
588
|
+
this.log('debug', 'now ready to publish event');
|
|
408
589
|
publish();
|
|
409
590
|
}
|
|
410
591
|
});
|
|
411
592
|
}
|
|
412
593
|
else {
|
|
413
|
-
|
|
594
|
+
this.log('debug', 'is ready to publish event');
|
|
414
595
|
publish();
|
|
415
596
|
}
|
|
416
597
|
}
|