Raw
1 import { SearchTypes } from "@medusajs/framework/types"
2 import { Modules } from "@medusajs/framework/utils"
3 import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
4 import { SearchIndex, SearchIndexSync, SearchIndexVersion } from "@models"
5 import { SearchIndexSeedAction } from "@types"
6 import { versionPhysicalName } from "../../src/utils/versions"
7 import {
8 baseProducts,
9 consumedContainers,
10 consumedEvents,
11 dataset,
12 productIndex,
13 removeProduct,
14 resetDataset,
15 setOnBulkSeedStart,
16 touchProduct,
17 } from "../__fixtures__/product-index"
18
19 jest.setTimeout(120000)
20
21 type SearchService = SearchTypes.ISearchModuleService
22
23 // The startup hook seeds indexes, so the lifecycle tests re-run it to simulate
24 // a boot.
25 const boot = (service: SearchService) =>
26 (service as any).onApplicationStart_() as Promise<void>
27
28 const seedPlan = (service: SearchService) =>
29 (service as any).createSeedPlan_() as Promise<SearchIndexSeedAction[]>
30
31 // Migrating is public — `db:migrate` plans and executes it — but reading the
32 // registered definitions is not.
33 const migrationPlan = (service: SearchService) =>
34 service.createIndexMigrationPlan()
35
36 const migrate = (
37 service: SearchService,
38 actions: SearchTypes.SearchIndexMigrationAction[]
39 ) => service.executeIndexMigrationPlan(actions)
40
41 const definition = (service: SearchService, name: string) =>
42 (service as any).indexes_.get(name) as
43 | SearchTypes.ResolvedSearchIndexDefinition
44 | undefined
45
46 // `SearchIndex`, `SearchIndexVersion` and `SearchIndexSync` are internal to the
47 // module — no generated CRUD, nothing on `SearchTypes` — so the bookkeeping is
48 // read through the internal services the module uses itself.
49 const indexRecords = (service: SearchService, filters: any = {}) =>
50 (service as any).context_.indexService.list(filters) as Promise<any[]>
51
52 const versionRecords = (service: SearchService, filters: any = {}) =>
53 (service as any).context_.versionService.list(filters) as Promise<any[]>
54
55 const syncRecords = (service: SearchService, filters: any = {}) =>
56 (service as any).context_.syncService.list(filters) as Promise<any[]>
57
58 const updateVersionRecords = (service: SearchService, input: any) =>
59 (service as any).context_.versionService.update(input) as Promise<any>
60
61 const updateIndexRecords = (service: SearchService, input: any) =>
62 (service as any).context_.indexService.update(input) as Promise<any>
63
64 const createSyncRecords = (service: SearchService, input: any[]) =>
65 (service as any).context_.syncService.create(input) as Promise<any[]>
66
67 const softDeleteIndexRecords = (service: SearchService, ids: string[]) =>
68 (service as any).context_.indexService.softDelete(ids) as Promise<any>
69
70 // The version currently serving reads for a logical index. Every version —
71 // including the first — has its own physical name, so this is what a raw
72 // provider call (rather than one going through the module service, which
73 // resolves this itself) has to look up.
74 const activeVersion = async (service: SearchService, name: string) => {
75 const [record] = await indexRecords(service, { name })
76 const [version] = await versionRecords(service, {
77 search_index_id: record.id,
78 version: record.active_version,
79 })
80 return version
81 }
82
83 const activePhysicalName = async (service: SearchService, name: string) =>
84 (await activeVersion(service, name)).physical_name
85
86 // The version a migration built that hasn't gone active yet, if any.
87 const pendingVersion = async (service: SearchService, name: string) => {
88 const [record] = await indexRecords(service, { name })
89 const versions = await versionRecords(service, {
90 search_index_id: record.id,
91 })
92 return versions
93 .filter(
94 (version: any) =>
95 record.active_version == null || version.version > record.active_version
96 )
97 .sort((a: any, b: any) => b.version - a.version)[0]
98 }
99
100 const ids = (result: SearchTypes.SearchResult) =>
101 result.hits.map((hit) => hit.id)
102
103 moduleIntegrationTestRunner<SearchService>({
104 moduleName: Modules.SEARCH,
105 moduleModels: [SearchIndex, SearchIndexVersion, SearchIndexSync],
106 resolve: __dirname + "/../..",
107 pathToMigrations: [
108 __dirname + "/../../src/migrations",
109 __dirname + "/../../../providers/search-postgres/src/migrations",
110 ],
111 moduleOptions: {
112 providers: [
113 {
114 resolve: "@medusajs/search-postgres",
115 id: "postgres",
116 },
117 ],
118 indexes: [productIndex],
119 },
120 hooks: {
121 // The dataset has to be in place before the module boots, because startup
122 // seeds the index from it.
123 beforeModuleInit: async () => {
124 resetDataset()
125 },
126 // Indexes are created by `db:migrate`, never by the application. The startup
127 // hook has already run by the time this fires, so migrate and boot again —
128 // which is the order a real deploy uses.
129 afterModuleInit: async (_app: any, service: SearchService) => {
130 await migrate(service, await migrationPlan(service))
131 await boot(service)
132 },
133 },
134 testSuite: ({ service }) =>
135 describe("Search Module", () => {
136 describe("startup", () => {
137 it("registers the injected index definition", () => {
138 const registered = definition(service, "product")
139
140 expect(registered).toMatchObject({
141 name: "product",
142 entity: "product",
143 provider: "search-postgres",
144 primary_key: "id",
145 physical_name: "product",
146 })
147 expect(registered!.definition_hash).toEqual(expect.any(String))
148 })
149
150 it("returns undefined for an unknown index", () => {
151 expect(definition(service, "nope")).toBeUndefined()
152 })
153
154 it("persists an index record and marks its first version ready", async () => {
155 const [record] = await indexRecords(service, { name: "product" })
156 expect(record).toMatchObject({ name: "product", active_version: 1 })
157
158 const version = await activeVersion(service, "product")
159 expect(version).toMatchObject({
160 version: 1,
161 provider: "search-postgres",
162 status: "ready",
163 })
164 })
165
166 it("seeds the index on first boot, because nothing was indexed yet", async () => {
167 const result = await service.search({
168 entity: "product",
169 fields: ["id", "title"],
170 })
171
172 expect(result.metadata.count).toBe(3)
173 expect(ids(result).sort()).toEqual(["prod_1", "prod_2", "prod_3"])
174 })
175
176 it("records the startup seed and its catch-up pass in the sync history", async () => {
177 const syncs = await syncRecords(service, {})
178
179 // The bulk pass, plus the catch-up pass that runs right after it,
180 // sharing its `job_id`.
181 expect(syncs).toHaveLength(2)
182 expect(syncs.every((sync) => sync.status === "done")).toBe(true)
183 expect(new Set(syncs.map((sync) => sync.job_id)).size).toBe(1)
184 expect(syncs.find((sync) => sync.documents_synced === 3)).toBeTruthy()
185 expect(syncs.every((sync) => sync.completed_at)).toBe(true)
186 })
187
188 it("lists index info with status and indexed fields", async () => {
189 const infos = await service.listIndexes()
190
191 expect(infos).toHaveLength(1)
192 expect(infos[0]).toMatchObject({
193 name: "product",
194 entity: "product",
195 provider: "search-postgres",
196 status: "ready",
197 })
198 expect(infos[0].fields.map((field) => field.name).sort()).toEqual(
199 [
200 "brand",
201 "created_at",
202 "description",
203 "handle",
204 "id",
205 "min_price",
206 "status",
207 "tags",
208 "title",
209 "updated_at",
210 "variants.color",
211 "variants.sku",
212 ].sort()
213 )
214 expect(
215 infos[0].fields.find((field) => field.name === "title")
216 ).toMatchObject({
217 type: "text",
218 searchable: true,
219 sortable: true,
220 filterable: false,
221 })
222 })
223
224 it("does not hold the application hook until seeding finishes", async () => {
225 const index = definition(service, "product")!
226 const originalSeed = index.seed
227
228 let release!: () => void
229 const hold = new Promise<void>((resolve) => {
230 release = resolve
231 })
232 let entered!: () => void
233 const enteredSeed = new Promise<void>((resolve) => {
234 entered = resolve
235 })
236 let finished!: () => void
237 const seedFinished = new Promise<void>((resolve) => {
238 finished = resolve
239 })
240
241 let started = false
242 index.seed = async function* (ctx) {
243 started = true
244 entered()
245 await hold
246 try {
247 yield* originalSeed(ctx)
248 } finally {
249 finished()
250 }
251 }
252
253 try {
254 const version = await activeVersion(service, "product")
255 await updateVersionRecords(service, {
256 selector: { id: version.id },
257 data: { status: "pending" },
258 })
259
260 const hook = (service as any).__hooks.onApplicationStart.call(
261 service
262 )
263
264 await enteredSeed
265 await hook
266
267 const rebuilding = await activeVersion(service, "product")
268 expect(rebuilding.status).toBe("building")
269 } finally {
270 release()
271 if (started) {
272 await seedFinished
273 }
274 index.seed = originalSeed
275 }
276 })
277
278 it("logs seeding failures from the application hook instead of rejecting", async () => {
279 const errorSpy = jest
280 .spyOn((service as any).logger_, "error")
281 .mockImplementation(() => {})
282
283 const provider = (service as any).searchProviderService_.retrieve(
284 "search-postgres"
285 )
286
287 try {
288 await provider.deleteIndex({
289 index: await activePhysicalName(service, "product"),
290 })
291
292 await expect(
293 (service as any).__hooks.onApplicationStart.call(service)
294 ).resolves.toBeUndefined()
295
296 const deadline = Date.now() + 5000
297 while (errorSpy.mock.calls.length === 0 && Date.now() < deadline) {
298 await new Promise((resolve) => setTimeout(resolve, 25))
299 }
300
301 expect(errorSpy).toHaveBeenCalledWith(
302 expect.stringContaining(
303 "[Search] Failed to seed search indexes:"
304 ),
305 expect.any(Error)
306 )
307 } finally {
308 errorSpy.mockRestore()
309 }
310 })
311 })
312
313 describe("migration and seeding lifecycle", () => {
314 // Simulates schema drift: the active version's `definition_hash` now
315 // lives on `SearchIndexVersion`, not `SearchIndex`.
316 const stale = async () => {
317 const version = await activeVersion(service, "product")
318 await updateVersionRecords(service, {
319 selector: { id: version.id },
320 data: { definition_hash: "stale" },
321 })
322 }
323
324 it("does not create an index at startup, which is a migration's job", async () => {
325 const [record] = await indexRecords(service, { name: "product" })
326 await softDeleteIndexRecords(service, [record.id])
327
328 expect(await indexRecords(service, {})).toHaveLength(0)
329
330 await boot(service)
331
332 // Still nothing. An index that was never migrated is left alone rather
333 // than conjured into existence by a booting app.
334 expect(await indexRecords(service, {})).toHaveLength(0)
335 expect(await seedPlan(service)).toEqual([])
336 })
337
338 it("plans nothing once everything is up to date", async () => {
339 expect(await migrationPlan(service)).toEqual([
340 {
341 action: "noop",
342 index: "product",
343 physical_name: "product_v1",
344 definition_hash: definition(service, "product")!.definition_hash,
345 },
346 ])
347
348 expect(await seedPlan(service)).toEqual([])
349 })
350
351 it("plans a new version on schema drift", async () => {
352 await stale()
353
354 const registered = definition(service, "product")!
355 const [action] = await migrationPlan(service)
356
357 expect(action).toEqual({
358 action: "migrate",
359 index: "product",
360 physical_name: versionPhysicalName(registered, 2),
361 definition_hash: registered.definition_hash,
362 version: 2,
363 active_physical_name: "product_v1",
364 active_definition_hash: "stale",
365 provider: "search-postgres",
366 })
367 })
368
369 it("keeps the active version ready while a new one is built", async () => {
370 await stale()
371
372 await migrate(service, await migrationPlan(service))
373
374 // The replacement stands beside the active version, so it stays
375 // ready and unswapped until the seed makes the new one active.
376 const version = await activeVersion(service, "product")
377 expect(version.status).toBe("ready")
378 expect(version.definition_hash).toBe("stale")
379 })
380
381 it("finishes a schema migration on the next boot", async () => {
382 await stale()
383 await migrate(service, await migrationPlan(service))
384
385 const registered = definition(service, "product")!
386 const pending = await pendingVersion(service, "product")
387 expect(await seedPlan(service)).toEqual([
388 {
389 index: "product",
390 target_version: expect.objectContaining({ id: pending.id }),
391 swap: true,
392 reason: "schema_changed",
393 },
394 ])
395
396 await boot(service)
397
398 const version = await activeVersion(service, "product")
399
400 expect(version.definition_hash).toBe(registered.definition_hash)
401 expect(version.status).toBe("ready")
402
403 const result = await service.search({
404 entity: "product",
405 fields: ["id"],
406 })
407 expect(ids(result).sort()).toEqual(["prod_1", "prod_2", "prod_3"])
408 })
409
410 it("reseeds an index that lost its data even though the record says ready", async () => {
411 // An engine wiped underneath us: the record is untouched and
412 // correct, the index holds nothing.
413 await service.deleteDocuments({
414 index: "product",
415 filters: { id: ["prod_1", "prod_2", "prod_3"] },
416 })
417
418 const emptied = await service.search({
419 entity: "product",
420 fields: ["id"],
421 })
422 expect(emptied.metadata.count).toBe(0)
423
424 const active = await activeVersion(service, "product")
425 expect(await seedPlan(service)).toEqual([
426 {
427 index: "product",
428 target_version: expect.objectContaining({ id: active.id }),
429 swap: false,
430 reason: "index_empty",
431 },
432 ])
433
434 await boot(service)
435
436 const result = await service.search({
437 entity: "product",
438 fields: ["id"],
439 })
440 expect(ids(result).sort()).toEqual(["prod_1", "prod_2", "prod_3"])
441 })
442
443 it("cleans up the previous provider's version once a new one takes over", async () => {
444 const previous = {
445 identifier: "search-previous",
446 deleteIndex: jest.fn().mockResolvedValue({
447 index: "product_v1",
448 status: "succeeded",
449 }),
450 listIndexes: jest.fn().mockResolvedValue([]),
451 }
452 ;(service as any).searchProviderService_.providers_.set(
453 "search-previous",
454 previous
455 )
456
457 const active = await activeVersion(service, "product")
458 await updateVersionRecords(service, {
459 selector: { id: active.id },
460 data: { provider: "search-previous" },
461 })
462
463 const plan = await migrationPlan(service)
464 expect(plan).toEqual([
465 expect.objectContaining({
466 action: "migrate",
467 previous_provider: "search-previous",
468 provider: "search-postgres",
469 }),
470 ])
471
472 await migrate(service, plan)
473
474 // Version 1, on the old provider, is still active — nothing to
475 // clean up until the new version takes over.
476 expect(previous.deleteIndex).not.toHaveBeenCalled()
477
478 const [migrated] = await indexRecords(service, { name: "product" })
479 expect(migrated.active_version).toBe(1)
480
481 await boot(service)
482
483 const seeded = await activeVersion(service, "product")
484 expect(seeded.provider).toBe("search-postgres")
485 expect(seeded.status).toBe("ready")
486
487 // Still not cleaned up: that's the next migration's job, not the seed's.
488 expect(previous.deleteIndex).not.toHaveBeenCalled()
489
490 await migrate(service, await migrationPlan(service))
491
492 expect(previous.deleteIndex).toHaveBeenCalledWith({
493 index: "product_v1",
494 })
495 })
496
497 describe("when a definition is removed", () => {
498 // The registry the module planned from is the live one, so taking a
499 // definition out of it is what removing its file amounts to.
500 const undeclare = (name: string) => {
501 const registered = definition(service, name)!
502 ;(service as any).indexes_.delete(name)
503 return registered
504 }
505
506 const physicalNames = async () => {
507 const provider = (service as any).searchProviderService_.retrieve(
508 "search-postgres"
509 )
510 return (await provider.listIndexes())
511 .map((info: SearchTypes.SearchIndexInfo) => info.name)
512 .sort()
513 }
514
515 it("plans a drop for it", async () => {
516 undeclare("product")
517
518 expect(await migrationPlan(service)).toEqual([
519 {
520 action: "drop",
521 index: "product",
522 physical_names: ["product_v1"],
523 },
524 ])
525 })
526
527 it("removes the index, its versions and its record", async () => {
528 undeclare("product")
529
530 await migrate(service, await migrationPlan(service))
531
532 expect(await physicalNames()).toEqual([])
533 expect(await indexRecords(service, {})).toEqual([])
534 expect(await versionRecords(service, {})).toEqual([])
535
536 // Nothing left to plan or seed, rather than a record that keeps
537 // coming back.
538 expect(await migrationPlan(service)).toEqual([])
539 expect(await seedPlan(service)).toEqual([])
540 })
541
542 it("takes every version, not just the one serving reads", async () => {
543 await service.reindex()
544 expect(await physicalNames()).toEqual(["product_v1", "product_v2"])
545
546 undeclare("product")
547 await migrate(service, await migrationPlan(service))
548
549 expect(await physicalNames()).toEqual([])
550 })
551
552 it("builds the index again when the definition comes back", async () => {
553 const registered = undeclare("product")
554
555 await migrate(service, await migrationPlan(service))
556 ;(service as any).indexes_.set("product", registered)
557
558 await migrate(service, await migrationPlan(service))
559 await boot(service)
560
561 // A fresh record and a fresh version 1 — the dropped ones are soft
562 // deleted, so neither name collides with what is being built.
563 const [record] = await indexRecords(service, { name: "product" })
564 expect(record.active_version).toBe(1)
565 expect(await physicalNames()).toEqual(["product_v1"])
566
567 const result = await service.search({
568 entity: "product",
569 fields: ["id"],
570 })
571 expect(ids(result).sort()).toEqual(["prod_1", "prod_2", "prod_3"])
572 })
573
574 it("keeps the record when the provider that holds it is gone", async () => {
575 const warn = jest.spyOn((service as any).logger_, "warn")
576 const version = await activeVersion(service, "product")
577
578 await updateVersionRecords(service, {
579 selector: { id: version.id },
580 data: { provider: "search-gone" },
581 })
582 undeclare("product")
583
584 await migrate(service, await migrationPlan(service))
585
586 expect(warn).toHaveBeenCalledWith(
587 expect.stringContaining("search-gone")
588 )
589
590 // Left standing on purpose: dropping the record would strand the
591 // physical index with nothing pointing at it.
592 expect(await indexRecords(service, {})).toHaveLength(1)
593 expect(await migrationPlan(service)).toEqual([
594 {
595 action: "drop",
596 index: "product",
597 physical_names: ["product_v1"],
598 },
599 ])
600
601 warn.mockRestore()
602 })
603 })
604
605 it("still migrates when the previous provider is no longer registered", async () => {
606 const warn = jest.spyOn((service as any).logger_, "warn")
607
608 const active = await activeVersion(service, "product")
609 await updateVersionRecords(service, {
610 selector: { id: active.id },
611 data: { provider: "search-gone" },
612 })
613
614 await migrate(service, await migrationPlan(service))
615 await boot(service)
616
617 // The stale, gone-provider version is what the warning is about —
618 // it only surfaces once a migration tries to clean it up.
619 await migrate(service, await migrationPlan(service))
620
621 expect(warn).toHaveBeenCalledWith(
622 expect.stringContaining("search-gone")
623 )
624
625 const seeded = await activeVersion(service, "product")
626 expect(seeded.provider).toBe("search-postgres")
627
628 warn.mockRestore()
629 })
630
631 it("leaves index creation to migrations", async () => {
632 const provider = (service as any).searchProviderService_.retrieve(
633 "search-postgres"
634 )
635
636 await provider.deleteIndex({
637 index: await activePhysicalName(service, "product"),
638 })
639
640 // Nothing creates the index on the way to seeding it, so the seed
641 // fails against the engine rather than papering over a migration
642 // that never ran.
643 await expect(boot(service)).rejects.toThrow(
644 /has no index "product_v1"/
645 )
646 expect(await provider.listIndexes()).toEqual([])
647 })
648
649 it("seeds an index that was created but never filled", async () => {
650 const version = await activeVersion(service, "product")
651 await updateVersionRecords(service, {
652 selector: { id: version.id },
653 data: { status: "pending" },
654 })
655
656 expect(await seedPlan(service)).toEqual([
657 {
658 index: "product",
659 target_version: expect.objectContaining({ id: version.id }),
660 swap: false,
661 reason: "index_created",
662 },
663 ])
664 })
665
666 it("retries an index whose last seed failed", async () => {
667 const version = await activeVersion(service, "product")
668 await updateVersionRecords(service, {
669 selector: { id: version.id },
670 data: { status: "error" },
671 })
672
673 expect(await seedPlan(service)).toEqual([
674 {
675 index: "product",
676 target_version: expect.objectContaining({ id: version.id }),
677 swap: false,
678 reason: "last_run_failed",
679 },
680 ])
681
682 await boot(service)
683
684 const after = await activeVersion(service, "product")
685 expect(after.status).toBe("ready")
686 })
687
688 it("is idempotent across repeated boots", async () => {
689 const before = await syncRecords(service, {})
690
691 await boot(service)
692 await boot(service)
693
694 // Nothing needed doing, so no new sync runs were recorded.
695 expect(await syncRecords(service, {})).toHaveLength(before.length)
696 })
697 })
698
699 describe("free-text search", () => {
700 it("matches on searchable fields and scores by relevance", async () => {
701 const result = await service.search({
702 entity: "product",
703 fields: ["id", "title"],
704 filters: { q: "running" },
705 search_options: { include_score: true },
706 })
707
708 expect(ids(result).sort()).toEqual(["prod_1", "prod_2"])
709 expect(result.hits[0].score).toEqual(expect.any(Number))
710 })
711
712 it("takes the free-text query from `filters.q`", async () => {
713 const result = await service.search({
714 entity: "product",
715 fields: ["id"],
716 filters: { q: "wool" },
717 })
718
719 expect(ids(result)).toEqual(["prod_3"])
720 })
721
722 it("matches on a field that is never returned", async () => {
723 // `description` is `retrievable: false`, so nothing asks for it back —
724 // but it is indexed, so it still matches.
725 const result = await service.search({
726 entity: "product",
727 fields: ["id", "title"],
728 filters: { q: "breathable" },
729 })
730
731 expect(ids(result)).toEqual(["prod_1"])
732 expect(result.hits[0].document).toEqual({
733 id: "prod_1",
734 title: "Red running shoe",
735 })
736 })
737
738 it("returns exactly the fields it is given", async () => {
739 // Narrowing to what the index can serve is `query.search`'s job, so the
740 // module projects the list as-is rather than filtering it again.
741 const result = await service.search({
742 entity: "product",
743 fields: ["id", "brand"],
744 filters: { q: "breathable" },
745 })
746
747 expect(Object.keys(result.hits[0].document).sort()).toEqual([
748 "brand",
749 "id",
750 ])
751 })
752
753 it("matches nested searchable fields", async () => {
754 const result = await service.search({
755 entity: "product",
756 fields: ["id"],
757 filters: { q: "SHIRT-BLUE-M" },
758 })
759
760 expect(ids(result)).toEqual(["prod_2"])
761 })
762
763 it("restricts matching to the given attributes", async () => {
764 const result = await service.search({
765 entity: "product",
766 fields: ["id"],
767 filters: { q: "breathable" },
768 search_options: { attributes_to_search_on: ["title"] },
769 })
770
771 expect(result.hits).toHaveLength(0)
772 })
773
774 it("ignores highlighting and typo tolerance when there is no text query", async () => {
775 const result = await service.search({
776 entity: "product",
777 fields: ["id"],
778 filters: { status: "published" },
779 search_options: { highlight: true, typo_tolerance: true },
780 })
781
782 expect(ids(result).sort()).toEqual(["prod_1", "prod_2"])
783 })
784 })
785
786 describe("filtering", () => {
787 it("filters on an exact keyword value", async () => {
788 const result = await service.search({
789 entity: "product",
790 fields: ["id"],
791 filters: { status: "published" },
792 })
793
794 expect(ids(result).sort()).toEqual(["prod_1", "prod_2"])
795 })
796
797 it("does not leak token matches into keyword filters", async () => {
798 // `title` is tokenized for matching; `handle` is an exact keyword.
799 // A partial value must not match.
800 const result = await service.search({
801 entity: "product",
802 fields: ["id"],
803 filters: { handle: "red-running" },
804 })
805
806 expect(result.hits).toHaveLength(0)
807 })
808
809 it("supports $in, $ne and $nin on keywords", async () => {
810 const inResult = await service.search({
811 entity: "product",
812 fields: ["id"],
813 filters: { id: { $in: ["prod_1", "prod_3"] } },
814 })
815 expect(ids(inResult).sort()).toEqual(["prod_1", "prod_3"])
816
817 const neResult = await service.search({
818 entity: "product",
819 fields: ["id"],
820 filters: { status: { $ne: "draft" } },
821 })
822 expect(ids(neResult).sort()).toEqual(["prod_1", "prod_2"])
823
824 const ninResult = await service.search({
825 entity: "product",
826 fields: ["id"],
827 filters: { brand: { $nin: ["acme"] } },
828 })
829 expect(ids(ninResult)).toEqual(["prod_2"])
830 })
831
832 it("supports numeric comparisons and ranges", async () => {
833 const gte = await service.search({
834 entity: "product",
835 fields: ["id"],
836 filters: { min_price: { $gte: 100 } },
837 })
838 expect(ids(gte).sort()).toEqual(["prod_1", "prod_3"])
839
840 const range = await service.search({
841 entity: "product",
842 fields: ["id"],
843 filters: { min_price: { $gte: 60, $lte: 150 } },
844 })
845 expect(ids(range)).toEqual(["prod_1"])
846 })
847
848 it("filters on dates", async () => {
849 const result = await service.search({
850 entity: "product",
851 fields: ["id"],
852 filters: {
853 created_at: { $gte: new Date("2026-02-15T00:00:00.000Z") },
854 },
855 })
856
857 expect(ids(result)).toEqual(["prod_3"])
858 })
859
860 it("supports $overlaps and $contains on arrays", async () => {
861 const overlaps = await service.search({
862 entity: "product",
863 fields: ["id"],
864 filters: { tags: { $overlaps: ["hat", "shirt"] } },
865 })
866 expect(ids(overlaps).sort()).toEqual(["prod_2", "prod_3"])
867
868 const contains = await service.search({
869 entity: "product",
870 fields: ["id"],
871 filters: { tags: { $contains: ["shoe", "sport"] } },
872 })
873 expect(ids(contains)).toEqual(["prod_1"])
874 })
875
876 it("filters on a nested field", async () => {
877 const result = await service.search({
878 entity: "product",
879 fields: ["id"],
880 filters: { "variants.color": "olive" },
881 })
882
883 expect(ids(result)).toEqual(["prod_3"])
884 })
885
886 it("does not correlate predicates across array elements", async () => {
887 // prod_3 has a green S and an olive L. On a `flattened` provider both
888 // predicates match the product, not a single variant. Asserting the
889 // documented behaviour rather than the desired one.
890 const result = await service.search({
891 entity: "product",
892 fields: ["id"],
893 filters: {
894 $and: [
895 { "variants.color": "green" },
896 { "variants.sku": "HAT-GREEN-L" },
897 ],
898 },
899 })
900
901 expect(ids(result)).toEqual(["prod_3"])
902 })
903
904 it("combines a term with filters", async () => {
905 const result = await service.search({
906 entity: "product",
907 fields: ["id"],
908 filters: { q: "running", min_price: { $lte: 60 } },
909 })
910
911 expect(ids(result)).toEqual(["prod_2"])
912 })
913 })
914
915 describe("sorting and pagination", () => {
916 it("sorts by a numeric field", async () => {
917 const asc = await service.search({
918 entity: "product",
919 fields: ["id"],
920 pagination: { order: { min_price: "ASC" } },
921 })
922 expect(ids(asc)).toEqual(["prod_2", "prod_1", "prod_3"])
923
924 const desc = await service.search({
925 entity: "product",
926 fields: ["id"],
927 pagination: { order: { min_price: "DESC" } },
928 })
929 expect(ids(desc)).toEqual(["prod_3", "prod_1", "prod_2"])
930 })
931
932 it("sorts by a date", async () => {
933 const result = await service.search({
934 entity: "product",
935 fields: ["id"],
936 pagination: { order: { created_at: "DESC" } },
937 })
938
939 expect(ids(result)).toEqual(["prod_3", "prod_2", "prod_1"])
940 })
941
942 it("paginates while reporting the full count", async () => {
943 const page = await service.search({
944 entity: "product",
945 fields: ["id"],
946 pagination: { skip: 1, take: 1, order: { min_price: "ASC" } },
947 })
948
949 expect(ids(page)).toEqual(["prod_1"])
950 expect(page.metadata).toMatchObject({
951 skip: 1,
952 take: 1,
953 count: 3,
954 })
955 })
956 })
957
958 describe("faceting", () => {
959 it("returns value facets over the filtered result set", async () => {
960 const result = await service.search({
961 entity: "product",
962 fields: ["id"],
963 filters: { status: "published" },
964 search_options: { facets: ["brand", "tags"] },
965 })
966
967 expect(result.facets!.brand).toEqual({
968 type: "value",
969 values: expect.arrayContaining([
970 { value: "acme", count: 1 },
971 { value: "borg", count: 1 },
972 ]),
973 })
974 expect(
975 (result.facets!.tags as any).values.find(
976 (v: any) => v.value === "sport"
977 )
978 ).toEqual({ value: "sport", count: 2 })
979 })
980
981 it("returns range facets with the requested keys", async () => {
982 const result = await service.search({
983 entity: "product",
984 fields: ["id"],
985 search_options: {
986 facets: [
987 {
988 field: "min_price",
989 type: "range",
990 ranges: [
991 { key: "cheap", from: 0, to: 99 },
992 { key: "premium", from: 100, to: 1000 },
993 ],
994 },
995 ],
996 },
997 })
998
999 expect(result.facets!.min_price).toEqual({
1000 type: "range",
1001 ranges: [
1002 { key: "cheap", from: 0, to: 99, count: 1 },
1003 { key: "premium", from: 100, to: 1000, count: 2 },
1004 ],
1005 })
1006 })
1007
1008 it("computes disjunctive facets ignoring the field's own filter", async () => {
1009 const conjunctive = await service.search({
1010 entity: "product",
1011 fields: ["id"],
1012 filters: { brand: "acme" },
1013 search_options: { facets: ["brand"] },
1014 })
1015
1016 // With the filter applied, only the selected brand is counted.
1017 expect((conjunctive.facets!.brand as any).values).toEqual([
1018 { value: "acme", count: 2 },
1019 ])
1020
1021 const disjunctive = await service.search({
1022 entity: "product",
1023 fields: ["id"],
1024 filters: { brand: "acme" },
1025 search_options: { facets: ["brand"], disjunctive_facets: true },
1026 })
1027
1028 // The hits stay filtered...
1029 expect(ids(disjunctive).sort()).toEqual(["prod_1", "prod_3"])
1030 // ...but the facet shows the siblings a storefront needs.
1031 expect(
1032 (disjunctive.facets!.brand as any).values.sort((a: any, b: any) =>
1033 a.value < b.value ? -1 : 1
1034 )
1035 ).toEqual([
1036 { value: "acme", count: 2 },
1037 { value: "borg", count: 1 },
1038 ])
1039 })
1040 })
1041
1042 describe("document writes", () => {
1043 it("upserts and finds new documents", async () => {
1044 await service.upsertDocuments({
1045 index: "product",
1046 documents: [
1047 {
1048 id: "prod_4",
1049 title: "Yellow rain jacket",
1050 handle: "yellow-rain-jacket",
1051 description: "Keeps the rain out",
1052 status: "published",
1053 brand: "acme",
1054 min_price: 300,
1055 created_at: new Date("2026-04-01T00:00:00.000Z"),
1056 tags: ["jacket"],
1057 variants: [{ sku: "JACKET-YELLOW-M", color: "yellow" }],
1058 },
1059 ],
1060 })
1061
1062 const result = await service.search({
1063 entity: "product",
1064 fields: ["id", "title"],
1065 filters: { q: "jacket" },
1066 })
1067
1068 expect(ids(result)).toEqual(["prod_4"])
1069 expect(result.hits[0].document).toMatchObject({
1070 title: "Yellow rain jacket",
1071 })
1072 })
1073
1074 it("returns the write's task rather than waiting on it", async () => {
1075 const task = await service.upsertDocuments({
1076 index: "product",
1077 documents: [{ ...baseProducts[0], id: "prod_task" }],
1078 })
1079
1080 // Whether to block on this is the caller's decision, not the module's.
1081 expect(task).toMatchObject({
1082 index: await activePhysicalName(service, "product"),
1083 })
1084 expect(task.status).toEqual(
1085 expect.stringMatching(/^(enqueued|processing|succeeded)$/)
1086 )
1087 })
1088
1089 it("overwrites an existing document", async () => {
1090 await service.upsertDocuments({
1091 index: "product",
1092 documents: [{ ...baseProducts[0], title: "Crimson walking shoe" }],
1093 })
1094
1095 const stale = await service.search({
1096 entity: "product",
1097 fields: ["id"],
1098 filters: { q: "running" },
1099 })
1100 expect(ids(stale)).toEqual(["prod_2"])
1101
1102 const fresh = await service.search({
1103 entity: "product",
1104 fields: ["id"],
1105 filters: { q: "crimson" },
1106 })
1107 expect(ids(fresh)).toEqual(["prod_1"])
1108 })
1109
1110 it("deletes documents by id, which is a filter on the primary key", async () => {
1111 await service.deleteDocuments({
1112 index: "product",
1113 filters: { id: ["prod_1"] },
1114 })
1115
1116 const result = await service.search({
1117 entity: "product",
1118 fields: ["id"],
1119 })
1120
1121 expect(ids(result).sort()).toEqual(["prod_2", "prod_3"])
1122 expect(result.metadata.count).toBe(2)
1123 })
1124
1125 it("round-trips a document without losing its shape", async () => {
1126 const result = await service.search({
1127 entity: "product",
1128 fields: ["id", "created_at", "tags", "variants.sku"],
1129 filters: { id: "prod_1" },
1130 })
1131
1132 expect(result.hits[0].document).toEqual({
1133 id: "prod_1",
1134 created_at: baseProducts[0].created_at.toISOString(),
1135 tags: ["shoe", "sport"],
1136 // Arrays of objects are collapsed for indexing, not for reads.
1137 variants: [{ sku: "SHOE-RED-41" }, { sku: "SHOE-RED-42" }],
1138 })
1139 })
1140
1141 it("deletes documents by any filter, not just by id", async () => {
1142 await service.deleteDocuments({
1143 index: "product",
1144 filters: { status: "published" },
1145 })
1146
1147 const result = await service.search({
1148 entity: "product",
1149 fields: ["id"],
1150 })
1151
1152 expect(ids(result)).toEqual(["prod_3"])
1153 })
1154
1155 it("refuses an unfiltered delete rather than emptying the index", async () => {
1156 await expect(
1157 service.deleteDocuments({ index: "product", filters: {} })
1158 ).rejects.toThrow(/requires filters/)
1159 })
1160
1161 it("rejects writes to an unknown index", async () => {
1162 await expect(
1163 service.upsertDocuments({ index: "nope", documents: [{ id: "x" }] })
1164 ).rejects.toThrow(/No search index registered for "nope"/)
1165 })
1166 })
1167
1168 describe("event ingestion", () => {
1169 const ingest = (name: string, id: string) =>
1170 service.ingest({ name, data: { id } } as any)
1171
1172 const found = async (q: string) =>
1173 ids(
1174 await service.search({
1175 entity: "product",
1176 fields: ["id"],
1177 filters: { q },
1178 })
1179 )
1180
1181 it("indexes a document the event says was created", async () => {
1182 dataset.products.push({
1183 ...baseProducts[0],
1184 id: "prod_4",
1185 title: "Yellow rain jacket",
1186 handle: "yellow-rain-jacket",
1187 })
1188
1189 const tasks = await ingest("product.created", "prod_4")
1190
1191 expect(tasks).toEqual([
1192 expect.objectContaining({ status: "succeeded" }),
1193 ])
1194 expect(await found("jacket")).toEqual(["prod_4"])
1195 })
1196
1197 it("routes the event to the index that declared it", async () => {
1198 await ingest("product.updated", "prod_1")
1199
1200 expect(consumedEvents).toEqual([
1201 { event: "product.updated", index: "product" },
1202 ])
1203 })
1204
1205 it("hands consume the logger", async () => {
1206 await ingest("product.updated", "prod_1")
1207
1208 expect(consumedContainers).toHaveLength(1)
1209 expect(consumedContainers[0].logger).toBe((service as any).logger_)
1210 })
1211
1212 it("reindexes the document an update points at, in place", async () => {
1213 const product = dataset.products.find((p) => p.id === "prod_1")!
1214 product.title = "Crimson trail runner"
1215
1216 await ingest("product.updated", "prod_1")
1217
1218 const result = await service.search({
1219 entity: "product",
1220 fields: ["id", "title"],
1221 filters: { q: "crimson" },
1222 })
1223
1224 expect(result.hits).toEqual([
1225 expect.objectContaining({
1226 id: "prod_1",
1227 document: expect.objectContaining({
1228 title: "Crimson trail runner",
1229 }),
1230 }),
1231 ])
1232
1233 // Replaced rather than added beside the old document.
1234 const all = await service.search({
1235 entity: "product",
1236 fields: ["id"],
1237 })
1238 expect(all.metadata.count).toBe(3)
1239 })
1240
1241 it("removes the document an event says was deleted", async () => {
1242 await ingest("product.deleted", "prod_1")
1243
1244 const result = await service.search({
1245 entity: "product",
1246 fields: ["id"],
1247 })
1248
1249 expect(ids(result).sort()).toEqual(["prod_2", "prod_3"])
1250 })
1251
1252 // The bus only promises at-least-once, so twice must look like once.
1253 it("is idempotent under a redelivered event", async () => {
1254 const product = dataset.products.find((p) => p.id === "prod_2")!
1255 product.title = "Azure running shirt"
1256
1257 await ingest("product.updated", "prod_2")
1258 await ingest("product.updated", "prod_2")
1259
1260 const result = await service.search({
1261 entity: "product",
1262 fields: ["id"],
1263 filters: { q: "azure" },
1264 })
1265
1266 expect(ids(result)).toEqual(["prod_2"])
1267 expect(result.metadata.count).toBe(1)
1268 })
1269
1270 it("does nothing for an event no index declared", async () => {
1271 const tasks = await ingest("order.placed", "order_1")
1272
1273 expect(tasks).toEqual([])
1274 expect(consumedEvents).toEqual([])
1275 })
1276
1277 it("writes nothing when the entity is already gone", async () => {
1278 const tasks = await ingest("product.created", "prod_missing")
1279
1280 expect(tasks).toEqual([])
1281 expect(await found("shoe")).toEqual(["prod_1"])
1282 })
1283
1284 it("propagates a write failure, so the event is redelivered", async () => {
1285 const provider = (service as any).searchProviderService_.retrieve(
1286 "search-postgres"
1287 )
1288 const upsert = jest
1289 .spyOn(provider, "upsertDocuments")
1290 .mockResolvedValue({
1291 index: "product",
1292 status: "failed",
1293 error: { message: "engine unavailable" },
1294 })
1295
1296 await expect(ingest("product.updated", "prod_1")).rejects.toThrow(
1297 /engine unavailable/
1298 )
1299
1300 upsert.mockRestore()
1301 })
1302 })
1303
1304 describe("reindexing", () => {
1305 it("rebuilds from the seed into a new version and makes it active", async () => {
1306 dataset.products = [
1307 { ...baseProducts[0], title: "Scarlet trail shoe" },
1308 ...baseProducts.slice(1),
1309 ]
1310
1311 const { job_id, indexes } = await service.reindex()
1312
1313 expect(indexes).toEqual(["product"])
1314 expect(job_id).toEqual(expect.any(String))
1315
1316 const result = await service.search({
1317 entity: "product",
1318 fields: ["id"],
1319 filters: { q: "scarlet" },
1320 })
1321 expect(ids(result)).toEqual(["prod_1"])
1322 })
1323
1324 it("keeps the index searchable and the new version ready after a rebuild", async () => {
1325 await service.reindex()
1326
1327 const version = await activeVersion(service, "product")
1328 expect(version.status).toBe("ready")
1329 expect(version.version).toBe(2)
1330
1331 const result = await service.search({
1332 entity: "product",
1333 fields: ["id", "title"],
1334 filters: { q: "running" },
1335 })
1336 expect(ids(result).sort()).toEqual(["prod_1", "prod_2"])
1337 })
1338
1339 it("appends a row per run instead of overwriting", async () => {
1340 await service.reindex()
1341 await service.reindex()
1342
1343 const syncs = await syncRecords(service, {})
1344
1345 // One run from startup plus the two reindexes above, each made up
1346 // of a bulk pass and a catch-up pass sharing its `job_id`.
1347 expect(syncs).toHaveLength(6)
1348 expect(syncs.every((sync) => sync.status === "done")).toBe(true)
1349 expect(new Set(syncs.map((sync) => sync.job_id)).size).toBe(3)
1350 })
1351
1352 it("drops the versions a rebuild takes out of rotation", async () => {
1353 const provider = (service as any).searchProviderService_.retrieve(
1354 "search-postgres"
1355 )
1356 const physicalNames = async () =>
1357 (await provider.listIndexes())
1358 .map((info: SearchTypes.SearchIndexInfo) => info.name)
1359 .sort()
1360
1361 expect(await physicalNames()).toEqual(["product_v1"])
1362
1363 await service.reindex()
1364
1365 // Version 1 served reads while version 2 was built, so it is still
1366 // standing right after the swap — long enough for another instance's
1367 // active-version cache to catch up.
1368 expect(await physicalNames()).toEqual(["product_v1", "product_v2"])
1369
1370 await service.reindex()
1371
1372 // ...and goes as the next rebuild starts, so what is left is the
1373 // version serving reads and the one it took over from, rather than a
1374 // physical index per rebuild.
1375 expect(await physicalNames()).toEqual(["product_v2", "product_v3"])
1376
1377 const [record] = await indexRecords(service, { name: "product" })
1378 expect(record.active_version).toBe(3)
1379
1380 const versions = await versionRecords(service, {
1381 search_index_id: record.id,
1382 })
1383 expect(
1384 versions.map((version: any) => version.version).sort()
1385 ).toEqual([2, 3])
1386
1387 // Dropping the old versions leaves the index itself untouched.
1388 const result = await service.search({
1389 entity: "product",
1390 fields: ["id"],
1391 })
1392 expect(ids(result).sort()).toEqual(["prod_1", "prod_2", "prod_3"])
1393 })
1394
1395 it("reindexes a subset in place and records the filters used", async () => {
1396 dataset.products = [
1397 { ...baseProducts[0], title: "Scarlet trail shoe" },
1398 ...baseProducts.slice(1),
1399 ]
1400
1401 await service.reindex({ filters: { ids: ["prod_1"] } })
1402
1403 // The filtered product is updated...
1404 const updated = await service.search({
1405 entity: "product",
1406 fields: ["id"],
1407 filters: { q: "scarlet" },
1408 })
1409 expect(ids(updated)).toEqual(["prod_1"])
1410
1411 // ...and everything outside the filter survives, which is why a
1412 // partial run must never swap.
1413 const all = await service.search({
1414 entity: "product",
1415 fields: ["id"],
1416 })
1417 expect(ids(all).sort()).toEqual(["prod_1", "prod_2", "prod_3"])
1418
1419 const syncs = await syncRecords(service, {})
1420 const partial = syncs.find((sync) => sync.filters !== null)
1421
1422 expect(partial).toMatchObject({
1423 status: "done",
1424 documents_synced: 1,
1425 filters: { ids: ["prod_1"] },
1426 })
1427 expect(partial!.last_key).toBe("prod_1")
1428 })
1429
1430 it("reindexes a subset in place using a since cursor, without swapping or catching up", async () => {
1431 resetDataset()
1432
1433 const activeBefore = await activePhysicalName(service, "product")
1434 const since = new Date()
1435 touchProduct("prod_1", { title: "Scarlet trail shoe" })
1436
1437 const { job_id } = await service.reindex({ since })
1438
1439 // Only the document that changed since the cursor is updated...
1440 const updated = await service.search({
1441 entity: "product",
1442 fields: ["id"],
1443 filters: { q: "scarlet" },
1444 })
1445 expect(ids(updated)).toEqual(["prod_1"])
1446
1447 // ...everything else survives, because a `since`-scoped run never
1448 // swaps in a version that only holds that slice.
1449 const all = await service.search({
1450 entity: "product",
1451 fields: ["id"],
1452 })
1453 expect(ids(all).sort()).toEqual(["prod_1", "prod_2", "prod_3"])
1454 expect(await activePhysicalName(service, "product")).toBe(
1455 activeBefore
1456 )
1457
1458 // ...and it's already a caller-scoped run, so no catch-up pass
1459 // follows it — one sync row, not two.
1460 const syncs = await syncRecords(service, { job_id })
1461 expect(syncs).toHaveLength(1)
1462 })
1463
1464 it("leaves an interrupted full run's cursor for that run to resume", async () => {
1465 resetDataset()
1466
1467 const version = await activeVersion(service, "product")
1468
1469 // Stands in for a full in-place rebuild that died mid-stream: the row
1470 // is still processing, and its `last_key` is where it got to.
1471 const [interrupted] = await createSyncRecords(service, [
1472 {
1473 search_index_version_id: version.id,
1474 job_id: "job_interrupted",
1475 status: "processing",
1476 filters: null,
1477 last_key: "prod_2",
1478 started_at: new Date(),
1479 },
1480 ])
1481
1482 touchProduct("prod_1", { title: "Scarlet trail shoe" })
1483
1484 await service.reindex({ since: new Date(0) })
1485
1486 // A scoped run covers a different set of documents, so it neither
1487 // resumes from that cursor (which would skip prod_1)...
1488 const updated = await service.search({
1489 entity: "product",
1490 fields: ["id"],
1491 filters: { q: "scarlet" },
1492 })
1493 expect(ids(updated)).toEqual(["prod_1"])
1494
1495 // ...nor cancels the run that owns it.
1496 const [after] = await syncRecords(service, { id: interrupted.id })
1497 expect(after).toMatchObject({
1498 status: "processing",
1499 last_key: "prod_2",
1500 })
1501 })
1502
1503 it("closes definition drift, which is the only way a schema changes", async () => {
1504 const before = await activeVersion(service, "product")
1505
1506 // Stand in for a deploy that changed the definition. `upsertIndex`
1507 // deliberately does not reconcile schemas, so a rebuild is what
1508 // migrates the index and clears the drift.
1509 await updateVersionRecords(service, {
1510 selector: { id: before.id },
1511 data: { definition_hash: "stale", status: "pending" },
1512 })
1513
1514 await service.reindex()
1515
1516 const after = await activeVersion(service, "product")
1517 expect(after.definition_hash).toBe(
1518 definition(service, "product")!.definition_hash
1519 )
1520 expect(after.status).toBe("ready")
1521
1522 // The rebuild has to end up populated. An empty one would mean the
1523 // seed never refilled it.
1524 const result = await service.search({
1525 entity: "product",
1526 fields: ["id"],
1527 })
1528 expect(ids(result).sort()).toEqual(["prod_1", "prod_2", "prod_3"])
1529 })
1530
1531 it("rebuilds in place, clearing documents the seed no longer produces", async () => {
1532 await service.upsertDocuments({
1533 index: "product",
1534 documents: [{ ...baseProducts[0], id: "prod_stale" }],
1535 })
1536
1537 dataset.products = [
1538 { ...baseProducts[0], title: "Vermilion trail shoe" },
1539 ...baseProducts.slice(1),
1540 ]
1541
1542 await service.reindex({ strategy: "in_place" })
1543
1544 // `in_place` writes into the active version rather than a new one,
1545 // but a full (unfiltered) rebuild still clears it first, so the
1546 // seed's documents are refreshed...
1547 const refreshed = await service.search({
1548 entity: "product",
1549 fields: ["id"],
1550 filters: { q: "vermilion" },
1551 })
1552 expect(ids(refreshed)).toEqual(["prod_1"])
1553
1554 // ...and anything the seed no longer produces is gone too.
1555 const all = await service.search({
1556 entity: "product",
1557 fields: ["id"],
1558 })
1559 expect(ids(all).sort()).toEqual(["prod_1", "prod_2", "prod_3"])
1560 })
1561
1562 it("rejects reindexing an unknown index", async () => {
1563 await expect(service.reindex({ index: "nope" })).rejects.toThrow(
1564 /No search index registered for "nope"/
1565 )
1566 })
1567
1568 it("catches an update that landed after the bulk pass took its snapshot", async () => {
1569 resetDataset()
1570 setOnBulkSeedStart(() => {
1571 touchProduct("prod_1", { title: "Scarlet trail shoe" })
1572 })
1573
1574 await service.reindex()
1575
1576 const result = await service.search({
1577 entity: "product",
1578 fields: ["id", "title"],
1579 filters: { q: "scarlet" },
1580 })
1581 expect(ids(result)).toEqual(["prod_1"])
1582 })
1583
1584 it("catches a delete that landed after the bulk pass took its snapshot", async () => {
1585 resetDataset()
1586 setOnBulkSeedStart(() => {
1587 removeProduct("prod_1")
1588 })
1589
1590 await service.reindex()
1591
1592 const result = await service.search({
1593 entity: "product",
1594 fields: ["id"],
1595 })
1596 expect(ids(result).sort()).toEqual(["prod_2", "prod_3"])
1597 })
1598 })
1599
1600 describe("when another process swaps the active version", () => {
1601 // Every process caches which version serves reads, and only the one
1602 // that performed the swap updates its own copy.
1603 const missTheSwap = async () => {
1604 await service.search({ entity: "product", fields: ["id"] })
1605
1606 await service.reindex()
1607 expect(await activePhysicalName(service, "product")).toBe(
1608 "product_v2"
1609 )
1610 ;(service as any).activeVersionCache_.set("product", {
1611 physical_name: "product_v1",
1612 provider: "search-postgres",
1613 version: 1,
1614 })
1615 }
1616
1617 // Reads are allowed to be briefly stale, so the checks below go to
1618 // whichever version actually serves reads rather than the pinned one.
1619 const searchTheLiveVersion = async (
1620 filters?: Record<string, unknown>
1621 ) => {
1622 ;(service as any).activeVersionCache_.invalidate()
1623 return await service.search({
1624 entity: "product",
1625 fields: ["id"],
1626 ...(filters ? { filters } : {}),
1627 })
1628 }
1629
1630 it("writes into the version serving reads, not the cached one", async () => {
1631 await missTheSwap()
1632
1633 await service.upsertDocuments({
1634 index: "product",
1635 documents: [
1636 {
1637 ...baseProducts[0],
1638 id: "prod_written",
1639 title: "Cobalt runner",
1640 },
1641 ],
1642 })
1643
1644 // Landing in the retired version would make the document invisible,
1645 // and lose it outright once that version is cleaned up.
1646 expect(ids(await searchTheLiveVersion({ q: "cobalt" }))).toEqual([
1647 "prod_written",
1648 ])
1649 })
1650
1651 it("deletes from the version serving reads, not the cached one", async () => {
1652 await missTheSwap()
1653
1654 await service.deleteDocuments({
1655 index: "product",
1656 filters: { id: ["prod_1"] },
1657 })
1658
1659 expect(ids(await searchTheLiveVersion()).sort()).toEqual([
1660 "prod_2",
1661 "prod_3",
1662 ])
1663 })
1664
1665 it("ingests an event into the version serving reads", async () => {
1666 await missTheSwap()
1667
1668 touchProduct("prod_1", { title: "Cobalt runner" })
1669 await service.ingest({
1670 name: "product.updated",
1671 data: { id: "prod_1" },
1672 } as any)
1673
1674 expect(ids(await searchTheLiveVersion({ q: "cobalt" }))).toEqual([
1675 "prod_1",
1676 ])
1677 })
1678
1679 it("recovers a read whose cached version has since been dropped", async () => {
1680 await missTheSwap()
1681
1682 // What a cleanup on the process that owns the swap does next.
1683 await (service as any).searchProviderService_
1684 .retrieve("search-postgres")
1685 .deleteIndex({ index: "product_v1" })
1686
1687 // The engine reporting no such index is the signal to resolve again
1688 // rather than fail the search.
1689 const result = await service.search({
1690 entity: "product",
1691 fields: ["id"],
1692 })
1693 expect(ids(result).sort()).toEqual(["prod_1", "prod_2", "prod_3"])
1694 })
1695
1696 it("still reports an index that genuinely has no active version", async () => {
1697 const [record] = await indexRecords(service, { name: "product" })
1698 await updateIndexRecords(service, {
1699 selector: { id: record.id },
1700 data: { active_version: null },
1701 })
1702 ;(service as any).activeVersionCache_.invalidate()
1703
1704 await expect(
1705 service.search({ entity: "product", fields: ["id"] })
1706 ).rejects.toThrow(/has no active version yet/)
1707 })
1708 })
1709
1710 describe("capability and definition validation", () => {
1711 it("forwards $or filters the engine can express", async () => {
1712 const result = await service.search({
1713 entity: "product",
1714 fields: ["id"],
1715 filters: {
1716 $or: [{ status: "draft" }, { brand: "borg" }],
1717 },
1718 })
1719
1720 expect(ids(result).sort()).toEqual(["prod_2", "prod_3"])
1721 })
1722
1723 it("rejects highlighting, which the provider has no support for", async () => {
1724 await expect(
1725 service.search({
1726 entity: "product",
1727 fields: ["id"],
1728 filters: { q: "running" },
1729 search_options: { highlight: { fields: ["title"] } },
1730 })
1731 ).rejects.toThrow(/does not support highlighting/)
1732 })
1733
1734 it("rejects filtering on a field that is not filterable", async () => {
1735 await expect(
1736 service.search({
1737 entity: "product",
1738 fields: ["id"],
1739 filters: { title: "Red running shoe" },
1740 })
1741 ).rejects.toThrow(/Field "title" is not filterable/)
1742 })
1743
1744 it("rejects sorting on a field that is not sortable", async () => {
1745 await expect(
1746 service.search({
1747 entity: "product",
1748 fields: ["id"],
1749 pagination: { order: { handle: "ASC" } },
1750 })
1751 ).rejects.toThrow(/Field "handle" is not sortable/)
1752 })
1753
1754 it("rejects an unknown field", async () => {
1755 await expect(
1756 service.search({
1757 entity: "product",
1758 fields: ["id"],
1759 filters: { nope: "x" },
1760 })
1761 ).rejects.toThrow(/Unknown field "nope" used in filters/)
1762 })
1763
1764 it("rejects searching an unknown index", async () => {
1765 await expect(
1766 service.search({ entity: "nope", fields: ["id"] })
1767 ).rejects.toThrow(/No search index registered for "nope"/)
1768 })
1769 })
1770
1771 describe("searchMany", () => {
1772 it("runs several queries and preserves their order", async () => {
1773 const results = await service.searchMany([
1774 { entity: "product", fields: ["id"], filters: { q: "running" } },
1775 { entity: "product", fields: ["id"], filters: { status: "draft" } },
1776 {
1777 entity: "product",
1778 fields: ["id"],
1779 pagination: { order: { min_price: "DESC" }, take: 1 },
1780 },
1781 ])
1782
1783 expect(results).toHaveLength(3)
1784 expect(ids(results[0]).sort()).toEqual(["prod_1", "prod_2"])
1785 expect(ids(results[1])).toEqual(["prod_3"])
1786 expect(ids(results[2])).toEqual(["prod_3"])
1787 })
1788 })
1789 }),
1790 })