1 import { QueryContextType, SearchTypes } from "@medusajs/types"
2
3 /**
4 * `seed` and `consume` implementations backed by `query.graph`.
5 *
6 * Nearly every index is a projection of an entity that already lives behind
7 * `query.graph`, so the helpers simplify catchup, soft-deletes and similar,
8 * which should be enough for most use cases.
9 */
10
11 type GraphRow = Record<string, any>
12
13 // The timestamps every Medusa entity carries, which the catch-up pass reads.
14 const UPDATED_AT_FIELD = "updated_at"
15 const DELETED_AT_FIELD = "deleted_at"
16
17 export type SearchConsumeEvent = Parameters<
18 NonNullable<SearchTypes.SearchIndexDefinition["consume"]>
19 >[0]
20
21 export type SearchGraphQueryContext =
22 | QueryContextType
23 | ((context: SearchTypes.SearchIngestionContext) => QueryContextType)
24
25 export interface SearchGraphSourceOptions<
26 Fields extends SearchTypes.SearchIndexFieldsInput,
27 TRow extends GraphRow = GraphRow
28 > {
29 /**
30 * The `query.graph` entrypoint to read from. Defaults to the index
31 * definition's `entity`.
32 */
33 entity?: string
34
35 /**
36 * The fields to select from `query.graph`. Without a `transform` the row is
37 * indexed as-is, so this should then select exactly what the index declares.
38 */
39 fields: string[]
40
41 /**
42 * The query context `query.graph` reads the rows with, e.g. the pricing
43 * context `variants.calculated_price` needs. Applied to seed, catch-up and
44 * `consume` alike.
45 */
46 context?: SearchGraphQueryContext
47
48 /**
49 * Maps a page of rows to the documents to index, e.g. `rows.map(toDocument)`.
50 * Async, and handed the whole page, so reads `query.graph` cannot make in
51 * one pass — prices in several currencies, say — cost a fixed number of
52 * queries per page. Every document must carry the row's primary key value
53 * as `id`; a row with no document is excluded, which `consume` and the
54 * catch-up pass turn into a delete so it leaves the index rather than
55 * going stale in it.
56 *
57 * Defaults to indexing the rows as-is.
58 */
59 transform?: (
60 rows: TRow[],
61 context: SearchTypes.SearchIngestionContext
62 ) =>
63 | SearchTypes.InferSearchDocumentType<Fields>[]
64 | Promise<SearchTypes.InferSearchDocumentType<Fields>[]>
65 }
66
67 export interface SearchGraphSeedOptions<
68 Fields extends SearchTypes.SearchIndexFieldsInput,
69 TRow extends GraphRow = GraphRow
70 > extends SearchGraphSourceOptions<Fields, TRow> {
71 /**
72 * The number of rows read from `query.graph` per page.
73 *
74 * @default 200
75 */
76 batch_size?: number
77 }
78
79 export interface SearchGraphConsumeOptions<
80 Fields extends SearchTypes.SearchIndexFieldsInput,
81 TRow extends GraphRow = GraphRow
82 > extends SearchGraphSourceOptions<Fields, TRow> {
83 /**
84 * The IDs of the documents the event affects, which are read back through
85 * `query.graph` and written to the index. May be async, e.g. to map an
86 * event about a variant or a category to the products it belongs to.
87 *
88 * Defaults to `event.data.id`, as a single ID or an array of them.
89 */
90 resolve_ids?: (
91 event: SearchConsumeEvent,
92 context: SearchTypes.SearchIngestionContext
93 ) => string[] | string | undefined | Promise<string[] | string | undefined>
94
95 /**
96 * Whether the event removes its documents from the index rather than
97 * updating them. A deleted row can't be read back, so it's deleted by ID
98 * without going to `query.graph`.
99 *
100 * @default an event whose name ends in `.deleted`
101 */
102 is_delete?: (event: SearchConsumeEvent) => boolean
103 }
104
105 function toArray(value: unknown): string[] {
106 if (value === null || value === undefined) {
107 return []
108 }
109 return (Array.isArray(value) ? value : [value]).map((entry) => String(entry))
110 }
111
112 /**
113 * The reindex filters, narrowed by the catch-up window and the paging cursor.
114 *
115 * Those two go under `$and` rather than beside the caller's filters: they are
116 * keyed on `updated_at` and on the primary key, so overwriting would quietly
117 * widen a `reindex({ filters: { id: [...] } })` into a full scan from the
118 * cursor once it pages.
119 */
120 function seedFilters(
121 filters: Record<string, any> | undefined,
122 constraints: Record<string, any>[]
123 ): Record<string, any> {
124 if (!constraints.length) {
125 return filters ?? {}
126 }
127
128 if (!filters || !Object.keys(filters).length) {
129 return Object.assign({}, ...constraints)
130 }
131
132 const existing = Array.isArray(filters.$and) ? filters.$and : []
133 return { ...filters, $and: [...existing, ...constraints] }
134 }
135
136 function withFields(fields: string[], ...extra: string[]): string[] {
137 const missing = extra.filter((field) => !fields.includes(field))
138 return missing.length ? [...fields, ...missing] : fields
139 }
140
141 /**
142 * The documents for a page of rows, and the keys they were produced for. A
143 * key with no document is what the callers delete.
144 */
145 async function toDocuments<
146 Fields extends SearchTypes.SearchIndexFieldsInput,
147 TRow extends GraphRow
148 >(
149 rows: TRow[],
150 options: SearchGraphSourceOptions<Fields, TRow>,
151 context: SearchTypes.SearchIngestionContext
152 ): Promise<{
153 documents: SearchTypes.InferSearchDocumentType<Fields>[]
154 produced: Set<string>
155 }> {
156 if (!options.transform) {
157 const documents =
158 rows as unknown as SearchTypes.InferSearchDocumentType<Fields>[]
159 return {
160 documents,
161 produced: new Set(
162 rows.map((row) => String(row[context.index.primary_key]))
163 ),
164 }
165 }
166
167 const documents = await options.transform(rows, context)
168 const produced = new Set<string>()
169
170 for (const document of documents) {
171 if (document.id === undefined || document.id === null) {
172 throw new Error(
173 `Search index "${context.index.name}": transform returned a document without an "id"`
174 )
175 }
176 produced.add(String(document.id))
177 }
178
179 return { documents, produced }
180 }
181
182 function queryContext(
183 option: SearchGraphQueryContext | undefined,
184 context: SearchTypes.SearchIngestionContext
185 ): { context: QueryContextType } | {} {
186 const resolved = typeof option === "function" ? option(context) : option
187 return resolved ? { context: resolved } : {}
188 }
189
190 /**
191 * Builds an index definition's `seed` from a `query.graph` query.
192 *
193 * The seed pages the entity in ascending order of the index' primary key, so
194 * the next page starts after the last row and a run interrupted halfway
195 * resumes from the context's `last_key` rather than restarting. The catch-up
196 * pass that follows a full seed reads the rows touched since it started with
197 * soft-deleted ones included, and turns those — along with any row the
198 * `transform` rejects — into deletes.
199 *
200 * @example
201 * const productFields = search.define({
202 * id: search.keyword().filterable(),
203 * title: search.text().searchable(),
204 * })
205 *
206 * export default defineSearchIndex({
207 * name: "product",
208 * entity: "product",
209 * fields: productFields,
210 * seed: graphSeed({ fields: ["id", "title"] }),
211 * })
212 */
213 export function graphSeed<
214 Fields extends SearchTypes.SearchIndexFieldsInput,
215 TRow extends GraphRow = GraphRow
216 >(
217 options: SearchGraphSeedOptions<Fields, TRow>
218 ): NonNullable<SearchTypes.SearchIndexDefinitionInput<Fields>["seed"]> {
219 const { fields, batch_size: batchSize = 200 } = options
220
221 return async function* graphSeedGenerator(context) {
222 const { container, index, catchup, last_key: lastKey } = context
223
224 const entity = options.entity ?? index.entity
225 const primaryKey = index.primary_key
226
227 // The key pages the rows and identifies them in a delete, and the
228 // soft-delete marker decides which is which — both have to be readable off
229 // the rows, whether or not the index itself holds them.
230 const selection = catchup
231 ? withFields(fields, primaryKey, DELETED_AT_FIELD)
232 : withFields(fields, primaryKey)
233
234 let cursor: string | undefined = lastKey
235
236 while (true) {
237 const { data } = (await container.query.graph({
238 entity,
239 fields: selection,
240 filters: seedFilters(context.filters, [
241 ...(catchup ? [{ [UPDATED_AT_FIELD]: { $gte: catchup.since } }] : []),
242 ...(cursor !== undefined ? [{ [primaryKey]: { $gt: cursor } }] : []),
243 ]),
244 pagination: { take: batchSize, order: { [primaryKey]: "ASC" } },
245 withDeleted: !!catchup,
246 ...queryContext(options.context, context),
247 })) as { data: TRow[] }
248
249 if (!data.length) {
250 return
251 }
252
253 // Only the catch-up pass can observe a row leaving the index — a full
254 // seed builds the index from nothing, so absence is enough there.
255 const rows = catchup ? data.filter((row) => !row[DELETED_AT_FIELD]) : data
256 const { documents, produced } = await toDocuments(rows, options, context)
257 const deletedIds = catchup
258 ? data
259 .map((row) => String(row[primaryKey]))
260 .filter((id) => !produced.has(id))
261 : []
262
263 const mutations: SearchTypes.SearchIndexSeedMutation<Fields>[] = []
264 if (documents.length) {
265 mutations.push({ action: "upsert", documents })
266 }
267
268 if (deletedIds.length) {
269 mutations.push({
270 action: "delete",
271 filters: { [primaryKey]: deletedIds },
272 })
273 }
274
275 if (mutations.length) {
276 yield mutations
277 }
278
279 if (data.length < batchSize) {
280 return
281 }
282
283 cursor = String(data[data.length - 1][primaryKey])
284 }
285 }
286 }
287
288 /**
289 * Builds an index definition's `consume` from a `query.graph` query.
290 *
291 * The event's IDs are read back through `query.graph` and upserted. An ID the
292 * read doesn't return, or whose row the `transform` rejects, is deleted
293 * instead — which is what keeps a row that was removed, unpublished, or
294 * filtered out of the index from lingering in it.
295 *
296 * @example
297 * export default defineSearchIndex({
298 * name: "product",
299 * entity: "product",
300 * fields: productFields,
301 * events: ["product.created", "product.updated", "product.deleted"],
302 * consume: graphConsume({ fields: ["id", "title"] }),
303 * seed: graphSeed({ fields: ["id", "title"] }),
304 * })
305 */
306 export function graphConsume<
307 Fields extends SearchTypes.SearchIndexFieldsInput,
308 TRow extends GraphRow = GraphRow
309 >(
310 options: SearchGraphConsumeOptions<Fields, TRow>
311 ): NonNullable<SearchTypes.SearchIndexDefinitionInput<Fields>["consume"]> {
312 const {
313 fields,
314 resolve_ids: resolveIds = (event) => (event.data as any)?.id,
315 is_delete: isDelete = (event) => event.name.endsWith(".deleted"),
316 } = options
317
318 return async function graphConsumer(event, context) {
319 const { container, index } = context
320
321 const entity = options.entity ?? index.entity
322 const primaryKey = index.primary_key
323 const ids = toArray(await resolveIds(event, context))
324
325 if (!ids.length) {
326 return []
327 }
328
329 if (isDelete(event)) {
330 return [{ action: "delete", filters: { [primaryKey]: ids } }]
331 }
332
333 const { data } = (await container.query.graph({
334 entity,
335 fields: withFields(fields, primaryKey),
336 filters: { [primaryKey]: ids },
337 ...queryContext(options.context, context),
338 })) as { data: TRow[] }
339
340 const { documents, produced } = await toDocuments(data, options, context)
341
342 const mutations: SearchTypes.SearchIndexSeedMutation<Fields>[] = []
343
344 if (documents.length) {
345 mutations.push({ action: "upsert", documents })
346 }
347
348 // Gone, or rejected by the transform — either way it has no business being
349 // in the index anymore.
350 const removedIds = ids.filter((id) => !produced.has(id))
351 if (removedIds.length) {
352 mutations.push({
353 action: "delete",
354 filters: { [primaryKey]: removedIds },
355 })
356 }
357
358 return mutations
359 }
360 }