Raw
1 import { Logger } from "@medusajs/framework/types"
2 import { Queue, Worker } from "bullmq"
3 import { Redis } from "ioredis"
4 import RedisEventBusService from "../event-bus-redis"
5
6 jest.mock("bullmq")
7 jest.mock("ioredis")
8
9 const loggerMock = {
10 info: jest.fn().mockImplementation(console.log),
11 warn: jest.fn().mockImplementation(console.warn),
12 error: jest.fn().mockImplementation(console.error),
13 } as unknown as Logger
14
15 const pipelineMock = {
16 rpush: jest.fn(),
17 expire: jest.fn(),
18 pexpire: jest.fn(),
19 del: jest.fn(),
20 exec: jest.fn().mockResolvedValue([]),
21 }
22
23 const redisMock = {
24 del: () => jest.fn(),
25 rpush: () => jest.fn(),
26 lrange: () => jest.fn(),
27 disconnect: () => jest.fn(),
28 expire: () => jest.fn(),
29 unlink: () => jest.fn(),
30 pipeline: jest.fn(() => pipelineMock),
31 } as unknown as Redis
32
33 const moduleDeps = {
34 logger: loggerMock,
35 eventBusRedisConnection: redisMock,
36 eventBusRedisQueueName: "events-queue",
37 eventBusRedisQueueOptions: {},
38 eventBusRedisWorkerOptions: {},
39 eventBusRedisJobOptions: {},
40 }
41
42 const moduleDeclaration = { scope: "internal" } as any
43
44 describe("RedisEventBusService", () => {
45 let eventBus: RedisEventBusService
46 let queue
47 let redis
48
49 describe("constructor", () => {
50 beforeEach(async () => {
51 jest.clearAllMocks()
52
53 eventBus = new RedisEventBusService(moduleDeps, {}, moduleDeclaration)
54 })
55
56 it("Creates a queue + worker", () => {
57 expect(Queue).toHaveBeenCalledTimes(1)
58 expect(Queue).toHaveBeenCalledWith("events-queue", {
59 connection: expect.any(Object),
60 prefix: "RedisEventBusService",
61 })
62
63 expect(Worker).toHaveBeenCalledTimes(1)
64 expect(Worker).toHaveBeenCalledWith(
65 "events-queue",
66 expect.any(Function),
67 {
68 connection: expect.any(Object),
69 prefix: "RedisEventBusService",
70 autorun: false,
71 }
72 )
73 })
74
75 it("Throws on isolated module declaration", () => {
76 try {
77 eventBus = new RedisEventBusService(moduleDeps, {}, moduleDeclaration)
78 } catch (error) {
79 expect(error.message).toEqual(
80 "At the moment this module can only be used with shared resources"
81 )
82 }
83 })
84 })
85
86 describe("emit", () => {
87 describe("Successfully emits events", () => {
88 beforeEach(async () => {
89 jest.clearAllMocks()
90
91 eventBus = new RedisEventBusService(moduleDeps, {}, moduleDeclaration)
92
93 queue = (eventBus as any).queue_
94 queue.addBulk = jest.fn()
95 redis = (eventBus as any).eventBusRedisConnection_
96 })
97
98 it("should add job to queue with default options", async () => {
99 eventBus.subscribe("eventName", () => Promise.resolve())
100
101 await eventBus.emit([
102 {
103 name: "eventName",
104 data: {
105 hi: "1234",
106 },
107 },
108 ])
109
110 expect(queue.addBulk).toHaveBeenCalledTimes(1)
111 expect(queue.addBulk).toHaveBeenCalledWith([
112 {
113 name: "eventName",
114 data: { data: { hi: "1234" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
115 opts: {
116 attempts: 1,
117 removeOnComplete: true,
118 priority: 100,
119 },
120 },
121 ])
122 })
123
124 it("should add job to queue with custom options passed directly upon emitting", async () => {
125 eventBus.subscribe("eventName", () => Promise.resolve())
126
127 await eventBus.emit([{ name: "eventName", data: { hi: "1234" } }], {
128 attempts: 3,
129 backoff: 5000,
130 delay: 1000,
131 })
132
133 expect(queue.addBulk).toHaveBeenCalledTimes(1)
134 expect(queue.addBulk).toHaveBeenCalledWith([
135 {
136 name: "eventName",
137 data: { data: { hi: "1234" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
138 opts: {
139 attempts: 3,
140 backoff: 5000,
141 delay: 1000,
142 removeOnComplete: true,
143 priority: 100,
144 },
145 },
146 ])
147 })
148
149 it("should add job to queue with module job options", async () => {
150 eventBus = new RedisEventBusService(
151 {
152 ...moduleDeps,
153 eventBusRedisJobOptions: {
154 removeOnComplete: { age: 5 },
155 attempts: 7,
156 },
157 },
158 {},
159 moduleDeclaration
160 )
161
162 queue = (eventBus as any).queue_
163 queue.addBulk = jest.fn()
164
165 eventBus.subscribe("eventName", () => Promise.resolve())
166
167 await eventBus.emit(
168 [
169 {
170 name: "eventName",
171 data: { hi: "1234" },
172 },
173 ],
174 { attempts: 3, backoff: 5000, delay: 1000 }
175 )
176
177 expect(queue.addBulk).toHaveBeenCalledTimes(1)
178 expect(queue.addBulk).toHaveBeenCalledWith([
179 {
180 name: "eventName",
181 data: { data: { hi: "1234" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
182 opts: {
183 attempts: 3,
184 backoff: 5000,
185 delay: 1000,
186 removeOnComplete: {
187 age: 5,
188 },
189 priority: 100,
190 },
191 },
192 ])
193 })
194
195 it("should add job to queue with default, local, and global options merged", async () => {
196 eventBus = new RedisEventBusService(
197 {
198 ...moduleDeps,
199 eventBusRedisJobOptions: {
200 removeOnComplete: 5,
201 },
202 },
203 {},
204 moduleDeclaration
205 )
206
207 queue = (eventBus as any).queue_
208 queue.addBulk = jest.fn()
209
210 eventBus.subscribe("eventName", () => Promise.resolve())
211
212 await eventBus.emit(
213 {
214 name: "eventName",
215 data: { hi: "1234" },
216 },
217 { delay: 1000 }
218 )
219
220 expect(queue.addBulk).toHaveBeenCalledTimes(1)
221 expect(queue.addBulk).toHaveBeenCalledWith([
222 {
223 name: "eventName",
224 data: { data: { hi: "1234" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
225 opts: {
226 attempts: 1,
227 removeOnComplete: 5,
228 delay: 1000,
229 priority: 100,
230 },
231 },
232 ])
233 })
234
235 it("should successfully group events", async () => {
236 const options = { delay: 1000 }
237 const event = {
238 name: "eventName",
239 data: { hi: "1234" },
240 metadata: { eventGroupId: "test-group-1" },
241 }
242
243 await eventBus.emit(event, options)
244
245 expect(queue.addBulk).toHaveBeenCalledTimes(0)
246 expect(pipelineMock.rpush).toHaveBeenCalledTimes(1)
247 expect(pipelineMock.rpush).toHaveBeenCalledWith(
248 "staging:test-group-1",
249 expect.any(String)
250 )
251 expect(pipelineMock.expire).toHaveBeenCalledWith(
252 "staging:test-group-1",
253 600
254 )
255 expect(pipelineMock.exec).toHaveBeenCalledTimes(1)
256
257 const stagedEvent = JSON.parse(pipelineMock.rpush.mock.calls[0][1])
258 expect(stagedEvent.data.metadata).toEqual(
259 expect.objectContaining({
260 eventGroupId: "test-group-1",
261 created_at: expect.any(String),
262 })
263 )
264 expect(stagedEvent.data.metadata.published_at).toBeUndefined()
265 })
266
267 it("should successfully group, release and clear events", async () => {
268 const options = { delay: 1000 }
269 const events = [
270 {
271 name: "grouped-event-1",
272 data: { hi: "1234" },
273 metadata: { eventGroupId: "test-group-1" },
274 },
275 {
276 name: "ungrouped-event-2",
277 data: { hi: "1234" },
278 },
279 {
280 name: "grouped-event-2",
281 data: { hi: "1234" },
282 metadata: { eventGroupId: "test-group-2" },
283 },
284 {
285 name: "grouped-event-3",
286 data: { hi: "1235" },
287 metadata: { eventGroupId: "test-group-2" },
288 },
289 ]
290
291 eventBus.subscribe("ungrouped-event-2", () => Promise.resolve())
292 eventBus.subscribe("grouped-event-1", () => Promise.resolve())
293 eventBus.subscribe("grouped-event-2", () => Promise.resolve())
294 eventBus.subscribe("grouped-event-3", () => Promise.resolve())
295
296 redis.unlink = jest.fn()
297
298 await eventBus.emit(events, options)
299
300 expect(queue.addBulk).toHaveBeenCalledTimes(1)
301 expect(pipelineMock.rpush).toHaveBeenCalledTimes(2)
302 expect(redis.unlink).not.toHaveBeenCalled()
303
304 const [testGroup1Event] = (eventBus as any).buildEvents(
305 [events[0]],
306 options
307 )
308 const [testGroup2Event] = (eventBus as any).buildEvents(
309 [events[2]],
310 options
311 )
312 const [testGroup2Event2] = (eventBus as any).buildEvents(
313 [events[3]],
314 options
315 )
316
317 const stagedGroup1Event = pipelineMock.rpush.mock.calls.find(
318 (call) => call[0] === "staging:test-group-1"
319 )![1]
320 const stagedGroup2Events = pipelineMock.rpush.mock.calls
321 .filter((call) => call[0] === "staging:test-group-2")
322 .flatMap((call) => call.slice(1))
323
324 redis.lrange = jest.fn((key) => {
325 if (key === "staging:test-group-1") {
326 return Promise.resolve([stagedGroup1Event])
327 }
328
329 if (key === "staging:test-group-2") {
330 return Promise.resolve(stagedGroup2Events)
331 }
332
333 return
334 })
335
336 queue = (eventBus as any).queue_
337 queue.addBulk = jest.fn()
338
339 await eventBus.releaseGroupedEvents("test-group-1")
340
341 expect(queue.addBulk).toHaveBeenCalledTimes(1)
342 expect(queue.addBulk).toHaveBeenCalledWith([
343 expect.objectContaining({
344 name: testGroup1Event.name,
345 data: {
346 data: testGroup1Event.data.data,
347 metadata: expect.objectContaining({
348 eventGroupId: "test-group-1",
349 created_at: expect.any(String),
350 published_at: expect.any(Date),
351 }),
352 },
353 opts: testGroup1Event.opts,
354 }),
355 ])
356 expect(redis.unlink).toHaveBeenCalledTimes(1)
357 expect(redis.unlink).toHaveBeenCalledWith("staging:test-group-1")
358
359 queue = (eventBus as any).queue_
360 queue.addBulk = jest.fn()
361 redis.unlink = jest.fn()
362
363 await eventBus.releaseGroupedEvents("test-group-2")
364
365 expect(queue.addBulk).toHaveBeenCalledTimes(1)
366 expect(queue.addBulk).toHaveBeenCalledWith([
367 expect.objectContaining({
368 name: testGroup2Event.name,
369 data: {
370 data: testGroup2Event.data.data,
371 metadata: expect.objectContaining({
372 eventGroupId: "test-group-2",
373 created_at: expect.any(String),
374 published_at: expect.any(Date),
375 }),
376 },
377 opts: testGroup2Event.opts,
378 }),
379 expect.objectContaining({
380 name: testGroup2Event2.name,
381 data: {
382 data: testGroup2Event2.data.data,
383 metadata: expect.objectContaining({
384 eventGroupId: "test-group-2",
385 created_at: expect.any(String),
386 published_at: expect.any(Date),
387 }),
388 },
389 opts: testGroup2Event2.opts,
390 }),
391 ])
392 expect(redis.unlink).toHaveBeenCalledTimes(1)
393 expect(redis.unlink).toHaveBeenCalledWith("staging:test-group-2")
394 })
395 })
396
397 describe("Priority levels", () => {
398 beforeEach(async () => {
399 jest.clearAllMocks()
400
401 eventBus = new RedisEventBusService(moduleDeps, {}, moduleDeclaration)
402
403 queue = (eventBus as any).queue_
404 queue.addBulk = jest.fn()
405 redis = (eventBus as any).eventBusRedisConnection_
406 })
407
408 it("should add job to queue with default priority (100) for normal events", async () => {
409 eventBus.subscribe("eventName", () => Promise.resolve())
410
411 await eventBus.emit([
412 {
413 name: "eventName",
414 data: { hi: "1234" },
415 },
416 ])
417
418 expect(queue.addBulk).toHaveBeenCalledTimes(1)
419 expect(queue.addBulk).toHaveBeenCalledWith([
420 {
421 name: "eventName",
422 data: { data: { hi: "1234" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
423 opts: {
424 attempts: 1,
425 removeOnComplete: true,
426 priority: 100,
427 },
428 },
429 ])
430 })
431
432 it("should add job to queue with lowest priority (2097152) for internal events", async () => {
433 eventBus.subscribe("eventName", () => Promise.resolve())
434
435 await eventBus.emit(
436 [
437 {
438 name: "eventName",
439 data: { hi: "1234" },
440 },
441 ],
442 { internal: true }
443 )
444
445 expect(queue.addBulk).toHaveBeenCalledTimes(1)
446 expect(queue.addBulk).toHaveBeenCalledWith([
447 {
448 name: "eventName",
449 data: { data: { hi: "1234" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
450 opts: {
451 attempts: 1,
452 removeOnComplete: true,
453 priority: 2097152,
454 internal: true,
455 },
456 },
457 ])
458 })
459
460 it("should add job to queue with custom priority override at emit time", async () => {
461 eventBus.subscribe("eventName", () => Promise.resolve())
462
463 await eventBus.emit(
464 [
465 {
466 name: "eventName",
467 data: { hi: "1234" },
468 },
469 ],
470 { priority: 50 }
471 )
472
473 expect(queue.addBulk).toHaveBeenCalledTimes(1)
474 expect(queue.addBulk).toHaveBeenCalledWith([
475 {
476 name: "eventName",
477 data: { data: { hi: "1234" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
478 opts: {
479 attempts: 1,
480 removeOnComplete: true,
481 priority: 50,
482 },
483 },
484 ])
485 })
486
487 it("should add job to queue with custom priority via module job options", async () => {
488 eventBus = new RedisEventBusService(
489 {
490 ...moduleDeps,
491 eventBusRedisJobOptions: {
492 priority: 200,
493 },
494 },
495 {},
496 moduleDeclaration
497 )
498
499 queue = (eventBus as any).queue_
500 queue.addBulk = jest.fn()
501
502 eventBus.subscribe("eventName", () => Promise.resolve())
503
504 await eventBus.emit([
505 {
506 name: "eventName",
507 data: { hi: "1234" },
508 },
509 ])
510
511 expect(queue.addBulk).toHaveBeenCalledTimes(1)
512 expect(queue.addBulk).toHaveBeenCalledWith([
513 {
514 name: "eventName",
515 data: { data: { hi: "1234" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
516 opts: {
517 attempts: 1,
518 removeOnComplete: true,
519 priority: 200,
520 },
521 },
522 ])
523 })
524
525 it("should override module priority with emit options priority", async () => {
526 eventBus = new RedisEventBusService(
527 {
528 ...moduleDeps,
529 eventBusRedisJobOptions: {
530 priority: 200,
531 },
532 },
533 {},
534 moduleDeclaration
535 )
536
537 queue = (eventBus as any).queue_
538 queue.addBulk = jest.fn()
539
540 eventBus.subscribe("eventName", () => Promise.resolve())
541
542 await eventBus.emit(
543 [
544 {
545 name: "eventName",
546 data: { hi: "1234" },
547 },
548 ],
549 { priority: 25 }
550 )
551
552 expect(queue.addBulk).toHaveBeenCalledTimes(1)
553 expect(queue.addBulk).toHaveBeenCalledWith([
554 {
555 name: "eventName",
556 data: { data: { hi: "1234" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
557 opts: {
558 attempts: 1,
559 removeOnComplete: true,
560 priority: 25,
561 },
562 },
563 ])
564 })
565
566 it("should allow module priority to override internal flag default", async () => {
567 eventBus = new RedisEventBusService(
568 {
569 ...moduleDeps,
570 eventBusRedisJobOptions: {
571 priority: 200,
572 },
573 },
574 {},
575 moduleDeclaration
576 )
577
578 queue = (eventBus as any).queue_
579 queue.addBulk = jest.fn()
580
581 eventBus.subscribe("eventName", () => Promise.resolve())
582
583 await eventBus.emit(
584 [
585 {
586 name: "eventName",
587 data: { hi: "1234" },
588 },
589 ],
590 { internal: true }
591 )
592
593 expect(queue.addBulk).toHaveBeenCalledTimes(1)
594 expect(queue.addBulk).toHaveBeenCalledWith([
595 {
596 name: "eventName",
597 data: { data: { hi: "1234" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
598 opts: {
599 attempts: 1,
600 removeOnComplete: true,
601 priority: 200,
602 internal: true,
603 },
604 },
605 ])
606 })
607
608 it("should allow explicit priority to override internal flag default", async () => {
609 eventBus.subscribe("eventName", () => Promise.resolve())
610
611 await eventBus.emit(
612 [
613 {
614 name: "eventName",
615 data: { hi: "1234" },
616 },
617 ],
618 { internal: true, priority: 50 }
619 )
620
621 expect(queue.addBulk).toHaveBeenCalledTimes(1)
622 expect(queue.addBulk).toHaveBeenCalledWith([
623 {
624 name: "eventName",
625 data: { data: { hi: "1234" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
626 opts: {
627 attempts: 1,
628 removeOnComplete: true,
629 priority: 50,
630 internal: true,
631 },
632 },
633 ])
634 })
635
636 describe("Message-level options", () => {
637 it("should allow message-level priority to override emit-level priority", async () => {
638 eventBus.subscribe("eventName", () => Promise.resolve())
639
640 await eventBus.emit(
641 [
642 {
643 name: "eventName",
644 data: { hi: "1234" },
645 options: { priority: 10 },
646 },
647 ],
648 { priority: 100 }
649 )
650
651 expect(queue.addBulk).toHaveBeenCalledTimes(1)
652 expect(queue.addBulk).toHaveBeenCalledWith([
653 {
654 name: "eventName",
655 data: { data: { hi: "1234" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
656 opts: {
657 attempts: 1,
658 removeOnComplete: true,
659 priority: 10,
660 },
661 },
662 ])
663 })
664
665 it("should allow different priorities per message in same emit call", async () => {
666 eventBus.subscribe("eventName1", () => Promise.resolve())
667 eventBus.subscribe("eventName2", () => Promise.resolve())
668 eventBus.subscribe("eventName3", () => Promise.resolve())
669
670 await eventBus.emit(
671 [
672 {
673 name: "eventName1",
674 data: { id: "1" },
675 options: { priority: 10 },
676 },
677 {
678 name: "eventName2",
679 data: { id: "2" },
680 options: { priority: 50 },
681 },
682 {
683 name: "eventName3",
684 data: { id: "3" },
685 // No options - should use emit-level priority
686 },
687 ],
688 { priority: 200 }
689 )
690
691 expect(queue.addBulk).toHaveBeenCalledTimes(1)
692 expect(queue.addBulk).toHaveBeenCalledWith([
693 {
694 name: "eventName1",
695 data: { data: { id: "1" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
696 opts: {
697 attempts: 1,
698 removeOnComplete: true,
699 priority: 10,
700 },
701 },
702 {
703 name: "eventName2",
704 data: { data: { id: "2" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
705 opts: {
706 attempts: 1,
707 removeOnComplete: true,
708 priority: 50,
709 },
710 },
711 {
712 name: "eventName3",
713 data: { data: { id: "3" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
714 opts: {
715 attempts: 1,
716 removeOnComplete: true,
717 priority: 200,
718 },
719 },
720 ])
721 })
722
723 it("should allow message-level priority to override module-level priority", async () => {
724 eventBus = new RedisEventBusService(
725 {
726 ...moduleDeps,
727 eventBusRedisJobOptions: {
728 priority: 300,
729 },
730 },
731 {},
732 moduleDeclaration
733 )
734
735 queue = (eventBus as any).queue_
736 queue.addBulk = jest.fn()
737
738 eventBus.subscribe("eventName", () => Promise.resolve())
739
740 await eventBus.emit([
741 {
742 name: "eventName",
743 data: { hi: "1234" },
744 options: { priority: 5 },
745 },
746 ])
747
748 expect(queue.addBulk).toHaveBeenCalledTimes(1)
749 expect(queue.addBulk).toHaveBeenCalledWith([
750 {
751 name: "eventName",
752 data: { data: { hi: "1234" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
753 opts: {
754 attempts: 1,
755 removeOnComplete: true,
756 priority: 5,
757 },
758 },
759 ])
760 })
761
762 it("should allow message-level priority to override internal flag", async () => {
763 eventBus.subscribe("eventName", () => Promise.resolve())
764
765 await eventBus.emit(
766 [
767 {
768 name: "eventName",
769 data: { hi: "1234" },
770 options: { priority: 15 },
771 },
772 ],
773 { internal: true }
774 )
775
776 expect(queue.addBulk).toHaveBeenCalledTimes(1)
777 expect(queue.addBulk).toHaveBeenCalledWith([
778 {
779 name: "eventName",
780 data: { data: { hi: "1234" }, metadata: { created_at: expect.any(Date), published_at: expect.any(Date) } },
781 opts: {
782 attempts: 1,
783 removeOnComplete: true,
784 priority: 15,
785 internal: true,
786 },
787 },
788 ])
789 })
790 })
791
792 describe("Grouped events priority", () => {
793 it("should stage grouped events with default priority (100)", async () => {
794 const event = {
795 name: "grouped-event",
796 data: { hi: "1234" },
797 metadata: { eventGroupId: "test-group-priority" },
798 }
799
800 await eventBus.emit(event)
801
802 expect(pipelineMock.rpush).toHaveBeenCalledTimes(1)
803 const calledWith = pipelineMock.rpush.mock.calls[0]
804 const stagedEvent = JSON.parse(calledWith[1])
805
806 expect(stagedEvent.opts.priority).toBe(100)
807 })
808
809 it("should stage grouped events with lowest priority (2097152) for internal events", async () => {
810 const event = {
811 name: "grouped-event",
812 data: { hi: "1234" },
813 metadata: { eventGroupId: "test-group-priority" },
814 }
815
816 await eventBus.emit(event, { internal: true })
817
818 expect(pipelineMock.rpush).toHaveBeenCalledTimes(1)
819 const calledWith = pipelineMock.rpush.mock.calls[0]
820 const stagedEvent = JSON.parse(calledWith[1])
821
822 expect(stagedEvent.opts.priority).toBe(2097152)
823 expect(stagedEvent.opts.internal).toBe(true)
824 })
825
826 it("should stage grouped events with custom priority", async () => {
827 const event = {
828 name: "grouped-event",
829 data: { hi: "1234" },
830 metadata: { eventGroupId: "test-group-priority" },
831 }
832
833 await eventBus.emit(event, { priority: 50 })
834
835 expect(pipelineMock.rpush).toHaveBeenCalledTimes(1)
836 const calledWith = pipelineMock.rpush.mock.calls[0]
837 const stagedEvent = JSON.parse(calledWith[1])
838
839 expect(stagedEvent.opts.priority).toBe(50)
840 })
841
842 it("should preserve priority when releasing grouped events", async () => {
843 const event = {
844 name: "grouped-event",
845 data: { hi: "1234" },
846 metadata: { eventGroupId: "test-group-priority" },
847 }
848
849 eventBus.subscribe("grouped-event", () => Promise.resolve())
850
851 await eventBus.emit(event, { priority: 75 })
852
853 const stagedEvent = pipelineMock.rpush.mock.calls.find(
854 (call) => call[0] === "staging:test-group-priority"
855 )![1]
856 const builtEvent = JSON.parse(stagedEvent)
857
858 redis.lrange = jest.fn((key) => {
859 if (key === "staging:test-group-priority") {
860 return Promise.resolve([stagedEvent])
861 }
862 return Promise.resolve([])
863 })
864 redis.unlink = jest.fn()
865
866 await eventBus.releaseGroupedEvents("test-group-priority")
867
868 expect(queue.addBulk).toHaveBeenCalledTimes(1)
869 expect(queue.addBulk).toHaveBeenCalledWith([
870 expect.objectContaining({
871 name: builtEvent.name,
872 data: {
873 data: builtEvent.data.data,
874 metadata: expect.objectContaining({
875 eventGroupId: "test-group-priority",
876 created_at: expect.any(String),
877 published_at: expect.any(Date),
878 }),
879 },
880 opts: builtEvent.opts,
881 }),
882 ])
883 expect(builtEvent.opts.priority).toBe(75)
884 })
885
886 it("should stage grouped events with message-level priority overriding emit-level priority", async () => {
887 const event = {
888 name: "grouped-event",
889 data: { hi: "1234" },
890 metadata: { eventGroupId: "test-group-priority" },
891 options: { priority: 20 },
892 }
893
894 await eventBus.emit(event, { priority: 100 })
895
896 expect(pipelineMock.rpush).toHaveBeenCalledTimes(1)
897 const calledWith = pipelineMock.rpush.mock.calls[0]
898 const stagedEvent = JSON.parse(calledWith[1])
899
900 expect(stagedEvent.opts.priority).toBe(20)
901 })
902
903 it("should allow different priorities per grouped message in same emit call", async () => {
904 const events = [
905 {
906 name: "grouped-event-1",
907 data: { id: "1" },
908 metadata: { eventGroupId: "test-group-multi" },
909 options: { priority: 10 },
910 },
911 {
912 name: "grouped-event-2",
913 data: { id: "2" },
914 metadata: { eventGroupId: "test-group-multi" },
915 options: { priority: 50 },
916 },
917 {
918 name: "grouped-event-3",
919 data: { id: "3" },
920 metadata: { eventGroupId: "test-group-multi" },
921 // No options - should use emit-level priority
922 },
923 ]
924
925 await eventBus.emit(events, { priority: 200 })
926
927 expect(pipelineMock.rpush).toHaveBeenCalledTimes(1)
928 const calledWith = pipelineMock.rpush.mock.calls[0]
929
930 // First argument is the key, rest are the events
931 const stagedEvent1 = JSON.parse(calledWith[1])
932 const stagedEvent2 = JSON.parse(calledWith[2])
933 const stagedEvent3 = JSON.parse(calledWith[3])
934
935 expect(stagedEvent1.opts.priority).toBe(10)
936 expect(stagedEvent2.opts.priority).toBe(50)
937 expect(stagedEvent3.opts.priority).toBe(200)
938 })
939 })
940 })
941
942 describe("Events without subscribers", () => {
943 beforeEach(async () => {
944 jest.clearAllMocks()
945
946 eventBus = new RedisEventBusService(moduleDeps, {}, moduleDeclaration)
947
948 queue = (eventBus as any).queue_
949 queue.addBulk = jest.fn()
950 redis = (eventBus as any).eventBusRedisConnection_
951 })
952
953 it("should not add events to queue when there are no subscribers", async () => {
954 await eventBus.emit([
955 {
956 name: "eventWithoutSubscribers",
957 data: { test: "data" },
958 },
959 ])
960
961 expect(queue.addBulk).not.toHaveBeenCalled()
962 })
963
964 it("should still call interceptors even when there are no subscribers", async () => {
965 const callInterceptorsSpy = jest.spyOn(
966 eventBus as any,
967 "callInterceptors"
968 )
969
970 await eventBus.emit([
971 {
972 name: "eventWithoutSubscribers",
973 data: { test: "data" },
974 },
975 ])
976
977 expect(callInterceptorsSpy).toHaveBeenCalledTimes(1)
978 expect(callInterceptorsSpy).toHaveBeenCalledWith(
979 {
980 name: "eventWithoutSubscribers",
981 data: { test: "data" },
982 metadata: {
983 created_at: expect.any(Date),
984 },
985 },
986 { isGrouped: false }
987 )
988
989 expect(queue.addBulk).not.toHaveBeenCalled()
990
991 callInterceptorsSpy.mockRestore()
992 })
993
994 it("should add events to queue only for events with subscribers using wildcard", async () => {
995 eventBus.subscribe("*", () => Promise.resolve())
996
997 await eventBus.emit([
998 {
999 name: "anyEvent",
1000 data: { test: "data" },
1001 },
1002 ])
1003
1004 expect(queue.addBulk).toHaveBeenCalledTimes(1)
1005 })
1006
1007 it("should not add grouped events to queue when releasing if there are no subscribers", async () => {
1008 const options = { delay: 1000 }
1009 const event = {
1010 name: "grouped-event-no-sub",
1011 data: { hi: "1234" },
1012 metadata: { eventGroupId: "test-group-no-sub" },
1013 }
1014
1015 await eventBus.emit(event, options)
1016
1017 expect(pipelineMock.rpush).toHaveBeenCalledTimes(1)
1018 expect(queue.addBulk).not.toHaveBeenCalled()
1019
1020 const [builtEvent] = (eventBus as any).buildEvents([event], options)
1021
1022 redis.lrange = jest.fn((key) => {
1023 if (key === "staging:test-group-no-sub") {
1024 return Promise.resolve([JSON.stringify(builtEvent)])
1025 }
1026 return Promise.resolve([])
1027 })
1028
1029 redis.unlink = jest.fn()
1030 queue.addBulk = jest.fn()
1031
1032 await eventBus.releaseGroupedEvents("test-group-no-sub")
1033
1034 expect(queue.addBulk).not.toHaveBeenCalled()
1035
1036 expect(redis.unlink).toHaveBeenCalledWith("staging:test-group-no-sub")
1037 })
1038
1039 it("should still call interceptors for grouped events without subscribers", async () => {
1040 const options = { delay: 1000 }
1041 const event = {
1042 name: "grouped-event-no-sub-2",
1043 data: { hi: "1234" },
1044 metadata: { eventGroupId: "test-group-no-sub-2" },
1045 }
1046
1047 await eventBus.emit(event, options)
1048
1049 const stagedEvent = pipelineMock.rpush.mock.calls.find(
1050 (call) => call[0] === "staging:test-group-no-sub-2"
1051 )![1]
1052
1053 redis.lrange = jest.fn((key) => {
1054 if (key === "staging:test-group-no-sub-2") {
1055 return Promise.resolve([stagedEvent])
1056 }
1057 return Promise.resolve([])
1058 })
1059
1060 redis.unlink = jest.fn()
1061 queue.addBulk = jest.fn()
1062
1063 const callInterceptorsSpy = jest.spyOn(
1064 eventBus as any,
1065 "callInterceptors"
1066 )
1067
1068 await eventBus.releaseGroupedEvents("test-group-no-sub-2")
1069
1070 expect(callInterceptorsSpy).toHaveBeenCalledTimes(1)
1071 expect(callInterceptorsSpy).toHaveBeenCalledWith(
1072 expect.objectContaining({
1073 name: "grouped-event-no-sub-2",
1074 metadata: expect.objectContaining({
1075 eventGroupId: "test-group-no-sub-2",
1076 created_at: expect.any(String),
1077 }),
1078 }),
1079 {
1080 isGrouped: true,
1081 eventGroupId: "test-group-no-sub-2",
1082 }
1083 )
1084
1085 expect(queue.addBulk).not.toHaveBeenCalled()
1086
1087 callInterceptorsSpy.mockRestore()
1088 })
1089 })
1090 })
1091
1092 describe("clearGroupedEvents", () => {
1093 beforeEach(async () => {
1094 jest.clearAllMocks()
1095
1096 eventBus = new RedisEventBusService(moduleDeps, {}, moduleDeclaration)
1097 redis = (eventBus as any).eventBusRedisConnection_
1098 })
1099
1100 it("should re-stage a large number of kept events without overflowing the call stack and keep the TTL", async () => {
1101 const keptCount = 300_000
1102 const staged = Array.from({ length: keptCount }, (_, i) =>
1103 JSON.stringify({ name: "kept-event", data: { data: { i } } })
1104 )
1105 staged.push(JSON.stringify({ name: "cleared-event", data: {} }))
1106
1107 redis.lrange = jest.fn().mockResolvedValue(staged)
1108 redis.pttl = jest.fn().mockResolvedValue(600_000)
1109
1110 await eventBus.clearGroupedEvents("large-group", {
1111 eventNames: ["cleared-event"],
1112 })
1113
1114 expect(pipelineMock.del).toHaveBeenCalledWith("staging:large-group")
1115
1116 const pushed = pipelineMock.rpush.mock.calls.flatMap((call) => {
1117 expect(call[0]).toEqual("staging:large-group")
1118 return call.slice(1)
1119 })
1120 expect(pushed).toHaveLength(keptCount)
1121 expect(pushed[0]).toEqual(staged[0])
1122 expect(pushed[keptCount - 1]).toEqual(staged[keptCount - 1])
1123
1124 expect(pipelineMock.pexpire).toHaveBeenCalledWith(
1125 "staging:large-group",
1126 600_000
1127 )
1128 expect(pipelineMock.exec).toHaveBeenCalledTimes(1)
1129 })
1130 })
1131
1132 describe("worker_", () => {
1133 describe("Successfully processes the jobs", () => {
1134 beforeEach(async () => {
1135 jest.clearAllMocks()
1136
1137 eventBus = new RedisEventBusService(moduleDeps, {}, moduleDeclaration)
1138 })
1139
1140 it("should process a simple event with no options", async () => {
1141 const test: string[] = []
1142
1143 eventBus.subscribe("eventName", () => {
1144 test.push("success")
1145
1146 return Promise.resolve()
1147 })
1148
1149 await eventBus.worker_({
1150 name: "eventName",
1151 data: { data: { test: 1 } },
1152 opts: { attempts: 1 },
1153 } as any)
1154
1155 expect(loggerMock.info).toHaveBeenCalledTimes(1)
1156 expect(loggerMock.info).toHaveBeenCalledWith(
1157 "Processing eventName which has 1 subscribers"
1158 )
1159
1160 expect(test).toEqual(["success"])
1161 })
1162
1163 it("should parse published_at and created_at as Dates after JSON serialization", async () => {
1164 const publishedAt = "2026-06-20T12:00:00.000Z"
1165 const createdAt = "2026-06-20T11:00:00.000Z"
1166 let receivedPublishedAt: unknown
1167 let receivedCreatedAt: unknown
1168
1169 eventBus.subscribe("eventName", (event) => {
1170 receivedPublishedAt = event.metadata?.published_at
1171 receivedCreatedAt = event.metadata?.created_at
1172 return Promise.resolve()
1173 })
1174
1175 await eventBus.worker_({
1176 name: "eventName",
1177 data: {
1178 data: { test: 1 },
1179 metadata: { published_at: publishedAt, created_at: createdAt },
1180 },
1181 opts: { attempts: 1 },
1182 } as any)
1183
1184 expect(receivedPublishedAt).toBeInstanceOf(Date)
1185 expect(receivedPublishedAt).toEqual(new Date(publishedAt))
1186 expect(receivedCreatedAt).toBeInstanceOf(Date)
1187 expect(receivedCreatedAt).toEqual(new Date(createdAt))
1188 })
1189
1190 it("should process event with failing subscribers", async () => {
1191 const test: string[] = []
1192
1193 eventBus.subscribe("eventName", () => {
1194 test.push("hi")
1195 return Promise.resolve()
1196 })
1197 eventBus.subscribe("eventName", () => {
1198 test.push("fail1")
1199 throw new Error("fail1")
1200 })
1201 eventBus.subscribe("eventName", () => {
1202 test.push("hi2")
1203 return Promise.resolve()
1204 })
1205 eventBus.subscribe("eventName", () => {
1206 test.push("fail2")
1207 return Promise.reject("fail2")
1208 })
1209
1210 await eventBus.worker_({
1211 name: "eventName",
1212 data: { data: { test: 1 } },
1213 opts: { attempts: 1 },
1214 update: (data) => data,
1215 } as any)
1216
1217 expect(loggerMock.info).toHaveBeenCalledTimes(1)
1218 expect(loggerMock.info).toHaveBeenCalledWith(
1219 "Processing eventName which has 4 subscribers"
1220 )
1221
1222 expect(loggerMock.warn).toHaveBeenCalledTimes(5)
1223 expect(loggerMock.warn).toHaveBeenNthCalledWith(
1224 1,
1225 "An error occurred while processing eventName:"
1226 )
1227 expect(loggerMock.warn).toHaveBeenNthCalledWith(2, new Error("fail1"))
1228
1229 expect(loggerMock.warn).toHaveBeenNthCalledWith(
1230 3,
1231 "An error occurred while processing eventName:"
1232 )
1233 expect(loggerMock.warn).toHaveBeenNthCalledWith(4, "fail2")
1234
1235 expect(loggerMock.warn).toHaveBeenNthCalledWith(
1236 5,
1237 "One or more subscribers of eventName failed. Retrying is not configured. Use 'attempts' option when emitting events."
1238 )
1239
1240 expect(test.sort()).toEqual(["hi", "fail1", "hi2", "fail2"].sort())
1241 })
1242
1243 it("should retry processing when subcribers fail, if configured - final attempt", async () => {
1244 eventBus.subscribe("eventName", async () => await Promise.resolve(), {
1245 subscriberId: "1",
1246 })
1247 eventBus.subscribe(
1248 "eventName",
1249 async () => await Promise.reject("fail1"),
1250 {
1251 subscriberId: "2",
1252 }
1253 )
1254
1255 await eventBus
1256 .worker_({
1257 name: "eventName",
1258 data: {
1259 data: {},
1260 completedSubscriberIds: ["1"],
1261 },
1262 attemptsMade: 2,
1263 update: (data) => data,
1264 opts: { attempts: 2 },
1265 } as any)
1266 .catch((error) => void 0)
1267
1268 expect(loggerMock.warn).toHaveBeenCalledTimes(2)
1269 expect(loggerMock.warn).toHaveBeenCalledWith(
1270 "An error occurred while processing eventName:"
1271 )
1272 expect(loggerMock.warn).toHaveBeenCalledWith("fail1")
1273
1274 expect(loggerMock.info).toHaveBeenCalledTimes(2)
1275 expect(loggerMock.info).toHaveBeenCalledWith(
1276 "Final retry attempt for eventName"
1277 )
1278 expect(loggerMock.info).toHaveBeenCalledWith(
1279 "Retrying eventName which has 2 subscribers (1 of them failed)"
1280 )
1281 })
1282
1283 it("should retry processing when subcribers fail, if configured", async () => {
1284 eventBus.subscribe("eventName", async () => await Promise.resolve(), {
1285 subscriberId: "1",
1286 })
1287 eventBus.subscribe(
1288 "eventName",
1289 async () => await Promise.reject("fail1"),
1290 {
1291 subscriberId: "2",
1292 }
1293 )
1294
1295 await eventBus
1296 .worker_({
1297 name: "eventName",
1298 data: {
1299 data: {},
1300 completedSubscriberIds: ["1"],
1301 },
1302 attemptsMade: 2,
1303 updateData: (data) => data,
1304 opts: { attempts: 3 },
1305 } as any)
1306 .catch((err) => void 0)
1307
1308 expect(loggerMock.warn).toHaveBeenCalledTimes(3)
1309 expect(loggerMock.warn).toHaveBeenCalledWith(
1310 "An error occurred while processing eventName:"
1311 )
1312 expect(loggerMock.warn).toHaveBeenCalledWith("fail1")
1313
1314 expect(loggerMock.warn).toHaveBeenCalledWith(
1315 "One or more subscribers of eventName failed. Retrying..."
1316 )
1317
1318 expect(loggerMock.info).toHaveBeenCalledTimes(1)
1319 expect(loggerMock.info).toHaveBeenCalledWith(
1320 "Retrying eventName which has 2 subscribers (1 of them failed)"
1321 )
1322 })
1323 })
1324 })
1325 })