rxjs-rabbitmq 2.2.0 → 2.2.2

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 CHANGED
@@ -1,99 +1,497 @@
1
1
  # RxJS RabbitMQ Client
2
2
 
3
+ A lightweight RabbitMQ client for Node.js that blends RabbitMQ messaging with RxJS-style event handling.
3
4
 
5
+ The library is intentionally small and stable: it focuses on four primary tasks:
4
6
 
5
- ```typescript
6
- import {
7
- RabbitMQClient,
8
- RmqEventMessage
9
- } from "rxjs-rabbitmq";
10
-
11
- const handleMessageTypes: string[] = [
12
- ClientsQueueMessageTypes.ADD_CLIENT,
13
- UsersQueueEventTypes.USER_CREATED,
14
- UsersQueueEventTypes.USER_DELETED,
15
- AuthoritiesQueueEventTypes.AUTHORITY_CREATED,
16
- AuthoritiesQueueEventTypes.AUTHORITY_DELETED,
7
+ - establishing a RabbitMQ connection and channel
8
+ - asserting queues, exchanges, and bindings
9
+ - exposing queue events as RxJS streams
10
+ - supporting basic request/reply messaging and typed publish helpers
11
+
12
+ It is designed for service-to-service messaging where you want a simple and familiar RxJS interface without introducing a larger messaging framework.
13
+
14
+ ## Why this library exists
15
+
16
+ This package is best when you want:
17
+
18
+ - RabbitMQ message handling with RxJS streams
19
+ - per-queue event subscriptions
20
+ - message type routing from `message.properties.type`
21
+ - simple request/reply patterns
22
+ - direct control over RabbitMQ resources without a heavy abstraction layer
23
+
24
+ It is not a full orchestration engine or a replacement for a full enterprise messaging platform. The library tries to stay small, explicit, and operationally predictable.
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ npm install rxjs-rabbitmq amqplib rxjs uuid
30
+ ```
31
+
32
+ ## Core concepts
33
+
34
+ ### Queue configuration
35
+
36
+ Each configured queue can optionally declare known message types:
37
+
38
+ ```ts
39
+ const queues = [
40
+ {
41
+ name: 'emails',
42
+ handleMessageTypes: ['SEND_EMAIL', 'EMAIL_SENT'],
43
+ options: { durable: true }
44
+ }
45
+ ];
46
+ ```
47
+
48
+ When a message arrives:
49
+
50
+ - the global `onMessage` stream receives it
51
+ - the queue-specific stream receives it
52
+ - if the message has a known `type`, it is routed to the matching registered stream or callback
53
+ - if no type is found, it is routed to the default queue handler when enabled
54
+
55
+ ### Exchange configuration
56
+
57
+ ```ts
58
+ const exchanges = [
59
+ {
60
+ name: 'user.events',
61
+ type: 'fanout',
62
+ options: { durable: true }
63
+ }
17
64
  ];
65
+ ```
66
+
67
+ ### Binding configuration
68
+
69
+ ```ts
70
+ const bindings = [
71
+ {
72
+ queue: 'emails',
73
+ exchange: 'user.events',
74
+ routingKey: '#'
75
+ }
76
+ ];
77
+ ```
78
+
79
+ ## Quick start
80
+
81
+ ```ts
82
+ import { RabbitMQClient, RmqEventMessage, ContentTypes } from 'rxjs-rabbitmq';
18
83
 
19
- const rmqClient = new RabbitMQClient({
20
- connection_url: AppEnvironment.RABBIT_MQ_URL,
21
- delayStart: 5000,
22
- prefetch: 5,
84
+ const client = new RabbitMQClient({
85
+ connection_url: process.env.RABBITMQ_URL!,
23
86
  retryAttempts: 3,
24
- retryDelay: 3000,
87
+ retryDelay: 2000,
88
+ prefetch: 10,
25
89
  autoAckUnhandledMessageTypes: true,
26
90
  queues: [
27
- { name: MicroservicesQueues.EMAILS, handleMessageTypes, options: { durable: true } },
91
+ {
92
+ name: 'emails',
93
+ handleMessageTypes: ['SEND_EMAIL'],
94
+ options: { durable: true }
95
+ }
28
96
  ],
29
97
  exchanges: [
30
- { name: MicroservicesExchanges.EMAIL_EVENTS, type: 'fanout', options: { durable: true } },
31
- { name: MicroservicesExchanges.USER_EVENTS, type: 'fanout', options: { durable: true } },
32
- { name: MicroservicesExchanges.AUTHORITY_EVENTS, type: 'fanout', options: { durable: true } },
98
+ {
99
+ name: 'app.events',
100
+ type: 'fanout',
101
+ options: { durable: true }
102
+ }
33
103
  ],
34
- bindings: [
35
- { queue: MicroservicesQueues.EMAILS, exchange: MicroservicesExchanges.USER_EVENTS, routingKey: RoutingKeys.EVENT },
36
- { queue: MicroservicesQueues.EMAILS, exchange: MicroservicesExchanges.AUTHORITY_EVENTS, routingKey: RoutingKeys.EVENT },
37
- ]
104
+ bindings: []
38
105
  });
39
106
 
107
+ client.onMessage.subscribe((event: RmqEventMessage) => {
108
+ console.log('Received message', event.data);
109
+ });
40
110
 
41
- // Listen to all messages from a queue
42
- rmqClient.forQueue(MicroservicesQueues.NOTIFICATIONS).subscribe({
111
+ client.onQueue('emails').handle('SEND_EMAIL').subscribe({
43
112
  next: (event: RmqEventMessage) => {
44
- const handler: RmqEventHandler = EventHandlersMap[event.message.properties.type];
45
- if (!!handler && typeof (handler) === 'function') {
46
- handler(event);
113
+ console.log('Email event payload:', event.data);
114
+ event.ack();
115
+ }
116
+ });
117
+ ```
118
+
119
+ ## Event handling patterns
120
+
121
+ ### 1. Listen to every message on a queue
122
+
123
+ ```ts
124
+ const queue$ = client.forQueue('emails');
125
+
126
+ queue$.subscribe({
127
+ next: (event) => {
128
+ console.log('event payload', event.data);
129
+ }
130
+ });
131
+ ```
132
+
133
+ ### 2. Handle a specific message type
134
+
135
+ ```ts
136
+ const emailsQueue = client.onQueue('emails');
137
+
138
+ emailsQueue.handle('SEND_EMAIL').subscribe({
139
+ next: (event) => {
140
+ console.log(event.data);
141
+ event.ack();
142
+ }
143
+ });
144
+ ```
145
+
146
+ ### 3. Use a callback-based event handler
147
+
148
+ ```ts
149
+ const emailsQueue = client.onQueue('emails');
150
+
151
+ emailsQueue.onEvent('SEND_EMAIL', (event) => {
152
+ console.log(event.data);
153
+ event.ack();
154
+ });
155
+ ```
156
+
157
+ ### 4. Listen to all messages on a queue with a custom handler
158
+
159
+ ```ts
160
+ client.onQueue('emails').handleAll((event) => {
161
+ console.log(event.message.properties.type, event.data);
162
+ });
163
+ ```
164
+
165
+ ## Publishing messages
166
+
167
+ ### Publish to a queue
168
+
169
+ ```ts
170
+ client.sendMessage({
171
+ queue: 'emails',
172
+ data: { to: 'user@example.com', body: 'Hello' },
173
+ publishOptions: {
174
+ contentType: 'application/json',
175
+ persistent: true
176
+ }
177
+ });
178
+ ```
179
+
180
+ ### Publish to an exchange
181
+
182
+ ```ts
183
+ client.publishEvent({
184
+ exchange: 'app.events',
185
+ routingKey: 'user.created',
186
+ data: { id: '123', name: 'Ada' },
187
+ publishOptions: {
188
+ contentType: 'application/json',
189
+ type: 'USER_CREATED',
190
+ persistent: true
191
+ }
192
+ });
193
+ ```
194
+
195
+ ## Request/reply pattern
196
+
197
+ ```ts
198
+ const response = await client.sendRequest<{ ok: boolean }>({
199
+ queue: 'worker',
200
+ data: { action: 'generate-report' },
201
+ publishOptions: {
202
+ correlationId: 'req-123',
203
+ contentType: 'application/json',
204
+ type: 'GENERATE_REPORT'
205
+ }
206
+ }, true, 30000);
207
+
208
+ console.log(response.data);
209
+ ```
210
+
211
+ The request helper creates a temporary exclusive reply queue and watches for a matching correlation ID. If a reply is not received before the timeout, the promise rejects and the temporary consumer is cancelled.
212
+
213
+ ## Message acknowledgement and recovery
214
+
215
+ The event object includes helper methods:
216
+
217
+ ```ts
218
+ client.onQueue('emails').handle('SEND_EMAIL').subscribe({
219
+ next: (event) => {
220
+ // ack once business logic succeeds
221
+ event.ack();
222
+
223
+ // or reject and requeue if necessary
224
+ client.nack(event.message, true);
225
+ }
226
+ });
227
+ ```
228
+
229
+ ### Retry and dead-letter helpers
230
+
231
+ ```ts
232
+ client.onQueue('emails').handle('SEND_EMAIL').subscribe({
233
+ next: (event) => {
234
+ try {
235
+ // business logic
236
+ } catch (error) {
237
+ client.retryMessage(event.message, {
238
+ delayMs: 1000,
239
+ requeue: true,
240
+ queue: 'emails.retry'
241
+ });
242
+ }
243
+ }
244
+ });
245
+ ```
246
+
247
+ ```ts
248
+ client.deadLetter(event.message, 'processing failed', 'emails.dlq');
249
+ ```
250
+
251
+ These helpers are intentionally opt-in and explicit; they avoid forcing a policy onto all consumers.
252
+
253
+ ### Dead-letter queue setup and centralized error handling
254
+
255
+ For production workloads, it is often easier to define the DLQ topology once and then route failures through a single helper.
256
+
257
+ ```ts
258
+ await client.setupDeadLetterQueue({
259
+ sourceQueue: 'emails',
260
+ deadLetterQueue: 'emails.dlq',
261
+ deadLetterExchange: 'emails.dlx',
262
+ deadLetterRoutingKey: 'emails.dlq',
263
+ queueOptions: { durable: true },
264
+ deadLetterQueueOptions: { durable: true },
265
+ messageTtlMs: 5000
266
+ });
267
+ ```
268
+
269
+ This config creates a dead-letter exchange and binds it to a dedicated DLQ, while also attaching the DLX metadata to the source queue so RabbitMQ can move failed work automatically.
270
+
271
+ For handling processing failures inside a consumer, prefer a centralized helper rather than duplicating retry logic in each handler:
272
+
273
+ ```ts
274
+ client.onQueue('emails').handle('SEND_EMAIL').subscribe({
275
+ next: (event) => {
276
+ try {
277
+ // process message
278
+ event.ack();
279
+ } catch (error) {
280
+ client.handleMessageError(event.message, error, {
281
+ reason: 'email processing failed',
282
+ deadLetterQueue: 'emails.dlq',
283
+ retryQueue: 'emails.retry',
284
+ retryDelayMs: 2000,
285
+ requeue: false
286
+ });
47
287
  }
48
288
  }
49
289
  });
290
+ ```
291
+
292
+ The helper returns an action summary and keeps the failure policy explicit:
293
+
294
+ - `retry`: requeue the message to a retry queue after a delay
295
+ - `dead-letter`: move the message into the configured DLQ
296
+ - `nack`: reject the message and optionally requeue it
297
+
298
+ This makes it easier to keep error handling consistent across queues without burying RabbitMQ semantics deep inside business logic.
299
+
300
+ ## Serialization
301
+
302
+ The library includes a built-in serializer registry in `SERIALIZERS` and supports custom registration.
303
+
304
+ ```ts
305
+ import { registerSerializer } from 'rxjs-rabbitmq';
306
+
307
+ registerSerializer('application/custom', {
308
+ serialize: (value) => Buffer.from(JSON.stringify(value)),
309
+ deserialize: (buffer) => JSON.parse(buffer.toString('utf8'))
310
+ });
311
+ ```
312
+
313
+ You can also call:
314
+
315
+ ```ts
316
+ RabbitMQClient.registerSerializer('application/custom', {
317
+ serialize: ...,
318
+ deserialize: ...
319
+ });
320
+ ```
321
+
322
+ ## Metrics and observability
323
+
324
+ When `metrics: true` is enabled, the client tracks counts for:
325
+
326
+ - received messages
327
+ - published messages
328
+ - acked messages
329
+ - nacked messages
330
+ - retried messages
331
+ - RPC requests
332
+ - RPC responses
333
+ - reconnects
334
+
335
+ ```ts
336
+ const client = new RabbitMQClient({
337
+ connection_url: process.env.RABBITMQ_URL!,
338
+ metrics: true,
339
+ queues: [],
340
+ exchanges: [],
341
+ bindings: [],
342
+ retryAttempts: 2,
343
+ retryDelay: 1000
344
+ });
345
+
346
+ console.log(client.getMetrics());
347
+ ```
50
348
 
349
+ This is useful for diagnostics and operational visibility, but it remains optional and should not be enabled unless you want the extra bookkeeping.
51
350
 
351
+ ## Logger configuration
52
352
 
53
- // Handle specific queue
54
- const emailsQueue = rmqClient.onQueue(MicroservicesQueues.EMAILS);
353
+ Logs are optional and fully configurable.
55
354
 
56
- // Handle specific message types from a queue
57
- emailsQueue.handle(EmailsQueueMessageTypes.SEND_EMAIL).subscribe({ next: SEND_EMAIL });
355
+ ```ts
356
+ const client = new RabbitMQClient({
357
+ connection_url: process.env.RABBITMQ_URL!,
358
+ logger: {
359
+ debug: (...args) => console.debug('[rabbitmq]', ...args),
360
+ info: (...args) => console.info('[rabbitmq]', ...args),
361
+ warn: (...args) => console.warn('[rabbitmq]', ...args),
362
+ error: (...args) => console.error('[rabbitmq]', ...args)
363
+ },
364
+ queues: [],
365
+ exchanges: [],
366
+ bindings: [],
367
+ retryAttempts: 3,
368
+ retryDelay: 2000
369
+ });
370
+ ```
58
371
 
59
- // shorthand/auto-subscribe and handle
60
- emailsQueue.onEvent(EmailsQueueMessageTypes.SEND_EMAIL, SEND_EMAIL);
372
+ This is especially helpful in production, where per-message logs can become a throughput bottleneck.
61
373
 
374
+ ## Lifecycle management
62
375
 
376
+ The client exposes a manual close method for clean shutdown:
63
377
 
64
- // event handler
378
+ ```ts
379
+ await client.close();
380
+ ```
65
381
 
66
- export async function SEND_EMAIL(event: RmqEventMessage) {
67
- console.log(`[${EmailsQueueMessageTypes.SEND_EMAIL}] Received message:`, { data: event.data });
382
+ This clears any reconnect timer, closes the channel and connection, and marks the client as no longer ready.
68
383
 
69
- const sendEmailParams = event.data as SendEmailDto;
384
+ ## Full example
70
385
 
71
- const email_send_results: SendEmailCommandOutput = await sendAwsEmail({
72
- to: sendEmailParams.to_email,
73
- subject: sendEmailParams.subject,
74
- message: sendEmailParams.text,
75
- html: sendEmailParams.html,
76
- });
386
+ ```ts
387
+ import {
388
+ RabbitMQClient,
389
+ RmqEventMessage,
390
+ ContentTypes
391
+ } from 'rxjs-rabbitmq';
77
392
 
78
- const serviceMethodResults: ServiceMethodResults = {
79
- status: HttpStatusCode.OK,
80
- error: false,
81
- info: {
82
- data: email_send_results
393
+ const client = new RabbitMQClient({
394
+ connection_url: process.env.RABBITMQ_URL!,
395
+ delayStart: 1500,
396
+ prefetch: 25,
397
+ retryAttempts: 3,
398
+ retryDelay: 2000,
399
+ rpcRequestTimeoutMs: 30000,
400
+ metrics: true,
401
+ autoAckUnhandledMessageTypes: true,
402
+ logger: {
403
+ info: (...args) => console.info('[rmq]', ...args),
404
+ warn: (...args) => console.warn('[rmq]', ...args),
405
+ error: (...args) => console.error('[rmq]', ...args)
406
+ },
407
+ queues: [
408
+ {
409
+ name: 'emails',
410
+ handleMessageTypes: ['SEND_EMAIL', 'EMAIL_SENT'],
411
+ options: { durable: true }
83
412
  }
84
- };
85
-
86
- event.ack(event.message);
87
- return rmqClient.publishEvent({
88
- exchange: MicroservicesExchanges.EMAIL_EVENTS,
89
- data: serviceMethodResults,
90
- publishOptions: {
91
- type: EmailsQueueEventTypes.SENT_EMAIL,
92
- contentType: ContentTypes.JSON,
93
- correlationId: event.message.properties.correlationId,
94
- replyTo: event.message.properties.replyTo,
413
+ ],
414
+ exchanges: [
415
+ {
416
+ name: 'app.events',
417
+ type: 'fanout',
418
+ options: { durable: true }
419
+ }
420
+ ],
421
+ bindings: [
422
+ {
423
+ queue: 'emails',
424
+ exchange: 'app.events',
425
+ routingKey: '#'
426
+ }
427
+ ]
428
+ });
429
+
430
+ const emailsQueue = client.onQueue('emails');
431
+
432
+ emailsQueue.handle('SEND_EMAIL').subscribe({
433
+ next: async (event: RmqEventMessage) => {
434
+ try {
435
+ const payload = event.data as { to: string; subject: string; html: string };
436
+ console.log('Sending email', payload);
437
+ event.ack();
438
+ client.publishEvent({
439
+ exchange: 'app.events',
440
+ routingKey: 'email.sent',
441
+ data: { ok: true, to: payload.to },
442
+ publishOptions: {
443
+ type: 'EMAIL_SENT',
444
+ contentType: ContentTypes.JSON,
445
+ persistent: true
446
+ }
447
+ });
448
+ } catch (error) {
449
+ client.deadLetter(event.message, 'email send failed', 'emails.dlq');
95
450
  }
96
- });
97
- }
451
+ }
452
+ });
453
+
454
+ process.on('SIGINT', async () => {
455
+ await client.close();
456
+ process.exit(0);
457
+ });
458
+ ```
459
+
460
+ ## Design goals and trade-offs
461
+
462
+ This package intentionally favors simplicity over abstraction. It does not hide RabbitMQ details completely, and it does not force a specific application-level architecture. Instead, it gives you:
463
+
464
+ - a direct client
465
+ - RxJS streams
466
+ - explicit message acknowledgement
467
+ - configurable production defaults
468
+ - small extension points for serializers, retries, and metrics
469
+
470
+ That makes it easy to reason about and safe to use in microservice environments without introducing lots of hidden behavior.
471
+
472
+ ## Stability guidance
473
+
474
+ The same library should remain stable if you follow a few rules:
475
+
476
+ - keep message types explicit
477
+ - prefer `ack()` only after successful processing
478
+ - use `nack()` and `retryMessage()` only when you own the retry strategy
479
+ - use `logger` and `metrics` as opt-in production controls
480
+ - do not rely on implicit routing behavior for critical workflows
481
+
482
+ ## Contributing
483
+
484
+ This project is intentionally small. Improvements are most welcome when they:
485
+
486
+ - reduce operational risk
487
+ - improve RxJS ergonomics
488
+ - maintain a simple public API
489
+ - do not quietly introduce opinionated infrastructure behavior
490
+
491
+ ## License
492
+
493
+ ISC
494
+
495
+ ## Support
98
496
 
99
- ```
497
+ This package assumes you already understand RabbitMQ semantics and the application-level contract around your queues, exchanges, and routing keys.
@@ -1,18 +1,22 @@
1
+ /// <reference types="node" />
1
2
  import { Connection, Channel, Options, ConsumeMessage } from "amqplib";
2
3
  import { Observable, Subscription } from "rxjs";
3
- import { RabbitMqInitConfig, RmqEventHandler, RmqEventMessage, RmqPublishEventParams, RmqSendMessageParams } from "./types";
4
+ import { DeadLetterQueueConfig, HandleMessageErrorOptions, RabbitMqInitConfig, RmqEventHandler, RmqEventMessage, RmqPublishEventParams, RmqSendMessageParams } from "./types";
4
5
  export type RmgOnEventHandler = (event: RmqEventMessage, rmqClient?: RabbitMQClient) => void;
5
6
  /**
6
7
  Rabbit MQ - RxJS Powered
7
8
  */
8
9
  export declare class RabbitMQClient {
9
10
  private clientInitConfig;
11
+ private logger;
10
12
  private connection;
11
13
  private channel;
12
14
  private isReady;
13
15
  private isReadyStream;
14
16
  private connectionErrorStream;
15
17
  private connectionCloseStream;
18
+ private reconnectTimeout;
19
+ private reconnectAttempts;
16
20
  private messagesStream;
17
21
  private messagesStreamsByQueue;
18
22
  private queues;
@@ -20,14 +24,34 @@ export declare class RabbitMQClient {
20
24
  private bindings;
21
25
  private DEFAULT_LISTENER_TYPE;
22
26
  private queueListeners;
27
+ private registeredQueueConsumers;
28
+ private metricsEnabled;
29
+ private metrics;
23
30
  private queueToEventHandleMapping;
24
31
  private queueToEventCallbackMapping;
32
+ private log;
25
33
  get onReady(): Observable<boolean>;
26
34
  get onConnectionError(): Observable<any>;
27
35
  get onConnectionClose(): Observable<any>;
28
36
  get onMessage(): Observable<RmqEventMessage>;
29
37
  constructor(clientInitConfig: RabbitMqInitConfig);
30
- init(): Promise<void> | undefined;
38
+ static registerSerializer(contentType: string, serializer: {
39
+ serialize: (value: unknown) => Buffer;
40
+ deserialize: (value: Buffer, encoding?: BufferEncoding) => unknown;
41
+ }): import("./types").RabbitMqSerializer;
42
+ getMetrics(): {
43
+ messagesReceived: number;
44
+ messagesPublished: number;
45
+ messagesAcked: number;
46
+ messagesNacked: number;
47
+ messagesRetried: number;
48
+ rpcRequests: number;
49
+ rpcResponses: number;
50
+ reconnects: number;
51
+ };
52
+ private resubscribeToRegisteredQueues;
53
+ private scheduleReconnect;
54
+ init(): Promise<void>;
31
55
  getConnection(): Connection;
32
56
  getChannel(): Channel;
33
57
  private getQueueListener;
@@ -40,12 +64,42 @@ export declare class RabbitMQClient {
40
64
  };
41
65
  forQueue(queue: string, options?: Options.Consume): Observable<RmqEventMessage>;
42
66
  ack(message: ConsumeMessage): void;
67
+ nack(message: ConsumeMessage, requeue?: boolean): void;
68
+ retryMessage(message: ConsumeMessage, options?: {
69
+ delayMs?: number;
70
+ requeue?: boolean;
71
+ queue?: string;
72
+ }): void;
73
+ deadLetter(message: ConsumeMessage, reason: string, queue?: string): void;
74
+ setupDeadLetterQueue(config: DeadLetterQueueConfig): Promise<{
75
+ sourceQueue: string;
76
+ deadLetterQueue: string;
77
+ deadLetterExchange: string;
78
+ deadLetterRoutingKey: string;
79
+ }>;
80
+ handleMessageError(message: ConsumeMessage, error: unknown, options?: HandleMessageErrorOptions): {
81
+ action: "retry";
82
+ targetQueue: string;
83
+ retryDelayMs: number;
84
+ requeue?: undefined;
85
+ } | {
86
+ action: "dead-letter";
87
+ targetQueue: string;
88
+ retryDelayMs?: undefined;
89
+ requeue?: undefined;
90
+ } | {
91
+ action: "nack";
92
+ requeue: boolean;
93
+ targetQueue?: undefined;
94
+ retryDelayMs?: undefined;
95
+ };
96
+ close(): Promise<void>;
43
97
  sendMessage(options: RmqSendMessageParams): void;
44
98
  private getRpcMethods;
45
99
  sendRequest<T = any>(options: {
46
100
  queue: string;
47
101
  data: any;
48
102
  publishOptions: Options.Publish;
49
- }, autoAckOnReceiveReply?: boolean): Promise<RmqEventMessage<T>>;
103
+ }, autoAckOnReceiveReply?: boolean, timeoutMs?: number): Promise<RmqEventMessage<T>>;
50
104
  publishEvent(options: RmqPublishEventParams): void;
51
105
  }