1 import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql"
2 import {
3 Constructor,
4 Context,
5 FilterQuery,
6 FindConfig,
7 IEventBusModuleService,
8 IndexTypes,
9 InferEntityType,
10 InternalModuleDeclaration,
11 Logger,
12 ModulesSdkTypes,
13 RemoteQueryFunction,
14 } from "@medusajs/framework/types"
15 import {
16 MikroOrmBaseRepository as BaseRepository,
17 ContainerRegistrationKeys,
18 GraphQLUtils,
19 InjectManager,
20 MedusaContext,
21 Modules,
22 ModulesSdkUtils,
23 promiseAll,
24 toMikroORMEntity,
25 } from "@medusajs/framework/utils"
26 import { IndexData, IndexMetadata, IndexRelation, IndexSync } from "@models"
27 import { schemaObjectRepresentationPropertiesToOmit } from "@types"
28 import {
29 buildSchemaObjectRepresentation,
30 Configuration,
31 defaultSchema,
32 gqlSchemaToTypes,
33 IndexMetadataStatus,
34 } from "@utils"
35 import { baseGraphqlSchema } from "../utils/base-graphql-schema"
36 import { DataSynchronizer } from "./data-synchronizer"
37
38 type InjectedDependencies = {
39 logger: Logger
40 [Modules.EVENT_BUS]: IEventBusModuleService
41 storageProviderCtr: Constructor<IndexTypes.StorageProvider>
42 [ContainerRegistrationKeys.QUERY]: RemoteQueryFunction
43 storageProviderCtrOptions: unknown
44 baseRepository: BaseRepository
45 indexMetadataService: ModulesSdkTypes.IMedusaInternalService<any>
46 indexSyncService: ModulesSdkTypes.IMedusaInternalService<any>
47 dataSynchronizer: DataSynchronizer
48 }
49
50 export default class IndexModuleService
51 extends ModulesSdkUtils.MedusaService({})
52 implements IndexTypes.IIndexService
53 {
54 #isWorkerMode: boolean = false
55
56 private static readonly SyncSubscribersDescriptor = {
57 continueSync: {
58 eventName: "index.continue-sync",
59 methodName: "continueSync",
60 },
61 fullSync: { eventName: "index.full-sync", methodName: "fullSync" },
62 resetSync: { eventName: "index.reset-sync", methodName: "resetSync" },
63 } as const
64
65 private readonly baseRepository_: BaseRepository
66
67 private readonly container_: InjectedDependencies
68 private readonly moduleOptions_: IndexTypes.IndexModuleOptions
69
70 protected readonly eventBusModuleService_: IEventBusModuleService
71
72 protected schemaObjectRepresentation_: IndexTypes.SchemaObjectRepresentation
73 protected schemaEntitiesMap_: Record<string, any>
74
75 protected readonly storageProviderCtr_: Constructor<IndexTypes.StorageProvider>
76 protected readonly storageProviderCtrOptions_: unknown
77
78 protected storageProvider_: IndexTypes.StorageProvider
79
80 private configurationChecker_: Configuration
81
82 private get indexMetadataService_(): ModulesSdkTypes.IMedusaInternalService<any> {
83 return this.container_.indexMetadataService
84 }
85
86 private get indexSyncService_(): ModulesSdkTypes.IMedusaInternalService<any> {
87 return this.container_.indexSyncService
88 }
89
90 private get dataSynchronizer_(): DataSynchronizer {
91 return this.container_.dataSynchronizer
92 }
93
94 private get logger_(): Logger {
95 try {
96 return this.container_.logger
97 } catch (e) {
98 return console as unknown as Logger
99 }
100 }
101
102 constructor(
103 container: InjectedDependencies,
104 moduleOptions: IndexTypes.IndexModuleOptions,
105 protected readonly moduleDeclaration: InternalModuleDeclaration
106 ) {
107 super(...arguments)
108
109 this.baseRepository_ = container.baseRepository
110 this.container_ = container
111 this.moduleOptions_ = (moduleOptions ??
112 moduleDeclaration.options ??
113 moduleDeclaration) as unknown as IndexTypes.IndexModuleOptions
114
115 this.#isWorkerMode = moduleDeclaration.worker_mode !== "server"
116
117 const {
118 [Modules.EVENT_BUS]: eventBusModuleService,
119 storageProviderCtr,
120 storageProviderCtrOptions,
121 } = container
122
123 this.eventBusModuleService_ = eventBusModuleService
124 this.storageProviderCtr_ = storageProviderCtr
125 this.storageProviderCtrOptions_ = storageProviderCtrOptions
126 if (!this.eventBusModuleService_) {
127 throw new Error(
128 "EventBusModuleService is required for the IndexModule to work"
129 )
130 }
131 }
132
133 __hooks = {
134 onApplicationStart(this: IndexModuleService) {
135 return this.onApplicationStart_()
136 },
137 }
138
139 protected async onApplicationStart_() {
140 try {
141 const executableSchema = this.buildSchemaObjectRepresentation_()
142
143 this.storageProvider_ = new this.storageProviderCtr_(
144 this.container_,
145 Object.assign(this.storageProviderCtrOptions_ ?? {}, {
146 schemaObjectRepresentation: this.schemaObjectRepresentation_,
147 entityMap: this.schemaEntitiesMap_,
148 }),
149 this.moduleOptions_
150 ) as IndexTypes.StorageProvider
151
152 this.registerListeners()
153
154 if (this.storageProvider_.onApplicationStart) {
155 await this.storageProvider_.onApplicationStart()
156 }
157
158 await gqlSchemaToTypes(executableSchema!)
159
160 /**
161 * Only run the data synchronization in worker mode
162 */
163
164 if (this.#isWorkerMode) {
165 this.dataSynchronizer_.onApplicationStart({
166 schemaObjectRepresentation: this.schemaObjectRepresentation_,
167 storageProvider: this.storageProvider_,
168 })
169
170 this.configurationChecker_ = new Configuration({
171 logger: this.logger_,
172 schemaObjectRepresentation: this.schemaObjectRepresentation_,
173 indexMetadataService: this.indexMetadataService_,
174 indexSyncService: this.indexSyncService_,
175 dataSynchronizer: this.dataSynchronizer_,
176 })
177 const entitiesMetadataChanged =
178 await this.configurationChecker_.checkChanges()
179
180 if (entitiesMetadataChanged.length) {
181 await this.dataSynchronizer_.syncEntities(entitiesMetadataChanged)
182 }
183 }
184 } catch (e) {
185 this.logger_.error(e)
186 }
187 }
188
189 async query<const TEntry extends string>(
190 config: IndexTypes.IndexQueryConfig<TEntry>
191 ): Promise<IndexTypes.QueryResultSet<TEntry>> {
192 return await this.storageProvider_.query(config)
193 }
194
195 protected registerListeners() {
196 if (!this.#isWorkerMode) {
197 return
198 }
199
200 const schemaObjectRepresentation = (this.schemaObjectRepresentation_ ??
201 {}) as IndexTypes.SchemaObjectRepresentation
202
203 // Register entity event listeners
204 for (const [entityName, schemaEntityObjectRepresentation] of Object.entries(
205 schemaObjectRepresentation
206 )) {
207 if (schemaObjectRepresentationPropertiesToOmit.includes(entityName)) {
208 continue
209 }
210
211 ;(
212 schemaEntityObjectRepresentation as IndexTypes.SchemaObjectEntityRepresentation
213 ).listeners.forEach((listener) => {
214 this.eventBusModuleService_.subscribe(
215 listener,
216 this.storageProvider_.consumeEvent(schemaEntityObjectRepresentation)
217 )
218 })
219 }
220
221 // Register sync subscribers
222 for (const { eventName, methodName } of Object.values(
223 IndexModuleService.SyncSubscribersDescriptor
224 )) {
225 this.eventBusModuleService_.subscribe(
226 eventName,
227 this[methodName].bind(this)
228 )
229 }
230 }
231
232 private buildSchemaObjectRepresentation_():
233 | GraphQLUtils.GraphQLSchema
234 | undefined {
235 if (this.schemaObjectRepresentation_) {
236 return
237 }
238
239 const { objectRepresentation, entitiesMap, executableSchema } =
240 buildSchemaObjectRepresentation(
241 baseGraphqlSchema + (this.moduleOptions_.schema ?? defaultSchema)
242 )
243
244 this.schemaObjectRepresentation_ = objectRepresentation
245 this.schemaEntitiesMap_ = entitiesMap
246
247 return executableSchema
248 }
249
250 /**
251 * Example output:
252 *
253 *
254 * ```json
255 * [
256 * {
257 * "id": "prod_123",
258 * "entity": "product",
259 * "status": "pending",
260 * "fields": ["id"],
261 * "updated_at": "<timestamp of last indexed data>",
262 * "last_synced_key": "prod_4321"
263 * },
264 * ...
265 * ]
266 * ```
267 * @returns Detailed index metadata with the last synced key for each entity
268 */
269 @InjectManager()
270 async getInfo(
271 @MedusaContext() sharedContext?: Context
272 ): Promise<IndexTypes.IndexInfo[]> {
273 const listArguments = [
274 {} as FilterQuery<InferEntityType<typeof IndexMetadata>>,
275 {} as FindConfig<InferEntityType<typeof IndexMetadata>>,
276 sharedContext,
277 ]
278
279 const [indexMetadata, indexSync] = await promiseAll([
280 this.indexMetadataService_.list(...listArguments) as Promise<
281 InferEntityType<typeof IndexMetadata>[]
282 >,
283 this.indexSyncService_.list(...listArguments) as Promise<
284 InferEntityType<typeof IndexSync>[]
285 >,
286 ])
287
288 const lastEntitySyncedKeyMap = new Map<string, string>(
289 indexSync
290 .filter((sync) => sync.last_key !== null)
291 .map((sync) => [sync.entity, sync.last_key!])
292 )
293
294 const indexInfo = indexMetadata.map((metadata) => {
295 return {
296 id: metadata.id,
297 entity: metadata.entity,
298 status: metadata.status,
299 fields: metadata.fields.split(","),
300 updated_at: metadata.updated_at,
301 last_synced_key: lastEntitySyncedKeyMap.get(metadata.entity) ?? null,
302 } satisfies IndexTypes.IndexInfo
303 })
304
305 return indexInfo
306 }
307
308 async sync({ strategy }: { strategy?: "full" | "reset" } = {}) {
309 if (strategy && !["full", "reset"].includes(strategy)) {
310 throw new Error(
311 `Invalid sync strategy: ${strategy}. Must be "full" or "reset"`
312 )
313 }
314
315 switch (strategy) {
316 case "full":
317 await this.fullSync()
318 break
319 case "reset":
320 await this.resetSync()
321 break
322 default:
323 await this.continueSync()
324 break
325 }
326 }
327
328 /**
329 * Continue the sync of the entities no matter their status
330 * @param sharedContext
331 * @returns
332 */
333 private async continueSync() {
334 if (!this.#isWorkerMode) {
335 await this.baseRepository_.transaction(async (transactionManager) => {
336 await this.indexMetadataService_.update(
337 {
338 selector: {
339 status: [
340 IndexMetadataStatus.DONE,
341 IndexMetadataStatus.ERROR,
342 IndexMetadataStatus.PROCESSING,
343 ],
344 },
345 data: {
346 status: IndexMetadataStatus.PENDING,
347 },
348 },
349 { transactionManager }
350 )
351
352 this.eventBusModuleService_.emit({
353 name: IndexModuleService.SyncSubscribersDescriptor.continueSync
354 .eventName,
355 data: {},
356 options: {
357 internal: true,
358 },
359 })
360 })
361
362 return
363 }
364
365 try {
366 const entities = await this.configurationChecker_.checkChanges()
367
368 if (!entities.length) {
369 return
370 }
371
372 return await this.dataSynchronizer_.syncEntities(entities)
373 } catch (e) {
374 this.logger_.error(e)
375 throw new Error("[Index engine] Failed to continue sync")
376 }
377 }
378
379 private async fullSync() {
380 if (!this.#isWorkerMode) {
381 await this.baseRepository_.transaction(async (transactionManager) => {
382 await promiseAll([
383 this.indexMetadataService_.update(
384 {
385 selector: {
386 status: [
387 IndexMetadataStatus.DONE,
388 IndexMetadataStatus.ERROR,
389 IndexMetadataStatus.PROCESSING,
390 ],
391 },
392 data: {
393 status: IndexMetadataStatus.PENDING,
394 },
395 },
396 { transactionManager }
397 ),
398 this.indexSyncService_.update(
399 {
400 selector: { last_key: { $ne: null } },
401 data: { last_key: null },
402 },
403 { transactionManager }
404 ),
405 ])
406
407 await this.eventBusModuleService_.emit({
408 name: IndexModuleService.SyncSubscribersDescriptor.fullSync.eventName,
409 data: {},
410 options: {
411 internal: true,
412 },
413 })
414 })
415
416 return
417 }
418
419 try {
420 const entities = await this.configurationChecker_.checkChanges()
421
422 if (!entities.length) {
423 return
424 }
425
426 return await this.dataSynchronizer_.syncEntities(entities)
427 } catch (e) {
428 this.logger_.error(e)
429 throw new Error("[Index engine] Failed to full sync")
430 }
431 }
432
433 private async resetSync() {
434 if (!this.#isWorkerMode) {
435 await this.baseRepository_.transaction(
436 async (transactionManager: SqlEntityManager) => {
437 const metadata = transactionManager.getDriver().getMetadata()
438 const truncableTables = [
439 toMikroORMEntity(IndexData),
440 toMikroORMEntity(IndexRelation),
441 toMikroORMEntity(IndexMetadata),
442 toMikroORMEntity(IndexSync),
443 ].map((entity) => metadata.get(entity.name).collection)
444
445 await transactionManager.execute(
446 `TRUNCATE TABLE ${truncableTables.join(", ")} CASCADE`
447 )
448
449 await this.eventBusModuleService_.emit({
450 name: IndexModuleService.SyncSubscribersDescriptor.resetSync
451 .eventName,
452 data: {},
453 options: {
454 internal: true,
455 },
456 })
457 }
458 )
459
460 return
461 }
462
463 try {
464 const changes = await this.configurationChecker_.checkChanges()
465
466 if (!changes.length) {
467 return
468 }
469
470 await this.dataSynchronizer_.syncEntities(changes)
471 } catch (e) {
472 this.logger_.error(e)
473 throw new Error("[Index engine] Failed to reset sync")
474 }
475 }
476 }