1 import { MedusaError } from "@medusajs/framework/utils"
2
3 export type ActiveIndexVersion = {
4 physical_name: string
5 provider: string
6 version: number
7 }
8
9 const SOFT_TTL_MS = 30_000
10 const HARD_TTL_MS = 2 * 60_000
11
12 /**
13 * Caches which physical index currently serves reads for every logical index,
14 * since that can change out from under a running process when another
15 * replica finishes seeding and flips it.
16 *
17 * Populated in one bulk fetch rather than one per index: there are never many
18 * search indexes in an app, so listing them all is cheap, and it means
19 * refreshing because of one index refreshes every other one for free.
20 *
21 * Fresh for `SOFT_TTL_MS`. Stale beyond that but still served while a
22 * background refresh runs (stale-while-revalidate) — a failed refresh leaves
23 * `fetchedAt_` untouched, so the age keeps counting from the last *successful*
24 * fetch rather than resetting. Never served past `HARD_TTL_MS` since that last
25 * success; a caller waits on a synchronous refetch instead.
26 */
27 export class ActiveIndexVersionCache {
28 protected values_ = new Map<string, ActiveIndexVersion>()
29 protected fetchedAt_ = 0
30 protected refreshing_?: Promise<void>
31
32 constructor(
33 protected readonly fetchAll_: () => Promise<Map<string, ActiveIndexVersion>>
34 ) {}
35
36 async get(
37 name: string,
38 { fresh = false }: { fresh?: boolean } = {}
39 ): Promise<ActiveIndexVersion> {
40 const age = Date.now() - this.fetchedAt_
41
42 if (fresh || !this.fetchedAt_ || age >= HARD_TTL_MS) {
43 await this.refresh()
44 } else if (age >= SOFT_TTL_MS) {
45 void this.refresh().catch(() => {
46 // Left stale on purpose — `fetchedAt_` is untouched, so `HARD_TTL_MS`
47 // keeps counting from the last success, not this failure.
48 })
49 }
50
51 const value = this.values_.get(name)
52
53 if (!value) {
54 throw new MedusaError(
55 MedusaError.Types.NOT_FOUND,
56 `Search index "${name}" has no active version yet. It has to be migrated and seeded first.`
57 )
58 }
59
60 return value
61 }
62
63 protected refresh(): Promise<void> {
64 this.refreshing_ ??= this.fetchAll_()
65 .then((values) => {
66 this.values_ = values
67 this.fetchedAt_ = Date.now()
68 })
69 .finally(() => {
70 this.refreshing_ = undefined
71 })
72
73 return this.refreshing_
74 }
75
76 /** Sets one value directly, e.g. right after this process itself flips it. */
77 async set(name: string, value: ActiveIndexVersion): Promise<void> {
78 await this.settle()
79 this.values_.set(name, value)
80 }
81
82 async invalidate(): Promise<void> {
83 await this.settle()
84 this.fetchedAt_ = 0
85 this.values_.clear()
86 }
87
88 // A fetch in flight may have read the database before the change the caller
89 // is about to make, so it has to land first rather than overwrite it later.
90 protected async settle(): Promise<void> {
91 await this.refreshing_?.catch(() => {})
92 }
93 }