-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSqsPermissionConsumer.spec.ts
893 lines (765 loc) · 27.1 KB
/
SqsPermissionConsumer.spec.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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
import { setTimeout } from 'node:timers/promises'
import {
ListQueueTagsCommand,
type SQSClient,
type SendMessageCommandInput,
} from '@aws-sdk/client-sqs'
import { ReceiveMessageCommand, SendMessageCommand } from '@aws-sdk/client-sqs'
import { waitAndRetry } from '@lokalise/node-core'
import type { BarrierResult, ProcessedMessageMetadata } from '@message-queue-toolkit/core'
import type { AwilixContainer } from 'awilix'
import { asClass, asFunction, asValue } from 'awilix'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ZodError } from 'zod'
import { FakeConsumerErrorResolver } from '../../lib/fakes/FakeConsumerErrorResolver'
import { assertQueue, deleteQueue, getQueueAttributes } from '../../lib/utils/sqsUtils'
import { FakeLogger } from '../fakes/FakeLogger'
import { SqsPermissionPublisher } from '../publishers/SqsPermissionPublisher'
import { SINGLETON_CONFIG, registerDependencies } from '../utils/testContext'
import type { Dependencies } from '../utils/testContext'
import { SqsPermissionConsumer, type SupportedMessages } from './SqsPermissionConsumer'
import type { PERMISSIONS_ADD_MESSAGE_TYPE } from './userConsumerSchemas'
describe('SqsPermissionConsumer', () => {
describe('init', () => {
const queueName = 'myTestQueue'
let diContainer: AwilixContainer<Dependencies>
let sqsClient: SQSClient
beforeEach(async () => {
diContainer = await registerDependencies()
sqsClient = diContainer.cradle.sqsClient
await deleteQueue(sqsClient, queueName)
})
afterEach(async () => {
await diContainer.cradle.awilixManager.executeDispose()
await diContainer.dispose()
})
it('throws an error when invalid queue locator is passed', async () => {
const newConsumer = new SqsPermissionConsumer(diContainer.cradle, {
locatorConfig: {
queueUrl: `http://s3.localhost.localstack.cloud:4566/000000000000/${queueName}`,
},
})
await expect(() => newConsumer.init()).rejects.toThrow(/does not exist/)
})
it('does not create a new queue when queue locator is passed', async () => {
await assertQueue(sqsClient, {
QueueName: queueName,
})
const newConsumer = new SqsPermissionConsumer(diContainer.cradle, {
locatorConfig: {
queueUrl: `http://s3.localhost.localstack.cloud:4566/000000000000/${queueName}`,
},
})
await newConsumer.init()
expect(newConsumer.queueProps.url).toBe(
`http://s3.localhost.localstack.cloud:4566/000000000000/${queueName}`,
)
})
describe('attributes update', () => {
it('updates existing queue when one with different attributes exist', async () => {
await assertQueue(sqsClient, {
QueueName: queueName,
Attributes: {
KmsMasterKeyId: 'somevalue',
},
})
const newConsumer = new SqsPermissionConsumer(diContainer.cradle, {
creationConfig: {
queue: {
QueueName: queueName,
Attributes: {
KmsMasterKeyId: 'othervalue',
VisibilityTimeout: '10',
},
},
updateAttributesIfExists: true,
},
deletionConfig: {
deleteIfExists: false,
},
logMessages: true,
})
const sqsSpy = vi.spyOn(sqsClient, 'send')
await newConsumer.init()
expect(newConsumer.queueProps.url).toBe(
`http://sqs.eu-west-1.localstack:4566/000000000000/${queueName}`,
)
const updateCall = sqsSpy.mock.calls.find((entry) => {
return entry[0].constructor.name === 'SetQueueAttributesCommand'
})
expect(updateCall).toBeDefined()
const attributes = await getQueueAttributes(sqsClient, newConsumer.queueProps.url)
expect(attributes.result?.attributes).toMatchObject({
KmsMasterKeyId: 'othervalue',
VisibilityTimeout: '10',
})
})
it('does not update existing queue when attributes did not change', async () => {
await assertQueue(sqsClient, {
QueueName: queueName,
Attributes: {
KmsMasterKeyId: 'somevalue',
},
})
const newConsumer = new SqsPermissionConsumer(diContainer.cradle, {
creationConfig: {
queue: {
QueueName: queueName,
Attributes: {
KmsMasterKeyId: 'somevalue',
},
},
updateAttributesIfExists: true,
},
deletionConfig: {
deleteIfExists: false,
},
logMessages: true,
})
const sqsSpy = vi.spyOn(sqsClient, 'send')
await newConsumer.init()
expect(newConsumer.queueProps.url).toBe(
`http://sqs.eu-west-1.localstack:4566/000000000000/${queueName}`,
)
const updateCall = sqsSpy.mock.calls.find((entry) => {
return entry[0].constructor.name === 'SetQueueAttributesCommand'
})
expect(updateCall).toBeUndefined()
const attributes = await getQueueAttributes(sqsClient, newConsumer.queueProps.url)
expect(attributes.result?.attributes!.KmsMasterKeyId).toBe('somevalue')
})
})
describe('tags update', () => {
const getTags = (queueUrl: string) =>
sqsClient.send(new ListQueueTagsCommand({ QueueUrl: queueUrl }))
it('updates existing queue tags when update is forced', async () => {
const initialTags = {
project: 'some-project',
service: 'some-service',
leftover: 'some-leftover',
}
const newTags = {
project: 'some-project',
service: 'changed-service',
cc: 'some-cc',
}
const assertResult = await assertQueue(sqsClient, {
QueueName: queueName,
tags: initialTags,
})
const preTags = await getTags(assertResult.queueUrl)
expect(preTags.Tags).toEqual(initialTags)
const newConsumer = new SqsPermissionConsumer(diContainer.cradle, {
creationConfig: {
queue: {
QueueName: queueName,
tags: newTags,
},
forceTagUpdate: true,
},
deletionConfig: {
deleteIfExists: false,
},
logMessages: true,
})
const sqsSpy = vi.spyOn(sqsClient, 'send')
await newConsumer.init()
expect(newConsumer.queueProps.url).toBe(
`http://sqs.eu-west-1.localstack:4566/000000000000/${queueName}`,
)
const updateCall = sqsSpy.mock.calls.find((entry) => {
return entry[0].constructor.name === 'TagQueueCommand'
})
expect(updateCall).toBeDefined()
const postTags = await getTags(assertResult.queueUrl)
expect(postTags.Tags).toEqual({
...newTags,
leftover: 'some-leftover',
})
})
it('does not update existing queue tags when update is not forced', async () => {
const assertResult = await assertQueue(sqsClient, {
QueueName: queueName,
tags: {
project: 'some-project',
service: 'some-service',
leftover: 'some-leftover',
},
})
const preTags = await getTags(assertResult.queueUrl)
expect(preTags.Tags).toEqual({
project: 'some-project',
service: 'some-service',
leftover: 'some-leftover',
})
const newConsumer = new SqsPermissionConsumer(diContainer.cradle, {
creationConfig: {
queue: {
QueueName: queueName,
tags: {
project: 'some-project',
service: 'changed-service',
cc: 'some-cc',
},
},
},
deletionConfig: {
deleteIfExists: false,
},
logMessages: true,
})
const sqsSpy = vi.spyOn(sqsClient, 'send')
await newConsumer.init()
expect(newConsumer.queueProps.url).toBe(
`http://sqs.eu-west-1.localstack:4566/000000000000/${queueName}`,
)
const updateCall = sqsSpy.mock.calls.find((entry) => {
return entry[0].constructor.name === 'TagQueueCommand'
})
expect(updateCall).toBeUndefined()
const postTags = await getTags(assertResult.queueUrl)
expect(postTags.Tags).toEqual({
project: 'some-project',
service: 'some-service',
leftover: 'some-leftover',
})
})
})
})
describe('logging', () => {
let logger: FakeLogger
let diContainer: AwilixContainer<Dependencies>
let publisher: SqsPermissionPublisher
beforeEach(async () => {
logger = new FakeLogger()
diContainer = await registerDependencies({
logger: asFunction(() => logger),
})
await diContainer.cradle.permissionConsumer.close()
publisher = diContainer.cradle.permissionPublisher
})
afterEach(async () => {
await diContainer.cradle.awilixManager.executeDispose()
await diContainer.dispose()
})
it('logs a message when logging is enabled', async () => {
const newConsumer = new SqsPermissionConsumer(diContainer.cradle, {
creationConfig: {
queue: {
QueueName: publisher.queueProps.name,
},
},
logMessages: true,
})
await newConsumer.start()
await publisher.publish({
id: '1',
messageType: 'add',
})
await newConsumer.handlerSpy.waitForMessageWithId('1', 'consumed')
expect(logger.loggedMessages.length).toBe(2)
expect(logger.loggedMessages).toMatchObject([
{
id: '1',
messageType: 'add',
timestamp: expect.any(String),
},
{
messageId: '1',
processingResult: 'consumed',
},
])
await newConsumer.close()
})
})
describe('metrics', () => {
let logger: FakeLogger
let diContainer: AwilixContainer<Dependencies>
let publisher: SqsPermissionPublisher
beforeEach(async () => {
logger = new FakeLogger()
diContainer = await registerDependencies({
logger: asFunction(() => logger),
})
await diContainer.cradle.permissionConsumer.close()
publisher = diContainer.cradle.permissionPublisher
})
afterEach(async () => {
await diContainer.cradle.awilixManager.executeDispose()
await diContainer.dispose()
})
it('registers metrics if metrics manager is provided', async () => {
const messagesRegisteredInMetrics: ProcessedMessageMetadata<SupportedMessages>[] = []
const newConsumer = new SqsPermissionConsumer({
...diContainer.cradle,
messageMetricsManager: {
registerProcessedMessage(metadata: ProcessedMessageMetadata<SupportedMessages>): void {
messagesRegisteredInMetrics.push(metadata)
},
},
})
await newConsumer.start()
publisher.publish({
id: '1',
messageType: 'add',
metadata: {
schemaVersions: '1.0.0',
},
})
await newConsumer.handlerSpy.waitForMessageWithId('1', 'consumed')
await newConsumer.close()
expect(messagesRegisteredInMetrics).toStrictEqual([
{
messageId: '1',
messageType: 'add',
processingResult: 'consumed',
messageProcessingMilliseconds: expect.any(Number),
message: expect.objectContaining({
id: '1',
messageType: 'add',
metadata: {
schemaVersions: '1.0.0',
},
}),
},
])
})
})
describe('preHandlerBarrier', () => {
let diContainer: AwilixContainer<Dependencies>
let publisher: SqsPermissionPublisher
beforeEach(async () => {
diContainer = await registerDependencies()
await diContainer.cradle.permissionConsumer.close()
publisher = diContainer.cradle.permissionPublisher
})
afterEach(async () => {
await diContainer.cradle.awilixManager.executeDispose()
await diContainer.dispose()
})
it('blocks first try', async () => {
let barrierCounter = 0
const newConsumer = new SqsPermissionConsumer(diContainer.cradle, {
creationConfig: {
queue: {
QueueName: publisher.queueProps.name,
},
},
addPreHandlerBarrier: (_msg): Promise<BarrierResult<number>> => {
barrierCounter++
if (barrierCounter < 2) {
return Promise.resolve({
isPassing: false,
})
}
return Promise.resolve({ isPassing: true, output: barrierCounter })
},
})
await newConsumer.start()
await publisher.publish({
id: '2',
messageType: 'add',
})
await newConsumer.handlerSpy.waitForMessageWithId('2', 'consumed')
expect(newConsumer.addCounter).toBe(1)
expect(barrierCounter).toBe(2)
await newConsumer.close()
})
it('can access preHandler output', async () => {
expect.assertions(1)
const newConsumer = new SqsPermissionConsumer(diContainer.cradle, {
creationConfig: {
queue: {
QueueName: publisher.queueProps.name,
},
},
addPreHandlerBarrier: (
message,
_executionContext,
preHandlerOutput,
): Promise<BarrierResult<number>> => {
expect(preHandlerOutput.messageId).toBe(message.id)
return Promise.resolve({ isPassing: true, output: 1 })
},
})
await newConsumer.start()
await publisher.publish({
id: '2',
messageType: 'add',
})
await newConsumer.handlerSpy.waitForMessageWithId('2', 'consumed')
await newConsumer.close()
})
it('throws an error on first try', async () => {
let barrierCounter = 0
const newConsumer = new SqsPermissionConsumer(diContainer.cradle, {
creationConfig: {
queue: {
QueueName: publisher.queueProps.name,
},
},
addPreHandlerBarrier: (_msg) => {
barrierCounter++
if (barrierCounter === 1) {
throw new Error()
}
return Promise.resolve({ isPassing: true, output: barrierCounter })
},
})
await newConsumer.start()
await publisher.publish({
id: '3',
messageType: 'add',
})
await newConsumer.handlerSpy.waitForMessageWithId('3', 'consumed')
expect(newConsumer.addCounter).toBe(1)
expect(barrierCounter).toBe(2)
await newConsumer.close()
})
})
describe('preHandlers', () => {
let diContainer: AwilixContainer<Dependencies>
let publisher: SqsPermissionPublisher
beforeEach(async () => {
diContainer = await registerDependencies()
await diContainer.cradle.permissionConsumer.close()
publisher = diContainer.cradle.permissionPublisher
})
afterEach(async () => {
await diContainer.cradle.awilixManager.executeDispose()
await diContainer.dispose()
})
it('processes one preHandler', async () => {
expect.assertions(1)
const newConsumer = new SqsPermissionConsumer(diContainer.cradle, {
creationConfig: {
queue: {
QueueName: publisher.queueProps.name,
},
},
removeHandlerOverride: (message, _context, preHandlerOutputs) => {
expect(preHandlerOutputs.preHandlerOutput.messageId).toEqual(message.id)
return Promise.resolve({
result: 'success',
})
},
removePreHandlers: [
(message, _context, preHandlerOutput, next) => {
preHandlerOutput.messageId = message.id
next({
result: 'success',
})
},
],
})
await newConsumer.start()
await publisher.publish({
id: '2',
messageType: 'remove',
})
await newConsumer.handlerSpy.waitForMessageWithId('2', 'consumed')
await newConsumer.close()
})
it('processes two preHandlers', async () => {
expect.assertions(1)
const newConsumer = new SqsPermissionConsumer(diContainer.cradle, {
creationConfig: {
queue: {
QueueName: publisher.queueProps.name,
},
},
removeHandlerOverride: (message, _context, preHandlerOutputs) => {
expect(preHandlerOutputs.preHandlerOutput.messageId).toEqual(`${message.id} adjusted`)
return Promise.resolve({
result: 'success',
})
},
removePreHandlers: [
(message, _context, preHandlerOutput, next) => {
preHandlerOutput.messageId = message.id
next({
result: 'success',
})
},
(_message, _context, preHandlerOutput, next) => {
preHandlerOutput.messageId += ' adjusted'
next({
result: 'success',
})
},
],
})
await newConsumer.start()
await publisher.publish({
id: '2',
messageType: 'remove',
})
await newConsumer.handlerSpy.waitForMessageWithId('2', 'consumed')
await newConsumer.close()
})
})
describe('consume', () => {
let diContainer: AwilixContainer<Dependencies>
let sqsClient: SQSClient
let publisher: SqsPermissionPublisher
let consumer: SqsPermissionConsumer
let errorResolver: FakeConsumerErrorResolver
beforeEach(async () => {
diContainer = await registerDependencies({
consumerErrorResolver: asClass(FakeConsumerErrorResolver, SINGLETON_CONFIG),
})
sqsClient = diContainer.cradle.sqsClient
publisher = diContainer.cradle.permissionPublisher
consumer = diContainer.cradle.permissionConsumer
const command = new ReceiveMessageCommand({
QueueUrl: publisher.queueProps.url,
})
const reply = await sqsClient.send(command)
expect(reply.Messages).toBeUndefined()
errorResolver = diContainer.cradle.consumerErrorResolver as FakeConsumerErrorResolver
errorResolver.clear()
})
afterEach(async () => {
await diContainer.cradle.awilixManager.executeDispose()
await diContainer.dispose()
})
it('bad event', async () => {
const message = {
messageType: 'add',
}
// not using publisher to avoid publisher validation
const input = {
QueueUrl: consumer.queueProps.url,
MessageBody: JSON.stringify(message),
} satisfies SendMessageCommandInput
const command = new SendMessageCommand(input)
await sqsClient.send(command)
await waitAndRetry(() => errorResolver.errors.length > 0, 100, 5)
expect(errorResolver.errors).toHaveLength(1)
expect(errorResolver.errors[0] instanceof ZodError).toBe(true)
expect(consumer.addCounter).toBe(0)
expect(consumer.removeCounter).toBe(0)
})
it('Processes messages', async () => {
await publisher.publish({
id: '10',
messageType: 'add',
})
await publisher.publish({
id: '20',
messageType: 'remove',
})
await publisher.publish({
id: '30',
messageType: 'remove',
})
await consumer.handlerSpy.waitForMessageWithId('10', 'consumed')
await consumer.handlerSpy.waitForMessageWithId('20', 'consumed')
await consumer.handlerSpy.waitForMessageWithId('30', 'consumed')
expect(consumer.addCounter).toBe(1)
expect(consumer.removeCounter).toBe(2)
})
})
describe('multiple consumers', () => {
let diContainer: AwilixContainer<Dependencies>
let sqsClient: SQSClient
let publisher: SqsPermissionPublisher
let consumer: SqsPermissionConsumer
beforeEach(async () => {
diContainer = await registerDependencies({
permissionConsumer: asFunction((dependencies) => {
return new SqsPermissionConsumer(dependencies, {
creationConfig: {
queue: {
QueueName: SqsPermissionConsumer.QUEUE_NAME,
},
},
concurrentConsumersAmount: 5,
})
}),
})
sqsClient = diContainer.cradle.sqsClient
publisher = diContainer.cradle.permissionPublisher
consumer = diContainer.cradle.permissionConsumer
await consumer.start()
const command = new ReceiveMessageCommand({
QueueUrl: publisher.queueProps.url,
})
const reply = await sqsClient.send(command)
expect(reply.Messages).toBeUndefined()
})
afterEach(async () => {
await diContainer.cradle.awilixManager.executeDispose()
await diContainer.dispose()
})
it('process all messages properly', async () => {
const messagesAmount = 100
const messages: PERMISSIONS_ADD_MESSAGE_TYPE[] = Array.from({ length: messagesAmount }).map(
(_, i) => ({
id: `${i}`,
messageType: 'add',
timestamp: new Date().toISOString(),
}),
)
messages.map((m) => publisher.publish(m))
await Promise.all(
messages.map((m) => consumer.handlerSpy.waitForMessageWithId(m.id, 'consumed')),
)
// Verifies that each message is executed only once
expect(consumer.addCounter).toBe(messagesAmount)
// Verifies that no message is lost
expect(consumer.processedMessagesIds).toHaveLength(messagesAmount)
})
})
describe('visibility timeout', () => {
const queueName = 'myTestQueue'
let diContainer: AwilixContainer<Dependencies>
beforeEach(async () => {
diContainer = await registerDependencies({
permissionPublisher: asValue(() => undefined),
permissionConsumer: asValue(() => undefined),
})
})
afterEach(async () => {
await diContainer.cradle.awilixManager.executeDispose()
await diContainer.dispose()
})
it('heartbeatInterval should be less than visibilityTimeout', async () => {
const consumer = new SqsPermissionConsumer(diContainer.cradle, {
creationConfig: { queue: { QueueName: queueName, Attributes: { VisibilityTimeout: '1' } } },
consumerOverrides: { heartbeatInterval: 2 },
})
await expect(() => consumer.start()).rejects.toThrow(
/heartbeatInterval must be less than visibilityTimeout/,
)
})
it.each([false, true])(
'using 2 consumers with heartbeat -> %s',
async (heartbeatEnabled) => {
let consumer1IsProcessing = false
let consumer1Counter = 0
let consumer2Counter = 0
const consumer1 = new SqsPermissionConsumer(diContainer.cradle, {
creationConfig: {
queue: { QueueName: queueName, Attributes: { VisibilityTimeout: '2' } },
},
consumerOverrides: { heartbeatInterval: heartbeatEnabled ? 1 : undefined },
removeHandlerOverride: async () => {
consumer1IsProcessing = true
await setTimeout(3100) // Wait to the visibility timeout to expire
consumer1Counter++
consumer1IsProcessing = false
return { result: 'success' }
},
})
await consumer1.start()
const consumer2 = new SqsPermissionConsumer(diContainer.cradle, {
locatorConfig: { queueUrl: consumer1.queueProps.url },
removeHandlerOverride: () => {
consumer2Counter++
return Promise.resolve({ result: 'success' })
},
})
const publisher = new SqsPermissionPublisher(diContainer.cradle, {
locatorConfig: { queueUrl: consumer1.queueProps.url },
})
await publisher.publish({ id: '10', messageType: 'remove' })
// wait for consumer1 to start processing to start second consumer
await waitAndRetry(() => consumer1IsProcessing, 5, 5)
await consumer2.start()
// wait for both consumers to process message
await waitAndRetry(() => consumer1Counter > 0 && consumer2Counter > 0, 100, 40)
expect(consumer1Counter).toBe(1)
expect(consumer2Counter).toBe(heartbeatEnabled ? 0 : 1)
await Promise.all([consumer1.close(), consumer2.close()])
},
// This reduces flakiness in CI
10000,
)
})
describe('exponential backoff retry', () => {
const queueName = 'myTestQueue_exponentialBackoffRetry'
let diContainer: AwilixContainer<Dependencies>
beforeEach(async () => {
diContainer = await registerDependencies({
permissionPublisher: asValue(() => undefined),
permissionConsumer: asValue(() => undefined),
})
})
afterEach(async () => {
await diContainer.cradle.awilixManager.executeDispose()
await diContainer.dispose()
})
it('should use internal field and 1 base delay', async () => {
const consumer = new SqsPermissionConsumer(diContainer.cradle, {
creationConfig: {
queue: { QueueName: queueName },
},
removeHandlerOverride: () => {
return Promise.resolve({ error: 'retryLater' })
},
})
await consumer.start()
const publisher = new SqsPermissionPublisher(diContainer.cradle, {
locatorConfig: { queueUrl: consumer.queueProps.url },
})
await publisher.init()
const sqsSpy = vi.spyOn(diContainer.cradle.sqsClient, 'send')
await publisher.publish({
id: '10',
messageType: 'remove',
})
await publisher.publish({
id: '20',
messageType: 'remove',
_internalNumberOfRetries: 1, // Note that publish will add 1 to this value, but it's fine for this test
} as any)
await publisher.publish({
id: '30',
messageType: 'remove',
_internalNumberOfRetries: 10, // Note that publish will add 1 to this value, but it's fine for this test
} as any)
await waitAndRetry(
() => {
const sendMessageCommands = sqsSpy.mock.calls
.map((call) => call[0].input)
.filter((input) => 'MessageBody' in input)
return sendMessageCommands.length === 6
},
5,
100,
)
const sendMessageCommands = sqsSpy.mock.calls
.map((call) => call[0].input)
.filter((input) => 'MessageBody' in input)
expect(sendMessageCommands).toHaveLength(6)
expect(sendMessageCommands).toEqual(
expect.arrayContaining([
expect.objectContaining({
MessageBody: expect.stringContaining('"_internalNumberOfRetries":0'),
}),
expect.objectContaining({
MessageBody: expect.stringContaining('"_internalNumberOfRetries":2'),
}),
expect.objectContaining({
MessageBody: expect.stringContaining('"_internalNumberOfRetries":11'),
}),
expect.objectContaining({
MessageBody: expect.stringContaining('"_internalNumberOfRetries":1'),
DelaySeconds: 1,
}),
expect.objectContaining({
MessageBody: expect.stringContaining('"_internalNumberOfRetries":3'),
DelaySeconds: 4,
}),
expect.objectContaining({
MessageBody: expect.stringContaining('"_internalNumberOfRetries":12'),
DelaySeconds: 2048,
}),
]),
)
await publisher.close()
await consumer.close()
})
})
})