1 import { SearchTypes } from "@medusajs/framework/types"
2 import {
3 SearchIndexRecord,
4 SearchIndexRegistry,
5 SearchIndexVersionRecord,
6 } from "@types"
7 import { SearchIndexState } from "./index"
8
9 /**
10 * The physical index a version is built under. Every version — including the
11 * first — gets one, so `definition.physical_name` is never itself a physical
12 * index: it is only virtual index name
13 */
14 export function versionPhysicalName(
15 definition: SearchTypes.ResolvedSearchIndexDefinition,
16 version: number
17 ): string {
18 return `${definition.physical_name}_v${version}`
19 }
20
21 /**
22 * Drops every version below the one currently serving reads — the physical
23 * index in the engine and the record pointing at it. Runs before a migration
24 * or a reindex builds a new version, so versions earlier builds left behind
25 * don't pile up: building v6 while v5 serves reads leaves v5 and v6 standing
26 * and takes everything under them.
27 *
28 * The version that was active until the last swap is deliberately kept: another
29 * process can still be serving reads off it until its active-version cache
30 * catches up, so it only goes once the next build starts.
31 */
32 export async function cleanupStaleVersions(
33 context: Pick<SearchIndexRegistry, "providers" | "versionService" | "logger">,
34 record: SearchIndexRecord
35 ): Promise<void> {
36 const activeVersion = record.active_version
37
38 if (activeVersion == null) {
39 return
40 }
41
42 const versions = (await context.versionService.list(
43 { search_index_id: record.id },
44 { take: null }
45 )) as SearchIndexVersionRecord[]
46
47 await deleteVersions(
48 context,
49 versions.filter((version) => version.version < activeVersion)
50 )
51 }
52
53 /**
54 * Drops every version above the active one that a run already started filling
55 * and never swapped in. Runs once a reindex has created the version it builds,
56 * which the startup seed then prefers, so nothing would ever resume these.
57 *
58 * Callers must hold the index's seed lock: it is what guarantees no other
59 * process is still filling one of them. A version nothing started filling yet
60 * is left alone, since it may be a migration's, waiting for its first seed.
61 */
62 export async function cleanupAbandonedVersions(
63 context: Pick<SearchIndexRegistry, "providers" | "versionService" | "logger">,
64 record: SearchIndexRecord
65 ): Promise<void> {
66 const activeVersion = record.active_version ?? 0
67
68 const versions = (await context.versionService.list(
69 { search_index_id: record.id },
70 { take: null }
71 )) as SearchIndexVersionRecord[]
72
73 await deleteVersions(
74 context,
75 versions.filter(
76 (version) =>
77 version.version > activeVersion &&
78 (version.status === SearchIndexState.BUILDING ||
79 version.status === SearchIndexState.ERROR)
80 )
81 )
82 }
83
84 /**
85 * Drops what a swap to `activeVersion` left behind: every version below it
86 * except `previousVersion`, which other processes may still read from until
87 * their active-version cache catches up. Nothing ever makes a version below
88 * the active one active again, so without this they wait for the next build.
89 *
90 * Callers must hold the index's seed lock. Never throws: the swap it follows
91 * has already happened, and failing to drop a stale index must not undo it.
92 */
93 export async function cleanupAfterSwap(
94 context: Pick<SearchIndexRegistry, "providers" | "versionService" | "logger">,
95 {
96 record_id,
97 active_version: activeVersion,
98 previous_version: previousVersion,
99 }: {
100 record_id: string
101 active_version: number
102 previous_version: number | null
103 }
104 ): Promise<void> {
105 try {
106 const versions = (await context.versionService.list(
107 { search_index_id: record_id },
108 { take: null }
109 )) as SearchIndexVersionRecord[]
110
111 await deleteVersions(
112 context,
113 versions.filter(
114 (version) =>
115 version.version < activeVersion && version.version !== previousVersion
116 )
117 )
118 } catch (error) {
119 context.logger.warn(
120 `[Search] Cannot clean up after swapping in version ${activeVersion}: ${error.message}`
121 )
122 }
123 }
124
125 /**
126 * Removes a logical index outright: every physical index ever built for it,
127 * then the record tracking them.
128 */
129 export async function dropIndex(
130 context: Pick<
131 SearchIndexRegistry,
132 "providers" | "indexService" | "versionService" | "logger"
133 >,
134 name: string
135 ): Promise<void> {
136 const [record] = (await context.indexService.list({
137 name,
138 })) as SearchIndexRecord[]
139
140 if (!record) {
141 return
142 }
143
144 const versions = (await context.versionService.list(
145 { search_index_id: record.id },
146 { take: null }
147 )) as SearchIndexVersionRecord[]
148
149 const failed = await deleteVersions(context, versions)
150
151 if (failed.length) {
152 context.logger.warn(
153 `[Search] Keeping the record for search index "${name}": ${failed.length} of its ${versions.length} version(s) could not be removed, so the next migration plans the drop again`
154 )
155 return
156 }
157
158 await context.indexService.softDelete([record.id])
159 }
160
161 /**
162 * Deletes each version's physical index and then its record. Returns the ones
163 * it could not delete: failing to drop a stale index is never worth failing the
164 * migration or reindex that triggered it, and the record surviving is what
165 * makes the next run retry it.
166 */
167 async function deleteVersions(
168 context: Pick<SearchIndexRegistry, "providers" | "versionService" | "logger">,
169 versions: SearchIndexVersionRecord[]
170 ): Promise<SearchIndexVersionRecord[]> {
171 const failed: SearchIndexVersionRecord[] = []
172
173 for (const version of versions) {
174 try {
175 const provider = context.providers.retrieve(version.provider)
176
177 await provider.deleteIndex({ index: version.physical_name })
178 // Soft delete: a hard delete would violate the foreign key from any
179 // `SearchIndexSync` row still pointing at this version's append-only
180 // history.
181 await context.versionService.softDelete([version.id])
182 } catch (error) {
183 failed.push(version)
184 context.logger.warn(
185 `[Search] Cannot delete search index "${version.physical_name}": ${error.message}`
186 )
187 }
188 }
189
190 return failed
191 }