|
1
|
import { |
|
2
|
Event, |
|
3
|
IEventBusModuleService, |
|
4
|
InternalModuleDeclaration, |
|
5
|
Logger, |
|
6
|
ModuleJoinerConfig, |
|
7
|
ModulesSdkTypes, |
|
8
|
RemoteQueryFunction, |
|
9
|
SearchTypes, |
|
10
|
} from "@medusajs/framework/types" |
|
11
|
import { |
|
12
|
ContainerRegistrationKeys, |
|
13
|
MedusaError, |
|
14
|
MedusaService, |
|
15
|
Modules, |
|
16
|
promiseAll, |
|
17
|
} from "@medusajs/framework/utils" |
|
18
|
import { |
|
19
|
SearchEventRoutes, |
|
20
|
SearchIndexContext, |
|
21
|
SearchIndexes, |
|
22
|
SearchIndexRecord, |
|
23
|
SearchIndexSeedAction, |
|
24
|
SearchModuleOptions, |
|
25
|
} from "@types" |
|
26
|
import { |
|
27
|
assertTaskAccepted, |
|
28
|
buildDisjunctiveFacetQueries, |
|
29
|
listIndexedFields, |
|
30
|
listRetrievablePaths, |
|
31
|
listVersionsByIndexId, |
|
32
|
mergeDisjunctiveFacetResults, |
|
33
|
normalizeSearchQuery, |
|
34
|
resolveActiveDefinition, |
|
35
|
withActiveIndexRetry, |
|
36
|
resolveIndexDefinitions, |
|
37
|
retrieveIndexDefinition, |
|
38
|
SearchIndexState, |
|
39
|
validateFieldUsage, |
|
40
|
} from "@utils" |
|
41
|
import { |
|
42
|
ActiveIndexVersion, |
|
43
|
ActiveIndexVersionCache, |
|
44
|
} from "../utils/active-version-cache" |
|
45
|
import { deleteIndexEntirely } from "../utils/deletion" |
|
46
|
import { buildEventRoutes, ingestEvent } from "../utils/ingestion" |
|
47
|
import { |
|
48
|
createIndexMigrationPlan, |
|
49
|
executeIndexMigrationPlan, |
|
50
|
} from "../utils/migrations" |
|
51
|
import { |
|
52
|
createSeedPlan, |
|
53
|
executeSeedPlan, |
|
54
|
reindexIndexes, |
|
55
|
} from "../utils/seeding" |
|
56
|
import { joinerConfig } from "../joiner-config" |
|
57
|
import { SearchProviderService } from "./search-provider" |
|
58
|
|
|
59
|
type InjectedDependencies = { |
|
60
|
logger: Logger |
|
61
|
[Modules.EVENT_BUS]: IEventBusModuleService |
|
62
|
[ContainerRegistrationKeys.QUERY]: RemoteQueryFunction |
|
63
|
searchProviderService: SearchProviderService |
|
64
|
searchIndexService: ModulesSdkTypes.IMedusaInternalService<any> |
|
65
|
searchIndexVersionService: ModulesSdkTypes.IMedusaInternalService<any> |
|
66
|
searchIndexSyncService: ModulesSdkTypes.IMedusaInternalService<any> |
|
67
|
} |
|
68
|
|
|
69
|
export default class SearchModuleService |
|
70
|
// Deliberately no models: `SearchIndex` and `SearchIndexSync` are the module's |
|
71
|
// own bookkeeping, so they get no generated CRUD and are not linkable. They are |
|
72
|
// still discovered from `src/models` for migrations. |
|
73
|
extends MedusaService({}) |
|
74
|
implements SearchTypes.ISearchModuleService |
|
75
|
{ |
|
76
|
protected isWorkerMode: boolean = true |
|
77
|
|
|
78
|
protected readonly logger_: Logger |
|
79
|
protected readonly searchProviderService_: SearchProviderService |
|
80
|
|
|
81
|
protected readonly moduleOptions_: SearchModuleOptions |
|
82
|
|
|
83
|
// Definitions keyed by name, resolved once in the constructor. Nothing registers |
|
84
|
// an index at runtime, which is what lets a `definition_hash` change count as a |
|
85
|
// migration rather than a race. |
|
86
|
protected readonly indexes_: SearchIndexes |
|
87
|
|
|
88
|
// Which physical index currently serves reads for each logical index. A |
|
89
|
// cache rather than a value resolved once, because — unlike `indexes_` — it |
|
90
|
// can change out from under this process when another replica finishes |
|
91
|
// seeding and flips it. |
|
92
|
protected readonly activeVersionCache_: ActiveIndexVersionCache |
|
93
|
|
|
94
|
// Passed down for migrations and seeding, among other things. |
|
95
|
protected readonly context_: SearchIndexContext |
|
96
|
|
|
97
|
// Built with the definitions, so routing a delivered event costs a lookup. |
|
98
|
protected readonly eventRoutes_: SearchEventRoutes |
|
99
|
|
|
100
|
constructor( |
|
101
|
container: InjectedDependencies, |
|
102
|
moduleOptions: SearchModuleOptions, |
|
103
|
protected readonly moduleDeclaration: InternalModuleDeclaration |
|
104
|
) { |
|
105
|
// @ts-ignore |
|
106
|
super(...arguments) |
|
107
|
|
|
108
|
this.logger_ = container.logger ?? (console as unknown as Logger) |
|
109
|
this.searchProviderService_ = container.searchProviderService |
|
110
|
|
|
111
|
this.moduleOptions_ = (moduleOptions ?? |
|
112
|
moduleDeclaration.options ?? |
|
113
|
{}) as SearchModuleOptions |
|
114
|
|
|
115
|
// `worker_mode` is stamped onto every module's declaration by the |
|
116
|
// modules-sdk from the application's own `projectConfig.workerMode`, so this |
|
117
|
// reads the same value `configModule` would give — an HTTP-only process |
|
118
|
// must not spend its boot seeding indexes. |
|
119
|
this.isWorkerMode = moduleDeclaration.worker_mode !== "server" |
|
120
|
|
|
121
|
// Resolved here rather than on application start, so anything that resolves the |
|
122
|
// module — `db:migrate` included — sees the definitions without booting first. |
|
123
|
this.indexes_ = this.moduleOptions_.indexes?.length |
|
124
|
? resolveIndexDefinitions({ |
|
125
|
definitions: this.moduleOptions_.indexes, |
|
126
|
default_provider: |
|
127
|
container.searchProviderService.getDefaultIdentifier( |
|
128
|
this.moduleOptions_.default_provider |
|
129
|
), |
|
130
|
index_prefix: this.moduleOptions_.index_prefix, |
|
131
|
}) |
|
132
|
: new Map() |
|
133
|
|
|
134
|
this.eventRoutes_ = buildEventRoutes(this.indexes_) |
|
135
|
|
|
136
|
this.activeVersionCache_ = new ActiveIndexVersionCache(() => |
|
137
|
this.fetchActiveVersions_(container) |
|
138
|
) |
|
139
|
|
|
140
|
this.context_ = { |
|
141
|
container: { |
|
142
|
get query() { |
|
143
|
return container[ContainerRegistrationKeys.QUERY] |
|
144
|
}, |
|
145
|
logger: this.logger_, |
|
146
|
}, |
|
147
|
logger: this.logger_, |
|
148
|
options: this.moduleOptions_, |
|
149
|
indexes: this.indexes_, |
|
150
|
providers: container.searchProviderService, |
|
151
|
indexService: container.searchIndexService, |
|
152
|
versionService: container.searchIndexVersionService, |
|
153
|
syncService: container.searchIndexSyncService, |
|
154
|
locking: resolveLocking(container), |
|
155
|
activeVersionCache: this.activeVersionCache_, |
|
156
|
} |
|
157
|
} |
|
158
|
|
|
159
|
// Reads the DB directly, for every index at once — there are never many |
|
160
|
// search indexes in an app, so listing them all is cheap, and it lets one |
|
161
|
// refresh (triggered by any index) serve every index. Called by |
|
162
|
// `activeVersionCache_` on a cache miss or refresh — never on the request |
|
163
|
// path itself. |
|
164
|
protected async fetchActiveVersions_( |
|
165
|
container: InjectedDependencies |
|
166
|
): Promise<Map<string, ActiveIndexVersion>> { |
|
167
|
const records = (await container.searchIndexService.list( |
|
168
|
{}, |
|
169
|
{ take: null } |
|
170
|
)) as SearchIndexRecord[] |
|
171
|
|
|
172
|
const versionsByIndexId = await listVersionsByIndexId( |
|
173
|
{ versionService: container.searchIndexVersionService }, |
|
174
|
records.map((record) => record.id) |
|
175
|
) |
|
176
|
|
|
177
|
const values = new Map<string, ActiveIndexVersion>() |
|
178
|
|
|
179
|
for (const record of records) { |
|
180
|
if (record.active_version == null) { |
|
181
|
continue |
|
182
|
} |
|
183
|
|
|
184
|
const version = versionsByIndexId |
|
185
|
.get(record.id) |
|
186
|
?.find((candidate) => candidate.version === record.active_version) |
|
187
|
|
|
188
|
if (version) { |
|
189
|
values.set(record.name, { |
|
190
|
physical_name: version.physical_name, |
|
191
|
provider: version.provider, |
|
192
|
version: version.version, |
|
193
|
}) |
|
194
|
} |
|
195
|
} |
|
196
|
|
|
197
|
return values |
|
198
|
} |
|
199
|
|
|
200
|
// Merges in the physical index and provider currently serving reads. Every |
|
201
|
// *live* read or write goes through this rather than `definition.physical_name` |
|
202
|
// directly, since the active version can change out from under this process. |
|
203
|
// Shared with the ingestion path (`resolveActiveDefinition` in `@utils`) so |
|
204
|
// the two can't drift apart. |
|
205
|
protected async resolveActiveDefinition_( |
|
206
|
name: string, |
|
207
|
options: { fresh?: boolean } = {} |
|
208
|
): Promise<SearchTypes.ResolvedSearchIndexDefinition> { |
|
209
|
return await resolveActiveDefinition(this.context_, name, options) |
|
210
|
} |
|
211
|
|
|
212
|
// Declared so that `Module()` does not derive one by scanning `src/models`, |
|
213
|
// which would make the module's bookkeeping linkable. |
|
214
|
__joinerConfig(): ModuleJoinerConfig { |
|
215
|
return joinerConfig |
|
216
|
} |
|
217
|
|
|
218
|
__hooks = { |
|
219
|
onApplicationStart: async () => { |
|
220
|
// Seeding can take a long time on a large catalog and must not delay the |
|
221
|
// worker from accepting jobs. Failures are logged rather than blocking boot. |
|
222
|
void this.onApplicationStart_().catch((error) => { |
|
223
|
this.logger_.error( |
|
224
|
`[Search] Failed to seed search indexes: ${error.message}`, |
|
225
|
error |
|
226
|
) |
|
227
|
}) |
|
228
|
}, |
|
229
|
} |
|
230
|
|
|
231
|
async search<T = Record<string, unknown>>( |
|
232
|
query: SearchTypes.SearchQuery |
|
233
|
): Promise<SearchTypes.SearchResult<T>> { |
|
234
|
const [result] = await this.searchMany([query]) |
|
235
|
return result as SearchTypes.SearchResult<T> |
|
236
|
} |
|
237
|
|
|
238
|
async searchMany( |
|
239
|
queries: SearchTypes.SearchQuery[] |
|
240
|
): Promise<SearchTypes.SearchResult[]> { |
|
241
|
if (!queries.length) { |
|
242
|
return [] |
|
243
|
} |
|
244
|
|
|
245
|
// Reads take the cached version, so this one can be pointed at a version |
|
246
|
// that has since been dropped. That surfaces as a `NOT_FOUND` from the |
|
247
|
// engine, and the retry resolves it again rather than failing the search. |
|
248
|
return await withActiveIndexRetry(this.context_, () => |
|
249
|
this.searchMany_(queries) |
|
250
|
) |
|
251
|
} |
|
252
|
|
|
253
|
protected async searchMany_( |
|
254
|
queries: SearchTypes.SearchQuery[] |
|
255
|
): Promise<SearchTypes.SearchResult[]> { |
|
256
|
const prepared = await promiseAll( |
|
257
|
queries.map(async (query) => { |
|
258
|
const index = await this.resolveActiveDefinition_(query.entity) |
|
259
|
const normalized = normalizeSearchQuery({ query, index }) |
|
260
|
const provider = this.searchProviderService_.retrieve(index.provider) |
|
261
|
|
|
262
|
// Whether the *provider* can serve the query is the provider's call, made |
|
263
|
// while it translates. This only checks the query against the definition, |
|
264
|
// which is provider-independent. |
|
265
|
validateFieldUsage({ index, query: normalized }) |
|
266
|
|
|
267
|
return { normalized, provider } |
|
268
|
}) |
|
269
|
) |
|
270
|
|
|
271
|
// Expand disjunctive facets into extra queries, then send the whole set to |
|
272
|
// `provider.searchMany` so the engine can pack them into one round-trip. |
|
273
|
type FlatQuery = { |
|
274
|
provider: SearchTypes.ISearchProvider |
|
275
|
query: SearchTypes.ProviderSearchQuery |
|
276
|
originalIndex: number |
|
277
|
facetField?: string |
|
278
|
} |
|
279
|
|
|
280
|
const flattened: FlatQuery[] = [] |
|
281
|
|
|
282
|
prepared.forEach(({ normalized, provider }, originalIndex) => { |
|
283
|
if (!normalized.search_options?.disjunctive_facets) { |
|
284
|
flattened.push({ provider, query: normalized, originalIndex }) |
|
285
|
return |
|
286
|
} |
|
287
|
|
|
288
|
const { base, per_facet } = buildDisjunctiveFacetQueries(normalized) |
|
289
|
flattened.push({ provider, query: base, originalIndex }) |
|
290
|
|
|
291
|
for (const [field, facetQuery] of per_facet) { |
|
292
|
flattened.push({ |
|
293
|
provider, |
|
294
|
query: facetQuery, |
|
295
|
originalIndex, |
|
296
|
facetField: field, |
|
297
|
}) |
|
298
|
} |
|
299
|
}) |
|
300
|
|
|
301
|
const groups = new Map< |
|
302
|
SearchTypes.ISearchProvider, |
|
303
|
{ item: FlatQuery; flatIndex: number }[] |
|
304
|
>() |
|
305
|
|
|
306
|
flattened.forEach((item, flatIndex) => { |
|
307
|
const group = groups.get(item.provider) |
|
308
|
if (group) { |
|
309
|
group.push({ item, flatIndex }) |
|
310
|
return |
|
311
|
} |
|
312
|
groups.set(item.provider, [{ item, flatIndex }]) |
|
313
|
}) |
|
314
|
|
|
315
|
const flatResults: SearchTypes.SearchResult[] = new Array(flattened.length) |
|
316
|
|
|
317
|
await promiseAll( |
|
318
|
[...groups].map(async ([provider, group]) => { |
|
319
|
const inputs = group.map(({ item }) => item.query) |
|
320
|
const results = provider.searchMany |
|
321
|
? await provider.searchMany(inputs) |
|
322
|
: await promiseAll(inputs.map((input) => provider.search(input))) |
|
323
|
|
|
324
|
group.forEach(({ flatIndex }, i) => { |
|
325
|
flatResults[flatIndex] = results[i] |
|
326
|
}) |
|
327
|
}) |
|
328
|
) |
|
329
|
|
|
330
|
const results: SearchTypes.SearchResult[] = new Array(queries.length) |
|
331
|
const pendingFacets = new Map< |
|
332
|
number, |
|
333
|
Map<string, SearchTypes.SearchResult> |
|
334
|
>() |
|
335
|
|
|
336
|
flattened.forEach((item, flatIndex) => { |
|
337
|
if (!item.facetField) { |
|
338
|
results[item.originalIndex] = flatResults[flatIndex] |
|
339
|
return |
|
340
|
} |
|
341
|
|
|
342
|
const perFacet = pendingFacets.get(item.originalIndex) ?? new Map() |
|
343
|
perFacet.set(item.facetField, flatResults[flatIndex]) |
|
344
|
pendingFacets.set(item.originalIndex, perFacet) |
|
345
|
}) |
|
346
|
|
|
347
|
for (const [index, perFacet] of pendingFacets) { |
|
348
|
results[index] = mergeDisjunctiveFacetResults({ |
|
349
|
base: results[index], |
|
350
|
per_facet: perFacet, |
|
351
|
}) |
|
352
|
} |
|
353
|
|
|
354
|
return results |
|
355
|
} |
|
356
|
|
|
357
|
async upsertDocuments({ |
|
358
|
index, |
|
359
|
documents, |
|
360
|
}: { |
|
361
|
index: string |
|
362
|
documents: SearchTypes.SearchDocument[] |
|
363
|
}): Promise<SearchTypes.SearchTask> { |
|
364
|
if (!documents.length) { |
|
365
|
return { index, status: "succeeded" } |
|
366
|
} |
|
367
|
|
|
368
|
return await withActiveIndexRetry(this.context_, async () => { |
|
369
|
const definition = await this.resolveActiveDefinition_(index, { |
|
370
|
fresh: true, |
|
371
|
}) |
|
372
|
const provider = this.searchProviderService_.retrieve(definition.provider) |
|
373
|
|
|
374
|
const task = await provider.upsertDocuments({ |
|
375
|
index: definition.physical_name, |
|
376
|
definition, |
|
377
|
documents, |
|
378
|
}) |
|
379
|
|
|
380
|
return assertTaskAccepted(task, index) |
|
381
|
}) |
|
382
|
} |
|
383
|
|
|
384
|
async deleteDocuments({ |
|
385
|
index, |
|
386
|
filters, |
|
387
|
}: { |
|
388
|
index: string |
|
389
|
filters: SearchTypes.SearchFilters |
|
390
|
}): Promise<SearchTypes.SearchTask> { |
|
391
|
if (!filters || !Object.keys(filters).length) { |
|
392
|
throw new MedusaError( |
|
393
|
MedusaError.Types.INVALID_DATA, |
|
394
|
`Deleting from search index "${index}" requires filters; pass { id: [...] } to delete by id, or clear the index through a reindex` |
|
395
|
) |
|
396
|
} |
|
397
|
|
|
398
|
return await withActiveIndexRetry(this.context_, async () => { |
|
399
|
const definition = await this.resolveActiveDefinition_(index, { |
|
400
|
fresh: true, |
|
401
|
}) |
|
402
|
const provider = this.searchProviderService_.retrieve(definition.provider) |
|
403
|
|
|
404
|
const task = await provider.deleteDocuments({ |
|
405
|
index: definition.physical_name, |
|
406
|
filters, |
|
407
|
}) |
|
408
|
|
|
409
|
return assertTaskAccepted(task, index) |
|
410
|
}) |
|
411
|
} |
|
412
|
|
|
413
|
// Waits for its writes, so awaiting this acknowledges the event. |
|
414
|
async ingest(event: Event<any>): Promise<SearchTypes.SearchTask[]> { |
|
415
|
return await ingestEvent(this.context_, { |
|
416
|
event, |
|
417
|
routes: this.eventRoutes_, |
|
418
|
}) |
|
419
|
} |
|
420
|
|
|
421
|
async listIndexes(): Promise<SearchTypes.SearchIndexDetails[]> { |
|
422
|
const definitions = [...this.indexes_.values()].sort((a, b) => |
|
423
|
a.name.localeCompare(b.name) |
|
424
|
) |
|
425
|
|
|
426
|
if (!definitions.length) { |
|
427
|
return [] |
|
428
|
} |
|
429
|
|
|
430
|
const records = (await this.context_.indexService.list( |
|
431
|
{ name: definitions.map((definition) => definition.name) }, |
|
432
|
{ take: null } |
|
433
|
)) as SearchIndexRecord[] |
|
434
|
const byName = new Map(records.map((record) => [record.name, record])) |
|
435
|
const versionsByIndexId = await listVersionsByIndexId( |
|
436
|
this.context_, |
|
437
|
records.map((record) => record.id) |
|
438
|
) |
|
439
|
|
|
440
|
return definitions.map((definition) => { |
|
441
|
const record = byName.get(definition.name) |
|
442
|
const versions = record ? versionsByIndexId.get(record.id) ?? [] : [] |
|
443
|
const activeVersion = |
|
444
|
record?.active_version != null |
|
445
|
? versions.find( |
|
446
|
(version) => version.version === record.active_version |
|
447
|
) |
|
448
|
: undefined |
|
449
|
|
|
450
|
return { |
|
451
|
name: definition.name, |
|
452
|
entity: definition.entity, |
|
453
|
provider: activeVersion?.provider ?? definition.provider, |
|
454
|
status: (activeVersion?.status ?? |
|
455
|
SearchIndexState.PENDING) as SearchTypes.SearchIndexStatus, |
|
456
|
fields: listIndexedFields(definition.fields), |
|
457
|
} |
|
458
|
}) |
|
459
|
} |
|
460
|
|
|
461
|
listRetrievableFields(index: string): string[] { |
|
462
|
return listRetrievablePaths( |
|
463
|
retrieveIndexDefinition(this.indexes_, index).fields |
|
464
|
) |
|
465
|
} |
|
466
|
|
|
467
|
getIndex(index: string): SearchTypes.ResolvedSearchIndexDefinition { |
|
468
|
return retrieveIndexDefinition(this.indexes_, index) |
|
469
|
} |
|
470
|
|
|
471
|
async reindex( |
|
472
|
input: SearchTypes.SearchReindexInput = {} |
|
473
|
): Promise<SearchTypes.SearchReindexResult> { |
|
474
|
return await reindexIndexes(this.context_, input) |
|
475
|
} |
|
476
|
|
|
477
|
async deleteIndex( |
|
478
|
index: string |
|
479
|
): Promise<SearchTypes.SearchIndexDeleteResult> { |
|
480
|
return await deleteIndexEntirely(this.context_, index) |
|
481
|
} |
|
482
|
|
|
483
|
/** |
|
484
|
* Seeds whatever needs data. Indexes that are not migrated yet are skipped — |
|
485
|
* creating and migrating physical indexes is the application's job |
|
486
|
* (e.g. `db:migrate`), not something a booting worker invents. |
|
487
|
*/ |
|
488
|
protected async onApplicationStart_(): Promise<void> { |
|
489
|
if (!this.indexes_.size || !this.isWorkerMode) { |
|
490
|
return |
|
491
|
} |
|
492
|
|
|
493
|
const seeds = await this.createSeedPlan_() |
|
494
|
|
|
495
|
if (!seeds.length) { |
|
496
|
return |
|
497
|
} |
|
498
|
|
|
499
|
this.logger_.info( |
|
500
|
`[Search] Seeding ${seeds.length} index(es): ${seeds |
|
501
|
.map((seed) => `${seed.index} (${seed.reason})`) |
|
502
|
.join(", ")}` |
|
503
|
) |
|
504
|
|
|
505
|
await this.executeSeedPlan_(seeds) |
|
506
|
} |
|
507
|
|
|
508
|
protected async createSeedPlan_(): Promise<SearchIndexSeedAction[]> { |
|
509
|
return await createSeedPlan(this.context_) |
|
510
|
} |
|
511
|
|
|
512
|
protected async executeSeedPlan_( |
|
513
|
actions: SearchIndexSeedAction[] |
|
514
|
): Promise<void> { |
|
515
|
await executeSeedPlan(this.context_, actions) |
|
516
|
} |
|
517
|
|
|
518
|
async createIndexMigrationPlan(): Promise< |
|
519
|
SearchTypes.SearchIndexMigrationAction[] |
|
520
|
> { |
|
521
|
return await createIndexMigrationPlan(this.context_) |
|
522
|
} |
|
523
|
|
|
524
|
async executeIndexMigrationPlan( |
|
525
|
actions: SearchTypes.SearchIndexMigrationAction[] |
|
526
|
): Promise<void> { |
|
527
|
await executeIndexMigrationPlan(this.context_, actions) |
|
528
|
} |
|
529
|
} |
|
530
|
|
|
531
|
// The Locking Module is optional, and reading a missing registration off the |
|
532
|
// container throws rather than returning undefined. |
|
533
|
function resolveLocking( |
|
534
|
container: InjectedDependencies |
|
535
|
): SearchIndexContext["locking"] { |
|
536
|
try { |
|
537
|
return container[Modules.LOCKING] |
|
538
|
} catch { |
|
539
|
return undefined |
|
540
|
} |
|
541
|
} |