1 import { SearchTypes } from "@medusajs/framework/types"
2 import { MedusaError } from "@medusajs/framework/utils"
3 import { SearchIndexRegistry } from "@types"
4 import {
5 createIndexMigrationPlan,
6 executeIndexMigrationPlan,
7 } from "../migrations"
8
9 const definition = (
10 overrides: Partial<SearchTypes.ResolvedSearchIndexDefinition> = {}
11 ): SearchTypes.ResolvedSearchIndexDefinition =>
12 ({
13 name: "product",
14 entity: "product",
15 provider: "search-new",
16 physical_name: "product",
17 definition_hash: "abcdef0123456789abcdef0123456789",
18 primary_key: "id",
19 fields: {
20 id: { type: "keyword", filterable: true },
21 },
22 settings: {},
23 async *seed() {},
24 ...overrides,
25 }) as SearchTypes.ResolvedSearchIndexDefinition
26
27 const logger = {
28 warn: jest.fn(),
29 info: jest.fn(),
30 }
31
32 const provider = (
33 identifier: string,
34 extras: Partial<SearchTypes.ISearchProvider> = {}
35 ) =>
36 ({
37 identifier,
38 upsertIndex: jest
39 .fn()
40 .mockResolvedValue({ index: "product", status: "succeeded" }),
41 deleteIndex: jest
42 .fn()
43 .mockResolvedValue({ index: "product", status: "succeeded" }),
44 listIndexes: jest.fn().mockResolvedValue([]),
45 upsertDocuments: jest.fn(),
46 deleteDocuments: jest.fn(),
47 clearIndex: jest.fn(),
48 search: jest.fn(),
49 ...extras,
50 }) as unknown as SearchTypes.ISearchProvider & {
51 upsertIndex: jest.Mock
52 deleteIndex: jest.Mock
53 listIndexes: jest.Mock
54 }
55
56 type IndexRecord = { id: string; name: string; active_version: number | null }
57 type VersionRecord = {
58 id: string
59 search_index_id: string
60 version: number
61 provider: string
62 physical_name: string
63 definition_hash: string
64 }
65
66 const registry = ({
67 indexes,
68 records = [],
69 versions = [],
70 providers,
71 }: {
72 indexes: SearchTypes.ResolvedSearchIndexDefinition[]
73 records?: IndexRecord[]
74 versions?: VersionRecord[]
75 providers: SearchTypes.ISearchProvider[]
76 }): SearchIndexRegistry & {
77 versionService: { softDelete: jest.Mock; create: jest.Mock }
78 indexService: { softDelete: jest.Mock }
79 } => {
80 const byId = new Map(providers.map((item) => [item.identifier, item]))
81
82 return {
83 logger: logger as any,
84 indexes: new Map(indexes.map((index) => [index.name, index])),
85 indexService: {
86 list: jest.fn().mockImplementation((filter?: { name?: string | string[] }) => {
87 if (!filter?.name) {
88 return Promise.resolve(records)
89 }
90 const names = Array.isArray(filter.name) ? filter.name : [filter.name]
91 return Promise.resolve(records.filter((r) => names.includes(r.name)))
92 }),
93 create: jest.fn().mockImplementation((data: Omit<IndexRecord, "id">[]) =>
94 Promise.resolve([{ id: "srhidx_new", ...data[0] }])
95 ),
96 update: jest.fn(),
97 softDelete: jest.fn(),
98 } as any,
99 versionService: {
100 list: jest
101 .fn()
102 .mockImplementation(
103 (filter?: { search_index_id?: string | string[] }) => {
104 const ids = !filter?.search_index_id
105 ? null
106 : Array.isArray(filter.search_index_id)
107 ? filter.search_index_id
108 : [filter.search_index_id]
109 const filtered = ids
110 ? versions.filter((v) => ids.includes(v.search_index_id))
111 : versions
112 return Promise.resolve(
113 [...filtered].sort((a, b) => b.version - a.version)
114 )
115 }
116 ),
117 create: jest
118 .fn()
119 .mockImplementation((data: Omit<VersionRecord, "id">[]) =>
120 Promise.resolve([{ id: "srhver_new", ...data[0] }])
121 ),
122 softDelete: jest.fn(),
123 } as any,
124 providers: {
125 retrieve: (identifier: string) => {
126 const found = byId.get(identifier)
127 if (!found) {
128 throw new MedusaError(
129 MedusaError.Types.NOT_FOUND,
130 `not registered: ${identifier}`
131 )
132 }
133 return found
134 },
135 },
136 }
137 }
138
139 describe("search index migrations", () => {
140 beforeEach(() => {
141 jest.clearAllMocks()
142 })
143
144 describe("createIndexMigrationPlan", () => {
145 it("creates version 1 of an index that has no record", async () => {
146 const index = definition()
147 const plan = await createIndexMigrationPlan(
148 registry({ indexes: [index], providers: [provider("search-new")] })
149 )
150
151 expect(plan).toEqual([
152 {
153 action: "create",
154 index: "product",
155 physical_name: "product_v1",
156 definition_hash: index.definition_hash,
157 version: 1,
158 },
159 ])
160 })
161
162 it("is a noop when the active version's hash and provider match", async () => {
163 const index = definition()
164 const plan = await createIndexMigrationPlan(
165 registry({
166 indexes: [index],
167 records: [{ id: "idx_1", name: "product", active_version: 1 }],
168 versions: [
169 {
170 id: "ver_1",
171 search_index_id: "idx_1",
172 version: 1,
173 provider: "search-new",
174 physical_name: "product_v1",
175 definition_hash: index.definition_hash,
176 },
177 ],
178 providers: [provider("search-new")],
179 })
180 )
181
182 expect(plan).toEqual([
183 {
184 action: "noop",
185 index: "product",
186 physical_name: "product_v1",
187 definition_hash: index.definition_hash,
188 },
189 ])
190 })
191
192 it("plans a new version on schema drift", async () => {
193 const index = definition()
194 const plan = await createIndexMigrationPlan(
195 registry({
196 indexes: [index],
197 records: [{ id: "idx_1", name: "product", active_version: 1 }],
198 versions: [
199 {
200 id: "ver_1",
201 search_index_id: "idx_1",
202 version: 1,
203 provider: "search-new",
204 physical_name: "product_v1",
205 definition_hash: "stale",
206 },
207 ],
208 providers: [provider("search-new")],
209 })
210 )
211
212 expect(plan).toEqual([
213 {
214 action: "migrate",
215 index: "product",
216 physical_name: "product_v2",
217 definition_hash: index.definition_hash,
218 version: 2,
219 active_physical_name: "product_v1",
220 active_definition_hash: "stale",
221 provider: "search-new",
222 },
223 ])
224 })
225
226 it("is a noop when a pending version above the active one already matches", async () => {
227 const index = definition()
228 const plan = await createIndexMigrationPlan(
229 registry({
230 indexes: [index],
231 records: [{ id: "idx_1", name: "product", active_version: 1 }],
232 versions: [
233 {
234 id: "ver_1",
235 search_index_id: "idx_1",
236 version: 1,
237 provider: "search-new",
238 physical_name: "product_v1",
239 definition_hash: "stale",
240 },
241 {
242 id: "ver_2",
243 search_index_id: "idx_1",
244 version: 2,
245 provider: "search-new",
246 physical_name: "product_v2",
247 definition_hash: index.definition_hash,
248 },
249 ],
250 providers: [provider("search-new")],
251 })
252 )
253
254 expect(plan).toEqual([
255 {
256 action: "noop",
257 index: "product",
258 physical_name: "product_v2",
259 definition_hash: index.definition_hash,
260 },
261 ])
262 })
263
264 it("plans a drop for an index no definition declares any more", async () => {
265 const index = definition()
266 const plan = await createIndexMigrationPlan(
267 registry({
268 indexes: [index],
269 records: [
270 { id: "idx_1", name: "product", active_version: 1 },
271 { id: "idx_2", name: "blog", active_version: 2 },
272 ],
273 versions: [
274 {
275 id: "ver_1",
276 search_index_id: "idx_1",
277 version: 1,
278 provider: "search-new",
279 physical_name: "product_v1",
280 definition_hash: index.definition_hash,
281 },
282 {
283 id: "ver_2",
284 search_index_id: "idx_2",
285 version: 1,
286 provider: "search-new",
287 physical_name: "blog_v1",
288 definition_hash: "whatever",
289 },
290 {
291 id: "ver_3",
292 search_index_id: "idx_2",
293 version: 2,
294 provider: "search-new",
295 physical_name: "blog_v2",
296 definition_hash: "whatever",
297 },
298 ],
299 providers: [provider("search-new")],
300 })
301 )
302
303 expect(plan).toEqual([
304 {
305 action: "noop",
306 index: "product",
307 physical_name: "product_v1",
308 definition_hash: index.definition_hash,
309 },
310 {
311 action: "drop",
312 index: "blog",
313 // Newest first, and every version — a drop takes all of them.
314 physical_names: ["blog_v2", "blog_v1"],
315 },
316 ])
317 })
318
319 it("plans a drop for a record whose version was never built", async () => {
320 const plan = await createIndexMigrationPlan(
321 registry({
322 indexes: [],
323 records: [{ id: "idx_1", name: "blog", active_version: null }],
324 providers: [provider("search-new")],
325 })
326 )
327
328 expect(plan).toEqual([
329 { action: "drop", index: "blog", physical_names: [] },
330 ])
331 })
332
333 it("plans nothing when there is neither a definition nor a record", async () => {
334 const plan = await createIndexMigrationPlan(
335 registry({ indexes: [], providers: [provider("search-new")] })
336 )
337
338 expect(plan).toEqual([])
339 })
340
341 it("records the previous provider when the engine changed", async () => {
342 const index = definition()
343 const plan = await createIndexMigrationPlan(
344 registry({
345 indexes: [index],
346 records: [{ id: "idx_1", name: "product", active_version: 1 }],
347 versions: [
348 {
349 id: "ver_1",
350 search_index_id: "idx_1",
351 version: 1,
352 provider: "search-old",
353 physical_name: "product_v1",
354 definition_hash: index.definition_hash,
355 },
356 ],
357 providers: [provider("search-new"), provider("search-old")],
358 })
359 )
360
361 expect(plan).toEqual([
362 {
363 action: "migrate",
364 index: "product",
365 physical_name: "product_v2",
366 definition_hash: index.definition_hash,
367 version: 2,
368 active_physical_name: "product_v1",
369 active_definition_hash: index.definition_hash,
370 provider: "search-new",
371 previous_provider: "search-old",
372 },
373 ])
374 })
375 })
376
377 describe("executeIndexMigrationPlan", () => {
378 it("creates the index record and its first version", async () => {
379 const index = definition()
380 const current = provider("search-new")
381 const context = registry({ indexes: [index], providers: [current] })
382
383 await executeIndexMigrationPlan(context, [
384 {
385 action: "create",
386 index: "product",
387 physical_name: "product_v1",
388 definition_hash: index.definition_hash,
389 version: 1,
390 },
391 ])
392
393 expect(current.upsertIndex).toHaveBeenCalledWith({
394 index: expect.objectContaining({ physical_name: "product_v1" }),
395 })
396 expect(context.indexService.create).toHaveBeenCalledWith([
397 { name: "product", active_version: null },
398 ])
399 expect(context.versionService.create).toHaveBeenCalledWith([
400 expect.objectContaining({
401 search_index_id: "srhidx_new",
402 version: 1,
403 provider: "search-new",
404 physical_name: "product_v1",
405 definition_hash: index.definition_hash,
406 }),
407 ])
408 expect(current.deleteIndex).not.toHaveBeenCalled()
409 })
410
411 it("builds a new version for a migrate action without touching the active one", async () => {
412 const index = definition()
413 const current = provider("search-new")
414 const context = registry({
415 indexes: [index],
416 records: [{ id: "idx_1", name: "product", active_version: 1 }],
417 versions: [
418 {
419 id: "ver_1",
420 search_index_id: "idx_1",
421 version: 1,
422 provider: "search-new",
423 physical_name: "product_v1",
424 definition_hash: "stale",
425 },
426 ],
427 providers: [current],
428 })
429
430 await executeIndexMigrationPlan(context, [
431 {
432 action: "migrate",
433 index: "product",
434 physical_name: "product_v2",
435 definition_hash: index.definition_hash,
436 version: 2,
437 active_physical_name: "product_v1",
438 active_definition_hash: "stale",
439 provider: "search-new",
440 },
441 ])
442
443 expect(current.upsertIndex).toHaveBeenCalledWith({
444 index: expect.objectContaining({ physical_name: "product_v2" }),
445 })
446 expect(context.versionService.create).toHaveBeenCalledWith([
447 expect.objectContaining({ search_index_id: "idx_1", version: 2 }),
448 ])
449 // Version 1 is still active, so it survives cleanup.
450 expect(current.deleteIndex).not.toHaveBeenCalled()
451 })
452
453 it("deletes every version older than the active one", async () => {
454 const index = definition()
455 const current = provider("search-new")
456 const old = provider("search-old")
457 const context = registry({
458 indexes: [index],
459 records: [{ id: "idx_1", name: "product", active_version: 2 }],
460 versions: [
461 {
462 id: "ver_1",
463 search_index_id: "idx_1",
464 version: 1,
465 provider: "search-old",
466 physical_name: "product_v1",
467 definition_hash: "older",
468 },
469 {
470 id: "ver_2",
471 search_index_id: "idx_1",
472 version: 2,
473 provider: "search-new",
474 physical_name: "product_v2",
475 definition_hash: "stale",
476 },
477 ],
478 providers: [current, old],
479 })
480
481 await executeIndexMigrationPlan(context, [
482 {
483 action: "migrate",
484 index: "product",
485 physical_name: "product_v3",
486 definition_hash: index.definition_hash,
487 version: 3,
488 active_physical_name: "product_v2",
489 active_definition_hash: "stale",
490 provider: "search-new",
491 },
492 ])
493
494 expect(old.deleteIndex).toHaveBeenCalledWith({ index: "product_v1" })
495 expect(current.deleteIndex).not.toHaveBeenCalledWith({
496 index: "product_v2",
497 })
498 expect(context.versionService.softDelete).toHaveBeenCalledWith(["ver_1"])
499 })
500
501 it("cleans up a stale version left over from an earlier swap even on a noop", async () => {
502 const index = definition()
503 const current = provider("search-new")
504 const old = provider("search-old")
505 const context = registry({
506 indexes: [index],
507 records: [{ id: "idx_1", name: "product", active_version: 2 }],
508 versions: [
509 {
510 id: "ver_1",
511 search_index_id: "idx_1",
512 version: 1,
513 provider: "search-old",
514 physical_name: "product_v1",
515 definition_hash: "older",
516 },
517 {
518 id: "ver_2",
519 search_index_id: "idx_1",
520 version: 2,
521 provider: "search-new",
522 physical_name: "product_v2",
523 definition_hash: index.definition_hash,
524 },
525 ],
526 providers: [current, old],
527 })
528
529 // Nothing drifted this time, so the plan for this index is a noop —
530 // but version 1 still needs cleaning up; that cannot wait for drift.
531 await executeIndexMigrationPlan(context, [
532 {
533 action: "noop",
534 index: "product",
535 physical_name: "product_v2",
536 definition_hash: index.definition_hash,
537 },
538 ])
539
540 expect(current.upsertIndex).not.toHaveBeenCalled()
541 expect(old.deleteIndex).toHaveBeenCalledWith({ index: "product_v1" })
542 expect(context.versionService.softDelete).toHaveBeenCalledWith(["ver_1"])
543 })
544
545 it("drops every physical index of an index nothing declares any more", async () => {
546 const current = provider("search-new")
547 const context = registry({
548 indexes: [],
549 records: [{ id: "idx_1", name: "blog", active_version: 2 }],
550 versions: [
551 {
552 id: "ver_1",
553 search_index_id: "idx_1",
554 version: 1,
555 provider: "search-new",
556 physical_name: "blog_v1",
557 definition_hash: "whatever",
558 },
559 {
560 id: "ver_2",
561 search_index_id: "idx_1",
562 version: 2,
563 provider: "search-new",
564 physical_name: "blog_v2",
565 definition_hash: "whatever",
566 },
567 ],
568 providers: [current],
569 })
570
571 await executeIndexMigrationPlan(context, [
572 {
573 action: "drop",
574 index: "blog",
575 physical_names: ["blog_v2", "blog_v1"],
576 },
577 ])
578
579 // The active version goes too — unlike a cleanup, a drop keeps nothing.
580 expect(current.deleteIndex.mock.calls.map(([call]) => call.index)).toEqual(
581 ["blog_v2", "blog_v1"]
582 )
583 expect(context.versionService.softDelete).toHaveBeenCalledWith(["ver_2"])
584 expect(context.versionService.softDelete).toHaveBeenCalledWith(["ver_1"])
585 expect(context.indexService.softDelete).toHaveBeenCalledWith(["idx_1"])
586 })
587
588 it("keeps the record when one of the versions could not be removed", async () => {
589 const current = provider("search-new")
590 const context = registry({
591 indexes: [],
592 records: [{ id: "idx_1", name: "blog", active_version: 2 }],
593 versions: [
594 {
595 id: "ver_1",
596 search_index_id: "idx_1",
597 version: 1,
598 provider: "search-gone",
599 physical_name: "blog_v1",
600 definition_hash: "whatever",
601 },
602 {
603 id: "ver_2",
604 search_index_id: "idx_1",
605 version: 2,
606 provider: "search-new",
607 physical_name: "blog_v2",
608 definition_hash: "whatever",
609 },
610 ],
611 providers: [current],
612 })
613
614 await executeIndexMigrationPlan(context, [
615 {
616 action: "drop",
617 index: "blog",
618 physical_names: ["blog_v2", "blog_v1"],
619 },
620 ])
621
622 // What could go, went...
623 expect(current.deleteIndex).toHaveBeenCalledWith({ index: "blog_v2" })
624 expect(context.versionService.softDelete).toHaveBeenCalledWith(["ver_2"])
625
626 // ...but the record stays, so the next migration plans the drop again
627 // rather than leaving a physical index nothing points at.
628 expect(context.indexService.softDelete).not.toHaveBeenCalled()
629 expect(logger.warn).toHaveBeenCalledWith(
630 expect.stringContaining("search-gone")
631 )
632 expect(logger.warn).toHaveBeenCalledWith(
633 expect.stringContaining('Keeping the record for search index "blog"')
634 )
635 })
636
637 it("drops nothing that the plan it is handed does not ask for", async () => {
638 const index = definition()
639 const current = provider("search-new")
640 const context = registry({
641 indexes: [index],
642 records: [
643 { id: "idx_1", name: "product", active_version: 1 },
644 // Undeclared, and so droppable — but this plan leaves it out, the way
645 // `db:migrate` does when the drop was declined or never confirmed.
646 { id: "idx_2", name: "blog", active_version: 1 },
647 ],
648 versions: [
649 {
650 id: "ver_1",
651 search_index_id: "idx_1",
652 version: 1,
653 provider: "search-new",
654 physical_name: "product_v1",
655 definition_hash: index.definition_hash,
656 },
657 {
658 id: "ver_2",
659 search_index_id: "idx_2",
660 version: 1,
661 provider: "search-new",
662 physical_name: "blog_v1",
663 definition_hash: "whatever",
664 },
665 ],
666 providers: [current],
667 })
668
669 await executeIndexMigrationPlan(context, [
670 {
671 action: "noop",
672 index: "product",
673 physical_name: "product_v1",
674 definition_hash: index.definition_hash,
675 },
676 ])
677
678 expect(current.deleteIndex).not.toHaveBeenCalled()
679 expect(context.indexService.softDelete).not.toHaveBeenCalled()
680 })
681
682 it("warns and continues when a stale version's provider is no longer registered", async () => {
683 const index = definition()
684 const current = provider("search-new")
685 const context = registry({
686 indexes: [index],
687 records: [{ id: "idx_1", name: "product", active_version: 2 }],
688 versions: [
689 {
690 id: "ver_1",
691 search_index_id: "idx_1",
692 version: 1,
693 provider: "search-gone",
694 physical_name: "product_v1",
695 definition_hash: "older",
696 },
697 {
698 id: "ver_2",
699 search_index_id: "idx_1",
700 version: 2,
701 provider: "search-new",
702 physical_name: "product_v2",
703 definition_hash: "stale",
704 },
705 ],
706 providers: [current],
707 })
708
709 await executeIndexMigrationPlan(context, [
710 {
711 action: "migrate",
712 index: "product",
713 physical_name: "product_v3",
714 definition_hash: index.definition_hash,
715 version: 3,
716 active_physical_name: "product_v2",
717 active_definition_hash: "stale",
718 provider: "search-new",
719 },
720 ])
721
722 expect(current.upsertIndex).toHaveBeenCalled()
723 expect(context.versionService.softDelete).not.toHaveBeenCalled()
724 expect(logger.warn).toHaveBeenCalledWith(
725 expect.stringContaining("search-gone")
726 )
727 })
728 })
729 })