-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
AmqpBridge.impl.ts
873 lines (767 loc) · 29.1 KB
/
AmqpBridge.impl.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
import { SpanKind, SpanStatusCode, trace } from '@opentelemetry/api'
import type {
Command,
CommandDefinitionMetadataBase,
CommandErrorResponse,
CommandSuccessResponse,
CustomMessage,
DefinitionEventBridgeConfig,
EBMessage,
EBMessageAddress,
EBMessageId,
EventBridge,
EventBridgeConfig,
PendigInvocation,
Subscription,
} from '@purista/core'
import {
createInfoMessage,
deserializeOtp,
EBMessageType,
EventBridgeBaseClass,
EventBridgeEventNames,
getCleanedMessage,
getNewCorrelationId,
getNewEBMessageId,
HandledError,
isCommandErrorResponse,
isCommandResponse,
isCommandSuccessResponse,
isInfoMessage,
PuristaSpanName,
PuristaSpanTag,
serializeOtp,
StatusCode,
UnhandledError,
} from '@purista/core'
import type { Channel, Connection } from 'amqplib'
import amqplib from 'amqplib'
import { deserializeOtpFromAmqpHeader } from './deserializeOtpFromAmqpHeader.impl.js'
import { getCommandQueueName } from './getCommandQueueName.impl.js'
import { getDefaultConfig } from './getDefaultConfig.impl.js'
import { getSubscriptionQueueName } from './getSubscriptionQueueName.impl.js'
import { jsonEncoder, plainEncrypter } from './payloadHandling/index.js'
import { serializeOtpForAmqpHeader } from './serializeOtpForAmqpHeader.impl.js'
import type { AmqpBridgeConfig, Encoder, Encrypter } from './types/index.js'
/**
* The AMQP event bridge connects to a AMQP broker.
*
* @example
* ```typescript
* import { AmqpBridge } from '@purista/amqpbridge'
*
* // create and init our eventbridge
* const config = {
* url: 'amqp://localhost'
* }
*
* const eventBridge = new AmqpBridge(config)
* await eventBridge.start()
*
* ```
*
* @group Event bridge
*/
export class AmqpBridge extends EventBridgeBaseClass<AmqpBridgeConfig> implements EventBridge {
protected connection?: Connection
protected channel?: Channel
protected healthy = false
protected ready = false
protected consumerTags: string[] = []
protected replyQueueName?: string
protected serviceFunctions = new Map<
string,
{
cb: (message: Command) => Promise<CommandSuccessResponse | CommandErrorResponse>
channel: Channel
}
>()
protected pendingInvocations = new Map<EBMessageId, PendigInvocation>()
protected runningSubscriptionCount = 0
protected subscriptions = new Map<
string,
{
cb: (message: CustomMessage) => Promise<Omit<CustomMessage, 'id' | 'timestamp'> | undefined>
channel: Channel
}
>()
protected encoder: Encoder = {
...jsonEncoder,
}
protected encrypter: Encrypter = {
...plainEncrypter,
}
constructor(config?: EventBridgeConfig<AmqpBridgeConfig>) {
//= getDefaultConfig()
const conf = {
...getDefaultConfig(),
...config,
}
super('AmqpBridge', conf)
this.encoder = {
...this.encoder,
...this.config.encoder,
}
this.encrypter = {
...this.encrypter,
...this.config.encrypter,
}
}
async isReady() {
return this.ready
}
async isHealthy() {
return this.healthy
}
/**
* Connect to RabbitMQ broker, ensure exchange, call back queue
*/
async start() {
await super.start()
try {
this.connection = await amqplib.connect(this.config.url ?? getDefaultConfig().url, this.config.socketOptions)
} catch (err) {
this.emit(EventBridgeEventNames.EventbridgeConnectionError, err)
this.logger.fatal({ err }, 'unable to connect to broker')
throw err
}
this.connection.on('error', (err) => {
this.healthy = false
this.logger.error({ err }, 'amqp lib error')
this.emit(EventBridgeEventNames.EventbridgeError, err)
})
this.connection.on('close', () => {
this.healthy = false
this.ready = false
this.emit(EventBridgeEventNames.EventbridgeDisconnected)
this.logger.info('amqp connection disconnected')
})
this.emit(EventBridgeEventNames.EventbridgeConnected)
this.logger.info('connected to broker')
this.channel = await this.connection.createChannel()
this.channel.on('close', () => {
this.healthy = false
this.ready = false
this.logger.info('channel closed')
this.emit(EventBridgeEventNames.EventbridgeDisconnected)
})
this.channel.on('error', (err) => {
this.healthy = false
this.logger.error({ err }, 'amqp channel error')
this.emit(EventBridgeEventNames.EventbridgeError, err)
})
this.logger.debug('ensured: default exchange')
await this.channel.assertExchange(
this.config.exchangeName ?? getDefaultConfig().exchangeName,
'headers',
this.config.exchangeOptions,
)
const responseQueue = await this.channel.assertQueue('', { exclusive: true, autoDelete: true, durable: false })
this.replyQueueName = responseQueue.queue
await this.channel.bindQueue(this.replyQueueName, this.config.exchangeName ?? getDefaultConfig().exchangeName, '', {
'x-match': 'all',
replyTo: this.replyQueueName,
})
const consume = await this.channel.consume(
this.replyQueueName,
async (msg) => {
if (!msg) {
return
}
const context = await deserializeOtpFromAmqpHeader(this.logger, msg, this.encrypter, this.encoder)
return this.startActiveSpan(
PuristaSpanName.EventBridgeCommandResponseReceived,
{ kind: SpanKind.CONSUMER },
context,
async (span) => {
try {
const message = await this.decodeContent<EBMessage>(
msg.content,
msg.properties.contentType,
msg.properties.contentEncoding,
)
if (message.eventName) {
span.addEvent(message.eventName)
}
const log = this.logger.getChildLogger({ customTraceId: message.traceId, ...span.spanContext() })
if (isCommandResponse(message)) {
const mapEntry = this.pendingInvocations.get(message.correlationId)
if (!mapEntry) {
const err = new UnhandledError(
StatusCode.BadRequest,
'InvalidCommandResponse: received invalid command response',
getCleanedMessage(message),
)
span.setStatus({
code: SpanStatusCode.ERROR,
message: err.message,
})
span.recordException(err)
log.error({ err }, 'received invalid command response')
this.emit(EventBridgeEventNames.EventbridgeError, err)
return
}
if (isCommandSuccessResponse(message)) {
mapEntry.resolve(message.payload)
} else if (isCommandErrorResponse(message)) {
const error = message.isHandledError
? HandledError.fromMessage(message)
: UnhandledError.fromMessage(message)
span.recordException(error)
log.error({ err: error }, error.message)
mapEntry.reject(error)
}
return
}
if (isInfoMessage(message)) {
log.trace('info message', message)
return
}
const err = new UnhandledError(StatusCode.BadRequest, 'InvalidMessage: received invalid message', message)
span.setStatus({
code: SpanStatusCode.ERROR,
message: err.message,
})
span.recordException(err)
log.error({ err }, 'received invalid message')
this.emit(EventBridgeEventNames.EventbridgeError, err)
} catch (error) {
const err = new HandledError(StatusCode.InternalServerError, 'failed to handle response message', error)
span.setStatus({
code: SpanStatusCode.ERROR,
message: err.message,
})
span.recordException(err)
this.emit(EventBridgeEventNames.EventbridgeError, err)
this.logger.error({ err, ...span.spanContext() }, 'failed to handle response message')
}
},
)
},
{ noAck: true },
)
this.consumerTags.push(consume.consumerTag)
this.healthy = true
this.ready = true
this.logger.debug('ensured: response queue')
this.logger.info('amqp event bridge ready')
}
async emitMessage<T extends EBMessage>(
message: Omit<EBMessage, 'id' | 'timestamp' | 'correlationId'>,
contentType = 'application/json',
contentEncoding = 'utf-8',
): Promise<Readonly<EBMessage>> {
const context = deserializeOtp(this.logger, message.otp)
const name = isCommandResponse(message as EBMessage)
? PuristaSpanName.EventBridgeCommandResponseSent
: PuristaSpanName.EventBridgeEmitMessage
return this.startActiveSpan(name, { kind: SpanKind.PRODUCER }, context, async (span) => {
if (!this.channel) {
const err = new UnhandledError(
StatusCode.InternalServerError,
'emit message: failed No channel - not connected',
)
span.setStatus({
code: SpanStatusCode.ERROR,
message: err.message,
})
span.recordException(err)
this.logger.error({ err, ...span.spanContext() }, err.message)
throw err
}
const msg = Object.freeze({
...message,
id: getNewEBMessageId(),
timestamp: Date.now(),
traceId: message.traceId,
otp: serializeOtp(),
sender: {
...message.sender,
instanceId: this.instanceId,
},
})
span.setAttribute(PuristaSpanTag.SenderServiceName, msg.sender.serviceName)
span.setAttribute(PuristaSpanTag.SenderServiceVersion, msg.sender.serviceVersion)
span.setAttribute(PuristaSpanTag.SenderServiceTarget, msg.sender.serviceTarget)
if (msg.eventName) {
span.addEvent(msg.eventName)
}
const headers: Record<string, string | undefined> = {
messageType: msg.messageType,
senderServiceName: msg.sender.serviceName,
senderServiceVersion: msg.sender.serviceVersion,
senderServiceTarget: msg.sender.serviceTarget,
senderInstanceId: msg.sender.instanceId,
eventName: msg.eventName,
principalId: msg.principalId,
tenantId: msg.tenantId,
}
serializeOtpForAmqpHeader(headers)
const payload = await this.encodeContent(msg, contentType, contentEncoding)
await this.channel.publish(this.config.exchangeName ?? getDefaultConfig().exchangeName, '', payload, {
messageId: msg.id,
timestamp: msg.timestamp,
contentType,
contentEncoding,
type: msg.messageType,
headers,
persistent: true,
})
return msg as Readonly<T>
})
}
async invoke<T>(
input: Omit<Command, 'id' | 'messageType' | 'timestamp' | 'correlationId'>,
commandTimeout: number = this.defaultCommandTimeout,
): Promise<T> {
const context = deserializeOtp(this.logger, input.otp)
return this.startActiveSpan(
PuristaSpanName.EventBridgeInvokeCommand,
{ kind: SpanKind.PRODUCER },
context,
async (span) => {
if (!this.channel) {
const err = new UnhandledError(StatusCode.InternalServerError, 'invoke failed: No channel - not connected')
span.setStatus({
code: SpanStatusCode.ERROR,
message: err.message,
})
span.recordException(err)
this.logger.error({ err, ...span.spanContext() }, err.message)
throw err
}
const correlationId = getNewCorrelationId()
const command: Command = Object.freeze({
...input,
id: getNewEBMessageId(),
correlationId,
timestamp: Date.now(),
messageType: EBMessageType.Command,
traceId: input.traceId,
otp: serializeOtp(),
sender: {
...input.sender,
instanceId: this.instanceId,
},
})
const removeFromPending = () => {
this.pendingInvocations.delete(correlationId)
}
const executionPromise = new Promise<T>((resolve, reject) => {
const timeout = setTimeout(() => {
const err = new UnhandledError(
StatusCode.GatewayTimeout,
'invocation timed out',
undefined,
command.traceId,
)
this.logger.warn({ err })
rejectFn(err)
}, commandTimeout)
const resolveFn = (successPayload: T) => {
clearTimeout(timeout)
removeFromPending()
resolve(successPayload)
}
const rejectFn = (err: unknown) => {
clearTimeout(timeout)
removeFromPending()
reject(err)
}
this.pendingInvocations.set(command.correlationId, {
resolve: resolveFn,
reject: rejectFn,
})
})
span.setAttribute(PuristaSpanTag.SenderServiceName, command.sender.serviceName)
span.setAttribute(PuristaSpanTag.SenderServiceVersion, command.sender.serviceVersion)
span.setAttribute(PuristaSpanTag.SenderServiceTarget, command.sender.serviceTarget)
span.setAttribute(PuristaSpanTag.ReceiverServiceName, command.receiver.serviceName)
span.setAttribute(PuristaSpanTag.ReceiverServiceVersion, command.receiver.serviceVersion)
span.setAttribute(PuristaSpanTag.ReceiverServiceTarget, command.receiver.serviceTarget)
const headers: Record<string, string | undefined> = {
messageType: command.messageType,
senderServiceName: command.sender.serviceName,
senderServiceVersion: command.sender.serviceVersion,
senderServiceTarget: command.sender.serviceTarget,
senderInstanceId: command.sender.instanceId,
receiverServiceName: command.receiver.serviceName,
receiverServiceVersion: command.receiver.serviceVersion,
receiverServiceTarget: command.receiver.serviceTarget,
eventName: command.eventName,
principalId: command.principalId,
tenantId: command.tenantId,
}
serializeOtpForAmqpHeader(headers)
const content = await this.encodeContent(command, 'application/json', 'utf-8')
this.channel.publish(this.config.exchangeName ?? getDefaultConfig().exchangeName, '', content, {
messageId: command.id,
timestamp: command.timestamp,
correlationId: command.correlationId,
contentType: 'application/json',
contentEncoding: 'utf-8',
type: command.messageType,
headers,
replyTo: this.replyQueueName,
persistent: true,
})
return executionPromise
},
)
}
/**
* Register a service function and ensure that there is a queue for all incoming command requests.
* @param address The service function address
* @param cb the function to call if a matching command message arrives
* @returns the id of command function queue
*/
async registerCommand(
address: EBMessageAddress,
cb: (message: Command) => Promise<CommandSuccessResponse | CommandErrorResponse>,
metadata: CommandDefinitionMetadataBase,
eventBridgeConfig: DefinitionEventBridgeConfig,
): Promise<string> {
if (!this.connection) {
throw new Error('No connection - not connected')
}
const queueName = getCommandQueueName(address, this.config.namePrefix)
const channel = await this.connection.createChannel()
const noAck = eventBridgeConfig.autoacknowledge ?? true
channel.on('close', () => {
this.healthy = false
this.logger.info({ queueName }, 'channel for command closed')
this.emit(EventBridgeEventNames.EventbridgeDisconnected)
})
channel.on('error', (err) => {
this.healthy = false
this.logger.error({ err, queueName }, 'command channel error')
this.emit(EventBridgeEventNames.EventbridgeError, err)
})
const queue = await channel.assertQueue(queueName, { durable: !!eventBridgeConfig.durable, autoDelete: true })
await channel.bindQueue(queue.queue, this.config.exchangeName ?? getDefaultConfig().exchangeName, '', {
'x-match': 'all',
messageType: EBMessageType.Command,
receiverServiceName: address.serviceName,
receiverServiceVersion: address.serviceVersion,
receiverServiceTarget: address.serviceTarget,
})
const consume = await channel.consume(
queue.queue,
async (msg) => {
const context = await deserializeOtpFromAmqpHeader(this.logger, msg, this.encrypter, this.encoder)
return this.startActiveSpan(
PuristaSpanName.EventBridgeCommandReceived,
{ kind: SpanKind.CONSUMER },
context,
async (span) => {
if (!msg) {
return
}
try {
const command = await this.decodeContent<Command>(
msg.content,
msg.properties.contentType,
msg.properties.contentEncoding,
)
command.otp = serializeOtp()
const result = await cb(command)
const returnContext = deserializeOtp(this.logger, result.otp)
return this.startActiveSpan(
PuristaSpanName.EventBridgeCommandResponseSent,
{ kind: SpanKind.PRODUCER },
returnContext,
async (subSpan) => {
const responseMessage = {
...result,
otp: serializeOtp(),
sennder: {
...result.sender,
instanceId: this.instanceId,
},
}
subSpan.setAttribute(PuristaSpanTag.SenderServiceName, responseMessage.sender.serviceName)
subSpan.setAttribute(PuristaSpanTag.SenderServiceVersion, responseMessage.sender.serviceVersion)
subSpan.setAttribute(PuristaSpanTag.SenderServiceTarget, responseMessage.sender.serviceTarget)
if (responseMessage.eventName) {
subSpan.addEvent(responseMessage.eventName)
}
const headers: Record<string, string | undefined> = {
messageType: responseMessage.messageType,
senderServiceName: responseMessage.sender.serviceName,
senderServiceVersion: responseMessage.sender.serviceVersion,
senderServiceTarget: responseMessage.sender.serviceTarget,
senderInstanceId: responseMessage.sender.instanceId,
receiverServiceName: responseMessage.receiver.serviceName,
receiverServiceVersion: responseMessage.receiver.serviceVersion,
receiverServiceTarget: responseMessage.receiver.serviceTarget,
receiverServiceInstanceId: responseMessage.receiver.instanceId,
replyTo: msg.properties.replyTo,
eventName: responseMessage.eventName,
principalId: responseMessage.principalId,
tenantId: responseMessage.tenantId,
}
serializeOtpForAmqpHeader(headers)
const contentType = 'application/json'
const contentEncoding = 'utf-8'
const payload = await this.encodeContent(responseMessage, contentType, contentEncoding)
this.channel?.publish(this.config.exchangeName ?? getDefaultConfig().exchangeName, '', payload, {
messageId: responseMessage.id,
timestamp: responseMessage.timestamp,
correlationId: msg.properties.correlationId,
contentType,
contentEncoding,
type: responseMessage.messageType,
headers,
persistent: true,
})
if (!noAck) {
channel.ack(msg)
}
},
)
} catch (error) {
const err = new UnhandledError(
StatusCode.InternalServerError,
'Failed to consume command response message',
{
error,
},
)
span.setStatus({
code: SpanStatusCode.ERROR,
message: err.message,
})
span.recordException(err)
this.emit(EventBridgeEventNames.EventbridgeError, err)
this.logger.error({ err }, 'Failed to consume command response message')
if (!noAck) {
channel.nack(msg)
}
}
},
)
},
{ noAck },
)
this.consumerTags.push(consume.consumerTag)
this.serviceFunctions.set(queueName, { cb, channel })
const info = createInfoMessage(
EBMessageType.InfoServiceFunctionAdded,
{ ...address, instanceId: this.instanceId },
{
payload: metadata,
},
)
await this.emitMessage(info)
return queueName
}
async unregisterCommand(address: EBMessageAddress): Promise<void> {
try {
const queueName = getCommandQueueName(address)
const entry = this.serviceFunctions.get(queueName)
if (!entry) {
return
}
await entry.channel.close()
this.serviceFunctions.delete(queueName)
} catch (error) {
const err = new UnhandledError(StatusCode.InternalServerError, 'Failed to unregister service function', {
error,
address,
})
this.emit(EventBridgeEventNames.EventbridgeError, err)
this.logger.error({ err }, 'Failed to unregister service function')
}
}
async registerSubscription(
subscription: Subscription,
cb: (message: EBMessage) => Promise<Omit<CustomMessage, 'id' | 'timestamp'> | undefined>,
): Promise<string> {
if (!this.connection) {
throw new Error('No connection - not connected')
}
const noAck = !!subscription.eventBridgeConfig.autoacknowledge
const isShared = subscription.eventBridgeConfig.shared === undefined || subscription.eventBridgeConfig.shared
const queueName = isShared ? getSubscriptionQueueName(subscription.subscriber, this.config.namePrefix) : ''
const queueOptions: amqplib.Options.AssertQueue = isShared
? {
durable: subscription.eventBridgeConfig.durable,
}
: { exclusive: true, autoDelete: true, durable: false }
const channel = await this.connection.createChannel()
channel.on('close', () => {
this.healthy = false
this.logger.info({ queueName }, 'channel for subscription closed')
this.emit(EventBridgeEventNames.EventbridgeDisconnected)
})
channel.on('error', (err) => {
this.healthy = false
this.logger.error({ err, queueName }, 'subscription channel error')
this.emit(EventBridgeEventNames.EventbridgeError, err)
})
const queue = await channel.assertQueue(queueName, queueOptions)
await channel.bindQueue(queue.queue, this.config.exchangeName ?? getDefaultConfig().exchangeName, '', {
'x-match': 'all',
messageType: subscription.messageType,
senderServiceName: subscription.sender?.serviceName,
senderServiceVersion: subscription.sender?.serviceVersion,
senderServiceTarget: subscription.sender?.serviceTarget,
senderInstanceId: subscription.sender?.instanceId,
receiverServiceName: subscription.receiver?.serviceName,
receiverServiceVersion: subscription.receiver?.serviceVersion,
receiverServiceTarget: subscription.receiver?.serviceTarget,
receiverInstanceId: subscription.receiver?.instanceId,
eventName: subscription.eventName,
principalId: subscription.principalId,
tenantId: subscription.tenantId,
})
const consume = await channel.consume(
queue.queue,
async (msg) => {
const context = await deserializeOtpFromAmqpHeader(this.logger, msg, this.encrypter, this.encoder)
const spanContext = context ? trace.getSpanContext(context) : undefined
this.startActiveSpan(
PuristaSpanName.EventBridgeSubscriptionEventReceived,
{ kind: SpanKind.CONSUMER, links: spanContext ? [{ context: spanContext }] : [] },
context,
async (span) => {
if (!msg) {
return
}
this.runningSubscriptionCount++
try {
const message = await this.decodeContent<EBMessage>(
msg.content,
msg.properties.contentType,
msg.properties.contentEncoding,
)
span.setAttribute(PuristaSpanTag.SenderServiceName, message.sender.serviceName)
span.setAttribute(PuristaSpanTag.SenderServiceVersion, message.sender.serviceVersion)
span.setAttribute(PuristaSpanTag.SenderServiceTarget, message.sender.serviceTarget)
if (message.eventName) {
span.addEvent(message.eventName)
}
message.otp = serializeOtp()
const result = await cb(message)
if (subscription.emitEventName && result) {
await this.emitMessage(result)
}
if (!noAck) {
channel.ack(msg)
}
this.runningSubscriptionCount--
} catch (error) {
this.runningSubscriptionCount--
const err = new UnhandledError(StatusCode.InternalServerError, 'Failed to consume subscription message', {
error,
subscription,
})
span.setStatus({
code: SpanStatusCode.ERROR,
message: err.message,
})
span.recordException(err)
this.emit(EventBridgeEventNames.EventbridgeError, err)
this.logger.error({ err }, 'Failed to consume subscription message')
if (!noAck) {
channel.nack(msg)
}
}
},
)
},
{ noAck },
)
this.consumerTags.push(consume.consumerTag)
this.subscriptions.set(queueName, { cb, channel })
return queueName
}
async unregisterSubscription(address: EBMessageAddress): Promise<void> {
try {
const queueName = getSubscriptionQueueName(address)
const entry = this.subscriptions.get(queueName)
if (!entry) {
return
}
await entry.channel.close()
this.subscriptions.delete(queueName)
} catch (error) {
const err = new UnhandledError(StatusCode.InternalServerError, 'Failed to unregister subscription', {
error,
address,
})
this.emit(EventBridgeEventNames.EventbridgeError, err)
this.logger.error({ err }, 'Failed to unregister subscription')
}
}
/**
* Encode given payload to buffer
* @param input
* @param contentType
* @param contentEncoding
* @returns
*/
protected async encodeContent<T>(input: T, contentType: string, contentEncoding: string): Promise<Buffer> {
const encoder = this.encoder[contentType]
if (!encoder) {
throw new Error(`Encode not defined for ${contentType}`)
}
const encodedPayload = await encoder.encode(input)
const encrypter = this.encrypter[contentEncoding]
if (!encrypter) {
throw new Error(`Encrypt not defined for ${contentEncoding}`)
}
return encrypter.encrypt(encodedPayload)
}
/**
* Decode buffer into given type
* @param input the input buffer
* @param contentType the content type of buffer content
* @param contentEncoding the encoding type of buffer content
* @returns
*/
protected async decodeContent<T>(input: Buffer, contentType: string, contentEncoding: string): Promise<T> {
const decrypter = this.encrypter[contentEncoding]
if (!decrypter) {
throw new Error(`Decrypt not defined for ${contentEncoding}`)
}
const decrypted = await decrypter.decrypt(input)
const decoder = this.encoder[contentType]
if (!decoder) {
throw new Error(`Decode not defined for ${contentType}`)
}
return decoder.decode(decrypted)
}
async destroy() {
if (this.channel) {
const channel = this.channel
// instruct message broker to no longer send messages
const cancelProms = this.consumerTags.map((tag) => channel.cancel(tag))
await Promise.all(cancelProms)
let isTimedOut = false
const timeout = setTimeout(() => {
isTimedOut = true
}, this.defaultCommandTimeout)
// ensure actual running commands and subscriptions are finished before closing connection
const waitForExecutionEnd = () => {
if (this.pendingInvocations.size <= 0 && this.runningSubscriptionCount <= 0) {
return
}
if (isTimedOut) {
this.logger.error('Some commands or subscriptions could not finish before connection was closed')
return
}
setImmediate(waitForExecutionEnd)
}
waitForExecutionEnd()
if (timeout) {
clearTimeout(timeout)
}
await this.channel.close()
}
if (this.connection) {
await this.connection.close()
}
await super.destroy()
}
}