1 import { SearchTypes } from "@medusajs/framework/types"
2 import { MedusaError } from "@medusajs/framework/utils"
3 import { SearchIndexRecord, SearchIndexVersionRecord } from "@types"
4 import { SearchIndexState } from "../index"
5 import { cleanupStaleVersions, versionPhysicalName } from "../versions"
6
7 const definition = (): SearchTypes.ResolvedSearchIndexDefinition =>
8 ({
9 name: "product",
10 entity: "product",
11 provider: "test",
12 physical_name: "product",
13 definition_hash: "abcdef0123456789abcdef0123456789",
14 primary_key: "id",
15 fields: { id: { type: "keyword", filterable: true } },
16 settings: {},
17 async *seed() {},
18 }) as unknown as SearchTypes.ResolvedSearchIndexDefinition
19
20 const version = (
21 overrides: Partial<SearchIndexVersionRecord> & { version: number }
22 ): SearchIndexVersionRecord => ({
23 id: `ver_${overrides.version}`,
24 search_index_id: "idx_1",
25 provider: "test",
26 physical_name: `product_v${overrides.version}`,
27 definition_hash: "abcdef0123456789abcdef0123456789",
28 status: SearchIndexState.READY,
29 ...overrides,
30 })
31
32 const provider = (
33 identifier: string,
34 deleteIndex: jest.Mock = jest
35 .fn()
36 .mockResolvedValue({ index: "product", status: "succeeded" })
37 ) => ({ identifier, deleteIndex })
38
39 const buildContext = ({
40 versions,
41 providers,
42 }: {
43 versions: SearchIndexVersionRecord[]
44 providers: { identifier: string; deleteIndex: jest.Mock }[]
45 }) => {
46 const byId = new Map(providers.map((item) => [item.identifier, item]))
47 const logger = { info: jest.fn(), warn: jest.fn(), error: jest.fn() }
48
49 return {
50 logger: logger as any,
51 versionService: {
52 list: jest.fn().mockResolvedValue(versions),
53 softDelete: jest.fn(),
54 } as any,
55 providers: {
56 retrieve: (identifier: string) => {
57 const found = byId.get(identifier)
58
59 if (!found) {
60 throw new MedusaError(
61 MedusaError.Types.NOT_FOUND,
62 `Search provider "${identifier}" is not registered.`
63 )
64 }
65
66 return found as unknown as SearchTypes.ISearchProvider
67 },
68 },
69 logger_: logger,
70 }
71 }
72
73 const record = (active_version: number | null): SearchIndexRecord => ({
74 id: "idx_1",
75 name: "product",
76 active_version,
77 })
78
79 describe("search index versions", () => {
80 beforeEach(() => {
81 jest.clearAllMocks()
82 })
83
84 describe("versionPhysicalName", () => {
85 it("appends the version number to the definition's physical name", () => {
86 expect(versionPhysicalName(definition(), 1)).toBe("product_v1")
87 expect(versionPhysicalName(definition(), 12)).toBe("product_v12")
88 })
89 })
90
91 describe("cleanupStaleVersions", () => {
92 it("deletes every version below the active one", async () => {
93 const current = provider("test")
94 const context = buildContext({
95 versions: [version({ version: 1 }), version({ version: 2 })],
96 providers: [current],
97 })
98
99 await cleanupStaleVersions(context, record(3))
100
101 expect(
102 current.deleteIndex.mock.calls.map(([call]) => call.index)
103 ).toEqual(["product_v1", "product_v2"])
104 expect(context.versionService.softDelete).toHaveBeenCalledWith(["ver_1"])
105 expect(context.versionService.softDelete).toHaveBeenCalledWith(["ver_2"])
106 })
107
108 it("keeps the active version and anything being built above it", async () => {
109 const current = provider("test")
110 const context = buildContext({
111 versions: [
112 version({ version: 1 }),
113 // Still serving reads while version 6 is built beside it.
114 version({ version: 5 }),
115 version({ version: 6, status: SearchIndexState.BUILDING }),
116 ],
117 providers: [current],
118 })
119
120 await cleanupStaleVersions(context, record(5))
121
122 expect(current.deleteIndex).toHaveBeenCalledTimes(1)
123 expect(current.deleteIndex).toHaveBeenCalledWith({
124 index: "product_v1",
125 })
126 expect(context.versionService.softDelete).toHaveBeenCalledWith(["ver_1"])
127 })
128
129 it("does nothing while no version has gone live yet", async () => {
130 const current = provider("test")
131 const context = buildContext({
132 versions: [version({ version: 1 })],
133 providers: [current],
134 })
135
136 await cleanupStaleVersions(context, record(null))
137
138 expect(context.versionService.list).not.toHaveBeenCalled()
139 expect(current.deleteIndex).not.toHaveBeenCalled()
140 })
141
142 it("keeps the record when its provider is no longer registered, so a later cleanup retries", async () => {
143 const context = buildContext({
144 versions: [version({ version: 1, provider: "search-gone" })],
145 providers: [provider("test")],
146 })
147
148 await cleanupStaleVersions(context, record(2))
149
150 expect(context.versionService.softDelete).not.toHaveBeenCalled()
151 expect(context.logger_.warn).toHaveBeenCalledWith(
152 expect.stringContaining("search-gone")
153 )
154 })
155
156 it("keeps going when the engine refuses to drop one of the indexes", async () => {
157 const current = provider(
158 "test",
159 jest
160 .fn()
161 .mockRejectedValueOnce(new Error("connection reset"))
162 .mockResolvedValue({ index: "product", status: "succeeded" })
163 )
164 const context = buildContext({
165 versions: [version({ version: 1 }), version({ version: 2 })],
166 providers: [current],
167 })
168
169 await cleanupStaleVersions(context, record(3))
170
171 expect(context.logger_.warn).toHaveBeenCalledWith(
172 expect.stringContaining("connection reset")
173 )
174 // The one that failed keeps its record, so the next run picks it up
175 // again; the one after it is still cleaned up.
176 expect(context.versionService.softDelete).toHaveBeenCalledTimes(1)
177 expect(context.versionService.softDelete).toHaveBeenCalledWith(["ver_2"])
178 })
179 })
180 })