-
Notifications
You must be signed in to change notification settings - Fork 39
/
rmq.service.ts
345 lines (317 loc) · 10.6 KB
/
rmq.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import { Inject, Injectable, LoggerService, OnModuleInit } from '@nestjs/common';
import {
CONNECT_EVENT,
CONNECTED_MESSAGE,
DEFAULT_PREFETCH_COUNT,
DEFAULT_RECONNECT_TIME,
DEFAULT_TIMEOUT,
DISCONNECT_EVENT,
DISCONNECT_MESSAGE,
ERROR_NO_ROUTE,
ERROR_NONE_RPC,
ERROR_TIMEOUT,
ERROR_TYPE,
REPLY_QUEUE,
DEFAULT_HEARTBEAT_TIME,
RMQ_MODULE_OPTIONS,
INITIALIZATION_STEP_DELAY,
ERROR_NO_QUEUE,
RMQ_PROTOCOL,
CONNECT_FAILED_MESSAGE,
WRONG_CREDENTIALS_MESSAGE,
CONNECT_FAILED,
} from './constants';
import { EventEmitter } from 'events';
import { Channel, Message } from 'amqplib';
import * as amqp from 'amqp-connection-manager';
// tslint:disable-next-line:no-duplicate-imports
import { AmqpConnectionManager, ChannelWrapper } from 'amqp-connection-manager';
import { IRMQConnection, IRMQServiceOptions } from './interfaces/rmq-options.interface';
import { requestEmitter, responseEmitter, ResponseEmitterResult } from './emmiters/router.emmiter';
import { IPublishOptions } from './interfaces/rmq-publish-options.interface';
import { RMQError } from './classes/rmq-error.class';
import { RQMColorLogger } from './helpers/logger';
import { validateOptions } from './option.validator';
import { RMQMetadataAccessor } from './rmq-metadata.accessor';
import { RmqErrorService } from './rmq-error.service';
import { getUniqId } from './utils/get-uniq-id';
import { IRMQService } from './interfaces/rmq-service.interface';
@Injectable()
export class RMQService implements OnModuleInit, IRMQService {
private server: AmqpConnectionManager = null;
private clientChannel: ChannelWrapper = null;
private subscriptionChannel: ChannelWrapper = null;
private options: IRMQServiceOptions;
private sendResponseEmitter: EventEmitter = new EventEmitter();
private replyQueue: string = REPLY_QUEUE;
private routes: string[];
private logger: LoggerService;
private isConnected = false;
private isInitialized = false;
constructor(
@Inject(RMQ_MODULE_OPTIONS) options: IRMQServiceOptions,
private readonly metadataAccessor: RMQMetadataAccessor,
private readonly errorService: RmqErrorService
) {
this.options = options;
this.logger = options.logger ? options.logger : new RQMColorLogger(this.options.logMessages);
validateOptions(this.options, this.logger);
}
async onModuleInit() {
await this.init();
this.isInitialized = true;
}
public async init(): Promise<void> {
return new Promise(async (resolve, reject) => {
const connectionURLs: string[] = this.options.connections.map((connection: IRMQConnection) => {
return this.createConnectionUri(connection);
});
const AMQPConnectionOptions: amqp.AmqpConnectionManagerOptions = {
reconnectTimeInSeconds: this.options.reconnectTimeInSeconds ?? DEFAULT_RECONNECT_TIME,
heartbeatIntervalInSeconds: this.options.heartbeatIntervalInSeconds ?? DEFAULT_HEARTBEAT_TIME,
connectionOptions: this.options.connectionOptions ?? {},
};
this.server = amqp.connect(connectionURLs, AMQPConnectionOptions);
this.server.on(CONNECT_EVENT, (connection) => {
this.isConnected = true;
this.attachEmitters();
});
this.server.on(DISCONNECT_EVENT, (err) => {
this.isConnected = false;
this.detachEmitters();
this.logger.error(DISCONNECT_MESSAGE);
this.logger.error(err.err);
});
this.server.on(CONNECT_FAILED, (err) => {
this.logger.error(CONNECT_FAILED_MESSAGE);
this.logger.error(err.err);
if (err.err.message.includes('ACCESS-REFUSED') || err.err.message.includes('403')) {
this.logger.error(WRONG_CREDENTIALS_MESSAGE);
reject(err);
}
});
await Promise.all([this.createClientChannel(), this.createSubscriptionChannel()]);
resolve();
});
}
public ack(...params: Parameters<Channel['ack']>): ReturnType<Channel['ack']> {
return this.subscriptionChannel.ack(...params);
}
public nack(...params: Parameters<Channel['nack']>): ReturnType<Channel['nack']> {
return this.subscriptionChannel.nack(...params);
}
public async send<IMessage, IReply>(topic: string, message: IMessage, options?: IPublishOptions): Promise<IReply> {
return new Promise<IReply>(async (resolve, reject) => {
await this.initializationCheck();
const correlationId = getUniqId();
const timeout = options?.timeout ?? this.options.messagesTimeout ?? DEFAULT_TIMEOUT;
const timerId = setTimeout(() => {
reject(new RMQError(`${ERROR_TIMEOUT}: ${timeout} while sending to ${topic}`, ERROR_TYPE.TRANSPORT));
}, timeout);
this.sendResponseEmitter.once(correlationId, (msg: Message) => {
clearTimeout(timerId);
if (msg.properties?.headers?.['-x-error']) {
reject(this.errorService.errorHandler(msg));
}
const { content } = msg;
if (content.toString()) {
this.logger.debug(content, `Received ▼,${topic}`);
resolve(JSON.parse(content.toString()));
} else {
reject(new RMQError(ERROR_NONE_RPC, ERROR_TYPE.TRANSPORT));
}
});
await this.clientChannel.publish(this.options.exchangeName, topic, Buffer.from(JSON.stringify(message)), {
replyTo: this.replyQueue,
appId: this.options.serviceName,
timestamp: new Date().getTime(),
correlationId,
...options,
});
this.logger.debug(message, `Sent ▲,${topic}`);
});
}
public async notify<IMessage>(topic: string, message: IMessage, options?: IPublishOptions): Promise<void> {
await this.initializationCheck();
await this.clientChannel.publish(this.options.exchangeName, topic, Buffer.from(JSON.stringify(message)), {
appId: this.options.serviceName,
timestamp: new Date().getTime(),
...options,
});
this.logger.debug(message, `Notify ▲,${topic}`);
}
public healthCheck() {
return this.isConnected;
}
public async disconnect() {
this.detachEmitters();
this.sendResponseEmitter.removeAllListeners();
await this.clientChannel.close();
await this.subscriptionChannel.close();
await this.server.close();
}
private createConnectionUri(connection: IRMQConnection): string {
let uri = `${connection.protocol ?? RMQ_PROTOCOL.AMQP}://${connection.login}:${connection.password}@${
connection.host
}`;
if (connection.port) {
uri += `:${connection.port}`;
}
if (connection.vhost) {
uri += `/${connection.vhost}`;
}
return uri;
}
private async createSubscriptionChannel() {
return new Promise<void>((resolve) => {
this.subscriptionChannel = this.server.createChannel({
json: false,
setup: async (channel: Channel) => {
await channel.assertExchange(
this.options.exchangeName,
this.options.assertExchangeType ? this.options.assertExchangeType : 'topic',
{
durable: this.options.isExchangeDurable ?? true,
...this.options.exchangeOptions,
}
);
await channel.prefetch(
this.options.prefetchCount ?? DEFAULT_PREFETCH_COUNT,
this.options.isGlobalPrefetchCount ?? false
);
if (typeof this.options.queueName === 'string') {
this.listen(channel);
}
this.logConnected();
resolve();
},
});
});
}
private async createClientChannel() {
return new Promise<void>((resolve) => {
this.clientChannel = this.server.createChannel({
json: false,
setup: async (channel: Channel) => {
await channel.consume(
this.replyQueue,
(msg: Message) => {
this.sendResponseEmitter.emit(msg.properties.correlationId, msg);
},
{
noAck: true,
}
);
resolve();
},
});
});
}
private async listen(channel: Channel) {
const queue = await channel.assertQueue(this.options.queueName, {
durable: this.options.isQueueDurable ?? true,
arguments: this.options.queueArguments ?? {},
...this.options.queueOptions,
});
this.options.queueName = queue.queue;
this.routes = this.metadataAccessor.getAllRMQPaths();
if (this.options.autoBindingRoutes ?? true) {
await this.bindRMQRoutes(channel);
}
await channel.consume(
this.options.queueName,
async (msg: Message) => {
this.logger.debug(msg.content, `Received ▼,${msg.fields.routingKey}`);
const route = this.getRouteByTopic(msg.fields.routingKey);
if (route) {
msg = await this.useMiddleware(msg);
requestEmitter.emit(route, msg);
} else {
this.reply('', msg, new RMQError(ERROR_NO_ROUTE, ERROR_TYPE.TRANSPORT));
this.ack(msg);
}
},
{ noAck: false }
);
}
private async bindRMQRoutes(channel: Channel): Promise<void> {
if (this.routes.length > 0) {
this.routes.map(async (r) => {
this.logger.log(`Mapped ${r}`, 'RMQRoute');
await channel.bindQueue(this.options.queueName, this.options.exchangeName, r);
});
}
}
private detachEmitters(): void {
responseEmitter.removeAllListeners();
}
private attachEmitters(): void {
responseEmitter.on(ResponseEmitterResult.success, async (msg, result) => {
this.reply(result, msg);
});
responseEmitter.on(ResponseEmitterResult.error, async (msg, err) => {
this.reply('', msg, err);
});
responseEmitter.on(ResponseEmitterResult.ack, async (msg) => {
this.ack(msg);
});
}
private async reply(res: any, msg: Message, error: Error | RMQError = null) {
try {
res = await this.intercept(res, msg, error);
} catch (e) {
error = e
}
await this.subscriptionChannel.sendToQueue(msg.properties.replyTo, Buffer.from(JSON.stringify(res)), {
correlationId: msg.properties.correlationId,
headers: {
...this.errorService.buildError(error),
},
});
this.logger.debug(res, `Sent ▲,${msg.fields.routingKey}`);
}
private getRouteByTopic(topic: string): string {
return this.routes.find((route) => {
if (route === topic) {
return true;
}
const regexString = '^' + route.replace(/\*/g, '([^.]+)').replace(/#/g, '([^.]+.?)+') + '$';
return topic.search(regexString) !== -1;
});
}
private async useMiddleware(msg: Message) {
if (!this.options.middleware || this.options.middleware.length === 0) {
return msg;
}
for (const middleware of this.options.middleware) {
msg = await new middleware(this.logger).transform(msg);
}
return msg;
}
private async intercept(res: any, msg: Message, error?: Error) {
if (!this.options.intercepters || this.options.intercepters.length === 0) {
return res;
}
for (const intercepter of this.options.intercepters) {
res = await new intercepter(this.logger).intercept(res, msg, error);
}
return res;
}
private async initializationCheck() {
if (this.isInitialized) {
return;
}
await new Promise<void>((resolve) => {
setTimeout(() => {
resolve();
}, INITIALIZATION_STEP_DELAY);
});
await this.initializationCheck();
}
private logConnected() {
this.logger.log(CONNECTED_MESSAGE, 'RMQModule');
if (!this.options.queueName && this.metadataAccessor.getAllRMQPaths().length > 0) {
this.logger.warn(ERROR_NO_QUEUE, 'RMQModule');
}
}
}