1 import {
2 Event,
3 // TODO: Comment temporarely and we will re enable it in the near future #14478
4 // EventBusEventsOptions,
5 InternalModuleDeclaration,
6 Logger,
7 Message,
8 } from "@medusajs/framework/types"
9 import {
10 AbstractEventBusModuleService,
11 EventPriority,
12 isPresent,
13 promiseAll,
14 } from "@medusajs/framework/utils"
15 import {
16 BulkJobOptions,
17 Queue,
18 QueueOptions,
19 Worker,
20 WorkerOptions,
21 } from "bullmq"
22 import { Redis } from "ioredis"
23 import {
24 BullJob,
25 EmitOptions,
26 EventBusRedisModuleOptions,
27 Options,
28 } from "../types"
29
30 type InjectedDependencies = {
31 logger: Logger
32 eventBusRedisConnection: Redis
33 eventBusRedisQueueName: string
34 eventBusRedisQueueOptions: Omit<QueueOptions, "connection">
35 eventBusRedisWorkerOptions: Omit<WorkerOptions, "connection">
36 eventBusRedisJobOptions: EmitOptions
37 }
38
39 type IORedisEventType<T = unknown> = {
40 name: string
41 data: Omit<Event<T>, "name"> // See comment in `buildEvents` method
42 opts: BulkJobOptions
43 }
44
45 const GROUPED_EVENTS_CHUNK_SIZE = 1000
46
47 /**
48 * Can keep track of multiple subscribers to different events and run the
49 * subscribers when events happen. Events will run asynchronously.
50 */
51 // eslint-disable-next-line max-len
52 export default class RedisEventBusService extends AbstractEventBusModuleService {
53 protected readonly logger_: Logger
54 protected readonly eventBusRedisConnection_: Redis
55
56 protected readonly queueName_: string
57 protected readonly queueOptions_: Omit<QueueOptions, "connection">
58 protected readonly workerOptions_: Omit<WorkerOptions, "connection">
59 protected readonly jobOptions_: EmitOptions
60 // TODO: Comment temporarely and we will re enable it in the near future #14478
61 // private readonly eventOptions_: EventBusEventsOptions
62
63 protected queue_: Queue
64 protected bullWorker_: Worker
65
66 constructor(
67 {
68 logger,
69 eventBusRedisConnection,
70 eventBusRedisQueueName,
71 eventBusRedisQueueOptions,
72 eventBusRedisWorkerOptions,
73 eventBusRedisJobOptions,
74 }: InjectedDependencies,
75 _moduleOptions: EventBusRedisModuleOptions = {},
76 _moduleDeclaration: InternalModuleDeclaration
77 ) {
78 // @ts-ignore
79 super(...arguments)
80
81 this.eventBusRedisConnection_ = eventBusRedisConnection
82 this.logger_ = logger
83
84 this.queueName_ = eventBusRedisQueueName ?? "events-queue"
85 this.queueOptions_ = eventBusRedisQueueOptions ?? {}
86 this.workerOptions_ = eventBusRedisWorkerOptions ?? {}
87 this.jobOptions_ = eventBusRedisJobOptions ?? {}
88 // TODO: Comment temporarely and we will re enable it in the near future #14478
89 // this.eventOptions_ =
90 // _moduleOptions.eventOptions ??
91 // _moduleDeclaration.options?.eventOptions ??
92 // {}
93
94 this.queue_ = new Queue(this.queueName_, {
95 prefix: `${this.constructor.name}`,
96 ...this.queueOptions_,
97 connection: eventBusRedisConnection,
98 })
99
100 // Register our worker to handle emit calls
101 if (this.isWorkerMode) {
102 this.bullWorker_ = new Worker(this.queueName_, this.worker_, {
103 prefix: `${this.constructor.name}`,
104 ...this.workerOptions_,
105 connection: eventBusRedisConnection,
106 autorun: false,
107 })
108 }
109 }
110
111 __hooks = {
112 onApplicationStart: async () => {
113 if (!this.bullWorker_) {
114 return
115 }
116
117 // `run()` only resolves when the worker is closed and must not be awaited
118 // during application startup. See https://github.com/taskforcesh/bullmq/issues/2128
119 void this.bullWorker_.run().catch((error) => {
120 this.logger_.error(
121 `Error running event bus worker: ${error.message}`,
122 error
123 )
124 })
125 },
126 onApplicationShutdown: async () => {
127 await this.queue_.close()
128 // eslint-disable-next-line max-len
129 this.eventBusRedisConnection_.disconnect()
130 },
131 onApplicationPrepareShutdown: async () => {
132 await this.bullWorker_?.close()
133 },
134 }
135
136 /**
137 * Build events for queue processing with priority handling.
138 *
139 * Priority levels (lower number = higher priority):
140 * - 10: Critical business events (e.g., order placed)
141 * - 100: Default priority for normal events (default)
142 * - 2,097,152: Lowest priority for internal events
143 *
144 * Priority override hierarchy (highest to lowest precedence):
145 * 1. Message-level options (eventData.options.priority)
146 * 2. Emit-level options (options.priority)
147 * 3. Module-level job options (this.jobOptions_.priority)
148 * 4. Internal flag default (options.internal ? EventPriority.LOWEST : EventPriority.DEFAULT)
149 */
150 private buildEvents<T>(
151 eventsData: Message<T>[],
152 options: Options = {}
153 ): IORedisEventType<T>[] {
154 const opts = {
155 // default options
156 removeOnComplete: true,
157 attempts: 1,
158 priority: options.internal ? EventPriority.LOWEST : EventPriority.DEFAULT,
159 // global options
160 ...this.jobOptions_,
161 ...options,
162 }
163
164 return eventsData.map((eventData) => {
165 // We want to preserve event data + metadata. However, bullmq only allows for a single data field.
166 // Therefore, upon adding jobs to the queue we will serialize the event data and metadata into a single field
167 // and upon processing the job, we will deserialize it back into the original format expected by the subscribers.
168 const event = {
169 data: eventData.data,
170 metadata: eventData.metadata,
171 }
172
173 const finalOptions: IORedisEventType<T>["opts"] = {
174 ...opts,
175 ...eventData.options,
176 }
177
178 // TODO: Comment temporarely and we will re enable it in the near future #14478
179 // finalOptions.priority =
180 // eventData.options?.priority ??
181 // this.eventOptions_[eventData.name]?.priority
182
183 if (
184 finalOptions.priority != undefined &&
185 (finalOptions.priority < 1 ||
186 finalOptions.priority > EventPriority.LOWEST)
187 ) {
188 this.logger_.warn(
189 `Invalid priority value: ${finalOptions.priority} for event ${eventData.name}. Must be between 1 and ${EventPriority.LOWEST}`
190 )
191 finalOptions.priority = EventPriority.DEFAULT
192 this.logger_.warn(
193 `Setting priority to default value: ${EventPriority.DEFAULT} for event ${eventData.name}`
194 )
195 }
196
197 return {
198 data: event,
199 name: eventData.name,
200 opts: finalOptions,
201 } as IORedisEventType<T>
202 })
203 }
204
205 /**
206 * Emit a single or number of events
207 * @param eventsData
208 * @param options
209 */
210 async emit<T = unknown>(
211 eventsData: Message<T> | Message<T>[],
212 options: Options = {}
213 ): Promise<void> {
214 let eventsDataArray = (
215 Array.isArray(eventsData) ? eventsData : [eventsData]
216 ).map((eventData) => ({
217 ...eventData,
218 metadata: this.withCreatedAtMetadata(eventData.metadata),
219 }))
220
221 const { groupedEventsTTL = 600 } = options
222 delete options.groupedEventsTTL
223
224 const eventsToEmit = eventsDataArray.filter(
225 (eventData) => !isPresent(eventData.metadata?.eventGroupId)
226 )
227
228 const eventsToGroup = eventsDataArray.filter((eventData) =>
229 isPresent(eventData.metadata?.eventGroupId)
230 )
231
232 const groupEventsMap = new Map<string, Message<T>[]>()
233
234 for (const event of eventsToGroup) {
235 const groupId = event.metadata?.eventGroupId!
236 const groupEvents = groupEventsMap.get(groupId) ?? []
237
238 groupEvents.push(event)
239 groupEventsMap.set(groupId, groupEvents)
240 }
241
242 const promises: Promise<unknown>[] = []
243
244 if (eventsToEmit.length) {
245 eventsToEmit.forEach((eventData) =>
246 this.callInterceptors(eventData, { isGrouped: false })
247 )
248
249 const eventsWithSubscribers = eventsToEmit
250 .filter((eventData) => {
251 const eventSubscribers =
252 this.eventToSubscribersMap.get(eventData.name) || []
253 const wildcardSubscribers = this.eventToSubscribersMap.get("*") || []
254 return eventSubscribers.length || wildcardSubscribers.length
255 })
256 .map((eventData) => ({
257 ...eventData,
258 metadata: this.withPublishedAtMetadata(eventData.metadata),
259 }))
260
261 if (eventsWithSubscribers.length) {
262 const emitData = this.buildEvents(eventsWithSubscribers, options)
263 promises.push(this.queue_.addBulk(emitData))
264 }
265 }
266
267 for (const [groupId, events] of groupEventsMap.entries()) {
268 if (!events?.length) {
269 continue
270 }
271
272 const eventsData = this.buildEvents(events, options)
273
274 promises.push(this.groupEvents(groupId, eventsData, groupedEventsTTL))
275 }
276
277 await promiseAll(promises)
278 }
279
280 private async groupEvents<T = unknown>(
281 eventGroupId: string,
282 events: IORedisEventType<T>[],
283 ttl: number
284 ) {
285 const key = `staging:${eventGroupId}`
286 const pipeline = this.eventBusRedisConnection_.pipeline()
287
288 pipeline.rpush(key, ...events.map((event) => JSON.stringify(event)))
289
290 // Set a TTL for the key of the list that is scoped to a group.
291 // This will be helpful in preventing stale data from staying in redis for too long
292 // in the event the module fails to cleanup events. For long running workflows, setting a much higher
293 // TTL or even skipping the TTL would be required.
294 // NOTE: expire must run in the same pipeline AFTER rpush, since EXPIRE on a
295 // non-existent key is a no-op and rpush is what creates the key.
296 pipeline.expire(key, ttl)
297
298 await pipeline.exec()
299 }
300
301 private async getGroupedEvents(
302 eventGroupId: string
303 ): Promise<IORedisEventType[]> {
304 return await this.eventBusRedisConnection_
305 .lrange(`staging:${eventGroupId}`, 0, -1)
306 .then((result) => {
307 return result.map((jsonString) => JSON.parse(jsonString))
308 })
309 }
310
311 async releaseGroupedEvents(eventGroupId: string) {
312 const groupedEvents = await this.getGroupedEvents(eventGroupId)
313
314 // Call interceptors before emitting grouped events
315 groupedEvents.map((jobData) => {
316 this.callInterceptors(
317 {
318 name: jobData.name,
319 data: jobData.data.data,
320 metadata: jobData.data.metadata,
321 },
322 {
323 isGrouped: true,
324 eventGroupId,
325 }
326 )
327 })
328
329 const eventsWithSubscribers = groupedEvents
330 .filter((jobData) => {
331 const eventSubscribers =
332 this.eventToSubscribersMap.get(jobData.name) || []
333 const wildcardSubscribers = this.eventToSubscribersMap.get("*") || []
334 return eventSubscribers.length || wildcardSubscribers.length
335 })
336 .map((jobData) => ({
337 ...jobData,
338 data: {
339 ...jobData.data,
340 metadata: this.withPublishedAtMetadata(jobData.data.metadata),
341 },
342 }))
343
344 if (eventsWithSubscribers.length) {
345 await this.queue_.addBulk(eventsWithSubscribers)
346 }
347
348 await this.clearGroupedEvents(eventGroupId)
349 }
350
351 async clearGroupedEvents(
352 eventGroupId: string,
353 {
354 eventNames,
355 }: {
356 eventNames?: string[]
357 } = {}
358 ) {
359 if (!eventGroupId) {
360 return
361 }
362
363 if (eventNames?.length) {
364 /**
365 * If any event names are provided, we keep all events except the ones that match the event
366 * names. which allow to partially clear an event group.
367 */
368
369 const [eventsToKeep, ttl] = await promiseAll([
370 this.eventBusRedisConnection_
371 .lrange(`staging:${eventGroupId}`, 0, -1)
372 .then((result) => {
373 return result
374 .map((jsonString) => JSON.parse(jsonString))
375 .filter((event) => !eventNames.includes(event.name))
376 }),
377 this.eventBusRedisConnection_.pttl(`staging:${eventGroupId}`),
378 ])
379
380 // Create a pipeline
381 const pipeline = this.eventBusRedisConnection_.pipeline()
382
383 // Empty the current list
384 pipeline.del(`staging:${eventGroupId}`)
385
386 // Add the remaining events to the list, if any.
387 // RPUSH with no members is a Redis argument error, so only issue it
388 // when there is at least one event left to keep. Push in chunks since
389 // spreading a large list into the call arguments overflows the stack.
390 for (let i = 0; i < eventsToKeep.length; i += GROUPED_EVENTS_CHUNK_SIZE) {
391 pipeline.rpush(
392 `staging:${eventGroupId}`,
393 ...eventsToKeep
394 .slice(i, i + GROUPED_EVENTS_CHUNK_SIZE)
395 .map((event) => JSON.stringify(event))
396 )
397 }
398
399 // Restore the TTL set by groupEvents, which DEL drops
400 if (eventsToKeep.length > 0 && ttl > 0) {
401 pipeline.pexpire(`staging:${eventGroupId}`, ttl)
402 }
403
404 await pipeline.exec()
405
406 return
407 }
408
409 await this.eventBusRedisConnection_.unlink(`staging:${eventGroupId}`)
410 }
411
412 /**
413 * Handles incoming jobs.
414 * @param job The job object
415 * @return resolves to the results of the subscriber calls.
416 */
417 worker_ = async <T>(job: BullJob<T>): Promise<unknown> => {
418 const { data, name, opts } = job
419 const eventSubscribers = this.eventToSubscribersMap.get(name) || []
420 const wildcardSubscribers = this.eventToSubscribersMap.get("*") || []
421
422 const allSubscribers = eventSubscribers.concat(wildcardSubscribers)
423
424 // Pull already completed subscribers from the job data
425 const completedSubscribers = job.data.completedSubscriberIds || []
426
427 // Filter out already completed subscribers from the all subscribers
428 const subscribersInCurrentAttempt = allSubscribers.filter(
429 (subscriber) =>
430 subscriber.id && !completedSubscribers.includes(subscriber.id)
431 )
432
433 const currentAttempt = job.attemptsMade
434 const isRetry = currentAttempt > 1
435 const configuredAttempts = job.opts.attempts
436
437 const isFinalAttempt = currentAttempt === configuredAttempts
438
439 if (!opts.internal) {
440 if (isRetry) {
441 if (isFinalAttempt) {
442 this.logger_.info(`Final retry attempt for ${name}`)
443 }
444
445 this.logger_.info(
446 `Retrying ${name} which has ${eventSubscribers.length} subscribers (${subscribersInCurrentAttempt.length} of them failed)`
447 )
448 } else {
449 const prioirityInfo =
450 opts.priority != undefined ? ` (priority: ${opts.priority})` : ""
451 this.logger_.info(
452 `Processing ${name}${prioirityInfo} which has ${eventSubscribers.length} subscribers`
453 )
454 }
455 }
456
457 const completedSubscribersInCurrentAttempt: string[] = []
458
459 const metadata = this.parseEventMetadataDates(data.metadata)
460
461 const subscribersResult = await Promise.all(
462 subscribersInCurrentAttempt.map(async ({ id, subscriber }) => {
463 // De-serialize the event data and metadata from a single field into the original format expected by the subscribers
464 const event = {
465 name,
466 data: data.data,
467 metadata,
468 }
469
470 try {
471 return await subscriber(event).then((data) => {
472 // For every subscriber that completes successfully, add their id to the list of completed subscribers
473 completedSubscribersInCurrentAttempt.push(id)
474 return data
475 })
476 } catch (err) {
477 this.logger_?.warn(`An error occurred while processing ${name}:`)
478 this.logger_?.warn(err)
479
480 return err
481 }
482 })
483 )
484
485 // If the number of completed subscribers is different from the number of subcribers to process in current attempt, some of them failed
486 const didSubscribersFail =
487 completedSubscribersInCurrentAttempt.length !==
488 subscribersInCurrentAttempt.length
489
490 const isRetriesConfigured = configuredAttempts! > 1
491
492 // Therefore, if retrying is configured, we try again
493 const shouldRetry =
494 didSubscribersFail && isRetriesConfigured && !isFinalAttempt
495
496 if (shouldRetry) {
497 const updatedCompletedSubscribers = [
498 ...completedSubscribers,
499 ...completedSubscribersInCurrentAttempt,
500 ]
501
502 job.data.completedSubscriberIds = updatedCompletedSubscribers
503
504 await job.updateData(job.data)
505
506 const errorMessage = `One or more subscribers of ${name} failed. Retrying...`
507
508 this.logger_.warn(errorMessage)
509
510 throw Error(errorMessage)
511 }
512
513 if (didSubscribersFail && !isFinalAttempt) {
514 // If retrying is not configured, we log a warning to allow server admins to recover manually
515 this.logger_.warn(
516 `One or more subscribers of ${name} failed. Retrying is not configured. Use 'attempts' option when emitting events.`
517 )
518 }
519
520 return subscribersResult
521 }
522 }