|
1
|
import { |
|
2
|
Event, |
|
3
|
EventBusTypes, |
|
4
|
InternalModuleDeclaration, |
|
5
|
Logger, |
|
6
|
MedusaContainer, |
|
7
|
Message, |
|
8
|
Subscriber, |
|
9
|
} from "@medusajs/framework/types" |
|
10
|
import { AbstractEventBusModuleService } from "@medusajs/framework/utils" |
|
11
|
import { EventEmitter } from "events" |
|
12
|
import { setTimeout } from "timers/promises" |
|
13
|
|
|
14
|
type InjectedDependencies = { |
|
15
|
logger: Logger |
|
16
|
} |
|
17
|
|
|
18
|
type StagingQueueType = Map<string, Message[]> |
|
19
|
|
|
20
|
const eventEmitter = new EventEmitter() |
|
21
|
eventEmitter.setMaxListeners(Infinity) |
|
22
|
|
|
23
|
// eslint-disable-next-line max-len |
|
24
|
export default class LocalEventBusService extends AbstractEventBusModuleService { |
|
25
|
protected readonly logger_: Logger |
|
26
|
protected readonly eventEmitter_: EventEmitter |
|
27
|
protected groupedEventsMap_: StagingQueueType |
|
28
|
|
|
29
|
constructor( |
|
30
|
{ logger }: MedusaContainer & InjectedDependencies, |
|
31
|
moduleOptions = {}, |
|
32
|
moduleDeclaration: InternalModuleDeclaration |
|
33
|
) { |
|
34
|
// @ts-ignore |
|
35
|
// eslint-disable-next-line prefer-rest-params |
|
36
|
super(...arguments) |
|
37
|
|
|
38
|
this.logger_ = logger ?? console |
|
39
|
this.eventEmitter_ = eventEmitter |
|
40
|
this.groupedEventsMap_ = new Map() |
|
41
|
} |
|
42
|
|
|
43
|
private logProcessingEvent( |
|
44
|
eventData: Message, |
|
45
|
options: Record<string, unknown> = {}, |
|
46
|
totalSubscribers: number |
|
47
|
) { |
|
48
|
if ( |
|
49
|
totalSubscribers && |
|
50
|
!options?.internal && |
|
51
|
!eventData.options?.internal |
|
52
|
) { |
|
53
|
this.logger_.info( |
|
54
|
`Processing ${eventData.name} which has ${totalSubscribers} subscribers` |
|
55
|
) |
|
56
|
} |
|
57
|
} |
|
58
|
|
|
59
|
/** |
|
60
|
* Accept an event name and some options |
|
61
|
* |
|
62
|
* @param eventsData |
|
63
|
* @param options The options can include `internal` which will prevent the event from being logged |
|
64
|
*/ |
|
65
|
async emit<T = unknown>( |
|
66
|
eventsData: Message<T> | Message<T>[], |
|
67
|
options: Record<string, unknown> = {} |
|
68
|
): Promise<void> { |
|
69
|
const normalizedEventsData = Array.isArray(eventsData) |
|
70
|
? eventsData |
|
71
|
: [eventsData] |
|
72
|
|
|
73
|
for (const eventData of normalizedEventsData.map((event) => ({ |
|
74
|
...event, |
|
75
|
metadata: this.withCreatedAtMetadata(event.metadata), |
|
76
|
}))) { |
|
77
|
await this.groupOrEmitEvent({ |
|
78
|
...eventData, |
|
79
|
options, |
|
80
|
}) |
|
81
|
} |
|
82
|
} |
|
83
|
|
|
84
|
// If the data of the event consists of a eventGroupId, we don't emit the event, instead |
|
85
|
// we add them to a queue grouped by the eventGroupId and release them when |
|
86
|
// explicitly requested. |
|
87
|
// This is useful in the event of a distributed transaction where you'd want to emit |
|
88
|
// events only once the transaction ends. |
|
89
|
private async groupOrEmitEvent<T = unknown>(eventData: Message<T>) { |
|
90
|
const { options, ...eventBody } = eventData |
|
91
|
const eventGroupId = eventBody.metadata?.eventGroupId |
|
92
|
const hasStarSubscriber = this.eventEmitter_.listenerCount("*") > 0 |
|
93
|
|
|
94
|
if (eventGroupId) { |
|
95
|
await this.groupEvent(eventGroupId, eventData) |
|
96
|
} else { |
|
97
|
const options_ = eventData.options as { delay: number } |
|
98
|
const delay = (ms?: number) => (ms ? setTimeout(ms) : Promise.resolve()) |
|
99
|
|
|
100
|
const eventListenersCount = this.eventEmitter_.listenerCount( |
|
101
|
eventData.name |
|
102
|
) |
|
103
|
|
|
104
|
delay(options_?.delay).then(async () => { |
|
105
|
// Call interceptors before emitting |
|
106
|
void this.callInterceptors(eventData, { isGrouped: false }) |
|
107
|
|
|
108
|
const publishedEventBody = { |
|
109
|
...eventBody, |
|
110
|
metadata: this.withPublishedAtMetadata(eventBody.metadata), |
|
111
|
} |
|
112
|
|
|
113
|
if (eventListenersCount) { |
|
114
|
this.eventEmitter_.emit(eventData.name, publishedEventBody) |
|
115
|
} |
|
116
|
|
|
117
|
if (hasStarSubscriber) { |
|
118
|
this.eventEmitter_.emit("*", publishedEventBody) |
|
119
|
} |
|
120
|
|
|
121
|
const totalSubscribers = |
|
122
|
eventListenersCount + (hasStarSubscriber ? 1 : 0) |
|
123
|
this.logProcessingEvent(eventData, options, totalSubscribers) |
|
124
|
}) |
|
125
|
} |
|
126
|
} |
|
127
|
|
|
128
|
// Groups an event to a queue to be emitted upon explicit release |
|
129
|
private async groupEvent<T = unknown>( |
|
130
|
eventGroupId: string, |
|
131
|
eventData: Message<T> |
|
132
|
) { |
|
133
|
const groupedEvents = this.groupedEventsMap_.get(eventGroupId) || [] |
|
134
|
|
|
135
|
groupedEvents.push(eventData) |
|
136
|
|
|
137
|
this.groupedEventsMap_.set(eventGroupId, groupedEvents) |
|
138
|
} |
|
139
|
|
|
140
|
async releaseGroupedEvents(eventGroupId: string) { |
|
141
|
let groupedEvents = this.groupedEventsMap_.get(eventGroupId) || [] |
|
142
|
groupedEvents = JSON.parse(JSON.stringify(groupedEvents)) |
|
143
|
|
|
144
|
const hasStarSubscriber = this.eventEmitter_.listenerCount("*") > 0 |
|
145
|
|
|
146
|
for (const event of groupedEvents) { |
|
147
|
const { options, ...eventBody } = event |
|
148
|
|
|
149
|
const eventListenersCount = this.eventEmitter_.listenerCount(event.name) |
|
150
|
|
|
151
|
const options_ = options as { delay: number } |
|
152
|
const delay = (ms?: number) => (ms ? setTimeout(ms) : Promise.resolve()) |
|
153
|
|
|
154
|
delay(options_?.delay).then(async () => { |
|
155
|
// Call interceptors before emitting grouped events |
|
156
|
void this.callInterceptors(event, { isGrouped: true, eventGroupId }) |
|
157
|
|
|
158
|
const publishedEventBody = { |
|
159
|
...eventBody, |
|
160
|
metadata: this.withPublishedAtMetadata( |
|
161
|
this.parseEventMetadataDates(eventBody.metadata) // necessary cause JSON.parse stringified created_at |
|
162
|
), |
|
163
|
} |
|
164
|
|
|
165
|
if (eventListenersCount) { |
|
166
|
this.eventEmitter_.emit(event.name, publishedEventBody) |
|
167
|
} |
|
168
|
|
|
169
|
if (hasStarSubscriber) { |
|
170
|
this.eventEmitter_.emit("*", publishedEventBody) |
|
171
|
} |
|
172
|
|
|
173
|
const totalSubscribers = |
|
174
|
eventListenersCount + (hasStarSubscriber ? 1 : 0) |
|
175
|
this.logProcessingEvent(event, options, totalSubscribers) |
|
176
|
}) |
|
177
|
} |
|
178
|
|
|
179
|
await this.clearGroupedEvents(eventGroupId) |
|
180
|
} |
|
181
|
|
|
182
|
async clearGroupedEvents( |
|
183
|
eventGroupId: string, |
|
184
|
{ eventNames }: { eventNames?: string[] } = {} |
|
185
|
) { |
|
186
|
if (eventNames?.length) { |
|
187
|
const groupedEvents = this.groupedEventsMap_.get(eventGroupId) || [] |
|
188
|
const eventsToKeep = groupedEvents.filter( |
|
189
|
(event) => !eventNames!.includes(event.name) |
|
190
|
) |
|
191
|
this.groupedEventsMap_.set(eventGroupId, eventsToKeep) |
|
192
|
} else { |
|
193
|
this.groupedEventsMap_.delete(eventGroupId) |
|
194
|
} |
|
195
|
} |
|
196
|
|
|
197
|
subscribe( |
|
198
|
event: string | symbol, |
|
199
|
subscriber: Subscriber, |
|
200
|
context?: EventBusTypes.SubscriberContext |
|
201
|
): this { |
|
202
|
super.subscribe(event, subscriber, context) |
|
203
|
|
|
204
|
const subscriberId = |
|
205
|
context?.subscriberId ?? (subscriber as any).subscriberId |
|
206
|
|
|
207
|
const wrappedSubscriber = async (data: Event) => { |
|
208
|
try { |
|
209
|
await subscriber(data) |
|
210
|
} catch (err) { |
|
211
|
this.logger_.error( |
|
212
|
`An error occurred while processing ${event.toString()}:` |
|
213
|
) |
|
214
|
this.logger_.error(err) |
|
215
|
} |
|
216
|
} |
|
217
|
|
|
218
|
if (subscriberId) { |
|
219
|
;(wrappedSubscriber as any).subscriberId = subscriberId |
|
220
|
} |
|
221
|
|
|
222
|
this.eventEmitter_.on(event, wrappedSubscriber) |
|
223
|
|
|
224
|
return this |
|
225
|
} |
|
226
|
|
|
227
|
unsubscribe( |
|
228
|
event: string | symbol, |
|
229
|
subscriber: Subscriber, |
|
230
|
context: EventBusTypes.SubscriberContext |
|
231
|
): this { |
|
232
|
super.unsubscribe(event, subscriber, context) |
|
233
|
|
|
234
|
const subscriberId = |
|
235
|
context?.subscriberId ?? (subscriber as any).subscriberId |
|
236
|
|
|
237
|
if (subscriberId) { |
|
238
|
const listeners = this.eventEmitter_.listeners(event) |
|
239
|
const wrappedSubscriber = listeners.find( |
|
240
|
(listener) => (listener as any).subscriberId === subscriberId |
|
241
|
) |
|
242
|
|
|
243
|
if (wrappedSubscriber) { |
|
244
|
this.eventEmitter_.off(event, wrappedSubscriber as any) |
|
245
|
} |
|
246
|
} else { |
|
247
|
this.eventEmitter_.off(event, subscriber) |
|
248
|
} |
|
249
|
|
|
250
|
return this |
|
251
|
} |
|
252
|
} |