|
1
|
import { SearchTypes } from "@medusajs/framework/types" |
|
2
|
import { MedusaError } from "@medusajs/framework/utils" |
|
3
|
import { |
|
4
|
SearchIndexSeedAction, |
|
5
|
SearchIndexSyncRecord, |
|
6
|
SearchIndexVersionRecord, |
|
7
|
} from "@types" |
|
8
|
import { SearchIndexState, SearchSyncStatus } from "../index" |
|
9
|
import { createSeedPlan, executeSeedPlan, reindexIndexes } from "../seeding" |
|
10
|
|
|
11
|
type Mutation = |
|
12
|
| { action: "upsert"; documents: Record<string, unknown>[] } |
|
13
|
| { action: "delete"; filters: Record<string, unknown> } |
|
14
|
|
|
15
|
type SeedFn = ( |
|
16
|
context: SearchTypes.SearchSeedContext |
|
17
|
) => AsyncGenerator<Mutation[]> |
|
18
|
|
|
19
|
const definition = ( |
|
20
|
name: string, |
|
21
|
seed: SeedFn |
|
22
|
): SearchTypes.ResolvedSearchIndexDefinition => |
|
23
|
({ |
|
24
|
name, |
|
25
|
entity: name, |
|
26
|
provider: "test", |
|
27
|
physical_name: name, |
|
28
|
definition_hash: "abcdef0123456789abcdef0123456789", |
|
29
|
primary_key: "id", |
|
30
|
fields: { id: { type: "keyword", filterable: true } }, |
|
31
|
settings: {}, |
|
32
|
seed, |
|
33
|
} as unknown as SearchTypes.ResolvedSearchIndexDefinition) |
|
34
|
|
|
35
|
/** |
|
36
|
* A context over in-memory records, close enough to the real services for the |
|
37
|
* bookkeeping these tests are about: sync rows are ordered by creation and |
|
38
|
* queried the way `startSync` queries them. |
|
39
|
*/ |
|
40
|
const buildContext = ({ |
|
41
|
indexes, |
|
42
|
locking, |
|
43
|
upsertDocuments, |
|
44
|
deleteDocuments, |
|
45
|
documentCounts, |
|
46
|
}: { |
|
47
|
indexes: SearchTypes.ResolvedSearchIndexDefinition[] |
|
48
|
locking?: { |
|
49
|
execute: jest.Mock |
|
50
|
} |
|
51
|
upsertDocuments?: jest.Mock |
|
52
|
deleteDocuments?: jest.Mock |
|
53
|
rateLimit?: { |
|
54
|
max_retries?: number |
|
55
|
initial_delay?: number |
|
56
|
max_delay?: number |
|
57
|
} |
|
58
|
// What the engine reports it holds, keyed by physical index name. Only the |
|
59
|
// planner asks, and only to tell an index that lost its data apart from one |
|
60
|
// that merely failed part-way through. |
|
61
|
documentCounts?: Record<string, number> |
|
62
|
}) => { |
|
63
|
const records = indexes.map((index, position) => ({ |
|
64
|
id: `idx_${position + 1}`, |
|
65
|
name: index.name, |
|
66
|
active_version: 1, |
|
67
|
})) |
|
68
|
|
|
69
|
const versions: SearchIndexVersionRecord[] = indexes.map( |
|
70
|
(index, position) => ({ |
|
71
|
id: `ver_${position + 1}`, |
|
72
|
search_index_id: `idx_${position + 1}`, |
|
73
|
version: 1, |
|
74
|
provider: "test", |
|
75
|
physical_name: `${index.name}_v1`, |
|
76
|
definition_hash: index.definition_hash, |
|
77
|
status: SearchIndexState.PENDING, |
|
78
|
}) |
|
79
|
) |
|
80
|
|
|
81
|
const syncs: (SearchIndexSyncRecord & { sequence: number })[] = [] |
|
82
|
let sequence = 0 |
|
83
|
|
|
84
|
const matches = ( |
|
85
|
row: SearchIndexSyncRecord, |
|
86
|
filter: Record<string, any> = {} |
|
87
|
) => |
|
88
|
Object.entries(filter).every(([field, expected]) => |
|
89
|
Array.isArray(expected) |
|
90
|
? expected.includes(row[field]) |
|
91
|
: row[field] === expected |
|
92
|
) |
|
93
|
|
|
94
|
const syncService = { |
|
95
|
list: jest.fn(async (filter: any = {}, config: any = {}) => { |
|
96
|
const found = syncs |
|
97
|
.filter((row) => matches(row, filter)) |
|
98
|
.sort((a, b) => b.sequence - a.sequence) |
|
99
|
|
|
100
|
return config.take ? found.slice(0, config.take) : found |
|
101
|
}), |
|
102
|
create: jest.fn(async (data: Partial<SearchIndexSyncRecord>[]) => { |
|
103
|
const created = data.map((values) => ({ |
|
104
|
id: `sync_${syncs.length + 1}`, |
|
105
|
documents_synced: 0, |
|
106
|
last_key: null, |
|
107
|
completed_at: null, |
|
108
|
error: null, |
|
109
|
sequence: ++sequence, |
|
110
|
...values, |
|
111
|
})) as (SearchIndexSyncRecord & { sequence: number })[] |
|
112
|
|
|
113
|
syncs.push(...created) |
|
114
|
return created |
|
115
|
}), |
|
116
|
update: jest.fn(async ({ selector, data }: any) => { |
|
117
|
syncs |
|
118
|
.filter((row) => matches(row, selector)) |
|
119
|
.forEach((row) => Object.assign(row, data)) |
|
120
|
}), |
|
121
|
} |
|
122
|
|
|
123
|
let versionSequence = versions.length |
|
124
|
|
|
125
|
const versionService = { |
|
126
|
list: jest.fn(async (filter: any = {}, config: any = {}) => { |
|
127
|
const found = versions.filter((version) => |
|
128
|
matches(version as any, filter) |
|
129
|
) |
|
130
|
|
|
131
|
if (config.order?.version === "DESC") { |
|
132
|
found.sort((a, b) => b.version - a.version) |
|
133
|
} |
|
134
|
|
|
135
|
return config.take ? found.slice(0, config.take) : found |
|
136
|
}), |
|
137
|
create: jest.fn(async (data: Partial<SearchIndexVersionRecord>[]) => { |
|
138
|
const created = data.map((values) => ({ |
|
139
|
id: `ver_${++versionSequence}`, |
|
140
|
...values, |
|
141
|
})) as SearchIndexVersionRecord[] |
|
142
|
|
|
143
|
versions.push(...created) |
|
144
|
return created |
|
145
|
}), |
|
146
|
update: jest.fn(async ({ selector, data }: any) => { |
|
147
|
versions |
|
148
|
.filter((version) => matches(version as any, selector)) |
|
149
|
.forEach((version) => Object.assign(version, data)) |
|
150
|
}), |
|
151
|
softDelete: jest.fn(async (ids: string[]) => { |
|
152
|
for (const id of ids) { |
|
153
|
const position = versions.findIndex((version) => version.id === id) |
|
154
|
|
|
155
|
if (position >= 0) { |
|
156
|
versions.splice(position, 1) |
|
157
|
} |
|
158
|
} |
|
159
|
}), |
|
160
|
} |
|
161
|
|
|
162
|
const indexService = { |
|
163
|
list: jest.fn(async (filter: any = {}) => |
|
164
|
records.filter((record) => matches(record as any, filter)) |
|
165
|
), |
|
166
|
update: jest.fn(async ({ selector, data }: any) => { |
|
167
|
records |
|
168
|
.filter((record) => matches(record as any, selector)) |
|
169
|
.forEach((record) => Object.assign(record, data)) |
|
170
|
}), |
|
171
|
} |
|
172
|
|
|
173
|
const provider = { |
|
174
|
identifier: "test", |
|
175
|
upsertDocuments: |
|
176
|
upsertDocuments ?? |
|
177
|
jest.fn().mockResolvedValue({ index: "x", status: "succeeded" }), |
|
178
|
deleteDocuments: |
|
179
|
deleteDocuments ?? |
|
180
|
jest.fn().mockResolvedValue({ index: "x", status: "succeeded" }), |
|
181
|
clearIndex: jest |
|
182
|
.fn() |
|
183
|
.mockResolvedValue({ index: "x", status: "succeeded" }), |
|
184
|
upsertIndex: jest.fn().mockResolvedValue(undefined), |
|
185
|
deleteIndex: jest |
|
186
|
.fn() |
|
187
|
.mockResolvedValue({ index: "x", status: "succeeded" }), |
|
188
|
listIndexes: jest.fn().mockResolvedValue( |
|
189
|
Object.entries(documentCounts ?? {}).map(([name, document_count]) => ({ |
|
190
|
name, |
|
191
|
document_count, |
|
192
|
})) |
|
193
|
), |
|
194
|
} |
|
195
|
|
|
196
|
const logger = { |
|
197
|
info: jest.fn(), |
|
198
|
warn: jest.fn(), |
|
199
|
error: jest.fn(), |
|
200
|
} |
|
201
|
|
|
202
|
return { |
|
203
|
container: {} as any, |
|
204
|
logger: logger as any, |
|
205
|
options: { reindex: { batch_size: 1 } }, |
|
206
|
indexes: new Map(indexes.map((index) => [index.name, index])), |
|
207
|
providers: { |
|
208
|
retrieve: (identifier: string) => { |
|
209
|
if (identifier !== "test") { |
|
210
|
throw new MedusaError( |
|
211
|
MedusaError.Types.NOT_FOUND, |
|
212
|
`not registered: ${identifier}` |
|
213
|
) |
|
214
|
} |
|
215
|
return provider as unknown as SearchTypes.ISearchProvider |
|
216
|
}, |
|
217
|
}, |
|
218
|
indexService: indexService as any, |
|
219
|
versionService: versionService as any, |
|
220
|
syncService: syncService as any, |
|
221
|
locking: locking as any, |
|
222
|
// Exposed for assertions rather than being part of the context. |
|
223
|
records, |
|
224
|
versions, |
|
225
|
syncs, |
|
226
|
provider, |
|
227
|
logger_: logger, |
|
228
|
} |
|
229
|
} |
|
230
|
|
|
231
|
const seedAction = ( |
|
232
|
index: string, |
|
233
|
version: SearchIndexVersionRecord |
|
234
|
): SearchIndexSeedAction => ({ |
|
235
|
index, |
|
236
|
target_version: version, |
|
237
|
swap: false, |
|
238
|
reason: "index_created", |
|
239
|
}) |
|
240
|
|
|
241
|
// Passes the job a signal it can abort, the way the Locking Module does. |
|
242
|
const lockingThatAborts = ( |
|
243
|
abortAfter: (abort: () => void) => void |
|
244
|
): { execute: jest.Mock } => ({ |
|
245
|
execute: jest.fn(async (_keys, job) => { |
|
246
|
const controller = new AbortController() |
|
247
|
abortAfter(() => controller.abort(new Error("Lost the lock"))) |
|
248
|
return await job(controller.signal) |
|
249
|
}), |
|
250
|
}) |
|
251
|
|
|
252
|
const passthroughLocking = (): { execute: jest.Mock } => ({ |
|
253
|
execute: jest.fn(async (_keys, job) => await job(undefined)), |
|
254
|
}) |
|
255
|
|
|
256
|
const streamOfFour = (cursors: (string | undefined)[]) => |
|
257
|
definition("product", async function* ({ catchup, last_key }: any) { |
|
258
|
if (catchup) { |
|
259
|
return |
|
260
|
} |
|
261
|
|
|
262
|
cursors.push(last_key) |
|
263
|
|
|
264
|
for (const id of ["1", "2", "3", "4"]) { |
|
265
|
if (last_key && id <= last_key) { |
|
266
|
continue |
|
267
|
} |
|
268
|
yield [{ action: "upsert", documents: [{ id }] }] |
|
269
|
} |
|
270
|
}) |
|
271
|
|
|
272
|
describe("search index seeding", () => { |
|
273
|
beforeEach(() => { |
|
274
|
jest.clearAllMocks() |
|
275
|
}) |
|
276
|
|
|
277
|
describe("when the seed loses its lock", () => { |
|
278
|
const runUntilLockLost = async () => { |
|
279
|
let abort: () => void |
|
280
|
|
|
281
|
const index = definition("product", async function* ({ catchup }) { |
|
282
|
if (catchup) { |
|
283
|
return |
|
284
|
} |
|
285
|
|
|
286
|
yield [{ action: "upsert", documents: [{ id: "1" }] }] |
|
287
|
abort!() |
|
288
|
yield [{ action: "upsert", documents: [{ id: "2" }] }] |
|
289
|
}) |
|
290
|
|
|
291
|
const context = buildContext({ |
|
292
|
indexes: [index], |
|
293
|
locking: lockingThatAborts((abortFn) => { |
|
294
|
abort = abortFn |
|
295
|
}), |
|
296
|
}) |
|
297
|
|
|
298
|
await executeSeedPlan(context as any, [ |
|
299
|
{ ...seedAction("product", context.versions[0]), swap: true }, |
|
300
|
]) |
|
301
|
|
|
302
|
return context |
|
303
|
} |
|
304
|
|
|
305
|
it("should stop writing documents", async () => { |
|
306
|
const context = await runUntilLockLost() |
|
307
|
|
|
308
|
expect(context.provider.upsertDocuments).toHaveBeenCalledTimes(1) |
|
309
|
expect(context.provider.upsertDocuments).toHaveBeenCalledWith( |
|
310
|
expect.objectContaining({ documents: [{ id: "1" }] }) |
|
311
|
) |
|
312
|
}) |
|
313
|
|
|
314
|
it("should stop advancing the sync it no longer owns", async () => { |
|
315
|
const context = await runUntilLockLost() |
|
316
|
const [ours] = context.syncs |
|
317
|
|
|
318
|
expect(ours.documents_synced).toBe(1) |
|
319
|
}) |
|
320
|
|
|
321
|
it("should not make the version it was filling active", async () => { |
|
322
|
const context = await runUntilLockLost() |
|
323
|
|
|
324
|
expect(context.indexService.update).not.toHaveBeenCalled() |
|
325
|
}) |
|
326
|
|
|
327
|
it("should leave the version to whoever holds the lock now", async () => { |
|
328
|
const context = await runUntilLockLost() |
|
329
|
|
|
330
|
// Neither ready (this run didn't finish it) nor error (it isn't broken, |
|
331
|
// and the instance that picked it up may already have finished). |
|
332
|
expect(context.versions[0].status).toEqual(SearchIndexState.BUILDING) |
|
333
|
}) |
|
334
|
|
|
335
|
it("should report it as a lost lock rather than a failure", async () => { |
|
336
|
const context = await runUntilLockLost() |
|
337
|
|
|
338
|
expect(context.logger_.warn).toHaveBeenCalledWith( |
|
339
|
expect.stringContaining('Seed of "product" lost its lock') |
|
340
|
) |
|
341
|
expect(context.logger_.error).not.toHaveBeenCalled() |
|
342
|
}) |
|
343
|
}) |
|
344
|
|
|
345
|
describe("an explicit reindex", () => { |
|
346
|
it("should take the same lock a startup seed takes", async () => { |
|
347
|
const index = definition("product", async function* () {}) |
|
348
|
const locking = passthroughLocking() |
|
349
|
const context = buildContext({ indexes: [index], locking }) |
|
350
|
|
|
351
|
await reindexIndexes(context as any, { strategy: "in_place" }) |
|
352
|
|
|
353
|
expect(locking.execute).toHaveBeenCalledWith( |
|
354
|
"search:seed:product", |
|
355
|
expect.any(Function) |
|
356
|
) |
|
357
|
}) |
|
358
|
}) |
|
359
|
|
|
360
|
describe("versions a reindex leaves behind", () => { |
|
361
|
const productIndex = () => |
|
362
|
definition("product", async function* ({ catchup }: any) { |
|
363
|
if (catchup) { |
|
364
|
return |
|
365
|
} |
|
366
|
|
|
367
|
yield [{ action: "upsert", documents: [{ id: "1" }] }] |
|
368
|
}) |
|
369
|
|
|
370
|
const deletedIndexes = (context: ReturnType<typeof buildContext>) => |
|
371
|
context.provider.deleteIndex.mock.calls.map(([call]) => call.index) |
|
372
|
|
|
373
|
const liveVersions = (context: ReturnType<typeof buildContext>) => |
|
374
|
context.versions.map((version) => version.version).sort((a, b) => a - b) |
|
375
|
|
|
376
|
const staleVersion = (version: number): SearchIndexVersionRecord => ({ |
|
377
|
id: `ver_old_${version}`, |
|
378
|
search_index_id: "idx_1", |
|
379
|
version, |
|
380
|
provider: "test", |
|
381
|
physical_name: `product_v${version}`, |
|
382
|
definition_hash: "abcdef0123456789abcdef0123456789", |
|
383
|
status: SearchIndexState.READY, |
|
384
|
}) |
|
385
|
|
|
386
|
// v1..v3 with v3 serving reads, the way earlier rebuilds leave it. |
|
387
|
const withHistory = () => { |
|
388
|
const context = buildContext({ |
|
389
|
indexes: [productIndex()], |
|
390
|
locking: passthroughLocking(), |
|
391
|
}) |
|
392
|
|
|
393
|
context.versions.push(staleVersion(2), staleVersion(3)) |
|
394
|
context.records[0].active_version = 3 |
|
395
|
|
|
396
|
return context |
|
397
|
} |
|
398
|
|
|
399
|
it("should drop everything below the active version before building the next one", async () => { |
|
400
|
const context = withHistory() |
|
401
|
|
|
402
|
await reindexIndexes(context as any, { index: "product" }) |
|
403
|
|
|
404
|
// Version 3 served reads throughout the rebuild, so only what sat under |
|
405
|
// it goes; version 4 is what the rebuild swapped in. |
|
406
|
expect(deletedIndexes(context)).toEqual(["product_v1", "product_v2"]) |
|
407
|
expect(liveVersions(context)).toEqual([3, 4]) |
|
408
|
expect(context.records[0].active_version).toBe(4) |
|
409
|
}) |
|
410
|
|
|
411
|
it("should never let more than the active version and its predecessor pile up", async () => { |
|
412
|
const context = withHistory() |
|
413
|
|
|
414
|
await reindexIndexes(context as any, { index: "product" }) |
|
415
|
await reindexIndexes(context as any, { index: "product" }) |
|
416
|
await reindexIndexes(context as any, { index: "product" }) |
|
417
|
|
|
418
|
// Three rebuilds, and what is left is the version serving reads plus the |
|
419
|
// one it took over from — not one version per run. |
|
420
|
expect(deletedIndexes(context)).toEqual([ |
|
421
|
"product_v1", |
|
422
|
"product_v2", |
|
423
|
"product_v3", |
|
424
|
"product_v4", |
|
425
|
]) |
|
426
|
expect(liveVersions(context)).toEqual([5, 6]) |
|
427
|
expect(context.records[0].active_version).toBe(6) |
|
428
|
}) |
|
429
|
|
|
430
|
it("should drop a rebuild that failed above the active version before building the next one", async () => { |
|
431
|
const context = withHistory() |
|
432
|
|
|
433
|
// A rebuild that failed before it could swap. The startup seed prefers |
|
434
|
// the newer version this reindex builds, so nothing would resume it. |
|
435
|
context.versions.push({ |
|
436
|
...staleVersion(4), |
|
437
|
status: SearchIndexState.ERROR, |
|
438
|
}) |
|
439
|
|
|
440
|
await reindexIndexes(context as any, { index: "product" }) |
|
441
|
|
|
442
|
expect(deletedIndexes(context)).toEqual([ |
|
443
|
"product_v1", |
|
444
|
"product_v2", |
|
445
|
"product_v4", |
|
446
|
]) |
|
447
|
expect(liveVersions(context)).toEqual([3, 5]) |
|
448
|
expect(context.records[0].active_version).toBe(5) |
|
449
|
}) |
|
450
|
|
|
451
|
it("should keep a version above the active one that nothing started filling", async () => { |
|
452
|
const context = withHistory() |
|
453
|
|
|
454
|
// What a migration leaves for the startup seed to fill. |
|
455
|
context.versions.push({ |
|
456
|
...staleVersion(4), |
|
457
|
status: SearchIndexState.PENDING, |
|
458
|
}) |
|
459
|
|
|
460
|
await reindexIndexes(context as any, { index: "product" }) |
|
461
|
|
|
462
|
// Swapping to version 5 is what makes it unreachable, and the cleanup |
|
463
|
// after the swap is what drops it. |
|
464
|
expect(deletedIndexes(context)).toEqual([ |
|
465
|
"product_v1", |
|
466
|
"product_v2", |
|
467
|
"product_v4", |
|
468
|
]) |
|
469
|
expect( |
|
470
|
context.provider.deleteIndex.mock.invocationCallOrder[2] |
|
471
|
).toBeGreaterThan(context.indexService.update.mock.invocationCallOrder[0]) |
|
472
|
expect(liveVersions(context)).toEqual([3, 5]) |
|
473
|
}) |
|
474
|
|
|
475
|
it("should clean up on an in-place reindex, which builds no new version", async () => { |
|
476
|
const context = withHistory() |
|
477
|
|
|
478
|
await reindexIndexes(context as any, { |
|
479
|
index: "product", |
|
480
|
strategy: "in_place", |
|
481
|
}) |
|
482
|
|
|
483
|
expect(deletedIndexes(context)).toEqual(["product_v1", "product_v2"]) |
|
484
|
expect(liveVersions(context)).toEqual([3]) |
|
485
|
expect(context.records[0].active_version).toBe(3) |
|
486
|
}) |
|
487
|
|
|
488
|
it("should rebuild even when an out-of-rotation version cannot be dropped", async () => { |
|
489
|
const context = withHistory() |
|
490
|
context.provider.deleteIndex.mockRejectedValueOnce( |
|
491
|
new Error("connection reset") |
|
492
|
) |
|
493
|
|
|
494
|
await reindexIndexes(context as any, { index: "product" }) |
|
495
|
|
|
496
|
expect(context.logger_.warn).toHaveBeenCalledWith( |
|
497
|
expect.stringContaining("connection reset") |
|
498
|
) |
|
499
|
// Version 1 kept its record, so the cleanup after the swap retried it. |
|
500
|
expect(deletedIndexes(context)).toEqual([ |
|
501
|
"product_v1", |
|
502
|
"product_v2", |
|
503
|
"product_v1", |
|
504
|
]) |
|
505
|
expect(liveVersions(context)).toEqual([3, 4]) |
|
506
|
expect(context.records[0].active_version).toBe(4) |
|
507
|
}) |
|
508
|
}) |
|
509
|
|
|
510
|
describe("when the lock cannot be acquired", () => { |
|
511
|
it("should skip the index without touching its records", async () => { |
|
512
|
const index = definition("product", async function* () {}) |
|
513
|
const context = buildContext({ |
|
514
|
indexes: [index], |
|
515
|
locking: { |
|
516
|
execute: jest |
|
517
|
.fn() |
|
518
|
.mockRejectedValue( |
|
519
|
new MedusaError( |
|
520
|
MedusaError.Types.CONFLICT, |
|
521
|
"Timed-out acquiring lock." |
|
522
|
) |
|
523
|
), |
|
524
|
}, |
|
525
|
}) |
|
526
|
|
|
527
|
await executeSeedPlan(context as any, [ |
|
528
|
seedAction("product", context.versions[0]), |
|
529
|
]) |
|
530
|
|
|
531
|
expect(context.logger_.info).toHaveBeenCalledWith( |
|
532
|
expect.stringContaining('Skipping seed of "product"') |
|
533
|
) |
|
534
|
expect(context.logger_.error).not.toHaveBeenCalled() |
|
535
|
expect(context.syncs).toHaveLength(0) |
|
536
|
expect(context.versions[0].status).toEqual(SearchIndexState.PENDING) |
|
537
|
}) |
|
538
|
}) |
|
539
|
|
|
540
|
describe("when a seed fails", () => { |
|
541
|
const runFailingSeed = async () => { |
|
542
|
const failing = definition("product", async function* () { |
|
543
|
yield [{ action: "upsert", documents: [{ id: "1" }] }] |
|
544
|
}) |
|
545
|
const healthy = definition("variant", async function* ({ catchup }) { |
|
546
|
if (catchup) { |
|
547
|
return |
|
548
|
} |
|
549
|
|
|
550
|
yield [{ action: "upsert", documents: [{ id: "2" }] }] |
|
551
|
}) |
|
552
|
|
|
553
|
const upsertDocuments = jest.fn(async ({ index }) => { |
|
554
|
if (index === "product_v1") { |
|
555
|
throw new Error("engine rejected the batch") |
|
556
|
} |
|
557
|
|
|
558
|
return { index, status: "succeeded" } |
|
559
|
}) |
|
560
|
|
|
561
|
const context = buildContext({ |
|
562
|
indexes: [failing, healthy], |
|
563
|
locking: passthroughLocking(), |
|
564
|
upsertDocuments, |
|
565
|
}) |
|
566
|
|
|
567
|
await executeSeedPlan(context as any, [ |
|
568
|
seedAction("product", context.versions[0]), |
|
569
|
seedAction("variant", context.versions[1]), |
|
570
|
]) |
|
571
|
|
|
572
|
return context |
|
573
|
} |
|
574
|
|
|
575
|
it("should report it as an error, not as a skipped index", async () => { |
|
576
|
const context = await runFailingSeed() |
|
577
|
|
|
578
|
expect(context.logger_.error).toHaveBeenCalledWith( |
|
579
|
expect.stringContaining('Failed to seed "product"'), |
|
580
|
expect.any(Error) |
|
581
|
) |
|
582
|
expect(context.logger_.info).not.toHaveBeenCalledWith( |
|
583
|
expect.stringContaining('Skipping seed of "product"') |
|
584
|
) |
|
585
|
}) |
|
586
|
|
|
587
|
it("should record the failure on the version and its sync", async () => { |
|
588
|
const context = await runFailingSeed() |
|
589
|
|
|
590
|
expect(context.versions[0].status).toEqual(SearchIndexState.ERROR) |
|
591
|
expect(context.syncs[0]).toMatchObject({ |
|
592
|
status: SearchSyncStatus.FAILED, |
|
593
|
error: "engine rejected the batch", |
|
594
|
}) |
|
595
|
}) |
|
596
|
|
|
597
|
it("should still seed the indexes after it", async () => { |
|
598
|
const context = await runFailingSeed() |
|
599
|
|
|
600
|
expect(context.versions[1].status).toEqual(SearchIndexState.READY) |
|
601
|
}) |
|
602
|
}) |
|
603
|
|
|
604
|
describe("a seed that keeps its lock throughout", () => { |
|
605
|
it("should fill the version, mark it ready and swap it in", async () => { |
|
606
|
const index = definition("product", async function* ({ catchup }) { |
|
607
|
if (catchup) { |
|
608
|
return |
|
609
|
} |
|
610
|
|
|
611
|
yield [{ action: "upsert", documents: [{ id: "1" }] }] |
|
612
|
yield [{ action: "upsert", documents: [{ id: "2" }] }] |
|
613
|
}) |
|
614
|
|
|
615
|
const context = buildContext({ |
|
616
|
indexes: [index], |
|
617
|
locking: passthroughLocking(), |
|
618
|
}) |
|
619
|
|
|
620
|
await executeSeedPlan(context as any, [ |
|
621
|
{ ...seedAction("product", context.versions[0]), swap: true }, |
|
622
|
]) |
|
623
|
|
|
624
|
expect(context.provider.upsertDocuments).toHaveBeenCalledTimes(2) |
|
625
|
expect(context.versions[0].status).toEqual(SearchIndexState.READY) |
|
626
|
expect(context.indexService.update).toHaveBeenCalledWith({ |
|
627
|
selector: { name: "product" }, |
|
628
|
data: { active_version: 1 }, |
|
629
|
}) |
|
630
|
expect(context.syncs[0]).toMatchObject({ |
|
631
|
status: SearchSyncStatus.DONE, |
|
632
|
documents_synced: 2, |
|
633
|
}) |
|
634
|
expect(context.logger_.error).not.toHaveBeenCalled() |
|
635
|
expect(context.logger_.warn).not.toHaveBeenCalled() |
|
636
|
}) |
|
637
|
}) |
|
638
|
|
|
639
|
describe("versions a startup seed leaves behind", () => { |
|
640
|
const pendingVersion = ( |
|
641
|
version: number, |
|
642
|
status = SearchIndexState.PENDING |
|
643
|
): SearchIndexVersionRecord => ({ |
|
644
|
id: `ver_${version}`, |
|
645
|
search_index_id: "idx_1", |
|
646
|
version, |
|
647
|
provider: "test", |
|
648
|
physical_name: `product_v${version}`, |
|
649
|
definition_hash: "abcdef0123456789abcdef0123456789", |
|
650
|
status, |
|
651
|
}) |
|
652
|
|
|
653
|
// v1 serves reads; migrations built v2 and v3 for definitions that changed |
|
654
|
// again before either was seeded. |
|
655
|
const withSkippedVersions = () => { |
|
656
|
const context = buildContext({ |
|
657
|
indexes: [ |
|
658
|
definition("product", async function* ({ catchup }: any) { |
|
659
|
if (catchup) { |
|
660
|
return |
|
661
|
} |
|
662
|
|
|
663
|
yield [{ action: "upsert", documents: [{ id: "1" }] }] |
|
664
|
}), |
|
665
|
], |
|
666
|
locking: passthroughLocking(), |
|
667
|
}) |
|
668
|
|
|
669
|
context.versions[0].status = SearchIndexState.READY |
|
670
|
context.records[0].active_version = 1 |
|
671
|
context.versions.push(pendingVersion(2), pendingVersion(3)) |
|
672
|
|
|
673
|
return context |
|
674
|
} |
|
675
|
|
|
676
|
it("should drop the versions it skipped once it swaps in the newest one", async () => { |
|
677
|
const context = withSkippedVersions() |
|
678
|
|
|
679
|
await executeSeedPlan( |
|
680
|
context as any, |
|
681
|
await createSeedPlan(context as any) |
|
682
|
) |
|
683
|
|
|
684
|
expect(context.records[0].active_version).toBe(3) |
|
685
|
expect( |
|
686
|
context.provider.deleteIndex.mock.calls.map(([call]) => call.index) |
|
687
|
).toEqual(["product_v2"]) |
|
688
|
// Version 1 served reads until the swap, so it stays until the next build. |
|
689
|
expect(context.versions.map((version) => version.version)).toEqual([1, 3]) |
|
690
|
}) |
|
691
|
|
|
692
|
it("should keep the swap when the cleanup after it fails", async () => { |
|
693
|
const context = withSkippedVersions() |
|
694
|
const list = context.versionService.list.getMockImplementation()! |
|
695
|
let calls = 0 |
|
696
|
context.versionService.list.mockImplementation(async (...args: any[]) => { |
|
697
|
// The seed plan reads the versions first; the cleanup reads them last. |
|
698
|
if (++calls > 1 && args[0]?.search_index_id) { |
|
699
|
throw new Error("connection reset") |
|
700
|
} |
|
701
|
return list(...args) |
|
702
|
}) |
|
703
|
|
|
704
|
await executeSeedPlan( |
|
705
|
context as any, |
|
706
|
await createSeedPlan(context as any) |
|
707
|
) |
|
708
|
|
|
709
|
expect(context.records[0].active_version).toBe(3) |
|
710
|
expect(context.versions[2].status).toEqual(SearchIndexState.READY) |
|
711
|
expect(context.logger_.warn).toHaveBeenCalledWith( |
|
712
|
expect.stringContaining("connection reset") |
|
713
|
) |
|
714
|
expect(context.logger_.error).not.toHaveBeenCalled() |
|
715
|
}) |
|
716
|
}) |
|
717
|
|
|
718
|
describe("picking up where a failed run stopped", () => { |
|
719
|
const ok = { index: "x", status: "succeeded" } |
|
720
|
|
|
721
|
const writtenIds = (upsertDocuments: jest.Mock) => |
|
722
|
upsertDocuments.mock.calls.map(([call]) => call.documents[0].id) |
|
723
|
|
|
724
|
it("should resume from the cursor after a document the engine rejected", async () => { |
|
725
|
const cursors: (string | undefined)[] = [] |
|
726
|
const upsertDocuments = jest |
|
727
|
.fn() |
|
728
|
.mockResolvedValueOnce(ok) |
|
729
|
.mockResolvedValueOnce(ok) |
|
730
|
.mockRejectedValueOnce( |
|
731
|
new Error('document IDs cannot exceed 64 bytes ("3")') |
|
732
|
) |
|
733
|
.mockResolvedValue(ok) |
|
734
|
|
|
735
|
const context = buildContext({ |
|
736
|
indexes: [streamOfFour(cursors)], |
|
737
|
upsertDocuments, |
|
738
|
locking: passthroughLocking(), |
|
739
|
}) |
|
740
|
const action = seedAction("product", context.versions[0]) |
|
741
|
|
|
742
|
await executeSeedPlan(context as any, [action]) |
|
743
|
|
|
744
|
expect(context.syncs[0]).toMatchObject({ |
|
745
|
status: SearchSyncStatus.FAILED, |
|
746
|
last_key: "2", |
|
747
|
resumable: true, |
|
748
|
}) |
|
749
|
expect(writtenIds(upsertDocuments)).toEqual(["1", "2", "3"]) |
|
750
|
|
|
751
|
await executeSeedPlan(context as any, [action]) |
|
752
|
|
|
753
|
// The second run is handed the cursor and writes only what is left. |
|
754
|
expect(cursors).toEqual([undefined, "2"]) |
|
755
|
expect(writtenIds(upsertDocuments)).toEqual(["1", "2", "3", "3", "4"]) |
|
756
|
expect(context.versions[0].status).toBe(SearchIndexState.READY) |
|
757
|
}) |
|
758
|
|
|
759
|
it("should count what the version took in across both runs", async () => { |
|
760
|
const cursors: (string | undefined)[] = [] |
|
761
|
const upsertDocuments = jest |
|
762
|
.fn() |
|
763
|
.mockResolvedValueOnce(ok) |
|
764
|
.mockResolvedValueOnce(ok) |
|
765
|
.mockRejectedValueOnce(new Error("engine rejected the batch")) |
|
766
|
.mockResolvedValue(ok) |
|
767
|
|
|
768
|
const context = buildContext({ |
|
769
|
indexes: [streamOfFour(cursors)], |
|
770
|
upsertDocuments, |
|
771
|
locking: passthroughLocking(), |
|
772
|
}) |
|
773
|
const action = seedAction("product", context.versions[0]) |
|
774
|
|
|
775
|
await executeSeedPlan(context as any, [action]) |
|
776
|
|
|
777
|
expect(context.syncs[0].documents_synced).toBe(2) |
|
778
|
|
|
779
|
await executeSeedPlan(context as any, [action]) |
|
780
|
|
|
781
|
// Two documents from the first run, two from the second — not the two |
|
782
|
// this run happened to write. |
|
783
|
expect(context.syncs[1]).toMatchObject({ |
|
784
|
status: SearchSyncStatus.DONE, |
|
785
|
documents_synced: 4, |
|
786
|
}) |
|
787
|
expect(context.logger_.info).toHaveBeenCalledWith( |
|
788
|
expect.stringContaining("4 documents in total") |
|
789
|
) |
|
790
|
}) |
|
791
|
|
|
792
|
it("should report only its own count when it started from nothing", async () => { |
|
793
|
const context = buildContext({ |
|
794
|
indexes: [streamOfFour([])], |
|
795
|
locking: passthroughLocking(), |
|
796
|
}) |
|
797
|
|
|
798
|
await executeSeedPlan(context as any, [ |
|
799
|
seedAction("product", context.versions[0]), |
|
800
|
]) |
|
801
|
|
|
802
|
expect(context.syncs[0].documents_synced).toBe(4) |
|
803
|
expect(context.logger_.info).not.toHaveBeenCalledWith( |
|
804
|
expect.stringContaining("in total") |
|
805
|
) |
|
806
|
}) |
|
807
|
|
|
808
|
it("should carry the cursor onto the run that picks it up", async () => { |
|
809
|
const cursors: (string | undefined)[] = [] |
|
810
|
const upsertDocuments = jest |
|
811
|
.fn() |
|
812
|
.mockResolvedValueOnce(ok) |
|
813
|
.mockRejectedValueOnce(new Error("engine rejected the batch")) |
|
814
|
.mockResolvedValue(ok) |
|
815
|
|
|
816
|
const context = buildContext({ |
|
817
|
indexes: [streamOfFour(cursors)], |
|
818
|
upsertDocuments, |
|
819
|
locking: passthroughLocking(), |
|
820
|
}) |
|
821
|
const action = seedAction("product", context.versions[0]) |
|
822
|
|
|
823
|
await executeSeedPlan(context as any, [action]) |
|
824
|
await executeSeedPlan(context as any, [action]) |
|
825
|
|
|
826
|
// The row the second run opened starts at the cursor the first one |
|
827
|
// reached, rather than at nothing. |
|
828
|
const [opened] = context.syncService.create.mock.calls[1][0] |
|
829
|
expect(opened).toMatchObject({ last_key: "1", resumable: true }) |
|
830
|
}) |
|
831
|
|
|
832
|
it("should resume a run that was interrupted rather than failed", async () => { |
|
833
|
const cursors: (string | undefined)[] = [] |
|
834
|
const upsertDocuments = jest.fn().mockResolvedValue(ok) |
|
835
|
const context = buildContext({ |
|
836
|
indexes: [streamOfFour(cursors)], |
|
837
|
upsertDocuments, |
|
838
|
locking: passthroughLocking(), |
|
839
|
}) |
|
840
|
|
|
841
|
// A killed process leaves its row open, the way a lost lock does. |
|
842
|
context.syncs.push({ |
|
843
|
id: "sync_interrupted", |
|
844
|
search_index_version_id: context.versions[0].id, |
|
845
|
status: SearchSyncStatus.PROCESSING, |
|
846
|
last_key: "3", |
|
847
|
resumable: true, |
|
848
|
documents_synced: 3, |
|
849
|
sequence: 99, |
|
850
|
} as any) |
|
851
|
|
|
852
|
await executeSeedPlan(context as any, [ |
|
853
|
seedAction("product", context.versions[0]), |
|
854
|
]) |
|
855
|
|
|
856
|
expect(cursors).toEqual(["3"]) |
|
857
|
expect(writtenIds(upsertDocuments)).toEqual(["4"]) |
|
858
|
expect( |
|
859
|
context.syncs.find((sync) => sync.id === "sync_interrupted")!.status |
|
860
|
).toBe(SearchSyncStatus.CANCELED) |
|
861
|
}) |
|
862
|
|
|
863
|
it("should start over when the failure was a delete the cursor cannot describe", async () => { |
|
864
|
const cursors: (string | undefined)[] = [] |
|
865
|
const index = definition( |
|
866
|
"product", |
|
867
|
async function* ({ catchup, last_key }: any) { |
|
868
|
if (catchup) { |
|
869
|
return |
|
870
|
} |
|
871
|
|
|
872
|
cursors.push(last_key) |
|
873
|
yield [{ action: "upsert", documents: [{ id: "1" }] }] |
|
874
|
yield [{ action: "delete", filters: { id: ["9"] } }] |
|
875
|
yield [{ action: "upsert", documents: [{ id: "2" }] }] |
|
876
|
} |
|
877
|
) |
|
878
|
|
|
879
|
const deleteDocuments = jest |
|
880
|
.fn() |
|
881
|
.mockRejectedValueOnce(new Error("engine refused the delete")) |
|
882
|
.mockResolvedValue(ok) |
|
883
|
|
|
884
|
const context = buildContext({ |
|
885
|
indexes: [index], |
|
886
|
deleteDocuments, |
|
887
|
locking: passthroughLocking(), |
|
888
|
}) |
|
889
|
const action = seedAction("product", context.versions[0]) |
|
890
|
|
|
891
|
await executeSeedPlan(context as any, [action]) |
|
892
|
|
|
893
|
expect(context.syncs[0]).toMatchObject({ |
|
894
|
status: SearchSyncStatus.FAILED, |
|
895
|
last_key: "1", |
|
896
|
resumable: false, |
|
897
|
}) |
|
898
|
expect(context.syncs[0].error).toContain("cannot be resumed") |
|
899
|
|
|
900
|
await executeSeedPlan(context as any, [action]) |
|
901
|
|
|
902
|
// A resumed stream would carry on past the delete and never apply it. |
|
903
|
expect(cursors).toEqual([undefined, undefined]) |
|
904
|
}) |
|
905
|
|
|
906
|
it("should start over when the stream finished and the run failed after it", async () => { |
|
907
|
const cursors: (string | undefined)[] = [] |
|
908
|
const index = definition( |
|
909
|
"product", |
|
910
|
async function* ({ catchup, last_key }: any) { |
|
911
|
if (catchup) { |
|
912
|
throw new Error("the catch-up query failed") |
|
913
|
} |
|
914
|
|
|
915
|
cursors.push(last_key) |
|
916
|
yield [{ action: "upsert", documents: [{ id: "1" }] }] |
|
917
|
yield [{ action: "upsert", documents: [{ id: "2" }] }] |
|
918
|
} |
|
919
|
) |
|
920
|
|
|
921
|
const context = buildContext({ |
|
922
|
indexes: [index], |
|
923
|
locking: passthroughLocking(), |
|
924
|
}) |
|
925
|
const action = seedAction("product", context.versions[0]) |
|
926
|
|
|
927
|
await executeSeedPlan(context as any, [action]) |
|
928
|
|
|
929
|
// The bulk stream ran out, so its cursor has nothing left to hand over — |
|
930
|
// and a fresh catch-up would only cover what changed since the new run |
|
931
|
// started, missing everything the failed one was meant to catch. |
|
932
|
expect(context.syncs[0]).toMatchObject({ |
|
933
|
status: SearchSyncStatus.FAILED, |
|
934
|
resumable: false, |
|
935
|
}) |
|
936
|
|
|
937
|
await executeSeedPlan(context as any, [action]) |
|
938
|
|
|
939
|
expect(cursors).toEqual([undefined, undefined]) |
|
940
|
}) |
|
941
|
|
|
942
|
it("should not hand the bulk pass's cursor to the catch-up pass", async () => { |
|
943
|
const catchupCursors: (string | undefined)[] = [] |
|
944
|
const index = definition( |
|
945
|
"product", |
|
946
|
async function* ({ catchup, last_key }: any) { |
|
947
|
if (catchup) { |
|
948
|
catchupCursors.push(last_key) |
|
949
|
return |
|
950
|
} |
|
951
|
|
|
952
|
yield [{ action: "upsert", documents: [{ id: "1" }] }] |
|
953
|
yield [{ action: "upsert", documents: [{ id: "2" }] }] |
|
954
|
} |
|
955
|
) |
|
956
|
|
|
957
|
const context = buildContext({ |
|
958
|
indexes: [index], |
|
959
|
locking: passthroughLocking(), |
|
960
|
}) |
|
961
|
|
|
962
|
await executeSeedPlan(context as any, [ |
|
963
|
seedAction("product", context.versions[0]), |
|
964
|
]) |
|
965
|
|
|
966
|
const [bulk, catchUp] = context.syncs |
|
967
|
|
|
968
|
expect(catchupCursors).toEqual([undefined]) |
|
969
|
// The catch-up walks its own stream, so it neither takes the bulk |
|
970
|
// pass's cursor nor supersedes its row. |
|
971
|
expect(catchUp).toMatchObject({ last_key: null, resumable: false }) |
|
972
|
expect(bulk.status).toBe(SearchSyncStatus.DONE) |
|
973
|
expect(context.syncService.update).not.toHaveBeenCalledWith( |
|
974
|
expect.objectContaining({ |
|
975
|
data: expect.objectContaining({ |
|
976
|
status: SearchSyncStatus.CANCELED, |
|
977
|
}), |
|
978
|
}) |
|
979
|
) |
|
980
|
}) |
|
981
|
|
|
982
|
it("should hand nothing over once a run has completed", async () => { |
|
983
|
const cursors: (string | undefined)[] = [] |
|
984
|
const context = buildContext({ |
|
985
|
indexes: [streamOfFour(cursors)], |
|
986
|
locking: passthroughLocking(), |
|
987
|
}) |
|
988
|
const action = seedAction("product", context.versions[0]) |
|
989
|
|
|
990
|
await executeSeedPlan(context as any, [action]) |
|
991
|
await executeSeedPlan(context as any, [action]) |
|
992
|
|
|
993
|
expect(cursors).toEqual([undefined, undefined]) |
|
994
|
}) |
|
995
|
|
|
996
|
it("should leave no cursor behind after a scoped reindex", async () => { |
|
997
|
const cursors: (string | undefined)[] = [] |
|
998
|
const context = buildContext({ |
|
999
|
indexes: [streamOfFour(cursors)], |
|
1000
|
locking: passthroughLocking(), |
|
1001
|
}) |
|
1002
|
|
|
1003
|
await reindexIndexes(context as any, { |
|
1004
|
index: "product", |
|
1005
|
filters: { status: "published" }, |
|
1006
|
strategy: "in_place", |
|
1007
|
}) |
|
1008
|
|
|
1009
|
expect(context.syncs[0]).toMatchObject({ |
|
1010
|
filters: { status: "published" }, |
|
1011
|
resumable: false, |
|
1012
|
}) |
|
1013
|
|
|
1014
|
// A slice of the index is not a position in the full stream, so a seed |
|
1015
|
// after it rebuilds rather than continuing from where it stopped. |
|
1016
|
await executeSeedPlan(context as any, [ |
|
1017
|
seedAction("product", context.versions[0]), |
|
1018
|
]) |
|
1019
|
|
|
1020
|
expect(cursors).toEqual([undefined, undefined]) |
|
1021
|
}) |
|
1022
|
}) |
|
1023
|
|
|
1024
|
describe("planning a rebuild after a failure", () => { |
|
1025
|
const index = () => |
|
1026
|
definition("product", async function* () { |
|
1027
|
yield [{ action: "upsert", documents: [{ id: "1" }] }] |
|
1028
|
}) |
|
1029
|
|
|
1030
|
const planFor = async (documentCounts: Record<string, number>) => { |
|
1031
|
const context = buildContext({ indexes: [index()], documentCounts }) |
|
1032
|
context.versions[0].status = SearchIndexState.ERROR |
|
1033
|
|
|
1034
|
return { context, plan: await createSeedPlan(context as any) } |
|
1035
|
} |
|
1036
|
|
|
1037
|
it("should continue an index that still holds what the failed run wrote", async () => { |
|
1038
|
const { plan } = await planFor({ product_v1: 1000 }) |
|
1039
|
|
|
1040
|
expect(plan).toEqual([ |
|
1041
|
expect.objectContaining({ |
|
1042
|
index: "product", |
|
1043
|
reason: "last_run_failed", |
|
1044
|
}), |
|
1045
|
]) |
|
1046
|
}) |
|
1047
|
|
|
1048
|
it("should rebuild an index that lost its data", async () => { |
|
1049
|
const { plan } = await planFor({ product_v1: 0 }) |
|
1050
|
|
|
1051
|
expect(plan).toEqual([ |
|
1052
|
expect.objectContaining({ index: "product", reason: "index_empty" }), |
|
1053
|
]) |
|
1054
|
}) |
|
1055
|
|
|
1056
|
it("should not resume into an index that lost its data", async () => { |
|
1057
|
const cursors: (string | undefined)[] = [] |
|
1058
|
const context = buildContext({ |
|
1059
|
indexes: [streamOfFour(cursors)], |
|
1060
|
locking: passthroughLocking(), |
|
1061
|
documentCounts: { product_v1: 0 }, |
|
1062
|
}) |
|
1063
|
|
|
1064
|
context.syncs.push({ |
|
1065
|
id: "sync_failed", |
|
1066
|
search_index_version_id: context.versions[0].id, |
|
1067
|
status: SearchSyncStatus.FAILED, |
|
1068
|
last_key: "3", |
|
1069
|
resumable: true, |
|
1070
|
documents_synced: 3, |
|
1071
|
sequence: 99, |
|
1072
|
} as any) |
|
1073
|
|
|
1074
|
await executeSeedPlan(context as any, [ |
|
1075
|
{ |
|
1076
|
...seedAction("product", context.versions[0]), |
|
1077
|
reason: "index_empty", |
|
1078
|
}, |
|
1079
|
]) |
|
1080
|
|
|
1081
|
expect(cursors).toEqual([undefined]) |
|
1082
|
}) |
|
1083
|
}) |
|
1084
|
|
|
1085
|
describe("when the engine rate limits the writes", () => { |
|
1086
|
// Cloud sends a `Retry-After` with its 429s, and the seed honours it — a |
|
1087
|
// zero wait is what keeps these tests from sitting through the backoff. |
|
1088
|
const rateLimited = () => |
|
1089
|
Object.assign(new Error("Too many requests"), { |
|
1090
|
status: 429, |
|
1091
|
type: "embedding_rate_limit", |
|
1092
|
retry_after: 0, |
|
1093
|
}) |
|
1094
|
|
|
1095
|
const twoDocuments = () => |
|
1096
|
definition("product", async function* ({ catchup }) { |
|
1097
|
if (catchup) { |
|
1098
|
return |
|
1099
|
} |
|
1100
|
|
|
1101
|
yield [{ action: "upsert", documents: [{ id: "1" }] }] |
|
1102
|
yield [{ action: "upsert", documents: [{ id: "2" }] }] |
|
1103
|
}) |
|
1104
|
|
|
1105
|
it("should wait out the rate limit and finish the seed", async () => { |
|
1106
|
const upsertDocuments = jest |
|
1107
|
.fn() |
|
1108
|
.mockRejectedValueOnce(rateLimited()) |
|
1109
|
.mockRejectedValueOnce(rateLimited()) |
|
1110
|
.mockResolvedValue({ index: "x", status: "succeeded" }) |
|
1111
|
|
|
1112
|
const context = buildContext({ |
|
1113
|
indexes: [twoDocuments()], |
|
1114
|
upsertDocuments, |
|
1115
|
locking: passthroughLocking(), |
|
1116
|
}) |
|
1117
|
|
|
1118
|
await executeSeedPlan(context as any, [ |
|
1119
|
seedAction("product", context.versions[0]), |
|
1120
|
]) |
|
1121
|
|
|
1122
|
expect(upsertDocuments).toHaveBeenCalledTimes(4) |
|
1123
|
expect(context.versions[0].status).toBe(SearchIndexState.READY) |
|
1124
|
|
|
1125
|
const [bulk] = context.syncs |
|
1126
|
expect(bulk.status).toBe(SearchSyncStatus.DONE) |
|
1127
|
expect(bulk.documents_synced).toBe(2) |
|
1128
|
expect(context.logger_.warn).toHaveBeenCalledWith( |
|
1129
|
expect.stringContaining("Rate limited") |
|
1130
|
) |
|
1131
|
}) |
|
1132
|
|
|
1133
|
it("should wait out a rate-limited delete before calling the run unresumable", async () => { |
|
1134
|
const index = definition("product", async function* ({ catchup }: any) { |
|
1135
|
if (catchup) { |
|
1136
|
return |
|
1137
|
} |
|
1138
|
|
|
1139
|
yield [{ action: "upsert", documents: [{ id: "1" }] }] |
|
1140
|
yield [{ action: "delete", filters: { id: ["9"] } }] |
|
1141
|
}) |
|
1142
|
|
|
1143
|
const deleteDocuments = jest |
|
1144
|
.fn() |
|
1145
|
.mockRejectedValueOnce(rateLimited()) |
|
1146
|
.mockRejectedValueOnce(rateLimited()) |
|
1147
|
.mockResolvedValue({ index: "x", status: "succeeded" }) |
|
1148
|
|
|
1149
|
const context = buildContext({ |
|
1150
|
indexes: [index], |
|
1151
|
deleteDocuments, |
|
1152
|
locking: passthroughLocking(), |
|
1153
|
}) |
|
1154
|
|
|
1155
|
await executeSeedPlan(context as any, [ |
|
1156
|
seedAction("product", context.versions[0]), |
|
1157
|
]) |
|
1158
|
|
|
1159
|
// A delete that cannot be resumed past is exactly the one worth waiting |
|
1160
|
// for, so the rate limit is ridden out before the run gives up on it. |
|
1161
|
expect(deleteDocuments).toHaveBeenCalledTimes(3) |
|
1162
|
expect(context.syncs[0]).toMatchObject({ |
|
1163
|
status: SearchSyncStatus.DONE, |
|
1164
|
resumable: false, |
|
1165
|
}) |
|
1166
|
expect(context.versions[0].status).toBe(SearchIndexState.READY) |
|
1167
|
}) |
|
1168
|
|
|
1169
|
it("should leave a run that gave up waiting resumable", async () => { |
|
1170
|
const cursors: (string | undefined)[] = [] |
|
1171
|
const upsertDocuments = jest |
|
1172
|
.fn() |
|
1173
|
.mockResolvedValueOnce({ index: "x", status: "succeeded" }) |
|
1174
|
.mockRejectedValueOnce(rateLimited()) |
|
1175
|
.mockRejectedValueOnce(rateLimited()) |
|
1176
|
.mockRejectedValueOnce(rateLimited()) |
|
1177
|
.mockRejectedValueOnce(rateLimited()) |
|
1178
|
.mockRejectedValueOnce(rateLimited()) |
|
1179
|
.mockRejectedValueOnce(rateLimited()) |
|
1180
|
.mockResolvedValue({ index: "x", status: "succeeded" }) |
|
1181
|
|
|
1182
|
const context = buildContext({ |
|
1183
|
indexes: [streamOfFour(cursors)], |
|
1184
|
upsertDocuments, |
|
1185
|
locking: passthroughLocking(), |
|
1186
|
}) |
|
1187
|
const action = seedAction("product", context.versions[0]) |
|
1188
|
|
|
1189
|
await executeSeedPlan(context as any, [action]) |
|
1190
|
|
|
1191
|
// Spending the retries is not the kind of failure that invalidates what |
|
1192
|
// was already written, so the cursor still stands. |
|
1193
|
expect(context.syncs[0]).toMatchObject({ |
|
1194
|
status: SearchSyncStatus.FAILED, |
|
1195
|
last_key: "1", |
|
1196
|
resumable: true, |
|
1197
|
}) |
|
1198
|
|
|
1199
|
await executeSeedPlan(context as any, [action]) |
|
1200
|
|
|
1201
|
expect(cursors).toEqual([undefined, "1"]) |
|
1202
|
expect(context.versions[0].status).toBe(SearchIndexState.READY) |
|
1203
|
}) |
|
1204
|
|
|
1205
|
it("should stop retrying when it no longer holds the lock", async () => { |
|
1206
|
let abort: () => void |
|
1207
|
const upsertDocuments = jest.fn(async () => { |
|
1208
|
// The lock goes to another instance while this batch is being |
|
1209
|
// rate limited. |
|
1210
|
abort!() |
|
1211
|
throw rateLimited() |
|
1212
|
}) |
|
1213
|
|
|
1214
|
const context = buildContext({ |
|
1215
|
indexes: [twoDocuments()], |
|
1216
|
upsertDocuments, |
|
1217
|
locking: lockingThatAborts((abortFn) => { |
|
1218
|
abort = abortFn |
|
1219
|
}), |
|
1220
|
}) |
|
1221
|
|
|
1222
|
await executeSeedPlan(context as any, [ |
|
1223
|
seedAction("product", context.versions[0]), |
|
1224
|
]) |
|
1225
|
|
|
1226
|
// Retried once, where the lock check that guards every attempt stopped |
|
1227
|
// it before it could write again. |
|
1228
|
expect(upsertDocuments).toHaveBeenCalledTimes(1) |
|
1229
|
// A run that lost its lock owns neither the version nor its syncs. |
|
1230
|
expect(context.versions[0].status).toBe(SearchIndexState.BUILDING) |
|
1231
|
expect(context.syncs[0].status).toBe(SearchSyncStatus.PROCESSING) |
|
1232
|
}) |
|
1233
|
}) |
|
1234
|
}) |