1 import {
2 Context,
3 Event,
4 ILockingModule,
5 IndexTypes,
6 QueryGraphFunction,
7 RemoteQueryFunction,
8 Subscriber,
9 } from "@medusajs/framework/types"
10 import {
11 MikroOrmBaseRepository as BaseRepository,
12 CommonEvents,
13 ContainerRegistrationKeys,
14 deepMerge,
15 InjectManager,
16 InjectTransactionManager,
17 isDefined,
18 MedusaContext,
19 Modules,
20 toMikroORMEntity,
21 unflattenObjectKeys,
22 } from "@medusajs/framework/utils"
23 import {
24 EntityManager,
25 EntityRepository,
26 SqlEntityManager,
27 } from "@medusajs/framework/mikro-orm/postgresql"
28 import { IndexData, IndexRelation } from "@models"
29 import { createPartitions, QueryBuilder } from "../utils"
30 import { flattenObjectKeys } from "../utils/flatten-object-keys"
31 import { normalizeFieldsSelection } from "../utils/normalize-fields-selection"
32
33 type InjectedDependencies = {
34 manager: EntityManager
35 [ContainerRegistrationKeys.QUERY]: RemoteQueryFunction
36 baseRepository: BaseRepository
37 [Modules.LOCKING]?: ILockingModule
38 }
39
40 const CREATE_PARTITIONS_LOCK_KEY = "index-module:create-partitions"
41 const CREATE_PARTITIONS_LOCK_TIMEOUT = 300
42
43 export class PostgresProvider implements IndexTypes.StorageProvider {
44 #isReady_: Promise<void>
45
46 protected readonly eventActionToMethodMap_ = {
47 created: "onCreate",
48 updated: "onUpdate",
49 deleted: "onDelete",
50 restored: "onCreate",
51 attached: "onAttach",
52 detached: "onDetach",
53 }
54
55 protected container_: InjectedDependencies
56 protected readonly schemaObjectRepresentation_: IndexTypes.SchemaObjectRepresentation
57 protected readonly schemaEntitiesMap_: Record<string, any>
58 protected readonly moduleOptions_: IndexTypes.IndexModuleOptions
59 protected readonly manager_: SqlEntityManager
60 protected readonly query_: RemoteQueryFunction
61 protected baseRepository_: BaseRepository
62
63 constructor(
64 container: InjectedDependencies,
65 options: {
66 schemaObjectRepresentation: IndexTypes.SchemaObjectRepresentation
67 entityMap: Record<string, any>
68 },
69 moduleOptions: IndexTypes.IndexModuleOptions
70 ) {
71 this.container_ = container
72 this.manager_ = container.manager
73 this.query_ = container.query
74 this.moduleOptions_ = moduleOptions
75 this.baseRepository_ = container.baseRepository
76
77 this.schemaObjectRepresentation_ = options.schemaObjectRepresentation
78 this.schemaEntitiesMap_ = options.entityMap
79 }
80
81 async onApplicationStart() {
82 let initalizedOk: (value: any) => void = () => {}
83 let initalizedNok: (value: any) => void = () => {}
84 this.#isReady_ = new Promise((resolve, reject) => {
85 initalizedOk = resolve
86 initalizedNok = reject
87 })
88
89 const locking = this.container_[Modules.LOCKING]
90
91 const run = () =>
92 createPartitions(this.schemaObjectRepresentation_, this.manager_.fork())
93
94 // Serialize partition DDL across instances
95 const work = locking
96 ? locking.execute(CREATE_PARTITIONS_LOCK_KEY, run, {
97 timeout: CREATE_PARTITIONS_LOCK_TIMEOUT,
98 })
99 : run()
100
101 await work.then(initalizedOk).catch(initalizedNok)
102 }
103
104 protected static parseData<
105 TData extends { id: string; [key: string]: unknown }
106 >(
107 data: TData | TData[],
108 schemaEntityObjectRepresentation: IndexTypes.SchemaObjectEntityRepresentation
109 ) {
110 const data_ = Array.isArray(data) ? data : [data]
111
112 // Always keep the id in the entity properties
113 const entityProperties: string[] = ["id"]
114 const parentsProperties: { [entity: string]: string[] } = {}
115
116 /**
117 * Split fields into entity properties and parents properties
118 */
119
120 schemaEntityObjectRepresentation.fields.forEach((field) => {
121 if (field.includes(".")) {
122 const parentAlias = field.split(".")[0]
123 const parentSchemaObjectRepresentation =
124 schemaEntityObjectRepresentation.parents.find(
125 (parent) => parent.inverseSideProp === parentAlias
126 )
127
128 if (!parentSchemaObjectRepresentation) {
129 throw new Error(
130 `IndexModule error, unable to parse data for ${schemaEntityObjectRepresentation.entity}. The parent schema object representation could not be found for the alias ${parentAlias} for the entity ${schemaEntityObjectRepresentation.entity}.`
131 )
132 }
133
134 parentsProperties[parentSchemaObjectRepresentation.ref.entity] ??= []
135 parentsProperties[parentSchemaObjectRepresentation.ref.entity].push(
136 field
137 )
138 } else {
139 entityProperties.push(field)
140 }
141 })
142
143 return {
144 data: data_,
145 entityProperties,
146 parentsProperties,
147 }
148 }
149
150 protected static parseMessageData<TData extends { id: string | string[] }>(
151 message?: Event
152 ): {
153 action: string
154 data: TData[]
155 ids: string[]
156 } | void {
157 const isExpectedFormat =
158 isDefined(message?.data) && isDefined(message?.metadata?.action)
159
160 if (!isExpectedFormat) {
161 return
162 }
163
164 const result: {
165 action: string
166 data: TData[]
167 ids: string[]
168 } = {
169 action: "",
170 data: [],
171 ids: [],
172 }
173
174 result.action = message!.metadata!.action as string
175 result.data = message!.data as TData[]
176 result.data = Array.isArray(result.data) ? result.data : [result.data]
177 result.ids = result.data.flatMap((d) =>
178 Array.isArray(d.id) ? d.id : [d.id]
179 )
180
181 return result
182 }
183
184 consumeEvent(
185 schemaEntityObjectRepresentation: IndexTypes.SchemaObjectEntityRepresentation
186 ): Subscriber<{ id: string | string[] }> {
187 return async (event: Event) => {
188 await this.#isReady_
189
190 const data_: { id: string }[] = Array.isArray(event.data)
191 ? event.data
192 : [event.data]
193 let ids: string[] = data_.flatMap((d) =>
194 Array.isArray(d.id) ? d.id : [d.id]
195 )
196 let action = event.name.split(".").pop() || ""
197
198 const parsedMessage = PostgresProvider.parseMessageData(event)
199 if (parsedMessage) {
200 action = parsedMessage.action
201 ids = parsedMessage.ids
202 }
203
204 const targetMethod = this.eventActionToMethodMap_[action]
205
206 if (!targetMethod) {
207 return
208 }
209
210 const { fields, alias } = schemaEntityObjectRepresentation
211
212 let withDeleted: boolean | undefined
213 if (action === CommonEvents.DELETED || action === CommonEvents.DETACHED) {
214 withDeleted = true
215 }
216
217 // Process ids in batches of 100
218 const batchSize = 100
219 const idsBatches: string[][] = []
220
221 for (let i = 0; i < ids.length; i += batchSize) {
222 idsBatches.push(ids.slice(i, i + batchSize))
223 }
224
225 for (const idsBatch of idsBatches) {
226 const graphConfig: Parameters<QueryGraphFunction>[0] = {
227 entity: alias,
228 filters: {
229 id: idsBatch,
230 },
231 fields: [...new Set(["id", ...fields])],
232 withDeleted,
233 }
234
235 const { data: entityData } = await this.query_.graph(graphConfig)
236
237 const argument = {
238 entity: schemaEntityObjectRepresentation.entity,
239 data: entityData,
240 schemaEntityObjectRepresentation,
241 }
242
243 await this[targetMethod](argument)
244 }
245 }
246 }
247
248 @InjectManager()
249 async query<const TEntry extends string>(
250 config: IndexTypes.IndexQueryConfig<TEntry>,
251 @MedusaContext() sharedContext: Context = {}
252 ): Promise<IndexTypes.QueryResultSet<TEntry>> {
253 await this.#isReady_
254
255 const { fields = [], filters = {}, joinFilters = {}, idsOnly } = config
256 const { take, skip, order: inputOrderBy = {} } = config.pagination ?? {}
257
258 const select = normalizeFieldsSelection(fields)
259 const where = flattenObjectKeys(unflattenObjectKeys(filters))
260
261 const inputOrderByObj = unflattenObjectKeys(inputOrderBy)
262 const joinWhere = flattenObjectKeys(unflattenObjectKeys(joinFilters))
263 const orderBy = flattenObjectKeys(inputOrderByObj)
264
265 const { manager } = sharedContext as { manager: SqlEntityManager }
266 let hasPagination = false
267 let hasCount = false
268 if (isDefined(skip) || isDefined(take)) {
269 hasPagination = true
270
271 if (isDefined(skip)) {
272 hasCount = true
273 }
274 }
275
276 const requestedFields = deepMerge(
277 deepMerge(select, filters),
278 inputOrderByObj
279 )
280
281 const connection = manager.getConnection()
282 const qb = new QueryBuilder({
283 schema: this.schemaObjectRepresentation_,
284 entityMap: this.schemaEntitiesMap_,
285 knex: connection.getKnex(),
286 selector: {
287 select,
288 where,
289 joinWhere,
290 },
291 options: {
292 skip,
293 take,
294 orderBy,
295 },
296 rawConfig: config,
297 requestedFields,
298 idsOnly,
299 })
300
301 const { sql, sqlCount } = qb.buildQuery({
302 hasPagination,
303 hasCount,
304 })
305
306 const [resultSet, countResult] = await Promise.all([
307 manager.execute(sql),
308 hasCount ? manager.execute(sqlCount!) : null,
309 ])
310
311 const resultMetadata: IndexTypes.QueryFunctionReturnPagination | undefined =
312 hasPagination
313 ? ({
314 estimate_count: hasCount
315 ? parseInt(countResult![0]?.estimate_count ?? 0)
316 : undefined,
317 skip,
318 take,
319 } as IndexTypes.QueryFunctionReturnPagination)
320 : undefined
321
322 return {
323 data: qb.buildObjectFromResultset(
324 resultSet
325 ) as IndexTypes.QueryResultSet<TEntry>["data"],
326 metadata: resultMetadata,
327 }
328 }
329
330 /**
331 * Create the index entry and the index relation entry when this event is emitted.
332 * @param entity
333 * @param data
334 * @param schemaEntityObjectRepresentation
335 * @param sharedContext
336 * @protected
337 */
338 @InjectTransactionManager()
339 async onCreate<TData extends { id: string; [key: string]: unknown }>(
340 {
341 entity,
342 data,
343 schemaEntityObjectRepresentation,
344 }: {
345 entity: string
346 data: TData | TData[]
347 schemaEntityObjectRepresentation: IndexTypes.SchemaObjectEntityRepresentation
348 },
349 @MedusaContext() sharedContext: Context<SqlEntityManager> = {}
350 ) {
351 const { transactionManager: em } = sharedContext
352 const indexRepository = em!.getRepository(
353 toMikroORMEntity(IndexData)
354 ) as EntityRepository<any>
355 const indexRelationRepository: EntityRepository<any> = em!.getRepository(
356 toMikroORMEntity(IndexRelation)
357 )
358
359 const {
360 data: data_,
361 entityProperties,
362 parentsProperties,
363 } = PostgresProvider.parseData(data, schemaEntityObjectRepresentation)
364
365 /**
366 * Clean the entity data to only keep the properties that are defined in the schema
367 */
368 const cleanedData = data_.map((entityData) => {
369 return entityProperties.reduce((acc, property) => {
370 acc[property] = entityData[property]
371 return acc
372 }, {}) as TData
373 })
374
375 /**
376 * Loop through the data and create index entries for each entity as well as the
377 * index relation entries if the entity has parents
378 */
379
380 const entitiesToUpsert: Set<string> = new Set()
381 const relationsToUpsert: Set<string> = new Set()
382
383 cleanedData.forEach((entityData, index) => {
384 entitiesToUpsert.add(
385 JSON.stringify({
386 id: entityData.id,
387 name: entity,
388 data: entityData,
389 staled_at: null,
390 })
391 )
392
393 /**
394 * Retrieve the parents to attach it to the index entry.
395 */
396
397 for (const [parentEntity, parentProperties] of Object.entries(
398 parentsProperties
399 )) {
400 const parentAlias = parentProperties[0].split(".")[0]
401 const parentData = data_[index][parentAlias] as TData[]
402
403 if (!parentData) {
404 continue
405 }
406
407 const parentDataCollection = Array.isArray(parentData)
408 ? parentData
409 : [parentData]
410
411 for (const parentData_ of parentDataCollection) {
412 relationsToUpsert.add(
413 JSON.stringify({
414 parent_id: parentData_.id,
415 parent_name: parentEntity,
416 child_id: entityData.id,
417 child_name: entity,
418 pivot: `${parentEntity}-${entity}`,
419 staled_at: null,
420 })
421 )
422 }
423 }
424 })
425
426 if (entitiesToUpsert.size) {
427 await indexRepository.upsertMany(
428 Array.from(entitiesToUpsert).map((entity) => JSON.parse(entity)),
429 {
430 onConflictAction: "merge",
431 onConflictFields: ["id", "name"],
432 onConflictMergeFields: ["data", "staled_at"],
433 }
434 )
435 }
436
437 if (relationsToUpsert.size) {
438 await indexRelationRepository.upsertMany(
439 Array.from(relationsToUpsert).map((relation) => JSON.parse(relation)),
440 {
441 onConflictAction: "merge",
442 onConflictFields: [
443 "pivot",
444 "parent_id",
445 "child_id",
446 "parent_name",
447 "child_name",
448 ],
449 onConflictMergeFields: ["staled_at"],
450 }
451 )
452 }
453 }
454
455 /**
456 * Update the index entry when this event is emitted.
457 * @param entity
458 * @param data
459 * @param schemaEntityObjectRepresentation
460 * @param sharedContext
461 * @protected
462 */
463 @InjectTransactionManager()
464 async onUpdate<TData extends { id: string; [key: string]: unknown }>(
465 {
466 entity,
467 data,
468 schemaEntityObjectRepresentation,
469 }: {
470 entity: string
471 data: TData | TData[]
472 schemaEntityObjectRepresentation: IndexTypes.SchemaObjectEntityRepresentation
473 },
474 @MedusaContext() sharedContext: Context<SqlEntityManager> = {}
475 ) {
476 const { transactionManager: em } = sharedContext
477 const indexRepository = em!.getRepository(
478 toMikroORMEntity(IndexData)
479 ) as EntityRepository<any>
480
481 const { data: data_, entityProperties } = PostgresProvider.parseData(
482 data,
483 schemaEntityObjectRepresentation
484 )
485
486 await indexRepository.upsertMany(
487 data_.map((entityData) => {
488 return {
489 id: entityData.id,
490 name: entity,
491 data: entityProperties.reduce((acc, property) => {
492 acc[property] = entityData[property]
493 return acc
494 }, {}),
495 staled_at: null,
496 }
497 }),
498 {
499 onConflictAction: "merge",
500 onConflictFields: ["id", "name"],
501 onConflictMergeFields: ["data", "staled_at"],
502 }
503 )
504 }
505
506 /**
507 * Delete the index entry when this event is emitted.
508 * @param entity
509 * @param data
510 * @param schemaEntityObjectRepresentation
511 * @param sharedContext
512 * @protected
513 */
514 @InjectTransactionManager()
515 async onDelete<TData extends { id: string; [key: string]: unknown }>(
516 {
517 entity,
518 data,
519 schemaEntityObjectRepresentation,
520 }: {
521 entity: string
522 data: TData | TData[]
523 schemaEntityObjectRepresentation: IndexTypes.SchemaObjectEntityRepresentation
524 },
525 @MedusaContext() sharedContext: Context<SqlEntityManager> = {}
526 ) {
527 const { transactionManager: em } = sharedContext
528 const indexRepository = em!.getRepository(toMikroORMEntity(IndexData))
529 const indexRelationRepository = em!.getRepository(
530 toMikroORMEntity(IndexRelation)
531 )
532
533 const { data: data_ } = PostgresProvider.parseData(
534 data,
535 schemaEntityObjectRepresentation
536 )
537
538 const ids = data_.map((entityData) => entityData.id)
539
540 await indexRepository.nativeDelete({
541 id: { $in: ids },
542 name: entity,
543 })
544
545 await indexRelationRepository.nativeDelete({
546 $or: [
547 {
548 parent_id: { $in: ids },
549 parent_name: entity,
550 },
551 {
552 child_id: { $in: ids },
553 child_name: entity,
554 },
555 ],
556 })
557 }
558
559 /**
560 * event emitted from the link modules to attach a link entity to its parent and child entities from the linked modules.
561 * @param entity
562 * @param data
563 * @param schemaEntityObjectRepresentation
564 * @protected
565 */
566 @InjectTransactionManager()
567 async onAttach<TData extends { id: string; [key: string]: unknown }>(
568 {
569 entity,
570 data,
571 schemaEntityObjectRepresentation,
572 }: {
573 entity: string
574 data: TData | TData[]
575 schemaEntityObjectRepresentation: IndexTypes.SchemaObjectEntityRepresentation
576 },
577 @MedusaContext() sharedContext: Context<SqlEntityManager> = {}
578 ) {
579 const { transactionManager: em } = sharedContext
580 const indexRepository = em!.getRepository(toMikroORMEntity(IndexData))
581 const indexRelationRepository = em!.getRepository(
582 toMikroORMEntity(IndexRelation)
583 ) as EntityRepository<any>
584
585 const { data: data_, entityProperties } = PostgresProvider.parseData(
586 data,
587 schemaEntityObjectRepresentation
588 )
589
590 /**
591 * Retrieve the property that represent the foreign key related to the parent entity of the link entity.
592 * Then from the service name of the parent entity, retrieve the entity name using the linkable keys.
593 */
594
595 const parentPropertyId =
596 schemaEntityObjectRepresentation.moduleConfig.relationships![0].foreignKey
597 const parentServiceName =
598 schemaEntityObjectRepresentation.moduleConfig.relationships![0]
599 .serviceName
600 const parentEntityName = (
601 this.schemaObjectRepresentation_._serviceNameModuleConfigMap[
602 parentServiceName
603 ] as IndexTypes.EntityNameModuleConfigMap[0]
604 ).linkableKeys?.[parentPropertyId]
605
606 if (!parentEntityName) {
607 throw new Error(
608 `IndexModule error, unable to handle attach event for ${entity}. The parent entity name could not be found using the linkable keys from the module ${parentServiceName}.`
609 )
610 }
611
612 /**
613 * Retrieve the property that represent the foreign key related to the child entity of the link entity.
614 * Then from the service name of the child entity, retrieve the entity name using the linkable keys.
615 */
616
617 const childPropertyId =
618 schemaEntityObjectRepresentation.moduleConfig.relationships![1].foreignKey
619 const childServiceName =
620 schemaEntityObjectRepresentation.moduleConfig.relationships![1]
621 .serviceName
622 const childEntityName = (
623 this.schemaObjectRepresentation_._serviceNameModuleConfigMap[
624 childServiceName
625 ] as IndexTypes.EntityNameModuleConfigMap[0]
626 ).linkableKeys?.[childPropertyId]
627
628 if (!childEntityName) {
629 throw new Error(
630 `IndexModule error, unable to handle attach event for ${entity}. The child entity name could not be found using the linkable keys from the module ${childServiceName}.`
631 )
632 }
633
634 /**
635 * Clean the link entity data to only keep the properties that are defined in the schema
636 */
637
638 const cleanedData = data_.map((entityData) => {
639 return entityProperties.reduce((acc, property) => {
640 acc[property] = entityData[property]
641 return acc
642 }, {}) as TData
643 })
644
645 let relationsToUpsert: any[] = []
646 const entitiesToUpsert = cleanedData.map((entityData) => {
647 relationsToUpsert.push(
648 {
649 parent_id: entityData[parentPropertyId] as string,
650 parent_name: parentEntityName,
651 child_id: entityData.id,
652 child_name: entity,
653 pivot: `${parentEntityName}-${entity}`,
654 staled_at: null,
655 },
656 {
657 parent_id: entityData.id,
658 parent_name: entity,
659 child_id: entityData[childPropertyId] as string,
660 child_name: childEntityName,
661 pivot: `${entity}-${childEntityName}`,
662 staled_at: null,
663 }
664 )
665
666 return {
667 id: entityData.id,
668 name: entity,
669 data: entityData,
670 staled_at: null,
671 }
672 })
673
674 if (entitiesToUpsert.length) {
675 await indexRepository.upsertMany(entitiesToUpsert, {
676 onConflictAction: "merge",
677 onConflictFields: ["id", "name"],
678 onConflictMergeFields: ["data", "staled_at"],
679 })
680 }
681
682 if (relationsToUpsert.length) {
683 await indexRelationRepository.upsertMany(relationsToUpsert, {
684 onConflictAction: "merge",
685 onConflictFields: [
686 "pivot",
687 "parent_id",
688 "child_id",
689 "parent_name",
690 "child_name",
691 ],
692 onConflictMergeFields: ["staled_at"],
693 })
694 }
695 }
696
697 /**
698 * Event emitted from the link modules to detach a link entity from its parent and child entities from the linked modules.
699 * @param entity
700 * @param data
701 * @param schemaEntityObjectRepresentation
702 * @param sharedContext
703 * @protected
704 */
705 @InjectTransactionManager()
706 async onDetach<TData extends { id: string; [key: string]: unknown }>(
707 {
708 entity,
709 data,
710 schemaEntityObjectRepresentation,
711 }: {
712 entity: string
713 data: TData | TData[]
714 schemaEntityObjectRepresentation: IndexTypes.SchemaObjectEntityRepresentation
715 },
716 @MedusaContext() sharedContext: Context<SqlEntityManager> = {}
717 ) {
718 const { transactionManager: em } = sharedContext
719 const indexRepository = em!.getRepository(toMikroORMEntity(IndexData))
720 const indexRelationRepository = em!.getRepository(
721 toMikroORMEntity(IndexRelation)
722 )
723
724 const { data: data_ } = PostgresProvider.parseData(
725 data,
726 schemaEntityObjectRepresentation
727 )
728
729 const ids = data_.map((entityData) => entityData.id)
730
731 await indexRepository.nativeDelete({
732 id: { $in: ids },
733 name: entity,
734 })
735
736 await indexRelationRepository.nativeDelete({
737 $or: [
738 {
739 parent_id: { $in: ids },
740 parent_name: entity,
741 },
742 {
743 child_id: { $in: ids },
744 child_name: entity,
745 },
746 ],
747 })
748 }
749 }