1 import { SearchTypes } from "@medusajs/framework/types"
2 import { SearchIndexRecord, SearchIndexRegistry } from "@types"
3 import {
4 listVersionsByIndexId,
5 retrieveIndexDefinition,
6 SearchIndexState,
7 } from "./index"
8 import {
9 cleanupStaleVersions,
10 dropIndex,
11 versionPhysicalName,
12 } from "./versions"
13
14 export async function createIndexMigrationPlan(
15 context: SearchIndexRegistry
16 ): Promise<SearchTypes.SearchIndexMigrationAction[]> {
17 const definitions = [...context.indexes.values()]
18
19 // Every record, not only the ones a definition names: an index nothing
20 // declares any more is exactly what a `drop` is planned from.
21 const records = (await context.indexService.list(
22 {},
23 { take: null }
24 )) as SearchIndexRecord[]
25
26 if (!definitions.length && !records.length) {
27 return []
28 }
29
30 const byName = new Map(records.map((record) => [record.name, record]))
31 const versionsByIndexId = await listVersionsByIndexId(
32 context,
33 records.map((record) => record.id)
34 )
35
36 const actions: SearchTypes.SearchIndexMigrationAction[] = definitions.map(
37 (definition) => {
38 const record = byName.get(definition.name)
39 const shared = {
40 index: definition.name,
41 definition_hash: definition.definition_hash,
42 }
43
44 if (!record) {
45 return {
46 ...shared,
47 action: "create" as const,
48 physical_name: versionPhysicalName(definition, 1),
49 version: 1,
50 }
51 }
52
53 const versions = versionsByIndexId.get(record.id) ?? []
54 const activeVersion =
55 record.active_version != null
56 ? versions.find((v) => v.version === record.active_version)
57 : undefined
58
59 if (
60 activeVersion &&
61 activeVersion.definition_hash === definition.definition_hash &&
62 activeVersion.provider === definition.provider
63 ) {
64 return {
65 ...shared,
66 action: "noop" as const,
67 physical_name: activeVersion.physical_name,
68 }
69 }
70
71 // Already building or built, waiting to be seeded — nothing new to plan.
72 const pending = versions.find(
73 (v) =>
74 (record.active_version == null ||
75 v.version > record.active_version) &&
76 v.definition_hash === definition.definition_hash &&
77 v.provider === definition.provider
78 )
79
80 if (pending) {
81 return {
82 ...shared,
83 action: "noop" as const,
84 physical_name: pending.physical_name,
85 }
86 }
87
88 const highest = versions[0]?.version ?? 0
89 const version = highest + 1
90 const physicalName = versionPhysicalName(definition, version)
91
92 if (!activeVersion) {
93 // A `SearchIndex` row exists — an earlier `create` ran — but nothing
94 // ever went live, so this is still a `create`, not a `migrate`.
95 return {
96 ...shared,
97 action: "create" as const,
98 physical_name: physicalName,
99 version,
100 }
101 }
102
103 return {
104 ...shared,
105 action: "migrate" as const,
106 physical_name: physicalName,
107 version,
108 active_physical_name: activeVersion.physical_name,
109 active_definition_hash: activeVersion.definition_hash,
110 provider: definition.provider,
111 ...(activeVersion.provider !== definition.provider
112 ? { previous_provider: activeVersion.provider }
113 : {}),
114 }
115 }
116 )
117
118 const declared = new Set(definitions.map((definition) => definition.name))
119
120 for (const record of records) {
121 if (declared.has(record.name)) {
122 continue
123 }
124
125 actions.push({
126 action: "drop",
127 index: record.name,
128 // Newest version first, the order `listVersionsByIndexId` returns.
129 physical_names: (versionsByIndexId.get(record.id) ?? []).map(
130 (version) => version.physical_name
131 ),
132 })
133 }
134
135 return actions
136 }
137
138 // Note: Seeding data is done by the application start hook, migrations are reserved for schema changes.
139 export async function executeIndexMigrationPlan(
140 context: SearchIndexRegistry,
141 actions: SearchTypes.SearchIndexMigrationAction[]
142 ): Promise<void> {
143 for (const action of actions) {
144 if (action.action === "drop") {
145 await dropIndex(context, action.index)
146 continue
147 }
148
149 if (action.action === "noop") {
150 // Nothing changed for this index, but a version below the active one —
151 // left behind by an earlier migration's swap — still needs cleaning up.
152 // That cannot wait for the index to drift again.
153 const record = await getOrCreateIndexRecord(context, action.index)
154 await cleanupStaleVersions(context, record)
155 continue
156 }
157
158 const definition = retrieveIndexDefinition(context.indexes, action.index)
159 const provider = context.providers.retrieve(definition.provider)
160
161 await provider.upsertIndex({
162 index: { ...definition, physical_name: action.physical_name },
163 })
164
165 const record = await getOrCreateIndexRecord(context, definition.name)
166
167 await context.versionService.create([
168 {
169 search_index_id: record.id,
170 version: action.version,
171 provider: definition.provider,
172 physical_name: action.physical_name,
173 definition_hash: action.definition_hash,
174 // Built but not filled; the seed at startup makes it ready.
175 status: SearchIndexState.PENDING,
176 },
177 ])
178
179 await cleanupStaleVersions(context, record)
180 }
181 }
182
183 async function getOrCreateIndexRecord(
184 context: SearchIndexRegistry,
185 name: string
186 ): Promise<SearchIndexRecord> {
187 const [existing] = (await context.indexService.list({
188 name,
189 })) as SearchIndexRecord[]
190
191 if (existing) {
192 return existing
193 }
194
195 const [created] = (await context.indexService.create([
196 { name, active_version: null },
197 ])) as SearchIndexRecord[]
198
199 return created
200 }