-
Notifications
You must be signed in to change notification settings - Fork 4
/
Amqp.ts
430 lines (375 loc) · 11.7 KB
/
Amqp.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
import { NodeRedApp, Node } from 'node-red'
import { v4 as uuidv4 } from 'uuid'
import cloneDeep = require('lodash.clonedeep')
import {
Connection,
Channel,
Replies,
connect,
ConsumeMessage,
MessageProperties,
} from 'amqplib'
import {
AmqpConfig,
BrokerConfig,
NodeType,
AssembledMessage,
GenericJsonObject,
ExchangeType,
AmqpInNodeDefaults,
AmqpOutNodeDefaults,
} from './types'
import { NODE_STATUS } from './constants'
export default class Amqp {
private config: AmqpConfig
private broker: Node
private connection: Connection
private channel: Channel
private q: Replies.AssertQueue
constructor(
private readonly RED: NodeRedApp,
private readonly node: Node,
config: AmqpInNodeDefaults & AmqpOutNodeDefaults,
) {
this.config = {
name: config.name,
broker: config.broker,
prefetch: config.prefetch,
reconnectOnError: config.reconnectOnError,
noAck: config.noAck,
exchange: {
name: config.exchangeName,
type: config.exchangeType,
routingKey: config.exchangeRoutingKey,
durable: config.exchangeDurable,
},
queue: {
name: config.queueName,
exclusive: config.queueExclusive,
durable: config.queueDurable,
autoDelete: config.queueAutoDelete,
},
amqpProperties: this.parseJson(
config.amqpProperties,
) as MessageProperties,
headers: this.parseJson(config.headers),
outputs: config.outputs,
rpcTimeout: config.rpcTimeoutMilliseconds,
}
}
public async connect(): Promise<Connection> {
const { broker } = this.config
// wtf happened to the types?
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this.broker = this.RED.nodes.getNode(broker)
const brokerUrl = this.getBrokerUrl(this.broker)
this.connection = await connect(brokerUrl, { heartbeat: 2 })
/* istanbul ignore next */
this.connection.on('error', (e): void => {
// Set node to disconnected status
this.node.status(NODE_STATUS.Disconnected)
})
/* istanbul ignore next */
this.connection.on('close', () => {
this.node.status(NODE_STATUS.Disconnected)
this.node.log(`AMQP Connection closed`);
})
return this.connection
}
public async initialize(): Promise<Channel> {
await this.createChannel()
await this.assertExchange()
return this.channel;
}
public async consume(): Promise<void> {
try {
const { noAck } = this.config
await this.assertQueue()
this.bindQueue()
await this.channel.consume(
this.q.queue,
amqpMessage => {
const msg = this.assembleMessage(amqpMessage)
this.node.send(msg)
/* istanbul ignore else */
if (!noAck && !this.isManualAck()) {
this.ack(msg)
}
},
{ noAck },
)
} catch (e) {
this.node.error(`Could not consume message: ${e}`)
}
}
public setRoutingKey(newRoutingKey: string): void {
this.config.exchange.routingKey = newRoutingKey
}
public ack(msg: AssembledMessage): void {
const allUpTo = !!msg.manualAck?.allUpTo
this.channel.ack(msg, allUpTo)
}
public ackAll(): void {
this.channel.ackAll()
}
public nack(msg: AssembledMessage): void {
const allUpTo = !!msg.manualAck?.allUpTo
const requeue = msg.manualAck?.requeue ?? true
this.channel.nack(msg, allUpTo, requeue)
}
public nackAll(msg: AssembledMessage): void {
const requeue = msg.manualAck?.requeue ?? true
this.channel.nackAll(requeue)
}
public reject(msg: AssembledMessage): void {
const requeue = msg.manualAck?.requeue ?? true
this.channel.reject(msg, requeue)
}
public async publish(
msg: unknown,
properties?: MessageProperties,
): Promise<void> {
this.parseRoutingKeys().forEach(async routingKey => {
this.handlePublish(this.config, msg, properties, routingKey)
})
}
private async handlePublish(
config: AmqpConfig,
msg: unknown,
properties?: MessageProperties,
routingKey?: string,
) {
const {
exchange: { name },
outputs: rpcRequested,
} = config
try {
let correlationId = ''
let replyTo = ''
if (rpcRequested) {
// Send request for remote procedure call
correlationId =
properties?.correlationId ||
this.config.amqpProperties?.correlationId ||
uuidv4()
replyTo =
properties?.replyTo || this.config.amqpProperties?.replyTo || uuidv4()
await this.handleRemoteProcedureCall(correlationId, replyTo)
}
const options = {
correlationId,
replyTo,
...this.config.amqpProperties,
...properties,
}
// when the name field is empty, publish just like the sendToQueue method;
// see https://amqp-node.github.io/amqplib/channel_api.html#channel_publish
this.channel.publish(
name,
routingKey,
Buffer.from(msg as string),
options,
)
} catch (e) {
this.node.error(`Could not publish message: ${e}`)
}
}
private getRpcConfig(replyTo: string): AmqpConfig {
const rpcConfig = cloneDeep(this.config)
rpcConfig.exchange.name = ''
rpcConfig.queue.name = replyTo
rpcConfig.queue.autoDelete = true
rpcConfig.queue.exclusive = true
rpcConfig.queue.durable = false
rpcConfig.noAck = true
return rpcConfig
}
private async handleRemoteProcedureCall(
correlationId: string,
replyTo: string,
): Promise<void> {
const rpcConfig = this.getRpcConfig(replyTo)
try {
// If we try to delete a queue that's already deleted
// bad things will happen.
let rpcQueueHasBeenDeleted = false
let additionalErrorMessaging = ''
/************************************
* assert queue and set up consumer
************************************/
const queueName = await this.assertQueue(rpcConfig)
await this.channel.consume(
queueName,
async amqpMessage => {
if (amqpMessage) {
const msg = this.assembleMessage(amqpMessage)
if (msg.properties.correlationId === correlationId) {
this.node.send(msg)
/* istanbul ignore else */
if (!rpcQueueHasBeenDeleted) {
await this.channel.deleteQueue(queueName)
rpcQueueHasBeenDeleted = true
}
} else {
additionalErrorMessaging += ` Correlation ids do not match. Expecting: ${correlationId}, received: ${msg.properties.correlationId}`
}
}
},
{ noAck: rpcConfig.noAck },
)
/****************************************
* Check if RPC has timed out and handle
****************************************/
setTimeout(async () => {
try {
if (!rpcQueueHasBeenDeleted) {
this.node.send({
payload: {
message: `Timeout while waiting for RPC response.${additionalErrorMessaging}`,
config: rpcConfig,
},
})
await this.channel.deleteQueue(queueName)
}
} catch (e) {
// TODO: Keep an eye on this
// This might close the whole channel
this.node.error(`Error trying to cancel RPC consumer: ${e}`)
}
}, rpcConfig.rpcTimeout || 3000)
} catch (e) {
this.node.error(`Could not consume RPC message: ${e}`)
}
}
public async close(): Promise<void> {
const { name: exchangeName } = this.config.exchange
const queueName = this.q?.queue
try {
/* istanbul ignore else */
if (exchangeName && queueName) {
const routingKeys = this.parseRoutingKeys()
try {
for (let x = 0; x < routingKeys.length; x++) {
await this.channel.unbindQueue(
queueName,
exchangeName,
routingKeys[x],
)
}
} catch (e) {
/* istanbul ignore next */
console.error('Error unbinding queue: ', e.message)
}
}
await this.channel.close()
await this.connection.close()
} catch (e) {} // Need to catch here but nothing further is necessary
}
private async createChannel(): Promise<Channel> {
const { prefetch } = this.config
this.channel = await this.connection.createChannel()
this.channel.prefetch(Number(prefetch))
/* istanbul ignore next */
this.channel.on('error', (e): void => {
// Set node to disconnected status
this.node.status(NODE_STATUS.Disconnected)
this.node.error(`AMQP Connection Error ${e}`, { payload: { error: e, source: 'Amqp' } })
})
return this.channel;
}
private async assertExchange(): Promise<void> {
const { name, type, durable } = this.config.exchange
/* istanbul ignore else */
if (name) {
await this.channel.assertExchange(name, type, {
durable,
})
}
}
private async assertQueue(configParams?: AmqpConfig): Promise<string> {
const { queue } = configParams || this.config
const { name, exclusive, durable, autoDelete } = queue
this.q = await this.channel.assertQueue(name, {
exclusive,
durable,
autoDelete,
})
return name
}
private async bindQueue(configParams?: AmqpConfig): Promise<void> {
const { name, type, routingKey } =
configParams?.exchange || this.config.exchange
const { headers } = configParams?.amqpProperties || this.config
if (this.canHaveRoutingKey(type)) {
/* istanbul ignore else */
if (name) {
this.parseRoutingKeys(routingKey).forEach(async routingKey => {
await this.channel.bindQueue(this.q.queue, name, routingKey)
})
}
}
if (type === ExchangeType.Fanout) {
await this.channel.bindQueue(this.q.queue, name, '')
}
if (type === ExchangeType.Headers) {
await this.channel.bindQueue(this.q.queue, name, '', headers)
}
}
private canHaveRoutingKey(type: ExchangeType): boolean {
return type === ExchangeType.Direct || type === ExchangeType.Topic
}
private getBrokerUrl(broker: Node): string {
let url = ''
if (broker) {
const { host, port, vhost, tls, credsFromSettings, credentials } =
broker as unknown as BrokerConfig
const { username, password } = credsFromSettings
? this.getCredsFromSettings()
: credentials
const protocol = tls ? /* istanbul ignore next */ 'amqps' : 'amqp'
url = `${protocol}://${encodeURIComponent(username)}:${encodeURIComponent(
password,
)}@${host}:${port}/${vhost}`
}
return url
}
private getCredsFromSettings(): {
username: string
password: string
} {
return {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
username: this.RED.settings.MW_CONTRIB_AMQP_USERNAME,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
password: this.RED.settings.MW_CONTRIB_AMQP_PASSWORD,
}
}
private parseRoutingKeys(routingKeyArg?: string): string[] {
const routingKey =
routingKeyArg || this.config.exchange.routingKey || this.q?.queue || ''
const keys = routingKey?.split(',').map(key => key.trim())
return keys
}
private assembleMessage(amqpMessage: ConsumeMessage): AssembledMessage {
const payload = this.parseJson(amqpMessage.content.toString())
return {
...amqpMessage,
payload,
}
}
private isManualAck(): boolean {
return this.node.type === NodeType.AmqpInManualAck
}
private parseJson(jsonInput: unknown): GenericJsonObject {
let output: unknown
try {
output = JSON.parse(jsonInput as string)
} catch {
output = jsonInput
}
return output
}
}