|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { describe, it, expect, vi } from 'vitest'; |
| 4 | +import { SeedLoaderService } from './seed-loader'; |
| 5 | +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; |
| 6 | + |
| 7 | +/** |
| 8 | + * framework#3150: the self-referencing seed path (`hasSelfRef`) writes records |
| 9 | + * sequentially via `writeRecord`, which — unlike the batched path (bulkWrite's |
| 10 | + * internal retry) and the update path — used to call `engine.insert` bare. A |
| 11 | + * single transient blip (`fetch failed`) therefore dropped the row with no |
| 12 | + * retry. These tests pin the now-wrapped behaviour. |
| 13 | + */ |
| 14 | + |
| 15 | +function createLogger() { |
| 16 | + return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; |
| 17 | +} |
| 18 | + |
| 19 | +function createFaithfulEngine(): { engine: IDataEngine; store: Record<string, any[]> } { |
| 20 | + const store: Record<string, any[]> = {}; |
| 21 | + let idCounter = 0; |
| 22 | + |
| 23 | + const engine = { |
| 24 | + find: vi.fn(async (objectName: string, query?: any) => { |
| 25 | + let records = store[objectName] || []; |
| 26 | + if (query?.where) { |
| 27 | + records = records.filter((r) => |
| 28 | + Object.entries(query.where).every(([k, v]) => r[k] === v), |
| 29 | + ); |
| 30 | + } |
| 31 | + if (typeof query?.limit === 'number') records = records.slice(0, query.limit); |
| 32 | + return records; |
| 33 | + }), |
| 34 | + findOne: vi.fn(async (objectName: string, query?: any) => { |
| 35 | + const rows = await (engine.find as any)(objectName, { ...query, limit: 1 }); |
| 36 | + return rows[0] ?? null; |
| 37 | + }), |
| 38 | + insert: vi.fn(async (objectName: string, data: any) => { |
| 39 | + if (!store[objectName]) store[objectName] = []; |
| 40 | + if (Array.isArray(data)) { |
| 41 | + const records = data.map((d) => ({ id: `gen-${++idCounter}`, ...d })); |
| 42 | + store[objectName].push(...records); |
| 43 | + return records; |
| 44 | + } |
| 45 | + const record = { id: `gen-${++idCounter}`, ...data }; |
| 46 | + store[objectName].push(record); |
| 47 | + return record; |
| 48 | + }), |
| 49 | + update: vi.fn(async (objectName: string, data: any) => { |
| 50 | + const records = store[objectName] || []; |
| 51 | + const idx = records.findIndex((r) => r.id === data.id); |
| 52 | + if (idx >= 0) { records[idx] = { ...records[idx], ...data }; return records[idx]; } |
| 53 | + return data; |
| 54 | + }), |
| 55 | + delete: vi.fn(async () => ({ deleted: 1 })), |
| 56 | + count: vi.fn(async (objectName: string) => (store[objectName] || []).length), |
| 57 | + aggregate: vi.fn(async () => []), |
| 58 | + } as unknown as IDataEngine; |
| 59 | + |
| 60 | + return { engine, store }; |
| 61 | +} |
| 62 | + |
| 63 | +// A self-referencing object: `manager` is a lookup back to the same object, so |
| 64 | +// the loader takes the historical sequential `writeRecord` path (`hasSelfRef`). |
| 65 | +function createMetadata(): IMetadataService { |
| 66 | + const objects: Record<string, any> = { |
| 67 | + my_app_employee: { |
| 68 | + name: 'my_app_employee', |
| 69 | + fields: { |
| 70 | + name: { type: 'text' }, |
| 71 | + manager: { type: 'lookup', reference: 'my_app_employee' }, |
| 72 | + }, |
| 73 | + }, |
| 74 | + }; |
| 75 | + return { |
| 76 | + getObject: vi.fn(async (name: string) => objects[name]), |
| 77 | + listObjects: vi.fn(async () => Object.values(objects)), |
| 78 | + register: vi.fn(async () => {}), |
| 79 | + get: vi.fn(async (_t: string, name: string) => objects[name]), |
| 80 | + list: vi.fn(async () => []), |
| 81 | + unregister: vi.fn(async () => {}), |
| 82 | + exists: vi.fn(async () => false), |
| 83 | + listNames: vi.fn(async () => []), |
| 84 | + } as unknown as IMetadataService; |
| 85 | +} |
| 86 | + |
| 87 | +const CONFIG = { |
| 88 | + dryRun: false, |
| 89 | + haltOnError: false, |
| 90 | + multiPass: true, |
| 91 | + defaultMode: 'insert', |
| 92 | + batchSize: 1000, |
| 93 | + transaction: false, |
| 94 | +} as any; |
| 95 | + |
| 96 | +const SEEDS = [ |
| 97 | + { |
| 98 | + object: 'my_app_employee', |
| 99 | + externalId: 'name', |
| 100 | + mode: 'insert', |
| 101 | + env: ['prod', 'dev', 'test'], |
| 102 | + records: [{ name: 'Alice' }, { name: 'Bob' }], |
| 103 | + }, |
| 104 | +] as any[]; |
| 105 | + |
| 106 | +describe('seed self-ref sequential path — transient retry (framework#3150)', () => { |
| 107 | + it('retries a transient insert on the self-referencing path instead of dropping the row', async () => { |
| 108 | + const { engine, store } = createFaithfulEngine(); |
| 109 | + const metadata = createMetadata(); |
| 110 | + |
| 111 | + // Bob's first insert hits a network blip, then succeeds on retry. |
| 112 | + const realInsert = (engine.insert as any).getMockImplementation(); |
| 113 | + let bobAttempts = 0; |
| 114 | + (engine.insert as any).mockImplementation(async (obj: string, data: any, opts: any) => { |
| 115 | + if (obj === 'my_app_employee' && !Array.isArray(data) && data.name === 'Bob') { |
| 116 | + bobAttempts++; |
| 117 | + if (bobAttempts === 1) throw new Error('fetch failed'); |
| 118 | + } |
| 119 | + return realInsert(obj, data, opts); |
| 120 | + }); |
| 121 | + |
| 122 | + const result = await new SeedLoaderService(engine, metadata, createLogger()).load({ |
| 123 | + seeds: SEEDS, |
| 124 | + config: CONFIG, |
| 125 | + }); |
| 126 | + |
| 127 | + expect(bobAttempts).toBe(2); // first threw, retried, succeeded |
| 128 | + expect(result.summary.totalErrored).toBe(0); |
| 129 | + expect((store.my_app_employee ?? []).map((r) => r.name).sort()).toEqual(['Alice', 'Bob']); |
| 130 | + }); |
| 131 | +}); |
0 commit comments