1 import { simpleHash } from "@medusajs/framework/utils"
2 import { IndexTypes, InferEntityType, Logger } from "@medusajs/types"
3 import { IndexMetadata } from "@models"
4 import { schemaObjectRepresentationPropertiesToOmit } from "@types"
5 import { DataSynchronizer } from "../../services/data-synchronizer"
6 import { IndexMetadataService } from "../../services/index-metadata"
7 import { IndexSyncService } from "../../services/index-sync"
8 import { IndexMetadataStatus } from "../index-metadata-status"
9
10 export class Configuration {
11 #schemaObjectRepresentation: IndexTypes.SchemaObjectRepresentation
12 #indexMetadataService: IndexMetadataService
13 #indexSyncService: IndexSyncService
14 #dataSynchronizer: DataSynchronizer
15 #logger: Logger
16
17 constructor({
18 schemaObjectRepresentation,
19 indexMetadataService,
20 indexSyncService,
21 dataSynchronizer,
22 logger,
23 }: {
24 schemaObjectRepresentation: IndexTypes.SchemaObjectRepresentation
25 indexMetadataService: IndexMetadataService
26 indexSyncService: IndexSyncService
27 dataSynchronizer: DataSynchronizer
28 logger: Logger
29 }) {
30 this.#schemaObjectRepresentation = schemaObjectRepresentation ?? {}
31 this.#indexMetadataService = indexMetadataService
32 this.#indexSyncService = indexSyncService
33 this.#dataSynchronizer = dataSynchronizer
34 this.#logger = logger
35 }
36
37 async checkChanges(): Promise<InferEntityType<typeof IndexMetadata>[]> {
38 this.#logger.info("[Index engine] Checking for index changes")
39 const schemaObjectRepresentation = this.#schemaObjectRepresentation
40
41 const currentConfig = await this.#indexMetadataService.list({})
42 const currentConfigMap = new Map(
43 currentConfig.map((c) => [c.entity, c] as const)
44 )
45
46 type modifiedConfig = {
47 id?: string
48 entity: string
49 fields: string[]
50 fields_hash: string
51 status?: IndexMetadataStatus
52 }[]
53
54 type dataSyncEntry = {
55 id?: string
56 entity: string
57 last_key: null
58 }[]
59
60 const entityPresent = new Set<string>()
61 const newConfig: modifiedConfig = []
62 const updatedConfig: modifiedConfig = []
63 const deletedConfig: { entity: string }[] = []
64 const idxSyncData: dataSyncEntry = []
65
66 for (const [entityName, schemaEntityObjectRepresentation] of Object.entries(
67 schemaObjectRepresentation
68 )) {
69 if (schemaObjectRepresentationPropertiesToOmit.includes(entityName)) {
70 continue
71 }
72
73 const entity = schemaEntityObjectRepresentation.entity
74 const fields = schemaEntityObjectRepresentation.fields.sort().join(",")
75 const fields_hash = simpleHash(fields)
76
77 const existingEntityConfig = currentConfigMap.get(entity)
78
79 entityPresent.add(entity)
80 if (
81 !existingEntityConfig ||
82 existingEntityConfig.fields_hash !== fields_hash
83 ) {
84 const meta = {
85 id: existingEntityConfig?.id,
86 entity,
87 fields,
88 fields_hash,
89 }
90
91 if (!existingEntityConfig) {
92 newConfig.push(meta)
93 } else {
94 updatedConfig.push({
95 ...meta,
96 status: IndexMetadataStatus.PENDING,
97 })
98 }
99
100 idxSyncData.push({
101 entity,
102 last_key: null,
103 })
104 }
105 }
106
107 for (const [entity] of currentConfigMap) {
108 if (!entityPresent.has(entity)) {
109 deletedConfig.push({ entity })
110 }
111 }
112
113 if (newConfig.length > 0) {
114 await this.#indexMetadataService.create(newConfig)
115 }
116 if (updatedConfig.length > 0) {
117 await this.#indexMetadataService.update(updatedConfig)
118 }
119
120 if (deletedConfig.length > 0) {
121 await this.#indexMetadataService.delete(deletedConfig)
122 await this.#dataSynchronizer.removeEntities(
123 deletedConfig.map((c) => c.entity)
124 )
125 }
126
127 if (idxSyncData.length > 0) {
128 const ids = await this.#indexSyncService.list({
129 entity: idxSyncData.map((c) => c.entity),
130 })
131 idxSyncData.forEach((sync) => {
132 const id = ids.find((i) => i.entity === sync.entity)?.id
133 if (id) {
134 sync.id = id
135 }
136 })
137
138 await this.#indexSyncService.upsert(idxSyncData)
139 }
140
141 const changes = await this.#indexMetadataService.list({
142 status: [
143 IndexMetadataStatus.PENDING,
144 IndexMetadataStatus.PROCESSING,
145 IndexMetadataStatus.ERROR,
146 ],
147 })
148
149 this.#logger.info(
150 `[Index engine] Found ${changes.length} index change${
151 changes.length > 1 ? "s" : ""
152 } that are either pending or processing`
153 )
154
155 return changes
156 }
157 }