@autofleet/rabbit 2.1.0 → 2.1.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/dist/index.d.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  import { Options } from 'amqplib';
3
3
  import { AmqpConnectionManager, ChannelWrapper } from 'amqp-connection-manager';
4
4
  import { EventEmitter } from 'events';
5
+ import { RedisConfig } from './redis';
5
6
  export interface IAfRabbitMq {
6
7
  ack: any;
7
8
  nack: any;
@@ -12,18 +13,23 @@ export interface IAfRabbitMq {
12
13
  consumeFromExchange: any;
13
14
  publish: any;
14
15
  sendToQueue: any;
16
+ redisClient?: any;
15
17
  }
16
18
  interface ExchangesCache {
17
19
  [key: string]: any;
18
20
  }
21
+ declare type CustomMessageHeaders = {
22
+ redisTimestampValidationKey?: string;
23
+ };
19
24
  export interface AfRabbitOptions {
20
25
  reconnect: boolean;
21
26
  }
22
27
  declare class RabbitMq implements IAfRabbitMq {
23
28
  static parseMsg(msg: any): any;
24
29
  static validateName(type: string, name: string): void;
25
- static getPublishOptions(): {
30
+ static getPublishOptions(customHeaders?: CustomMessageHeaders): {
26
31
  timestamp: number;
32
+ headers: CustomMessageHeaders;
27
33
  };
28
34
  PUBLISH_TIMEOUT: number;
29
35
  PUBLISH_ERROR_MSG: string;
@@ -35,8 +41,10 @@ declare class RabbitMq implements IAfRabbitMq {
35
41
  creatingConnection: boolean;
36
42
  exchanges: ExchangesCache;
37
43
  options: AfRabbitOptions | undefined;
38
- constructor(options?: AfRabbitOptions);
39
- ack: (channel: ChannelWrapper) => (msg: any) => Promise<void>;
44
+ redisClient: any;
45
+ constructor(options?: AfRabbitOptions, redisConfig?: RedisConfig);
46
+ private shouldConsumeMessageByTimestamp;
47
+ ack: (channel: ChannelWrapper, shouldUpdateRedisTimestamp?: boolean) => (msg: any) => Promise<void>;
40
48
  nack: (channel: ChannelWrapper, queue: string, options: any, deadQueueOptions: Options.AssertQueue) => (msg: any, { skipRetry, }?: any) => Promise<void>;
41
49
  getConnection(): Promise<AmqpConnectionManager>;
42
50
  getNewChannel(): Promise<ChannelWrapper>;
@@ -47,7 +55,7 @@ declare class RabbitMq implements IAfRabbitMq {
47
55
  assertQueue(queue: string, options?: Options.AssertQueue): Promise<void>;
48
56
  consume(queue: string, callback: (msg: any, ack: Function, nack: Function) => any, options?: any): Promise<void>;
49
57
  consumeFromExchange(queue: string, exchange: string, callback: (msg: any, ack: Function, nack: Function) => any, options?: any): Promise<void>;
50
- publish(exchange: string, content: any): Promise<unknown>;
51
- sendToQueue(queue: string, content: any, options?: any): Promise<void>;
58
+ publish(exchange: string, content: any, customHeaders?: any): Promise<unknown>;
59
+ sendToQueue(queue: string, content: any, options?: any, customHeaders?: any): Promise<void>;
52
60
  }
53
61
  export default RabbitMq;
package/dist/index.js CHANGED
@@ -39,22 +39,37 @@ const amqp_connection_manager_1 = require("amqp-connection-manager");
39
39
  const events_1 = require("events");
40
40
  const outbreak_1 = require("@autofleet/outbreak");
41
41
  const rabbitError_1 = __importDefault(require("./rabbitError"));
42
+ const redis_1 = __importDefault(require("./redis"));
42
43
  const DEFAULT_DEAD_TTL_TWO_DAYS = 60000 * 60 * 48;
43
44
  const defaultOptions = {
44
45
  limit: 1,
45
46
  retries: 1,
46
47
  deadMessageTtl: DEFAULT_DEAD_TTL_TWO_DAYS,
47
48
  };
49
+ const SECONDS_TO_MILLISECONDS = 1000;
48
50
  const assertExchangeFanout = (c, exchangeName) => c.assertExchange(exchangeName, 'fanout');
49
51
  const connectionCreatedConst = 'connectionCreated';
50
52
  class RabbitMq {
51
- constructor(options) {
53
+ constructor(options, redisConfig) {
52
54
  this.PUBLISH_TIMEOUT = Number(process.env.RABBITMQ_PUBLISH_TIMEOUT) || 60000;
53
55
  this.PUBLISH_ERROR_MSG = `rabbit: publish timeout(${this.PUBLISH_TIMEOUT}ms) has pass, exchange: `;
54
56
  this.DISCONNECT_MSG = 'rabbit: connection disconnect';
55
57
  this.RESCONNECT_MSG = 'rabbit: reconnecting';
56
- this.ack = (channel) => (msg) => __awaiter(this, void 0, void 0, function* () {
58
+ this.shouldConsumeMessageByTimestamp = (msg) => __awaiter(this, void 0, void 0, function* () {
59
+ const { properties: { timestamp, headers } } = msg;
60
+ if (timestamp && (headers === null || headers === void 0 ? void 0 : headers.redisTimestampValidationKey) && this.redisClient) {
61
+ const lastMessageTimestamp = yield this.redisClient.getAsync(headers.redisTimestampValidationKey);
62
+ return !lastMessageTimestamp || !moment_1.default(parseInt(lastMessageTimestamp, 10) * SECONDS_TO_MILLISECONDS).isAfter(moment_1.default(timestamp * SECONDS_TO_MILLISECONDS));
63
+ }
64
+ return true;
65
+ });
66
+ this.ack = (channel, shouldUpdateRedisTimestamp = false) => (msg) => __awaiter(this, void 0, void 0, function* () {
57
67
  yield channel.ack(msg);
68
+ const { properties: { timestamp, headers } } = msg;
69
+ if (shouldUpdateRedisTimestamp && timestamp && (headers === null || headers === void 0 ? void 0 : headers.redisTimestampValidationKey) && this.redisClient) {
70
+ const parsedTimestamp = parseInt(timestamp, 10);
71
+ yield this.redisClient.setAsync(headers.redisTimestampValidationKey, parsedTimestamp);
72
+ }
58
73
  });
59
74
  this.nack = (channel, queue, options, deadQueueOptions) => (msg, { skipRetry = false, } = {}) => __awaiter(this, void 0, void 0, function* () {
60
75
  if (channel) {
@@ -78,6 +93,7 @@ class RabbitMq {
78
93
  this.creatingConnection = false;
79
94
  this.exchanges = {};
80
95
  this.options = options;
96
+ this.redisClient = redisConfig && redis_1.default(redisConfig);
81
97
  }
82
98
  static parseMsg(msg) {
83
99
  let { content } = msg;
@@ -93,9 +109,10 @@ class RabbitMq {
93
109
  throw new rabbitError_1.default(`error while using ${type} with no name`);
94
110
  }
95
111
  }
96
- static getPublishOptions() {
112
+ static getPublishOptions(customHeaders = {}) {
97
113
  return {
98
- timestamp: moment_1.default().unix() * 1000,
114
+ timestamp: moment_1.default().unix(),
115
+ headers: customHeaders,
99
116
  };
100
117
  }
101
118
  getConnection() {
@@ -200,10 +217,16 @@ class RabbitMq {
200
217
  yield c.assertQueue(queue);
201
218
  yield c.prefetch(limit, true);
202
219
  return Promise.all([
203
- c.consume(queue, (msg) => {
220
+ c.consume(queue, (msg) => __awaiter(this, void 0, void 0, function* () {
221
+ const parsedMessage = RabbitMq.parseMsg(msg);
204
222
  outbreak_1.newTrace(outbreak_1.traceTypes.RABBIT);
205
- callback(RabbitMq.parseMsg(msg), this.ack(channel), this.nack(channel, queue, optionsWithDefaults, { messageTtl: deadMessageTtl }));
206
- }),
223
+ const shouldConsume = yield this.shouldConsumeMessageByTimestamp(parsedMessage);
224
+ if (!shouldConsume) {
225
+ this.ack(channel);
226
+ return;
227
+ }
228
+ callback(parsedMessage, this.ack(channel, true), this.nack(channel, queue, optionsWithDefaults, { messageTtl: deadMessageTtl }));
229
+ })),
207
230
  ]);
208
231
  }));
209
232
  });
@@ -222,22 +245,28 @@ class RabbitMq {
222
245
  yield c.prefetch(limit, true);
223
246
  return Promise.all([
224
247
  c.bindQueue(queue, exchange, ''),
225
- c.consume(queue, (msg) => {
248
+ c.consume(queue, (msg) => __awaiter(this, void 0, void 0, function* () {
249
+ const parsedMessage = RabbitMq.parseMsg(msg);
226
250
  outbreak_1.newTrace(outbreak_1.traceTypes.RABBIT);
227
- callback(RabbitMq.parseMsg(msg), this.ack(channel), this.nack(channel, queue, optionsWithDefaults, { messageTtl: deadMessageTtl }));
228
- }),
251
+ const shouldConsume = yield this.shouldConsumeMessageByTimestamp(parsedMessage);
252
+ if (!shouldConsume) {
253
+ this.ack(channel);
254
+ return;
255
+ }
256
+ callback(parsedMessage, this.ack(channel, true), this.nack(channel, queue, optionsWithDefaults, { messageTtl: deadMessageTtl }));
257
+ })),
229
258
  ]);
230
259
  }));
231
260
  });
232
261
  }
233
- publish(exchange, content) {
262
+ publish(exchange, content, customHeaders) {
234
263
  return __awaiter(this, void 0, void 0, function* () {
235
264
  RabbitMq.validateName('exchange', exchange);
236
265
  const channel = yield this.assertChannel();
237
266
  yield this.assertExchange(exchange);
238
267
  return new bluebird.Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
239
268
  try {
240
- yield channel.publish(exchange, '', Buffer.from(JSON.stringify(content)), RabbitMq.getPublishOptions());
269
+ yield channel.publish(exchange, '', Buffer.from(JSON.stringify(content)), RabbitMq.getPublishOptions(customHeaders));
241
270
  return resolve();
242
271
  }
243
272
  catch (e) {
@@ -246,12 +275,12 @@ class RabbitMq {
246
275
  })).timeout(this.PUBLISH_TIMEOUT, `${this.PUBLISH_ERROR_MSG}${exchange}`);
247
276
  });
248
277
  }
249
- sendToQueue(queue, content, options) {
278
+ sendToQueue(queue, content, options, customHeaders) {
250
279
  return __awaiter(this, void 0, void 0, function* () {
251
280
  RabbitMq.validateName('queue', queue);
252
281
  const channel = yield this.assertChannel();
253
282
  yield this.assertQueue(queue, options);
254
- return channel.sendToQueue(queue, Buffer.from(JSON.stringify(content)), RabbitMq.getPublishOptions());
283
+ return channel.sendToQueue(queue, Buffer.from(JSON.stringify(content)), RabbitMq.getPublishOptions(customHeaders));
255
284
  });
256
285
  }
257
286
  }
@@ -0,0 +1,7 @@
1
+ export declare type RedisConfig = {
2
+ host: string;
3
+ port: number | undefined;
4
+ prefix?: string;
5
+ };
6
+ declare const getRedisInstance: (config: RedisConfig) => any;
7
+ export default getRedisInstance;
package/dist/redis.js ADDED
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const redis_1 = __importDefault(require("redis"));
7
+ const bluebird_1 = __importDefault(require("bluebird"));
8
+ bluebird_1.default.promisifyAll(redis_1.default.RedisClient.prototype);
9
+ bluebird_1.default.promisifyAll(redis_1.default.Multi.prototype);
10
+ const getRedisInstance = (config) => redis_1.default.createClient(config);
11
+ exports.default = getRedisInstance;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/rabbit",
3
- "version": "2.1.0",
3
+ "version": "2.1.2",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -17,10 +17,14 @@
17
17
  "dependencies": {
18
18
  "@types/amqp-connection-manager": "^2.0.10",
19
19
  "@types/amqplib": "^0.5.16",
20
+ "@types/redis": "^2.8.32",
21
+ "@types/uuid": "^8.3.3",
20
22
  "amqp-connection-manager": "^3.2.1",
21
23
  "amqplib": "^0.6.0",
22
24
  "bluebird": "^3.7.2",
23
- "moment": "^2.29.1"
25
+ "moment": "^2.29.1",
26
+ "redis": "^3.1.2",
27
+ "uuid": "^8.3.2"
24
28
  },
25
29
  "devDependencies": {
26
30
  "@autofleet/outbreak": "*",
package/src/index.ts CHANGED
@@ -6,7 +6,9 @@ import { ConfirmChannel, Options } from 'amqplib';
6
6
  import { AmqpConnectionManager, ChannelWrapper, connect } from 'amqp-connection-manager';
7
7
  import { EventEmitter } from 'events';
8
8
  import { newTrace, traceTypes } from '@autofleet/outbreak';
9
+ import { RedisClient } from 'redis';
9
10
  import RabbitError from './rabbitError';
11
+ import getRedisInstance, { RedisConfig } from './redis';
10
12
 
11
13
  export interface IAfRabbitMq {
12
14
  ack: any;
@@ -18,14 +20,19 @@ export interface IAfRabbitMq {
18
20
  consumeFromExchange: any;
19
21
  publish: any;
20
22
  sendToQueue: any;
23
+ redisClient?: any;
21
24
  }
22
25
 
23
26
  interface ExchangesCache {
24
27
  [key: string]: any
25
28
  }
26
29
 
30
+ type CustomMessageHeaders = {
31
+ redisTimestampValidationKey?: string;
32
+ }
33
+
27
34
  export interface AfRabbitOptions {
28
- reconnect: boolean
35
+ reconnect: boolean;
29
36
  }
30
37
 
31
38
  const DEFAULT_DEAD_TTL_TWO_DAYS = 60000 * 60 * 48;
@@ -35,6 +42,7 @@ const defaultOptions = {
35
42
  retries: 1,
36
43
  deadMessageTtl: DEFAULT_DEAD_TTL_TWO_DAYS,
37
44
  };
45
+ const SECONDS_TO_MILLISECONDS = 1000;
38
46
 
39
47
  const assertExchangeFanout = (c: any, exchangeName: string) => c.assertExchange(exchangeName, 'fanout');
40
48
 
@@ -60,9 +68,10 @@ class RabbitMq implements IAfRabbitMq {
60
68
  }
61
69
  }
62
70
 
63
- static getPublishOptions() {
71
+ static getPublishOptions(customHeaders: CustomMessageHeaders = {}) {
64
72
  return {
65
- timestamp: moment().unix() * 1000,
73
+ timestamp: moment().unix(),
74
+ headers: customHeaders,
66
75
  };
67
76
  }
68
77
 
@@ -86,17 +95,34 @@ class RabbitMq implements IAfRabbitMq {
86
95
 
87
96
  options: AfRabbitOptions | undefined;
88
97
 
89
- constructor(options?: AfRabbitOptions) {
98
+ redisClient: any;
99
+
100
+ constructor(options?: AfRabbitOptions, redisConfig?: RedisConfig) {
90
101
  this.em = new EventEmitter();
91
102
  this.channel = null;
92
103
  this.connection = null;
93
104
  this.creatingConnection = false;
94
105
  this.exchanges = {};
95
106
  this.options = options;
107
+ this.redisClient = redisConfig && getRedisInstance(redisConfig);
96
108
  }
97
109
 
98
- public ack = (channel: ChannelWrapper) => async (msg: any) => {
110
+ private shouldConsumeMessageByTimestamp = async (msg: any) => {
111
+ const { properties: { timestamp, headers } } = msg;
112
+ if (timestamp && headers?.redisTimestampValidationKey && this.redisClient) {
113
+ const lastMessageTimestamp = await this.redisClient.getAsync(headers.redisTimestampValidationKey);
114
+ return !lastMessageTimestamp || !moment(parseInt(lastMessageTimestamp, 10) * SECONDS_TO_MILLISECONDS).isAfter(moment(timestamp * SECONDS_TO_MILLISECONDS));
115
+ }
116
+ return true;
117
+ }
118
+
119
+ public ack = (channel: ChannelWrapper, shouldUpdateRedisTimestamp = false) => async (msg: any) => {
99
120
  await channel.ack(msg);
121
+ const { properties: { timestamp, headers } } = msg;
122
+ if (shouldUpdateRedisTimestamp && timestamp && headers?.redisTimestampValidationKey && this.redisClient) {
123
+ const parsedTimestamp = parseInt(timestamp, 10);
124
+ await this.redisClient.setAsync(headers.redisTimestampValidationKey, parsedTimestamp);
125
+ }
100
126
  }
101
127
 
102
128
  public nack = (
@@ -223,9 +249,15 @@ class RabbitMq implements IAfRabbitMq {
223
249
  return Promise.all([
224
250
  c.consume(
225
251
  queue,
226
- (msg: any) => {
252
+ async (msg: any) => {
253
+ const parsedMessage = RabbitMq.parseMsg(msg);
227
254
  newTrace(traceTypes.RABBIT);
228
- callback(RabbitMq.parseMsg(msg), this.ack(channel), this.nack(channel, queue, optionsWithDefaults, { messageTtl: deadMessageTtl }));
255
+ const shouldConsume = await this.shouldConsumeMessageByTimestamp(parsedMessage);
256
+ if (!shouldConsume) {
257
+ this.ack(channel);
258
+ return;
259
+ }
260
+ callback(parsedMessage, this.ack(channel, true), this.nack(channel, queue, optionsWithDefaults, { messageTtl: deadMessageTtl }));
229
261
  },
230
262
  ),
231
263
  ]);
@@ -248,22 +280,30 @@ class RabbitMq implements IAfRabbitMq {
248
280
  c.bindQueue(queue, exchange, ''),
249
281
  c.consume(
250
282
  queue,
251
- (msg: any) => {
283
+ async (msg: any) => {
284
+ const parsedMessage = RabbitMq.parseMsg(msg);
252
285
  newTrace(traceTypes.RABBIT);
253
- callback(RabbitMq.parseMsg(msg), this.ack(channel), this.nack(channel, queue, optionsWithDefaults, { messageTtl: deadMessageTtl }));
286
+ const shouldConsume = await this.shouldConsumeMessageByTimestamp(parsedMessage);
287
+ if (!shouldConsume) {
288
+ this.ack(channel);
289
+ return;
290
+ }
291
+ callback(parsedMessage, this.ack(channel, true), this.nack(channel, queue, optionsWithDefaults, { messageTtl: deadMessageTtl }));
254
292
  },
255
293
  ),
256
294
  ]);
257
295
  });
258
296
  }
259
297
 
260
- async publish(exchange: string, content: any) {
298
+ async publish(exchange: string, content: any, customHeaders?: any) {
261
299
  RabbitMq.validateName('exchange', exchange);
262
300
  const channel: ChannelWrapper = await this.assertChannel();
263
301
  await this.assertExchange(exchange);
264
302
  return new bluebird.Promise(async (resolve, reject) => {
265
303
  try {
266
- await channel.publish(exchange, '', Buffer.from(JSON.stringify(content)), RabbitMq.getPublishOptions());
304
+ await channel.publish(exchange, '',
305
+ Buffer.from(JSON.stringify(content)),
306
+ RabbitMq.getPublishOptions(customHeaders));
267
307
  return resolve();
268
308
  } catch (e) {
269
309
  reject(e);
@@ -271,11 +311,13 @@ class RabbitMq implements IAfRabbitMq {
271
311
  }).timeout(this.PUBLISH_TIMEOUT, `${this.PUBLISH_ERROR_MSG}${exchange}`);
272
312
  }
273
313
 
274
- async sendToQueue(queue: string, content: any, options?: any) {
314
+ async sendToQueue(queue: string, content: any, options?: any, customHeaders?: any) {
275
315
  RabbitMq.validateName('queue', queue);
276
316
  const channel: ChannelWrapper = await this.assertChannel();
277
317
  await this.assertQueue(queue, options);
278
- return channel.sendToQueue(queue, Buffer.from(JSON.stringify(content)), RabbitMq.getPublishOptions());
318
+ return channel.sendToQueue(queue,
319
+ Buffer.from(JSON.stringify(content)),
320
+ RabbitMq.getPublishOptions(customHeaders));
279
321
  }
280
322
  }
281
323
 
package/src/redis.ts ADDED
@@ -0,0 +1,15 @@
1
+ import redis from 'redis';
2
+ import bluebird from 'bluebird';
3
+
4
+ bluebird.promisifyAll(redis.RedisClient.prototype);
5
+ bluebird.promisifyAll(redis.Multi.prototype);
6
+
7
+ export type RedisConfig = {
8
+ host: string;
9
+ port: number | undefined;
10
+ prefix?: string;
11
+ }
12
+
13
+ const getRedisInstance = (config: RedisConfig): any => redis.createClient(config);
14
+
15
+ export default getRedisInstance;