1 import { SearchTypes } from "@medusajs/framework/types"
2 import { MedusaError } from "@medusajs/framework/utils"
3 import {
4 SearchIndexContext,
5 SearchIndexRecord,
6 SearchIndexRegistry,
7 SearchIndexSeedAction,
8 SearchIndexSeedReason,
9 SearchIndexSyncRecord,
10 SearchIndexVersionRecord,
11 SearchSeedRuntime,
12 } from "@types"
13 import { randomUUID } from "crypto"
14 import {
15 assertTaskAccepted,
16 DEFAULT_REINDEX_BATCH_SIZE,
17 listVersionsByIndexId,
18 retrieveIndexDefinition,
19 SearchIndexState,
20 SearchSyncStatus,
21 } from "./index"
22 import {
23 cleanupAbandonedVersions,
24 cleanupAfterSwap,
25 cleanupStaleVersions,
26 versionPhysicalName,
27 } from "./versions"
28 import { retryOnRateLimit } from "./rate-limit"
29
30 type LockContext = Pick<SearchIndexContext, "locking" | "logger">
31 type SyncContext = Pick<SearchIndexContext, "syncService">
32
33 /** How often a long seed reports how many documents it has written. */
34 const PROGRESS_LOG_INTERVAL_MS = 10_000
35
36 /* -------------------------------- planning -------------------------------- */
37
38 /**
39 * Which indexes need data, and which version it goes into. The highest version
40 * above the active one is what a migration built for a schema or provider
41 * change; it needs filling and then becoming active. Otherwise an index needs
42 * seeding in place if its active version was never filled, its last attempt
43 * failed, or it holds nothing — the last catching an engine that lost its data
44 * while the record still says ready.
45 */
46 export async function createSeedPlan(
47 context: SearchIndexRegistry
48 ): Promise<SearchIndexSeedAction[]> {
49 const definitions = [...context.indexes.values()]
50
51 if (!definitions.length) {
52 return []
53 }
54
55 const records = (await context.indexService.list(
56 { name: definitions.map((definition) => definition.name) },
57 { take: null }
58 )) as SearchIndexRecord[]
59
60 const byName = new Map(records.map((record) => [record.name, record]))
61 const versionsByIndexId = await listVersionsByIndexId(
62 context,
63 records.map((record) => record.id)
64 )
65 const actions: SearchIndexSeedAction[] = []
66
67 for (const definition of definitions) {
68 const record = byName.get(definition.name)
69
70 // No record means the index was never migrated, so there is nothing to fill.
71 // Creating one is a migration's job, not a booting app's.
72 if (!record) {
73 continue
74 }
75
76 const versions = versionsByIndexId.get(record.id) ?? []
77
78 const pending = versions
79 .filter(
80 (version) =>
81 record.active_version == null ||
82 version.version > record.active_version
83 )
84 .sort((a, b) => b.version - a.version)[0]
85
86 if (pending) {
87 actions.push({
88 index: definition.name,
89 target_version: pending,
90 swap: true,
91 reason: "schema_changed",
92 })
93 continue
94 }
95
96 const activeVersion = versions.find(
97 (version) => version.version === record.active_version
98 )
99
100 if (!activeVersion) {
101 continue
102 }
103
104 if (activeVersion.status === SearchIndexState.ERROR) {
105 // A failed run leaves a cursor the next one picks up from — but only
106 // while the engine still holds what it wrote. An index that lost its
107 // data has to be rebuilt from the start, however far that run got.
108 const empty =
109 (await countDocuments(
110 context,
111 definition,
112 activeVersion.physical_name
113 )) === 0
114
115 actions.push(
116 inPlace(
117 definition,
118 activeVersion,
119 empty ? "index_empty" : "last_run_failed"
120 )
121 )
122 continue
123 }
124
125 if (activeVersion.status !== SearchIndexState.READY) {
126 actions.push(inPlace(definition, activeVersion, "index_created"))
127 continue
128 }
129
130 if (
131 (await countDocuments(
132 context,
133 definition,
134 activeVersion.physical_name
135 )) === 0
136 ) {
137 actions.push(inPlace(definition, activeVersion, "index_empty"))
138 }
139 }
140
141 return actions
142 }
143
144 function inPlace(
145 definition: SearchTypes.ResolvedSearchIndexDefinition,
146 version: SearchIndexVersionRecord,
147 reason: SearchIndexSeedReason
148 ): SearchIndexSeedAction {
149 return {
150 index: definition.name,
151 target_version: version,
152 swap: false,
153 reason,
154 }
155 }
156
157 export async function executeSeedPlan(
158 context: SearchSeedRuntime & LockContext,
159 actions: SearchIndexSeedAction[]
160 ): Promise<void> {
161 for (const action of actions) {
162 const definition = retrieveIndexDefinition(context.indexes, action.index)
163
164 // One instance per index. Without this every replica in a rolling deploy
165 // would seed the same index at the same time.
166 await withIndexLock(context, definition.name, async (signal) => {
167 await runSeed(context, { definition, action, signal })
168 })
169 }
170 }
171
172 async function runSeed(
173 context: SearchSeedRuntime,
174 {
175 definition,
176 action,
177 signal,
178 }: {
179 definition: SearchTypes.ResolvedSearchIndexDefinition
180 action: SearchIndexSeedAction
181 signal?: AbortSignal
182 }
183 ): Promise<void> {
184 const target = action.target_version
185 const sync = await startSync(context, {
186 versionId: target.id,
187 resume: action.reason !== "index_empty",
188 })
189 const startedAt = Date.now()
190 const assertLockHeld = lockGuard(definition.name, signal)
191
192 context.logger.info(
193 `[Search] Seeding "${definition.name}" (${action.reason}) into "${
194 target.physical_name
195 }"${formatResume(sync.last_key)}`
196 )
197
198 await context.versionService.update({
199 selector: { id: target.id },
200 data: { status: SearchIndexState.BUILDING },
201 })
202
203 try {
204 const { documents_synced, written } = await streamSeed(context, {
205 index: definition,
206 sync_id: sync.id,
207 target_index: target.physical_name,
208 last_key: sync.last_key ?? undefined,
209 synced_before: sync.documents_synced,
210 assertLockHeld,
211 })
212
213 await catchUp(context, {
214 definition,
215 target,
216 since: sync.started_at!,
217 jobId: sync.job_id!,
218 assertLockHeld,
219 })
220
221 // Ensure it is this instance that holds the lock before marking anything as ready.
222 assertLockHeld()
223
224 await context.versionService.update({
225 selector: { id: target.id },
226 data: { status: SearchIndexState.READY },
227 })
228
229 let previousVersion: number | null | undefined
230
231 if (action.swap) {
232 previousVersion = (await retrieveIndexRecord(context, definition.name))
233 .active_version
234 context.logger.info(
235 `[Search] Making "${definition.name}" version ${target.version} active`
236 )
237 await context.indexService.update({
238 selector: { name: definition.name },
239 data: { active_version: target.version },
240 })
241 await context.activeVersionCache?.set(definition.name, {
242 physical_name: target.physical_name,
243 provider: target.provider,
244 version: target.version,
245 })
246 }
247
248 await completeSync(context, { sync_id: sync.id, documents_synced })
249
250 if (action.swap && !signal?.aborted) {
251 await cleanupAfterSwap(context, {
252 record_id: target.search_index_id,
253 active_version: target.version,
254 previous_version: previousVersion ?? null,
255 })
256 }
257
258 context.logger.info(
259 `[Search] Seeded "${definition.name}": ${formatCount(
260 written
261 )} in ${formatElapsed(Date.now() - startedAt)}${formatTotal(
262 documents_synced,
263 written
264 )}`
265 )
266 } catch (error) {
267 await failSync(context, {
268 sync_id: sync.id,
269 version_id: target.id,
270 error,
271 })
272 throw error
273 }
274 }
275
276 // A second seed pass, filtered to what changed since the first one started —
277 // catches a live write the bulk pass's own snapshot could otherwise miss or
278 // revert, including a delete (`streamSeed` applies whatever mutations `seed`
279 // yields, in order). Runs once, into the same target, right before the
280 // version is considered ready. Race-conditions are still possible, but unlikely.
281 async function catchUp(
282 context: SearchSeedRuntime,
283 {
284 definition,
285 target,
286 since,
287 jobId,
288 assertLockHeld,
289 }: {
290 definition: SearchTypes.ResolvedSearchIndexDefinition
291 target: SearchIndexVersionRecord
292 since: Date
293 jobId: string
294 assertLockHeld: () => void
295 }
296 ): Promise<void> {
297 const sync = await startSync(context, {
298 versionId: target.id,
299 jobId,
300 resume: false,
301 resumable: false,
302 })
303
304 try {
305 const { documents_synced } = await streamSeed(context, {
306 index: definition,
307 sync_id: sync.id,
308 target_index: target.physical_name,
309 catchup: { since },
310 assertLockHeld,
311 })
312
313 await completeSync(context, { sync_id: sync.id, documents_synced })
314
315 context.logger.info(
316 `[Search] Caught up "${definition.name}": ${formatCount(
317 documents_synced
318 )} synced since ${since.toISOString()}`
319 )
320 } catch (error) {
321 await failSync(context, { sync_id: sync.id, version_id: target.id, error })
322 throw error
323 }
324 }
325
326 export async function reindexIndexes(
327 context: SearchSeedRuntime & LockContext,
328 input: SearchTypes.SearchReindexInput = {}
329 ): Promise<SearchTypes.SearchReindexResult> {
330 const names = input.index
331 ? Array.isArray(input.index)
332 ? input.index
333 : [input.index]
334 : [...context.indexes.keys()]
335
336 const definitions = names.map((name) =>
337 retrieveIndexDefinition(context.indexes, name)
338 )
339 const jobId = randomUUID()
340
341 for (const definition of definitions) {
342 // Same lock boot seeding takes, so a reindex never races a startup seed
343 // (or another reindex) on the same index. Unlike boot, an explicit reindex
344 // must not quietly skip — the caller asked for work to happen.
345 if (context.locking) {
346 await context.locking.execute(
347 `search:seed:${definition.name}`,
348 (signal) => reindexOne(context, { definition, jobId, input, signal })
349 )
350 } else {
351 await reindexOne(context, { definition, jobId, input })
352 }
353 }
354
355 return { job_id: jobId, indexes: names }
356 }
357
358 async function reindexOne(
359 context: SearchSeedRuntime,
360 {
361 definition,
362 jobId,
363 input,
364 signal,
365 }: {
366 definition: SearchTypes.ResolvedSearchIndexDefinition
367 jobId: string
368 input: SearchTypes.SearchReindexInput
369 signal?: AbortSignal
370 }
371 ): Promise<void> {
372 const provider = context.providers.retrieve(definition.provider)
373 const record = await retrieveIndexRecord(context, definition.name)
374 const previousVersion = record.active_version
375
376 // We want to clean up stale versions before we start the reindex.
377 await cleanupStaleVersions(context, record)
378
379 const scoped = !!input.filters || !!input.since
380
381 // A partial rebuild must never swap: the replacement would only hold that
382 // slice, so making it active would drop everything else.
383 const useSwap = (input.strategy ?? "swap") === "swap" && !scoped
384
385 const target = useSwap
386 ? await createPendingVersion(context, { definition, record, provider })
387 : await retrieveActiveVersion(context, { definition, record })
388
389 // Only once the new version exists, so version numbers are never reused.
390 if (useSwap) {
391 await cleanupAbandonedVersions(context, record)
392 }
393
394 const sync = await startSync(context, {
395 versionId: target.id,
396 jobId,
397 filters: input.filters,
398 // A scoped run covers a different set of documents than the full run whose
399 // cursor it would otherwise inherit
400 resume: !scoped,
401 resumable: !scoped,
402 })
403 const startedAt = Date.now()
404 const assertLockHeld = lockGuard(definition.name, signal)
405
406 context.logger.info(
407 `[Search] Reindexing "${definition.name}" into "${
408 target.physical_name
409 }"${formatResume(sync.last_key)}`
410 )
411
412 await context.versionService.update({
413 selector: { id: target.id },
414 data: { status: SearchIndexState.BUILDING },
415 })
416
417 try {
418 // A fresh version has nothing to discard. Rebuilding in place does, so a
419 // record the new seed stream doesn't re-emit (a deleted row, say) doesn't
420 // survive as stale data — but only for a full rebuild: a scoped run
421 // selects source records for the seed, not search-engine filter syntax,
422 // so it can't be reused to delete a matching subset here. And skip this
423 // entirely when resuming an interrupted run, since the target already
424 // holds that run's progress.
425 if (!useSwap && !sync.last_key && !scoped) {
426 await retryOnRateLimit(
427 async () => {
428 const clearTask = await provider.clearIndex({
429 index: target.physical_name,
430 })
431
432 assertTaskAccepted(clearTask, definition.name)
433 await settle(context, definition, clearTask)
434 },
435 {
436 label: `clearing "${definition.name}"`,
437 logger: context.logger,
438 }
439 )
440 }
441
442 const { documents_synced, written } = await streamSeed(context, {
443 index: definition,
444 sync_id: sync.id,
445 target_index: target.physical_name,
446 filters: input.filters,
447 last_key: sync.last_key ?? undefined,
448 synced_before: sync.documents_synced,
449 // `since` is the same "only what changed at or after this" question the
450 // catch-up pass asks, so it reaches `seed` the same way.
451 catchup: input.since ? { since: input.since } : undefined,
452 assertLockHeld,
453 })
454
455 // Skipped for a scoped reindex: it's already a narrow, caller-scoped
456 // rebuild, and catching up on everything changed since would silently
457 // do more than asked.
458 if (!scoped) {
459 await catchUp(context, {
460 definition,
461 target,
462 since: sync.started_at!,
463 jobId,
464 assertLockHeld,
465 })
466 }
467
468 // Ensure it is this instance that holds the lock before marking anything as ready.
469 assertLockHeld()
470
471 await context.versionService.update({
472 selector: { id: target.id },
473 data: { status: SearchIndexState.READY },
474 })
475
476 if (useSwap) {
477 context.logger.info(
478 `[Search] Making "${definition.name}" version ${target.version} active`
479 )
480 await context.indexService.update({
481 selector: { id: record.id },
482 data: { active_version: target.version },
483 })
484 await context.activeVersionCache?.set(definition.name, {
485 physical_name: target.physical_name,
486 provider: target.provider,
487 version: target.version,
488 })
489 }
490
491 await completeSync(context, { sync_id: sync.id, documents_synced })
492
493 if (useSwap && !signal?.aborted) {
494 await cleanupAfterSwap(context, {
495 record_id: record.id,
496 active_version: target.version,
497 previous_version: previousVersion,
498 })
499 }
500
501 context.logger.info(
502 `[Search] Reindexed "${definition.name}": ${formatCount(
503 written
504 )} in ${formatElapsed(Date.now() - startedAt)}${formatTotal(
505 documents_synced,
506 written
507 )}`
508 )
509 } catch (error) {
510 // Leave the new version behind on failure; the active one is untouched.
511 await failSync(context, { sync_id: sync.id, version_id: target.id, error })
512 throw error
513 }
514 }
515
516 /** Builds a brand-new version, whether or not the definition actually drifted. */
517 async function createPendingVersion(
518 context: Pick<SearchIndexContext, "versionService">,
519 {
520 definition,
521 record,
522 provider,
523 }: {
524 definition: SearchTypes.ResolvedSearchIndexDefinition
525 record: SearchIndexRecord
526 provider: SearchTypes.ISearchProvider
527 }
528 ): Promise<SearchIndexVersionRecord> {
529 const versions = (await context.versionService.list(
530 { search_index_id: record.id },
531 { order: { version: "DESC" }, take: 1 }
532 )) as SearchIndexVersionRecord[]
533
534 const version = (versions[0]?.version ?? record.active_version ?? 0) + 1
535 const physicalName = versionPhysicalName(definition, version)
536
537 await provider.upsertIndex({
538 index: { ...definition, physical_name: physicalName },
539 })
540
541 const [created] = (await context.versionService.create([
542 {
543 search_index_id: record.id,
544 version,
545 provider: definition.provider,
546 physical_name: physicalName,
547 definition_hash: definition.definition_hash,
548 status: SearchIndexState.PENDING,
549 },
550 ])) as SearchIndexVersionRecord[]
551
552 return created
553 }
554
555 async function retrieveActiveVersion(
556 context: Pick<SearchIndexContext, "versionService">,
557 {
558 definition,
559 record,
560 }: {
561 definition: SearchTypes.ResolvedSearchIndexDefinition
562 record: SearchIndexRecord
563 }
564 ): Promise<SearchIndexVersionRecord> {
565 if (record.active_version == null) {
566 throw new MedusaError(
567 MedusaError.Types.NOT_ALLOWED,
568 `Search index "${definition.name}" has no active version to reindex in place`
569 )
570 }
571
572 const [active] = (await context.versionService.list({
573 search_index_id: record.id,
574 version: record.active_version,
575 })) as SearchIndexVersionRecord[]
576
577 return active
578 }
579
580 /* -------------------------------- streaming ------------------------------- */
581
582 // Streams one index' `seed` in, advancing the sync row's `last_key` per batch so
583 // an interrupted run resumes rather than restarting. `seed` yields mutations
584 // (not bare documents), so a delete is applied directly, in order — flushing
585 // any buffered upserts first so it isn't reordered ahead of them.
586 async function streamSeed(
587 context: SearchSeedRuntime,
588 {
589 index,
590 sync_id,
591 target_index,
592 filters,
593 last_key,
594 synced_before,
595 catchup,
596 assertLockHeld,
597 }: {
598 index: SearchTypes.ResolvedSearchIndexDefinition
599 sync_id: string
600 target_index: string
601 filters?: Record<string, unknown>
602 last_key?: string
603 synced_before?: number
604 catchup?: { since: Date }
605 assertLockHeld: () => void
606 }
607 ): Promise<{ documents_synced: number; written: number }> {
608 const provider = context.providers.retrieve(index.provider)
609 const batchSize =
610 context.options.reindex?.batch_size ?? DEFAULT_REINDEX_BATCH_SIZE
611
612 let buffer: SearchTypes.SearchDocument[] = []
613 // What this run wrote, without the previous runs' writes.
614 let written = 0
615 const total = () => (synced_before ?? 0) + written
616 let lastKey: string | undefined
617 const startedAt = Date.now()
618 let lastLoggedAt = startedAt
619 let lastLoggedCount = 0
620
621 const reportProgress = (force = false) => {
622 const now = Date.now()
623 if (
624 !force &&
625 (written === lastLoggedCount ||
626 now - lastLoggedAt < PROGRESS_LOG_INTERVAL_MS)
627 ) {
628 return
629 }
630
631 const elapsedMs = now - startedAt
632 const elapsedSec = Math.max(elapsedMs / 1000, 0.001)
633 const rate = Math.round(written / elapsedSec)
634 const cursor = lastKey ? `, last key ${lastKey}` : ""
635
636 context.logger.info(
637 `[Search] "${index.name}": ${formatCount(
638 written
639 )} synced in ${formatElapsed(elapsedMs)} (${rate}/s)${cursor}`
640 )
641 lastLoggedAt = now
642 lastLoggedCount = written
643 }
644
645 const flushUpserts = async () => {
646 if (!buffer.length) {
647 return
648 }
649
650 const batch = buffer
651 buffer = []
652
653 await retryOnRateLimit(
654 async () => {
655 assertLockHeld()
656
657 const task = await provider.upsertDocuments({
658 index: target_index,
659 definition: index,
660 documents: batch,
661 })
662
663 assertTaskAccepted(task, index.name)
664 await settle(context, index, task)
665 },
666 {
667 label: `writing ${batch.length} document(s) to "${index.name}"`,
668 logger: context.logger,
669 }
670 )
671
672 written += batch.length
673 lastKey = batch[batch.length - 1][index.primary_key] as string
674
675 await context.syncService.update({
676 selector: { id: sync_id },
677 data: {
678 documents_synced: total(),
679 last_key: lastKey,
680 },
681 })
682
683 // First flush so a long seed is visibly moving; then at most every 10s.
684 reportProgress(lastLoggedCount === 0)
685 }
686
687 const applyDelete = async (deleteFilters: SearchTypes.SearchFilters) => {
688 await flushUpserts()
689
690 try {
691 await retryOnRateLimit(
692 async () => {
693 assertLockHeld()
694
695 const task = await provider.deleteDocuments({
696 index: target_index,
697 filters: deleteFilters,
698 })
699
700 assertTaskAccepted(task, index.name)
701 await settle(context, index, task)
702 },
703 {
704 label: `deleting documents from "${index.name}"`,
705 logger: context.logger,
706 }
707 )
708 } catch (error) {
709 if (error instanceof SearchSeedLockLost) {
710 throw error
711 }
712
713 throw new SearchSeedProgressLost(
714 `Seed of "${index.name}" failed while deleting documents, so its progress cannot be resumed: ${error.message}`,
715 error
716 )
717 }
718 }
719
720 for await (const mutations of index.seed({
721 container: context.container,
722 index,
723 filters,
724 last_key,
725 catchup,
726 })) {
727 for (const mutation of mutations) {
728 if (mutation.action === "delete") {
729 await applyDelete(mutation.filters)
730 continue
731 }
732
733 for (const document of mutation.documents) {
734 buffer.push(document)
735
736 if (buffer.length >= batchSize) {
737 await flushUpserts()
738 }
739 }
740 }
741 }
742
743 await flushUpserts()
744
745 await context.syncService.update({
746 selector: { id: sync_id },
747 data: { resumable: false },
748 })
749
750 return { documents_synced: total(), written }
751 }
752
753 // Blocks until a write lands. Not optional here: a swap puts the new version
754 // in front of reads, so its documents have to be in it first.
755 async function settle(
756 context: Pick<SearchIndexContext, "providers">,
757 definition: SearchTypes.ResolvedSearchIndexDefinition,
758 task: SearchTypes.SearchTask
759 ): Promise<void> {
760 const provider = context.providers.retrieve(definition.provider)
761
762 if (!provider.waitForTask || task.status === "succeeded") {
763 return
764 }
765
766 assertTaskAccepted(await provider.waitForTask(task), definition.name)
767 }
768
769 /* -------------------------------- the lock -------------------------------- */
770
771 /**
772 * A seed failed in a way that leaves the index inconsistent with the run's
773 * cursor, so the next run has to rebuild from the start rather than carry on
774 * from where this one stopped.
775 */
776 export class SearchSeedProgressLost extends MedusaError {
777 constructor(message: string, readonly cause?: unknown) {
778 super(MedusaError.Types.UNEXPECTED_STATE, message)
779 this.name = "SearchSeedProgressLost"
780 }
781 }
782
783 export class SearchSeedLockLost extends MedusaError {
784 constructor(message: string) {
785 super(MedusaError.Types.CONFLICT, message)
786 this.name = "SearchSeedLockLost"
787 }
788 }
789
790 /**
791 * If the lock got aborted we want to throw, as the lock may be held by another instance now.
792 */
793 function lockGuard(index: string, signal?: AbortSignal): () => void {
794 return () => {
795 if (signal?.aborted) {
796 throw new SearchSeedLockLost(
797 `Seed of "${index}" lost its lock while running, so another instance may already be seeding it`
798 )
799 }
800 }
801 }
802
803 /* ------------------------------ sync records ------------------------------ */
804
805 async function startSync(
806 context: SyncContext,
807 {
808 versionId,
809 jobId,
810 filters,
811 resume = true,
812 resumable = true,
813 }: {
814 versionId: string
815 jobId?: string
816 filters?: Record<string, unknown>
817 resume?: boolean
818 resumable?: boolean
819 }
820 ): Promise<SearchIndexSyncRecord> {
821 const previous = resume
822 ? await findResumableSync(context, versionId)
823 : undefined
824
825 const [sync] = await context.syncService.create([
826 {
827 search_index_version_id: versionId,
828 job_id: jobId ?? randomUUID(),
829 status: SearchSyncStatus.PROCESSING,
830 filters: filters ?? null,
831 last_key: previous?.last_key ?? null,
832 // Carried along with the cursor, so a version filled over several runs reports the complete count.
833 documents_synced: previous?.documents_synced ?? 0,
834 resumable,
835 started_at: new Date(),
836 },
837 ])
838
839 if (previous && isUnfinished(previous)) {
840 await context.syncService.update({
841 selector: { id: previous.id },
842 data: { status: SearchSyncStatus.CANCELED },
843 })
844 }
845
846 return sync as SearchIndexSyncRecord
847 }
848
849 async function completeSync(
850 context: Pick<SearchIndexContext, "syncService">,
851 { sync_id, documents_synced }: { sync_id: string; documents_synced: number }
852 ): Promise<void> {
853 await context.syncService.update({
854 selector: { id: sync_id },
855 data: {
856 status: SearchSyncStatus.DONE,
857 documents_synced,
858 completed_at: new Date(),
859 },
860 })
861 }
862
863 async function failSync(
864 context: Pick<SearchIndexContext, "versionService" | "syncService">,
865 {
866 sync_id,
867 version_id,
868 error,
869 }: { sync_id: string; version_id: string; error: Error }
870 ): Promise<void> {
871 // A run that lost its lock doesn't own the version or its syncs any more, so
872 // it must not mark either as failed.
873 if (error instanceof SearchSeedLockLost) {
874 return
875 }
876
877 await context.syncService.update({
878 selector: { id: sync_id },
879 data: {
880 status: SearchSyncStatus.FAILED,
881 error: error.message,
882 completed_at: new Date(),
883 ...(error instanceof SearchSeedProgressLost ? { resumable: false } : {}),
884 },
885 })
886
887 await context.versionService.update({
888 selector: { id: version_id },
889 data: { status: SearchIndexState.ERROR },
890 })
891 }
892
893 function isUnfinished(sync: SearchIndexSyncRecord): boolean {
894 return (
895 sync.status === SearchSyncStatus.PENDING ||
896 sync.status === SearchSyncStatus.PROCESSING
897 )
898 }
899
900 async function findResumableSync(
901 context: SyncContext,
902 versionId: string
903 ): Promise<SearchIndexSyncRecord | undefined> {
904 const [latest] = (await context.syncService.list(
905 { search_index_version_id: versionId },
906 { order: { created_at: "DESC" }, take: 1 }
907 )) as SearchIndexSyncRecord[]
908
909 if (!latest?.resumable) {
910 return undefined
911 }
912
913 return isUnfinished(latest) || latest.status === SearchSyncStatus.FAILED
914 ? latest
915 : undefined
916 }
917
918 /* --------------------------------- helpers -------------------------------- */
919
920 function formatCount(count: number): string {
921 return `${count.toLocaleString("en-US")} document${count === 1 ? "" : "s"}`
922 }
923
924 function formatElapsed(ms: number): string {
925 const seconds = Math.max(0, Math.round(ms / 1000))
926 if (seconds < 60) {
927 return `${seconds}s`
928 }
929
930 const minutes = Math.floor(seconds / 60)
931 const rest = seconds % 60
932 if (minutes < 60) {
933 return rest ? `${minutes}m ${rest}s` : `${minutes}m`
934 }
935
936 const hours = Math.floor(minutes / 60)
937 const minutesRest = minutes % 60
938 return minutesRest ? `${hours}h ${minutesRest}m` : `${hours}h`
939 }
940
941 function formatResume(lastKey: string | null | undefined): string {
942 return lastKey ? `, resuming after ${lastKey}` : ""
943 }
944
945 function formatTotal(documentsSynced: number, written: number): string {
946 return documentsSynced === written
947 ? ""
948 : `, ${formatCount(documentsSynced)} in total`
949 }
950
951 async function countDocuments(
952 context: Pick<SearchIndexContext, "providers">,
953 definition: SearchTypes.ResolvedSearchIndexDefinition,
954 physicalName: string
955 ): Promise<number> {
956 const indexes = await context.providers
957 .retrieve(definition.provider)
958 .listIndexes()
959
960 return indexes.find((info) => info.name === physicalName)?.document_count ?? 0
961 }
962
963 async function withIndexLock<T>(
964 context: LockContext,
965 name: string,
966 job: (signal?: AbortSignal) => Promise<T>
967 ): Promise<T | undefined> {
968 if (!context.locking) {
969 return await job()
970 }
971
972 let started = false
973
974 try {
975 return await context.locking.execute(`search:seed:${name}`, (signal) => {
976 started = true
977 return job(signal)
978 })
979 } catch (error) {
980 // Happens when a lock could not be acquired.
981 if (!started) {
982 context.logger.info(
983 `[Search] Skipping seed of "${name}": ${error.message}`
984 )
985 return undefined
986 }
987
988 if (error instanceof SearchSeedLockLost) {
989 context.logger.warn(`[Search] ${error.message}`)
990 return undefined
991 }
992
993 context.logger.error(
994 `[Search] Failed to seed "${name}": ${error.message}`,
995 error
996 )
997 return undefined
998 }
999 }
1000
1001 async function retrieveIndexRecord(
1002 context: Pick<SearchIndexContext, "indexService">,
1003 name: string
1004 ): Promise<SearchIndexRecord> {
1005 const [record] = (await context.indexService.list({
1006 name,
1007 })) as SearchIndexRecord[]
1008
1009 if (!record) {
1010 throw new MedusaError(
1011 MedusaError.Types.NOT_FOUND,
1012 `Search index "${name}" has no record; run migrations to create it`
1013 )
1014 }
1015
1016 return record
1017 }