message-brokers 1.8.2 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -36,10 +36,51 @@ RABBITMQ_URL=amqp://admin:pwd@localhost:5672
36
36
 
37
37
  (Optional)
38
38
  ACTIVE_MESSAGE_BROKER=rabbitmq
39
+ # Defines the active message broker used by the system.
40
+ # Supported values: rabbitmq | redis (future support possible)
41
+
39
42
  REDIS_PORT=6260
43
+ # Port used for Redis connection (used for caching / broker fallback mechanisms)
44
+
40
45
  CACHING_ENABLED=true
41
- RABBITMQ_DEPLOYMENT_ENV=stage (if using same rabbitmq stack for multiple environments, exchanges/queues/routing-keys get appended with this value. e.g. if rabbitmq deployment env is stage, then exchanges/queues/routing-keys will be appended with .stage)
42
- DATACLOAK_DISABLE=true (if you want to disable datacloak queue for stage/demo deployments)
46
+ # Enables/disables caching layer for message publishing and broker operations
47
+
48
+
49
+ RABBITMQ_DEPLOYMENT_ENV=stage
50
+ # Logical deployment identifier for shared RabbitMQ infrastructure.
51
+ # When set, it is appended to ALL RabbitMQ entities:
52
+ # - exchanges
53
+ # - queues
54
+ # - routing keys
55
+ #
56
+ # Example:
57
+ # base.queue → base.queue.stage
58
+ # base-key → base-key.stage
59
+ #
60
+ # Use this when multiple environments (stage/dev/prod) share the same RabbitMQ cluster.
61
+
62
+
63
+ DATACLOAK_DISABLE=true
64
+ # Disables Datacloak-related queues for non-production environments (e.g. stage/demo).
65
+ # When enabled, Datacloak queues will be skipped and removed if they exist.
66
+ # Useful for reducing unnecessary processing in shared or test deployments.
67
+
68
+
69
+ RABBITMQ_ISOLATED_NAMESPACE=prod-2
70
+ # Applies an isolation namespace ONLY to selected queues and routing keys.
71
+ #
72
+ # This is used together with an isolation prefix list (e.g. rabbitmqIsolatedQueues).
73
+ # If a queue/routing key matches the isolation rule, this namespace is appended:
74
+ #
75
+ # Example:
76
+ # messaging.queue → messaging.queue.prod-2
77
+ #
78
+ # Purpose:
79
+ # - Enables tenant-level or client-level isolation within the same broker
80
+ # - Prevents cross-communication between shared deployments
81
+ #
82
+ # Note:
83
+ # This does NOT apply globally — only to explicitly configured isolated queues/routing keys.
43
84
  ```
44
85
 
45
86
  ```javascript
@@ -75,6 +116,7 @@ db.on("error", (err) => {
75
116
  });
76
117
 
77
118
  const messageBrokers = new MessageBrokers(mongoConnectionHolder, "app_name");
119
+ await messageBrokers.init();
78
120
  ```
79
121
 
80
122
  #### 2. Native Mongodb driver initialization
@@ -102,6 +144,7 @@ client
102
144
  .catch((error) => console.error("❌ MongoDB connection failed:", error));
103
145
 
104
146
  const messageBrokers = new MessageBrokers(mongoConnectionHolder, "app_name");
147
+ await messageBrokers.init();
105
148
  ```
106
149
 
107
150
  ## Usage
@@ -136,4 +179,7 @@ messageBrokers.publishNotificationMessagesLogs(notification_messages_logs);
136
179
 
137
180
  // Publish amqp_lab_api_response
138
181
  messageBrokers.publishAmqpLabApiResponse(amqp_lab_api_response);
182
+
183
+ // Publish billing_events
184
+ messageBrokers.publishBillingEvents(billing_events);
139
185
  ```
@@ -2,6 +2,10 @@ const mbConfigs = {
2
2
  rabbitmqUrl: process.env.RABBITMQ_URL,
3
3
  activeMessageBroker: process.env.ACTIVE_MESSAGE_BROKER || "rabbitmq",
4
4
  redisPort: process.env.REDIS_PORT || 6260,
5
- cachingEnabled: process.env.CACHING_ENABLED || false
5
+ cachingEnabled: process.env.CACHING_ENABLED || false,
6
+ // Queues that are used in env where multiple instances of same stack share the same rabbitmq.
7
+ // To avoid messages between different instances, we are isolating the queues.
8
+ rabbitmqIsolatedQueues: ["messaging.har.lab-api.queue", "billing.events"],
9
+ rabbitmqIsolatedRoutingKeys: ["har.lab_api_response", "billing"]
6
10
  };
7
11
  module.exports = mbConfigs;
@@ -12,7 +12,7 @@ class MessageBrokers {
12
12
  this.applicationName = applicationName || "mb_app";
13
13
  this._initialized = false;
14
14
  }
15
- async _ensureInitialized() {
15
+ async init() {
16
16
  if (this._initialized) return;
17
17
  try {
18
18
  setActiveApplication(this.applicationName);
@@ -32,7 +32,6 @@ class MessageBrokers {
32
32
  * @returns
33
33
  */
34
34
  async publishHar(har) {
35
- await this._ensureInitialized();
36
35
  const response = await AmqpController.publishMessage(hv_exchange, "har", har);
37
36
  return response;
38
37
  }
@@ -43,7 +42,6 @@ class MessageBrokers {
43
42
  * @returns
44
43
  */
45
44
  async publishHarMeta(har_meta) {
46
- await this._ensureInitialized();
47
45
  const response = await AmqpController.publishMessage(hv_exchange, "har_meta", har_meta);
48
46
  return response;
49
47
  }
@@ -54,7 +52,6 @@ class MessageBrokers {
54
52
  * @returns
55
53
  */
56
54
  async publishLabApiResponse(lab_api_response) {
57
- await this._ensureInitialized();
58
55
  const response = await AmqpController.publishMessage(hv_exchange, "lab_api_response", lab_api_response, 2);
59
56
  return response;
60
57
  }
@@ -65,7 +62,6 @@ class MessageBrokers {
65
62
  * @returns
66
63
  */
67
64
  async publishHarLabApiResponse(harLab_api_response) {
68
- await this._ensureInitialized();
69
65
  const response = await AmqpController.publishMessage(hv_exchange, "har.lab_api_response", harLab_api_response);
70
66
  return response;
71
67
  }
@@ -76,7 +72,6 @@ class MessageBrokers {
76
72
  * @returns
77
73
  */
78
74
  async publishPurchaseDetails(purchase_details) {
79
- await this._ensureInitialized();
80
75
  const response = await AmqpController.publishMessage(hv_exchange, "purchase_details", purchase_details);
81
76
  return response;
82
77
  }
@@ -87,7 +82,6 @@ class MessageBrokers {
87
82
  * @returns
88
83
  */
89
84
  async publishLabLocationData(lab_location_data) {
90
- await this._ensureInitialized();
91
85
  const response = await AmqpController.publishMessage(hv_exchange, "lab_location_data", lab_location_data);
92
86
  return response;
93
87
  }
@@ -98,7 +92,6 @@ class MessageBrokers {
98
92
  * @returns
99
93
  */
100
94
  async publishInputObject(input_object) {
101
- await this._ensureInitialized();
102
95
  const response = await AmqpController.publishMessage(hv_exchange, "input_object", input_object);
103
96
  return response;
104
97
  }
@@ -109,7 +102,6 @@ class MessageBrokers {
109
102
  * @returns
110
103
  */
111
104
  async publishHarStub(har_stub) {
112
- await this._ensureInitialized();
113
105
  const response = await AmqpController.publishMessage(hv_exchange, "har_stub", har_stub);
114
106
  return response;
115
107
  }
@@ -120,7 +112,6 @@ class MessageBrokers {
120
112
  * @returns
121
113
  */
122
114
  async publishTrendingData(trending_data) {
123
- await this._ensureInitialized();
124
115
  const response = await AmqpController.publishMessage(hv_exchange, "trending_data", trending_data);
125
116
  return response;
126
117
  }
@@ -131,7 +122,6 @@ class MessageBrokers {
131
122
  * @returns
132
123
  */
133
124
  async publishRawQueue(raw_queue) {
134
- await this._ensureInitialized();
135
125
  const response = await AmqpController.publishMessage(hv_exchange, "raw_queue", raw_queue);
136
126
  return response;
137
127
  }
@@ -142,7 +132,6 @@ class MessageBrokers {
142
132
  * @returns
143
133
  */
144
134
  async publishNotificationMessagesLogs(notification_messages_logs) {
145
- await this._ensureInitialized();
146
135
  const response = await AmqpController.publishMessage(hv_exchange, "notification_messages_logs", notification_messages_logs);
147
136
  return response;
148
137
  }
@@ -153,7 +142,6 @@ class MessageBrokers {
153
142
  * @returns
154
143
  */
155
144
  async publishAmqpLabApiResponse(amqp_lab_api_response) {
156
- await this._ensureInitialized();
157
145
  const response = await AmqpController.publishMessage(hv_exchange, "lab_api_response.amqp", amqp_lab_api_response);
158
146
  return response;
159
147
  }
@@ -164,12 +152,10 @@ class MessageBrokers {
164
152
  * @returns
165
153
  */
166
154
  async publishBillingEvents(billing_events) {
167
- await this._ensureInitialized();
168
155
  const response = await AmqpController.publishMessage(hv_exchange, "billing", billing_events);
169
156
  return response;
170
157
  }
171
158
  async publishPendingMessageInCache() {
172
- await this._ensureInitialized();
173
159
  return await AmqpController.publishPendingMessageInCache();
174
160
  }
175
161
  }
@@ -10,6 +10,12 @@ const {
10
10
  const mqConfigs = require("../configs/mqConfigs");
11
11
  const mbConfigs = require("../configs/mb.configs");
12
12
  const CacheService = require("../services/cache.service");
13
+ const {
14
+ applyQueueName,
15
+ applyRoutingKey,
16
+ applyExchangeName,
17
+ applyRoutingKeyIsolationForPublish
18
+ } = require("@/utils/rabbitmq.utils");
13
19
  const offlinePubQueue = [];
14
20
  const RabbitMQHelper = {};
15
21
  const CachingEnabled = mbConfigs.cachingEnabled === "true";
@@ -20,19 +26,14 @@ RabbitMQHelper.initializePubSub = async () => {
20
26
  const rabbitmqChannel = await rabbitmq();
21
27
  const exchangeType = "direct";
22
28
  for (const mq of mqConfigs) {
23
- let exchangeName = mq.exchangeName;
24
- if (RABBITMQ_DEPLOYMENT_ENV) {
25
- exchangeName = `${mq.exchangeName}.${RABBITMQ_DEPLOYMENT_ENV}`;
26
- }
29
+ let exchangeName = applyExchangeName(mq.exchangeName);
27
30
  await rabbitmqChannel.assertExchange(exchangeName, exchangeType, {
28
31
  durable: true
29
32
  });
30
33
  await exchangeLogger(exchangeName);
31
34
  for (const queueConfig of mq.queueConfigList) {
32
35
  if (process.env.DATACLOAK_DISABLE === "true" && queueConfig.queueName.startsWith("datacloak.queue")) {
33
- if (RABBITMQ_DEPLOYMENT_ENV) {
34
- queue_name = `${queueConfig.queueName}.${RABBITMQ_DEPLOYMENT_ENV}`;
35
- }
36
+ let queue_name = applyQueueName(queueConfig.queueName);
36
37
  console.log(`Skipping queue ${queue_name} initialization due to DATACLOAK_DISABLE environment variable.`);
37
38
  console.log(`Deleting queue ${queue_name} if it exists.`);
38
39
  await RabbitMQHelper.deleteQueue(queue_name);
@@ -55,10 +56,7 @@ RabbitMQHelper.initializeAndBindQueue = async (rabbitmqChannel, exchangeName, qu
55
56
  priorityQueue,
56
57
  maxPriority
57
58
  } = queueConfig;
58
- let queue_name = queueName;
59
- if (RABBITMQ_DEPLOYMENT_ENV) {
60
- queue_name = `${queueName}.${RABBITMQ_DEPLOYMENT_ENV}`;
61
- }
59
+ let queue_name = applyQueueName(queueName);
62
60
  await rabbitmqChannel.assertQueue(queue_name, {
63
61
  durable: true,
64
62
  ...(priorityQueue && {
@@ -69,10 +67,7 @@ RabbitMQHelper.initializeAndBindQueue = async (rabbitmqChannel, exchangeName, qu
69
67
  });
70
68
  await queueLogger(`${queue_name} queue created!`);
71
69
  for (const routingKey of routingKeyList) {
72
- let routing_key = routingKey;
73
- if (RABBITMQ_DEPLOYMENT_ENV) {
74
- routing_key = `${routingKey}-${RABBITMQ_DEPLOYMENT_ENV}`;
75
- }
70
+ let routing_key = applyRoutingKey(queueName, routingKey);
76
71
  rabbitmqChannel.bindQueue(queue_name, exchangeName, routing_key);
77
72
  await bindingLogger([`${exchangeName}`, `${queue_name} queue with routing key ${routing_key}`]);
78
73
  }
@@ -95,12 +90,8 @@ RabbitMQHelper.publish = async (exchangeName, routingKey, message, priority = 0,
95
90
  const rabbitmqChannel = await rabbitmq();
96
91
  const parsedMessage = typeof message === "object" ? JSON.stringify(message) : message;
97
92
  const cacheGeneratedKey = cacheKey || randomUUID();
98
- let exchange_name = exchangeName;
99
- let routing_key = routingKey;
100
- if (RABBITMQ_DEPLOYMENT_ENV) {
101
- exchange_name = `${exchangeName}.${RABBITMQ_DEPLOYMENT_ENV}`;
102
- routing_key = `${routingKey}-${RABBITMQ_DEPLOYMENT_ENV}`;
103
- }
93
+ let exchange_name = applyExchangeName(exchangeName);
94
+ let routing_key = applyRoutingKeyIsolationForPublish(routingKey);
104
95
  if (CachingEnabled) {
105
96
  if (cacheKey) {} else {
106
97
  const setCacheResponse = await CacheService.setCache(cacheGeneratedKey, {
@@ -139,12 +130,8 @@ RabbitMQHelper.publish = async (exchangeName, routingKey, message, priority = 0,
139
130
  };
140
131
  }
141
132
  } catch (error) {
142
- let exchange_name = exchangeName;
143
- let routing_key = routingKey;
144
- if (RABBITMQ_DEPLOYMENT_ENV) {
145
- exchange_name = `${exchangeName}.${RABBITMQ_DEPLOYMENT_ENV}`;
146
- routing_key = `${routingKey}-${RABBITMQ_DEPLOYMENT_ENV}`;
147
- }
133
+ let exchange_name = applyExchangeName(exchangeName);
134
+ let routing_key = applyRoutingKeyIsolationForPublish(routingKey);
148
135
  const message = `Error while publishing to the ${exchange_name} with the routing key ${routing_key}`;
149
136
  console.log(message, error.message);
150
137
  offlinePubQueue.push([exchange_name, routing_key, message]);
@@ -0,0 +1,107 @@
1
+ const mbConfigs = require("../configs/mb.configs");
2
+ const RABBITMQ_DEPLOYMENT_ENV = process.env.RABBITMQ_DEPLOYMENT_ENV;
3
+
4
+ /**
5
+ * Determines if a queue is part of isolated set.
6
+ * This function is used to determine if the queue is in the isolated queues list.
7
+ */
8
+ function isIsolatedQueue(queueName) {
9
+ return mbConfigs.rabbitmqIsolatedQueues.some(prefix => queueName.startsWith(prefix));
10
+ }
11
+
12
+ /**
13
+ * Returns isolation namespace if applicable.
14
+ * This function is used to get the rabbitmq isolation namespace.
15
+ * If the queue name is in the isolated queues list, then the namespace is returned.
16
+ * If the namespace is not set, then null is returned.
17
+ */
18
+ function getIsolationNamespace(queueName) {
19
+ if (isIsolatedQueue(queueName) && process.env.RABBITMQ_ISOLATED_NAMESPACE) {
20
+ return process.env.RABBITMQ_ISOLATED_NAMESPACE;
21
+ }
22
+ return null;
23
+ }
24
+
25
+ /**
26
+ * Apply isolation + deployment env to base value.
27
+ * This function is used to apply the rabbitmq isolation namespace to the queue name.
28
+ * If the queue name is in the isolated queues list, then the namespace is appended to the queue name.
29
+ * If the namespace is not set, then the queue name is not changed.
30
+ * If the deployment env is set, then the deployment env is appended to the queue name.
31
+ */
32
+ function applyQueueName(queueName) {
33
+ let name = queueName;
34
+ const ns = getIsolationNamespace(queueName);
35
+ if (ns) {
36
+ name = `${name}.${ns}`;
37
+ }
38
+ if (RABBITMQ_DEPLOYMENT_ENV) {
39
+ name = `${name}.${RABBITMQ_DEPLOYMENT_ENV}`;
40
+ }
41
+ return name;
42
+ }
43
+
44
+ /**
45
+ * Routing key inherits queue isolation context.
46
+ * This function is used to apply the rabbitmq isolation namespace to the routing key.
47
+ * If the routing key is in the isolated queues list, then the namespace is appended to the routing key.
48
+ * If the namespace is not set, then the routing key is not changed.
49
+ * If the deployment env is set, then the deployment env is appended to the routing key.
50
+ */
51
+ function applyRoutingKey(queueName, routingKey) {
52
+ let key = routingKey;
53
+ const ns = getIsolationNamespace(queueName);
54
+ if (ns) {
55
+ key = `${key}-${ns}`;
56
+ }
57
+ if (RABBITMQ_DEPLOYMENT_ENV) {
58
+ key = `${key}-${RABBITMQ_DEPLOYMENT_ENV}`;
59
+ }
60
+ return key;
61
+ }
62
+
63
+ /**
64
+ * Exchange only gets deployment env (no isolation concept).
65
+ * This function is used to apply the rabbitmq deployment env to the exchange name.
66
+ * If the deployment env is set, then the deployment env is appended to the exchange name.
67
+ */
68
+ function applyExchangeName(exchangeName) {
69
+ if (RABBITMQ_DEPLOYMENT_ENV) {
70
+ return `${exchangeName}.${RABBITMQ_DEPLOYMENT_ENV}`;
71
+ }
72
+ return exchangeName;
73
+ }
74
+
75
+ /**
76
+ * Checks if the routing key needs to be isolated.
77
+ * This function is used to check if the routing key is in the isolated routing keys list.
78
+ */
79
+ function shouldIsolateRoutingKey(routingKey) {
80
+ return mbConfigs.rabbitmqIsolatedRoutingKeys.some(prefix => routingKey.startsWith(prefix));
81
+ }
82
+
83
+ /**
84
+ * Apply isolation + deployment env to routing key for publishing.
85
+ * This function is used to apply the rabbitmq isolation namespace and deployment env to the routing key.
86
+ * If the routing key is in the isolated routing keys list, then the namespace is appended to the routing key.
87
+ * If the namespace is not set, then the routing key is not changed.
88
+ * If the deployment env is set, then the deployment env is appended to the routing key.
89
+ */
90
+ function applyRoutingKeyIsolationForPublish(routingKey) {
91
+ let key = routingKey;
92
+ if (shouldIsolateRoutingKey(key) && process.env.RABBITMQ_ISOLATED_NAMESPACE) {
93
+ const ns = process.env.RABBITMQ_ISOLATED_NAMESPACE;
94
+ key = `${key}-${ns}`;
95
+ }
96
+ if (RABBITMQ_DEPLOYMENT_ENV) {
97
+ key = `${key}-${RABBITMQ_DEPLOYMENT_ENV}`;
98
+ }
99
+ return key;
100
+ }
101
+ module.exports = {
102
+ isIsolatedQueue,
103
+ applyQueueName,
104
+ applyRoutingKey,
105
+ applyExchangeName,
106
+ applyRoutingKeyIsolationForPublish
107
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "message-brokers",
3
- "version": "1.8.2",
3
+ "version": "1.9.0",
4
4
  "description": "This package contains functions to publish the messages into the message brokers like rabbitmq.",
5
5
  "main": "lib/message-brokers.js",
6
6
  "types": "lib/types/message-brokers.d.ts",