1 import { SearchTypes } from "@medusajs/framework/types"
2 import { SearchIndexContext } from "@types"
3 import { MedusaError } from "@medusajs/framework/utils"
4 import { ActiveIndexVersionCache } from "../active-version-cache"
5 import { resolveActiveDefinition, withActiveIndexRetry } from "../index"
6
7 const SOFT_TTL_MS = 30_000
8 const HARD_TTL_MS = 2 * 60_000
9
10 const version = (n: number) => ({
11 physical_name: `product_v${n}`,
12 provider: "test",
13 version: n,
14 })
15
16 /**
17 * A cache over a fetcher whose answer the test controls, with the clock under
18 * the test's control too — every behaviour here is a function of elapsed time.
19 */
20 const buildCache = () => {
21 let now = 1_000_000
22 let active = 1
23 let failNext = false
24
25 const fetchAll = jest.fn(async () => {
26 if (failNext) {
27 throw new Error("db unreachable")
28 }
29 return new Map([["product", version(active)]])
30 })
31
32 jest.spyOn(Date, "now").mockImplementation(() => now)
33
34 return {
35 cache: new ActiveIndexVersionCache(fetchAll),
36 fetchAll,
37 advance: (ms: number) => {
38 now += ms
39 },
40 /** Stands in for another process finishing a swap. */
41 flipTo: (n: number) => {
42 active = n
43 },
44 breakFetch: (broken: boolean) => {
45 failNext = broken
46 },
47 // Lets a background refresh settle before the next assertion.
48 settle: () => new Promise((resolve) => setImmediate(resolve)),
49 }
50 }
51
52 describe("ActiveIndexVersionCache", () => {
53 afterEach(() => {
54 jest.restoreAllMocks()
55 })
56
57 it("serves from memory inside the soft TTL", async () => {
58 const { cache, fetchAll, advance, flipTo } = buildCache()
59
60 expect((await cache.get("product")).version).toBe(1)
61
62 flipTo(2)
63 advance(SOFT_TTL_MS - 1)
64
65 expect((await cache.get("product")).version).toBe(1)
66 expect(fetchAll).toHaveBeenCalledTimes(1)
67 })
68
69 it("serves the stale value once past the soft TTL, then the fresh one", async () => {
70 const { cache, advance, flipTo, settle } = buildCache()
71
72 await cache.get("product")
73 flipTo(2)
74 advance(SOFT_TTL_MS)
75
76 // Stale-while-revalidate: this call still answers 1 and kicks off the fetch.
77 expect((await cache.get("product")).version).toBe(1)
78 await settle()
79 expect((await cache.get("product")).version).toBe(2)
80 })
81
82 it("keeps refreshing in the background after one refresh fails", async () => {
83 const { cache, fetchAll, advance, flipTo, breakFetch, settle } =
84 buildCache()
85
86 await cache.get("product")
87 flipTo(2)
88
89 advance(SOFT_TTL_MS)
90 breakFetch(true)
91 await cache.get("product")
92 await settle()
93
94 expect(fetchAll).toHaveBeenCalledTimes(2)
95
96 // The engine is healthy again and the value is still stale, so the next
97 // access past the soft TTL has to try again rather than wait out the hard
98 // TTL
99 breakFetch(false)
100 advance(SOFT_TTL_MS)
101 await cache.get("product")
102 await settle()
103
104 expect(fetchAll).toHaveBeenCalledTimes(3)
105 expect((await cache.get("product")).version).toBe(2)
106 })
107
108 it("counts the hard TTL from the last success, not the last attempt", async () => {
109 const { cache, advance, flipTo, breakFetch, settle } = buildCache()
110
111 await cache.get("product")
112 flipTo(2)
113
114 // A failed refresh must not look like a fill.
115 advance(SOFT_TTL_MS)
116 breakFetch(true)
117 await cache.get("product")
118 await settle()
119 breakFetch(false)
120
121 advance(HARD_TTL_MS - SOFT_TTL_MS)
122
123 // Past the hard TTL since the last *successful* fetch, so this one waits.
124 expect((await cache.get("product")).version).toBe(2)
125 })
126
127 it("waits for a fetch rather than serving anything past the hard TTL", async () => {
128 const { cache, advance, flipTo } = buildCache()
129
130 await cache.get("product")
131 flipTo(2)
132 advance(HARD_TTL_MS)
133
134 expect((await cache.get("product")).version).toBe(2)
135 })
136
137 it("refetches on every `fresh` read, whatever the age", async () => {
138 const { cache, fetchAll, flipTo } = buildCache()
139
140 await cache.get("product")
141 flipTo(2)
142
143 // No time has passed, so a plain read would be served from memory.
144 expect((await cache.get("product", { fresh: true })).version).toBe(2)
145 expect(fetchAll).toHaveBeenCalledTimes(2)
146 })
147
148 it("coalesces concurrent fetches into one", async () => {
149 const { cache, fetchAll } = buildCache()
150
151 const results = await Promise.all([
152 cache.get("product"),
153 cache.get("product"),
154 cache.get("product"),
155 ])
156
157 expect(fetchAll).toHaveBeenCalledTimes(1)
158 expect(results.map((result) => result.version)).toEqual([1, 1, 1])
159 })
160
161 it("refetches after being invalidated", async () => {
162 const { cache, fetchAll, flipTo } = buildCache()
163
164 await cache.get("product")
165 flipTo(2)
166 await cache.invalidate()
167
168 expect((await cache.get("product")).version).toBe(2)
169 expect(fetchAll).toHaveBeenCalledTimes(2)
170 })
171
172 it("throws when the index has no active version", async () => {
173 const { cache } = buildCache()
174
175 await expect(cache.get("blog")).rejects.toThrow(
176 /Search index "blog" has no active version yet/
177 )
178 })
179
180 it("surfaces the failure when it cannot serve anything", async () => {
181 const { cache, breakFetch } = buildCache()
182
183 breakFetch(true)
184
185 await expect(cache.get("product")).rejects.toThrow("db unreachable")
186 })
187
188 describe("with a fetch in flight", () => {
189 // Every fetch stays pending until the test lands it, so a fetch that read
190 // the database before a flip can be made to land after the flip was made.
191 const buildDeferredCache = () => {
192 let now = 1_000_000
193 jest.spyOn(Date, "now").mockImplementation(() => now)
194
195 const pending: ((values: Map<string, unknown>) => void)[] = []
196 const fetchAll = jest.fn(
197 () => new Promise<Map<string, any>>((resolve) => pending.push(resolve))
198 )
199
200 return {
201 cache: new ActiveIndexVersionCache(fetchAll),
202 fetchAll,
203 advance: (ms: number) => {
204 now += ms
205 },
206 land: async (fetch: number, active?: number) => {
207 pending[fetch](new Map(active ? [["product", version(active)]] : []))
208 await new Promise((resolve) => setImmediate(resolve))
209 },
210 }
211 }
212
213 it("keeps a first activation that the fetch did not see", async () => {
214 const { cache, fetchAll, land } = buildDeferredCache()
215
216 // Read the database before the activation, so it answers "no version".
217 const cold = cache.get("product").catch(() => undefined)
218 const set = cache.set("product", version(1))
219 await land(0)
220 await Promise.all([cold, set])
221
222 expect((await cache.get("product")).version).toBe(1)
223 expect(fetchAll).toHaveBeenCalledTimes(1)
224 })
225
226 it("does not roll a flip back to the version the fetch read", async () => {
227 const { cache, advance, land } = buildDeferredCache()
228
229 const initial = cache.get("product")
230 await land(0, 1)
231 await initial
232
233 // Past the soft TTL, so this starts a background fetch that reads the
234 // database before the flip below.
235 advance(SOFT_TTL_MS)
236 await cache.get("product")
237 const set = cache.set("product", version(2))
238 await land(1, 1)
239 await set
240
241 expect((await cache.get("product")).version).toBe(2)
242 })
243
244 it("does not join or keep a fetch that started before invalidate()", async () => {
245 const { cache, fetchAll, land } = buildDeferredCache()
246
247 const before = cache.get("product")
248 const invalidated = cache.invalidate()
249 await land(0, 1)
250 await Promise.all([before, invalidated])
251
252 const after = cache.get("product")
253 await land(1, 2)
254
255 expect((await after).version).toBe(2)
256 expect(fetchAll).toHaveBeenCalledTimes(2)
257 })
258 })
259 })
260
261 describe("resolveActiveDefinition", () => {
262 const definition = {
263 name: "product",
264 physical_name: "product",
265 provider: "stale-provider",
266 } as SearchTypes.ResolvedSearchIndexDefinition
267
268 const context = (get: jest.Mock) => ({
269 indexes: new Map([["product", definition]]),
270 activeVersionCache: { get, set: jest.fn(), invalidate: jest.fn() },
271 })
272
273 it("merges in the physical index and provider serving reads", async () => {
274 const get = jest.fn().mockResolvedValue({
275 physical_name: "product_v3",
276 provider: "live-provider",
277 version: 3,
278 })
279
280 const resolved = await resolveActiveDefinition(
281 context(get) as any,
282 "product"
283 )
284
285 expect(resolved).toMatchObject({
286 physical_name: "product_v3",
287 provider: "live-provider",
288 })
289 expect(get).toHaveBeenCalledWith("product", { fresh: false })
290 })
291
292 it("asks for a fresh value when the caller is about to write", async () => {
293 const get = jest.fn().mockResolvedValue(version(3))
294
295 await resolveActiveDefinition(context(get) as any, "product", {
296 fresh: true,
297 })
298
299 expect(get).toHaveBeenCalledWith("product", { fresh: true })
300 })
301 })
302
303 describe("withActiveIndexRetry", () => {
304 // Typed rather than cast, so dropping a method the helper calls off
305 // `activeVersionCache` fails here and not only in a downstream build.
306 const context = (): Pick<SearchIndexContext, "activeVersionCache"> & {
307 activeVersionCache: { invalidate: jest.Mock }
308 } => ({
309 activeVersionCache: {
310 get: jest.fn(),
311 set: jest.fn(),
312 invalidate: jest.fn(),
313 },
314 })
315
316 const missingIndex = () =>
317 new MedusaError(
318 MedusaError.Types.NOT_FOUND,
319 'The postgres search provider has no index "product_v1"'
320 )
321
322 it("returns the first result when nothing is missing", async () => {
323 const ctx = context()
324 const run = jest.fn().mockResolvedValue("ok")
325
326 expect(await withActiveIndexRetry(ctx, run)).toBe("ok")
327 expect(run).toHaveBeenCalledTimes(1)
328 expect(ctx.activeVersionCache.invalidate).not.toHaveBeenCalled()
329 })
330
331 it("invalidates and retries once when the engine has no such index", async () => {
332 const ctx = context()
333 const run = jest
334 .fn()
335 .mockRejectedValueOnce(missingIndex())
336 .mockResolvedValue("healed")
337
338 expect(await withActiveIndexRetry(ctx, run)).toBe("healed")
339 expect(ctx.activeVersionCache.invalidate).toHaveBeenCalledTimes(1)
340 expect(run).toHaveBeenCalledTimes(2)
341 })
342
343 it("gives up after the second failure", async () => {
344 const ctx = context()
345 const run = jest.fn().mockRejectedValue(missingIndex())
346
347 await expect(withActiveIndexRetry(ctx, run)).rejects.toThrow(
348 'no index "product_v1"'
349 )
350 expect(run).toHaveBeenCalledTimes(2)
351 })
352
353 it("does not retry a failure that a fresher version cannot fix", async () => {
354 const ctx = context()
355 const run = jest
356 .fn()
357 .mockRejectedValue(
358 new MedusaError(MedusaError.Types.INVALID_DATA, "unsortable field")
359 )
360
361 await expect(withActiveIndexRetry(ctx, run)).rejects.toThrow(
362 "unsortable field"
363 )
364 expect(run).toHaveBeenCalledTimes(1)
365 expect(ctx.activeVersionCache.invalidate).not.toHaveBeenCalled()
366 })
367 })