1 import { SearchTypes } from "@medusajs/framework/types"
2 import { MedusaError } from "@medusajs/framework/utils"
3 import {
4 SearchIndexContext,
5 SearchIndexes,
6 SearchIndexVersionRecord,
7 } from "@types"
8 import { createHash } from "crypto"
9
10 export enum SearchIndexState {
11 PENDING = "pending",
12 BUILDING = "building",
13 READY = "ready",
14 ERROR = "error",
15 }
16
17 export enum SearchSyncStatus {
18 PENDING = "pending",
19 PROCESSING = "processing",
20 DONE = "done",
21 FAILED = "failed",
22 CANCELED = "canceled",
23 }
24
25 const DEFAULT_TAKE = 20
26 export const DEFAULT_REINDEX_BATCH_SIZE = 100
27
28 /* ----------------------------- field traversal ---------------------------- */
29
30 export type FlatSearchField = {
31 path: string
32 field: SearchTypes.SearchFieldDefinition
33 }
34
35 // Walks fields into dotted paths. Object fields yield themselves and their
36 // descendants, so `retrievable` can be asked about either.
37 export function flattenFields(
38 fields: Record<string, SearchTypes.SearchFieldDefinition>,
39 prefix = ""
40 ): FlatSearchField[] {
41 const flat: FlatSearchField[] = []
42
43 for (const [name, field] of Object.entries(fields)) {
44 const path = prefix ? `${prefix}.${name}` : name
45 flat.push({ path, field })
46
47 if (field.type === "object" && field.fields) {
48 flat.push(...flattenFields(field.fields, path))
49 }
50 }
51
52 return flat
53 }
54
55 function buildFieldMap(
56 definition: Pick<SearchTypes.SearchIndexDefinition, "fields">
57 ): Map<string, FlatSearchField> {
58 return new Map(flattenFields(definition.fields).map((f) => [f.path, f]))
59 }
60
61 export function isSearchable(
62 field: SearchTypes.SearchFieldDefinition
63 ): boolean {
64 return field.searchable === true || typeof field.searchable === "object"
65 }
66
67 export function isFacetable(
68 field: SearchTypes.SearchFieldDefinition,
69 kind: SearchTypes.SearchFacetKind
70 ): boolean {
71 if (field.facetable === true) {
72 return defaultFacetKinds(field).includes(kind)
73 }
74 if (typeof field.facetable === "object") {
75 return (field.facetable.types ?? defaultFacetKinds(field)).includes(kind)
76 }
77 return false
78 }
79
80 // `stats` is opt-in: it is the least widely supported facet kind, so implying
81 // it would make numeric fields unusable on providers that lack aggregations.
82 function defaultFacetKinds(
83 field: SearchTypes.SearchFieldDefinition
84 ): SearchTypes.SearchFacetKind[] {
85 switch (field.type) {
86 case "integer":
87 case "float":
88 case "date":
89 return ["range"]
90 default:
91 return ["value"]
92 }
93 }
94
95 /**
96 * Whether a field is returned on hits. Vectors default to off — embeddings
97 * are not useful on hits. Set `retrievable: true` to return them.
98 */
99 function isRetrievableField(field: SearchTypes.SearchFieldDefinition): boolean {
100 if (field.type === "object") {
101 return false
102 }
103 if (field.type === "vector") {
104 return field.retrievable === true
105 }
106 return field.retrievable !== false
107 }
108
109 /**
110 * The dotted paths an index can hand back on hits. Object containers are
111 * excluded — only their declared leaves are stored, so returning the container
112 * would silently hand back a partial object.
113 */
114 export function listRetrievablePaths(
115 fields: Record<string, SearchTypes.SearchFieldDefinition>
116 ): string[] {
117 return flattenFields(fields)
118 .filter(({ field }) => isRetrievableField(field))
119 .map(({ path }) => path)
120 }
121
122 /**
123 * Leaf fields the index stores, with the capabilities declared on each. Object
124 * containers are omitted — only their leaves are indexed.
125 */
126 export function listIndexedFields(
127 fields: Record<string, SearchTypes.SearchFieldDefinition>
128 ): SearchTypes.SearchIndexFieldInfo[] {
129 return flattenFields(fields)
130 .filter(({ field }) => field.type !== "object")
131 .map(({ path, field }) => ({
132 name: path,
133 type: field.type,
134 searchable: isSearchable(field),
135 filterable: !!field.filterable,
136 sortable: !!field.sortable,
137 facetable:
138 field.facetable === true || typeof field.facetable === "object",
139 }))
140 }
141
142 // Key order must not change the hash, so object keys are emitted sorted.
143 function stableStringify(value: unknown): string {
144 if (value === null || typeof value !== "object") {
145 return JSON.stringify(value) ?? "null"
146 }
147 if (Array.isArray(value)) {
148 return `[${value.map(stableStringify).join(",")}]`
149 }
150 const entries = Object.entries(value as Record<string, unknown>)
151 .filter(([, v]) => v !== undefined)
152 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
153 .map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`)
154 return `{${entries.join(",")}}`
155 }
156
157 /**
158 * Stable hash over what affects the physical index. `events`, `consume` and
159 * `seed` are excluded: how documents are produced is not the index' shape.
160 * `primary_key` and `physical_name` are included even though they are not
161 * strictly shape, because changing either strands the index the record points
162 * at — the mismatch is what makes `db:migrate` rebuild.
163 */
164 function buildDefinitionHash(
165 definition: Pick<SearchTypes.SearchIndexDefinition, "fields" | "settings"> & {
166 primary_key: string
167 physical_name: string
168 }
169 ): string {
170 return createHash("sha256")
171 .update(
172 stableStringify({
173 fields: definition.fields,
174 settings: definition.settings ?? {},
175 primary_key: definition.primary_key,
176 physical_name: definition.physical_name,
177 })
178 )
179 .digest("hex")
180 .slice(0, 32)
181 }
182
183 // Accounts for `index_prefix` and, for a shadow index, the schema suffix.
184 function buildPhysicalIndexName({
185 name,
186 prefix,
187 suffix,
188 }: {
189 name: string
190 prefix?: string
191 suffix?: string
192 }): string {
193 return [prefix, name, suffix].filter(Boolean).join("_")
194 }
195
196 // Lifts `q` out of the filters, applies pagination defaults, and expands
197 // shorthand facets. When `attributes_to_search_on` is omitted the provider
198 // matches on every field marked `searchable`.
199 export function normalizeSearchQuery({
200 query,
201 index,
202 }: {
203 query: SearchTypes.SearchQuery
204 index: SearchTypes.ResolvedSearchIndexDefinition
205 }): SearchTypes.ProviderSearchQuery {
206 const filters = { ...(query.filters ?? {}) } as Record<string, unknown>
207
208 // `q` travels with the filters so that a `query.graph` call converts to a
209 // `query.search` one unchanged, but it is not a field — lift it out before the
210 // rest is compiled into a provider filter DSL.
211 const q = filters.q as string | undefined
212 delete filters.q
213
214 const searchOptions = { ...(query.search_options ?? {}) }
215
216 searchOptions.facets = searchOptions.facets?.map((facet) =>
217 typeof facet === "string" ? { field: facet, type: "value" as const } : facet
218 )
219
220 if (searchOptions.vector && !searchOptions.vector.field) {
221 const vectorFields = flattenFields(index.fields).filter(
222 ({ field }) => field.type === "vector"
223 )
224 if (vectorFields.length === 1) {
225 searchOptions.vector = {
226 ...searchOptions.vector,
227 field: vectorFields[0].path,
228 }
229 }
230 }
231
232 return {
233 index,
234 // Taken as given when set: `query.search` has already dropped anything the
235 // index cannot return and left only what the provider should project. A
236 // direct caller that names no fields gets everything retrievable.
237 attributes_to_retrieve: query.fields ?? listRetrievablePaths(index.fields),
238 q,
239 filters: Object.keys(filters).length
240 ? (filters as SearchTypes.SearchFilters)
241 : undefined,
242 pagination: {
243 skip: query.pagination?.skip ?? 0,
244 take: query.pagination?.take ?? DEFAULT_TAKE,
245 order: query.pagination?.order,
246 cursor: query.pagination?.cursor,
247 },
248 search_options: searchOptions,
249 }
250 }
251
252 // Drops every predicate on `field`, including inside `$and` / `$or` / `$not`.
253 function withoutFieldFilter(
254 filters: SearchTypes.SearchFilters | undefined,
255 field: string
256 ): SearchTypes.SearchFilters | undefined {
257 if (!filters) {
258 return undefined
259 }
260
261 const next: Record<string, unknown> = {}
262
263 for (const [key, value] of Object.entries(filters)) {
264 if (key === field) {
265 continue
266 }
267
268 if ((key === "$and" || key === "$or") && Array.isArray(value)) {
269 const branches = value
270 .map((branch) => withoutFieldFilter(branch, field))
271 .filter((branch) => branch && Object.keys(branch).length)
272 if (branches.length) {
273 next[key] = branches
274 }
275 continue
276 }
277
278 if (key === "$not") {
279 const stripped = withoutFieldFilter(
280 value as SearchTypes.SearchFilters,
281 field
282 )
283 if (stripped && Object.keys(stripped).length) {
284 next.$not = stripped
285 }
286 continue
287 }
288
289 next[key] = value
290 }
291
292 return Object.keys(next).length
293 ? (next as SearchTypes.SearchFilters)
294 : undefined
295 }
296
297 /**
298 * The base query plus one per faceted field with that field's own filter dropped.
299 * Every engine reviewed needs a query per facet, so the fan-out lives here rather
300 * than in each provider. The expanded set is then handed to `provider.searchMany`
301 * so the engine can pack them into one round-trip. `disjunctive_facets` is
302 * stripped from what is handed on — a provider should never see an option it is
303 * not expected to act on.
304 */
305 export function buildDisjunctiveFacetQueries(
306 query: SearchTypes.ProviderSearchQuery
307 ): {
308 base: SearchTypes.ProviderSearchQuery
309 per_facet: Map<string, SearchTypes.ProviderSearchQuery>
310 } {
311 const perFacet = new Map<string, SearchTypes.ProviderSearchQuery>()
312 const facets = (query.search_options?.facets ??
313 []) as SearchTypes.SearchFacetRequest[]
314
315 const { disjunctive_facets: _, ...searchOptions } = query.search_options ?? {}
316 const base: SearchTypes.ProviderSearchQuery = {
317 ...query,
318 search_options: searchOptions,
319 }
320
321 for (const facet of facets) {
322 const relaxed = withoutFieldFilter(query.filters, facet.field)
323
324 // Nothing filters this field, so the base result's facet is already right.
325 if (stableStringify(relaxed) === stableStringify(query.filters)) {
326 continue
327 }
328
329 perFacet.set(facet.field, {
330 ...base,
331 filters: relaxed,
332 // Only the facet is wanted; skip the hits and the count.
333 pagination: { ...query.pagination, skip: 0, take: 0 },
334 search_options: { ...searchOptions, facets: [facet], count: "none" },
335 })
336 }
337
338 return { base, per_facet: perFacet }
339 }
340
341 export function mergeDisjunctiveFacetResults({
342 base,
343 per_facet,
344 }: {
345 base: SearchTypes.SearchResult
346 per_facet: Map<string, SearchTypes.SearchResult>
347 }): SearchTypes.SearchResult {
348 if (!per_facet.size) {
349 return base
350 }
351
352 const facets = { ...(base.facets ?? {}) }
353
354 for (const [field, result] of per_facet) {
355 const relaxed = result.facets?.[field]
356 if (relaxed) {
357 facets[field] = relaxed
358 }
359 }
360
361 return { ...base, facets }
362 }
363
364 function collectFilterPaths(
365 filters: SearchTypes.SearchFilters,
366 into: Set<string> = new Set()
367 ): Set<string> {
368 for (const [key, value] of Object.entries(filters)) {
369 if (key === "$and" || key === "$or") {
370 for (const branch of (value ?? []) as SearchTypes.SearchFilters[]) {
371 collectFilterPaths(branch, into)
372 }
373 } else if (key === "$not") {
374 collectFilterPaths(value as SearchTypes.SearchFilters, into)
375 } else {
376 into.add(key)
377 }
378 }
379 return into
380 }
381
382 // Checks a field is declared for the use the query puts it to. Engines reject
383 // these too, but with errors that do not name the definition to fix.
384 export function validateFieldUsage({
385 index,
386 query,
387 }: {
388 index: SearchTypes.ResolvedSearchIndexDefinition
389 // Accepts a normalized query too, and must run on one: `filters.q` is sugar
390 // for the top-level `q` and is only lifted out during normalization.
391 query: Pick<
392 SearchTypes.SearchQuery,
393 "filters" | "pagination" | "search_options"
394 >
395 }): void {
396 const fieldMap = buildFieldMap(index)
397
398 function fail(message: string): never {
399 throw new MedusaError(MedusaError.Types.INVALID_DATA, message)
400 }
401
402 const lookup = (path: string, usage: string) => {
403 const known = fieldMap.get(path)
404 if (!known) {
405 fail(
406 `Unknown field "${path}" used in ${usage} on search index "${index.name}"`
407 )
408 }
409 return known.field
410 }
411
412 if (query.filters) {
413 for (const path of collectFilterPaths(query.filters)) {
414 const field = lookup(path, "filters")
415 if (!field.filterable) {
416 fail(
417 `Field "${path}" is not filterable on search index "${index.name}"`
418 )
419 }
420 }
421 }
422
423 for (const path of Object.keys(query.pagination?.order ?? {})) {
424 if (path === "_score") {
425 continue
426 }
427 const field = lookup(path, "pagination.order")
428 if (!field.sortable) {
429 fail(`Field "${path}" is not sortable on search index "${index.name}"`)
430 }
431 }
432
433 for (const facet of query.search_options?.facets ?? []) {
434 const request =
435 typeof facet === "string"
436 ? { field: facet, type: "value" as const }
437 : facet
438 const field = lookup(request.field, "search_options.facets")
439 const kind = request.type ?? "value"
440 if (!isFacetable(field, kind)) {
441 fail(
442 `Field "${request.field}" does not support "${kind}" facets on search index "${index.name}"`
443 )
444 }
445 }
446
447 for (const path of query.search_options?.attributes_to_search_on ?? []) {
448 const field = lookup(path, "search_options.attributes_to_search_on")
449 if (!isSearchable(field)) {
450 fail(`Field "${path}" is not searchable on search index "${index.name}"`)
451 }
452 }
453
454 if (query.search_options?.distinct) {
455 lookup(query.search_options.distinct, "search_options.distinct")
456 }
457
458 const vector = query.search_options?.vector
459 if (vector) {
460 if (!vector.field) {
461 const vectorFields = [...fieldMap.values()].filter(
462 ({ field }) => field.type === "vector"
463 )
464 fail(
465 vectorFields.length
466 ? `search_options.vector.field is required when the index has more than one vector field`
467 : `search_options.vector requires a vector field on search index "${index.name}"`
468 )
469 }
470
471 const field = lookup(vector.field, "search_options.vector.field")
472 if (field.type !== "vector") {
473 fail(
474 `Field "${vector.field}" is not a vector field on search index "${index.name}"`
475 )
476 }
477
478 if (vector.value && vector.query) {
479 fail(
480 `search_options.vector.value and search_options.vector.query are mutually exclusive`
481 )
482 }
483
484 if (!vector.value && !vector.query) {
485 fail(
486 `search_options.vector requires either "value" (embedding) or "query" (text to embed)`
487 )
488 }
489
490 if (vector.query && !field.embed) {
491 fail(
492 `search_options.vector.query requires vector field "${vector.field}" to declare "embed"`
493 )
494 }
495
496 if (
497 vector.value &&
498 field.dimensions &&
499 vector.value.length !== field.dimensions
500 ) {
501 fail(
502 `Vector value for "${vector.field}" expected ${field.dimensions} dimensions, got ${vector.value.length}`
503 )
504 }
505
506 if (
507 vector.semantic_ratio !== undefined &&
508 (vector.semantic_ratio < 0 || vector.semantic_ratio > 1)
509 ) {
510 fail("search_options.vector.semantic_ratio must be between 0 and 1")
511 }
512 }
513 }
514
515 /**
516 * Resolves every definition once, at construction. Duplicates and incoherent
517 * definitions fail here, so everything downstream can treat the result as given.
518 */
519 export function resolveIndexDefinitions({
520 definitions,
521 default_provider,
522 index_prefix,
523 }: {
524 definitions: SearchTypes.SearchIndexDefinition[]
525 default_provider: string
526 index_prefix?: string
527 }): SearchIndexes {
528 const resolved: SearchIndexes = new Map()
529
530 for (const definition of definitions) {
531 const primaryKey = definition.primary_key ?? "id"
532
533 if (!definition.name) {
534 throw new MedusaError(
535 MedusaError.Types.INVALID_DATA,
536 "A search index definition requires a name"
537 )
538 }
539
540 if (resolved.has(definition.name)) {
541 throw new MedusaError(
542 MedusaError.Types.INVALID_DATA,
543 `Duplicate search index definition for "${definition.name}"`
544 )
545 }
546
547 if (!definition.fields?.[primaryKey]) {
548 throw new MedusaError(
549 MedusaError.Types.INVALID_DATA,
550 `Search index "${definition.name}" must declare its primary key field "${primaryKey}"`
551 )
552 }
553
554 const physicalName = buildPhysicalIndexName({
555 name: definition.name,
556 prefix: index_prefix,
557 })
558
559 const entry: SearchTypes.ResolvedSearchIndexDefinition = {
560 ...definition,
561 primary_key: primaryKey,
562 provider: definition.provider ?? default_provider,
563 settings: definition.settings ?? {},
564 definition_hash: buildDefinitionHash({
565 fields: definition.fields,
566 settings: definition.settings,
567 primary_key: primaryKey,
568 physical_name: physicalName,
569 }),
570 physical_name: physicalName,
571 }
572
573 validateIndexDefinition({ definition: entry })
574
575 resolved.set(entry.name, entry)
576 }
577
578 return resolved
579 }
580
581 /**
582 * Checks a definition is internally coherent regardless of provider — a field
583 * asking for something that makes no sense for its type. Whether a *particular*
584 * provider can serve it is settled in `upsertIndex`, which runs for every
585 * definition at startup, so it still fails at boot but with a better error.
586 */
587 function validateIndexDefinition({
588 definition,
589 }: {
590 definition: SearchTypes.ResolvedSearchIndexDefinition
591 }): void {
592 function fail(message: string): never {
593 throw new MedusaError(
594 MedusaError.Types.INVALID_DATA,
595 `Invalid search index definition "${definition.name}": ${message}`
596 )
597 }
598
599 const hasEvents = !!definition.events?.length
600 const hasConsume = !!definition.consume
601
602 if (hasEvents && !hasConsume) {
603 fail(`declares "events" but no "consume" to turn them into documents`)
604 }
605
606 if (hasConsume && !hasEvents) {
607 fail(`declares "consume" but no "events" for it to be called on`)
608 }
609
610 for (const { path, field } of flattenFields(definition.fields)) {
611 if (field.type === "vector" && !field.dimensions) {
612 fail(`vector field "${path}" must declare its "dimensions"`)
613 }
614
615 if (field.type === "vector" && field.array) {
616 fail(`vector field "${path}" cannot be an array`)
617 }
618
619 if (typeof (field.embed as unknown) === "string") {
620 fail(
621 `vector field "${path}" "embed" must be true; pass the text on this field rather than naming a source`
622 )
623 }
624
625 if (field.embed) {
626 if (field.type !== "vector") {
627 fail(
628 `field "${path}" sets "embed", which only applies to vector fields`
629 )
630 }
631 }
632
633 if (field.type === "object" && !field.fields) {
634 fail(`object field "${path}" must declare its "fields"`)
635 }
636
637 const numeric = ["integer", "float", "date"].includes(field.type)
638
639 if (isFacetable(field, "range") && !numeric) {
640 fail(`field "${path}" is not numeric, so it cannot have range facets`)
641 }
642
643 if (isFacetable(field, "stats") && !numeric) {
644 fail(`field "${path}" is not numeric, so it cannot have stats facets`)
645 }
646
647 if (isSearchable(field) && !["text", "keyword"].includes(field.type)) {
648 fail(
649 `field "${path}" is of type "${field.type}", which cannot be searched as free text`
650 )
651 }
652 }
653 }
654
655 /** Every version of every listed index, grouped by the index's id, newest first. */
656 export async function listVersionsByIndexId(
657 context: Pick<SearchIndexContext, "versionService">,
658 indexIds: string[]
659 ): Promise<Map<string, SearchIndexVersionRecord[]>> {
660 const byId = new Map<string, SearchIndexVersionRecord[]>()
661
662 if (!indexIds.length) {
663 return byId
664 }
665
666 const versions = (await context.versionService.list(
667 { search_index_id: indexIds },
668 { order: { version: "DESC" }, take: null }
669 )) as SearchIndexVersionRecord[]
670
671 for (const version of versions) {
672 const list = byId.get(version.search_index_id) ?? []
673 list.push(version)
674 byId.set(version.search_index_id, list)
675 }
676
677 return byId
678 }
679
680 /**
681 * The definition merged with whichever physical index and provider currently
682 * serve reads/writes. Every *live* operation (a direct write, an event
683 * ingested, a query) must resolve through this rather than
684 * `definition.physical_name` directly — that field is only the root a
685 * version's name is derived from, and which version is active can change out
686 * from under this process.
687 */
688 export async function resolveActiveDefinition(
689 context: Pick<SearchIndexContext, "indexes" | "activeVersionCache">,
690 name: string,
691 { fresh = false }: { fresh?: boolean } = {}
692 ): Promise<SearchTypes.ResolvedSearchIndexDefinition> {
693 const definition = retrieveIndexDefinition(context.indexes, name)
694
695 if (!context.activeVersionCache) {
696 return definition
697 }
698
699 const active = await context.activeVersionCache.get(name, { fresh })
700
701 return {
702 ...definition,
703 physical_name: active.physical_name,
704 provider: active.provider,
705 }
706 }
707
708 /**
709 * Runs an operation against whichever version is active, and gives it a second
710 * go on a `NOT_FOUND` with the cache invalidated first.
711 */
712 export async function withActiveIndexRetry<T>(
713 context: Pick<SearchIndexContext, "activeVersionCache">,
714 run: () => Promise<T>
715 ): Promise<T> {
716 try {
717 return await run()
718 } catch (error) {
719 if (
720 !context.activeVersionCache ||
721 !(error instanceof MedusaError) ||
722 error.type !== MedusaError.Types.NOT_FOUND
723 ) {
724 throw error
725 }
726
727 await context.activeVersionCache.invalidate()
728
729 return await run()
730 }
731 }
732
733 export function retrieveIndexDefinition(
734 indexes: SearchIndexes,
735 name: string
736 ): SearchTypes.ResolvedSearchIndexDefinition {
737 const definition = indexes.get(name)
738
739 if (!definition) {
740 throw new MedusaError(
741 MedusaError.Types.NOT_FOUND,
742 `No search index registered for "${name}". Registered indexes: ${
743 [...indexes.keys()].join(", ") || "(none)"
744 }`
745 )
746 }
747
748 return definition
749 }
750
751 export function assertTaskAccepted(
752 task: SearchTypes.SearchTask,
753 index: string
754 ): SearchTypes.SearchTask {
755 if (task.status === "failed") {
756 throw new MedusaError(
757 MedusaError.Types.UNEXPECTED_STATE,
758 `Search write failed on index "${index}": ${
759 task.error?.message ?? "unknown error"
760 }`
761 )
762 }
763
764 return task
765 }