fix(ingestion): await container-owned handler initialization (CL27)
This commit is contained in:
parent
cd1aa61481
commit
5c9e32d0ef
11 changed files with 424 additions and 317 deletions
224
test/integration/ingestion-handler-initialization.test.ts
Normal file
224
test/integration/ingestion-handler-initialization.test.ts
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
|
||||
// Isolate logging mocks. Scanner, Awilix, ingestion handlers and operation registries
|
||||
// are real; no provider requests, databases, queues or browser processes are started.
|
||||
const harness = String.raw`
|
||||
import { mock } from 'bun:test';
|
||||
import { asValue, createContainer } from 'awilix';
|
||||
const logger = {info() {},debug() {},trace() {},warn() {},error() {}};
|
||||
mock.module('@stock-bot/logger', () => ({getLogger:()=>logger}));
|
||||
const {HandlerScanner} = await import('./libs/core/di/src/scanner/handler-scanner.ts');
|
||||
const {HandlerRegistry} = await import('./libs/core/handler-registry/src/registry.ts');
|
||||
function fixture(id, options = {}) {
|
||||
const indexes = [], updates = [], queues = new Map();
|
||||
const createIndex = async (collection, spec, settings) => {
|
||||
indexes.push({collection, spec, settings});
|
||||
if (options.failIndexes) throw new Error('fixture index failure');
|
||||
};
|
||||
const services = {id, logger, cache:{}, browser:{}, proxy:{},
|
||||
queueManager:{getQueue(name) { if (!queues.has(name)) queues.set(name, {}); return queues.get(name); }},
|
||||
mongodb:{createIndex, async countDocuments() {return 0;},
|
||||
collection(name) {return {createIndex:(spec, settings)=>createIndex(name,spec,settings)};},
|
||||
async updateOne(collection, filter) {updates.push({collection,filter}); return {matchedCount:1,modifiedCount:1};}
|
||||
}
|
||||
};
|
||||
const container = createContainer();
|
||||
container.register({serviceContainer:asValue(services)});
|
||||
const registry = new HandlerRegistry();
|
||||
const scanner = new HandlerScanner(registry, container, {serviceName:'data-ingestion'});
|
||||
return {services,container,registry,scanner,indexes,updates,queues,
|
||||
context:{handlerScanner:scanner,handlerRegistry:registry}};
|
||||
}
|
||||
const output = value => process.stdout.write('__handler_init__' + JSON.stringify(value) + '\n');
|
||||
`;
|
||||
|
||||
async function probe(source: string): Promise<Record<string, unknown>> {
|
||||
const child = Bun.spawn([process.execPath, '--no-env-file', '-e', harness + source], {
|
||||
stdout: 'pipe',
|
||||
stderr: 'pipe',
|
||||
});
|
||||
const [stdout, stderr, code] = await Promise.all([
|
||||
new Response(child.stdout).text(),
|
||||
new Response(child.stderr).text(),
|
||||
child.exited,
|
||||
]);
|
||||
if (code !== 0) {
|
||||
throw new Error(`Handler initialization probe failed: ${stderr}`);
|
||||
}
|
||||
const line = stdout.split('\n').find(value => value.startsWith('__handler_init__'));
|
||||
if (!line) {
|
||||
throw new Error('Handler initialization probe returned no evidence');
|
||||
}
|
||||
return JSON.parse(line.slice('__handler_init__'.length));
|
||||
}
|
||||
|
||||
test('ingestion initializes only enabled container instances once and retains schedules', async () => {
|
||||
const result = await probe(String.raw`
|
||||
const {initializeAllHandlers} = await import('./apps/stock/data-ingestion/src/handlers/index.ts');
|
||||
const f = fixture('one');
|
||||
await Promise.all([initializeAllHandlers(f.services, f.context), initializeAllHandlers(f.services, f.context)]);
|
||||
const instances = f.registry.getHandlerNames().map(name=>f.container.resolve(name));
|
||||
const indexCount = f.indexes.length;
|
||||
await initializeAllHandlers(f.services, f.context);
|
||||
output({handlers:f.registry.getHandlerNames(), queues:[...f.queues.keys()], indexCount,
|
||||
repeatedIndexCount:f.indexes.length, collections:[...new Set(f.indexes.map(i=>i.collection))],
|
||||
sameInstances:instances.every((instance,i)=>instance===f.container.resolve(f.registry.getHandlerNames()[i])),
|
||||
schedules:Object.fromEntries(f.registry.getHandlerNames().map(name=>[name,f.registry.getScheduledJobs(name).map(job=>({operation:job.operation,cron:job.cronPattern,immediately:job.immediately}))]))});
|
||||
`);
|
||||
expect(result.handlers).toEqual(['webshare', 'te', 'tt']);
|
||||
expect(result.queues).toEqual(['webshare', 'te', 'tt']);
|
||||
expect(result.indexCount).toBe(14);
|
||||
expect(result.repeatedIndexCount).toBe(14);
|
||||
expect(result.collections).toEqual(['teUrls', 'teData', 'teMarketData', 'ttFutures']);
|
||||
expect(result.sameInstances).toBe(true);
|
||||
expect(result.schedules).toEqual({
|
||||
webshare: [{ operation: 'fetch-proxies', cron: '0 */6 * * *', immediately: false }],
|
||||
te: [
|
||||
{ operation: 'te-countries', cron: '0 0 * * 0', immediately: true },
|
||||
{ operation: 'te-indicators', cron: '0 0 * * 0', immediately: true },
|
||||
{ operation: 'te-spider', cron: '* * * * *', immediately: true },
|
||||
{ operation: 'te-crawl-scheduler', cron: '*/5 * * * *', immediately: true },
|
||||
{ operation: 'te-data-scheduler', cron: '*/10 * * * *', immediately: true },
|
||||
{ operation: 'te-market-data-scheduler', cron: '*/10 * * * *', immediately: true },
|
||||
],
|
||||
tt: [{ operation: 'tt-import', cron: '0 0 * * 0', immediately: true }],
|
||||
});
|
||||
});
|
||||
|
||||
test('EOD and QM registries belong to the executing singleton in each container', async () => {
|
||||
const result = await probe(String.raw`
|
||||
const {EodHandler} = await import('./apps/stock/data-ingestion/src/handlers/eod/eod.handler.ts');
|
||||
const {QMHandler} = await import('./apps/stock/data-ingestion/src/handlers/qm/qm.handler.ts');
|
||||
class EnabledEod extends EodHandler {static __disabled=false;}
|
||||
class EnabledQM extends QMHandler {static __disabled=false;}
|
||||
const first = fixture('first'), second = fixture('second');
|
||||
for (const f of [first,second]) {
|
||||
f.scanner.registerHandlerClass(EnabledEod);
|
||||
f.scanner.registerHandlerClass(EnabledQM);
|
||||
f.container.resolve('eod'); f.container.resolve('qm');
|
||||
}
|
||||
const beforeInit = [first.indexes.length,second.indexes.length];
|
||||
await Promise.all([first.scanner.initializeHandlers(), second.scanner.initializeHandlers()]);
|
||||
const isolated = ['eod','qm'].every(name=>first.container.resolve(name).operationRegistry!==second.container.resolve(name).operationRegistry);
|
||||
for (const f of [first,second]) {
|
||||
for (const name of ['eod','qm']) {
|
||||
await f.container.resolve(name).operationRegistry.updateOperation(name, f.services.id, 'price_update', {status:'success'});
|
||||
}
|
||||
}
|
||||
const counts = [first.indexes.length,second.indexes.length];
|
||||
await Promise.all([first.scanner.initializeHandlers(), second.scanner.initializeHandlers()]);
|
||||
output({beforeInit, isolated, counts, repeatedCounts:[first.indexes.length,second.indexes.length],
|
||||
firstUpdates:first.updates,secondUpdates:second.updates,
|
||||
statics:['operationRegistry' in EodHandler,'operationRegistry' in QMHandler]});
|
||||
`);
|
||||
expect(result.beforeInit).toEqual([0, 0]);
|
||||
expect(result.isolated).toBe(true);
|
||||
expect(result.counts).toEqual(result.repeatedCounts);
|
||||
expect((result.counts as number[]).every(count => count > 0)).toBe(true);
|
||||
expect(result.firstUpdates).toEqual([
|
||||
{ collection: 'eodSymbols', filter: { eodSearchCode: 'first' } },
|
||||
{ collection: 'qmSymbols', filter: { qmSearchCode: 'first' } },
|
||||
]);
|
||||
expect(result.secondUpdates).toEqual([
|
||||
{ collection: 'eodSymbols', filter: { eodSearchCode: 'second' } },
|
||||
{ collection: 'qmSymbols', filter: { qmSearchCode: 'second' } },
|
||||
]);
|
||||
expect(result.statics).toEqual([false, false]);
|
||||
});
|
||||
|
||||
test('dispatch and repeated startup await initialization of the same executing instance', async () => {
|
||||
const result = await probe(String.raw`
|
||||
let release, entered;
|
||||
const gate = new Promise(resolve=>release=resolve), started = new Promise(resolve=>entered=resolve);
|
||||
let constructions=0, initializations=0, executions=0;
|
||||
class Handler {
|
||||
static __handlerName='fixture';
|
||||
static __operations=[{name:'run',method:'run'}];
|
||||
constructor(services) {this.services=services;constructions++;}
|
||||
async onInit() {initializations++;entered();await gate;this.ready=true;}
|
||||
async execute() {executions++;return {ready:this.ready,owner:this.services.id};}
|
||||
}
|
||||
const f = fixture('one');
|
||||
f.scanner.registerHandlerClass(Handler);
|
||||
const first=f.scanner.initializeHandlers();
|
||||
await started;
|
||||
f.scanner.registerHandlerClass(Handler);
|
||||
const operation=f.registry.getOperation('fixture','run')();
|
||||
const repeated=f.scanner.initializeHandlers();
|
||||
await Promise.resolve();
|
||||
const during={constructions,initializations,executions};
|
||||
release();
|
||||
const [,value]=await Promise.all([first,operation,repeated]);
|
||||
output({during,after:{constructions,initializations,executions},value,
|
||||
ready:f.container.resolve('fixture').ready});
|
||||
`);
|
||||
expect(result.during).toEqual({ constructions: 1, initializations: 1, executions: 0 });
|
||||
expect(result.after).toEqual({ constructions: 1, initializations: 1, executions: 1 });
|
||||
expect(result.value).toEqual({ ready: true, owner: 'one' });
|
||||
expect(result.ready).toBe(true);
|
||||
});
|
||||
|
||||
test('failed provider initialization rejects startup and dispatch without retrying or executing', async () => {
|
||||
const result = await probe(String.raw`
|
||||
const paths = ['eod','qm','te','tt'];
|
||||
const names = ['EodHandler','QMHandler','TeHandler','TtHandler'];
|
||||
const failures=[];
|
||||
for (let i=0;i<paths.length;i++) {
|
||||
const module=await import('./apps/stock/data-ingestion/src/handlers/'+paths[i]+'/'+paths[i]+'.handler.ts');
|
||||
class Enabled extends module[names[i]] {static __disabled=false;}
|
||||
const f=fixture(paths[i],{failIndexes:true});
|
||||
f.scanner.registerHandlerClass(Enabled);
|
||||
const operation=f.registry.getMetadata(paths[i]).operations[0].name;
|
||||
const settled=await Promise.allSettled([f.scanner.initializeHandlers(),f.registry.getOperation(paths[i],operation)({})]);
|
||||
const again=await Promise.allSettled([f.scanner.initializeHandlers()]);
|
||||
failures.push({handler:paths[i],errors:[...settled,...again].map(r=>r.status==='rejected'?r.reason.message:'unexpected success'),attempts:f.indexes.length});
|
||||
}
|
||||
output({failures});
|
||||
`);
|
||||
expect(result.failures).toEqual(
|
||||
['eod', 'qm', 'te', 'tt'].map(handler => ({
|
||||
handler,
|
||||
errors: ['fixture index failure', 'fixture index failure', 'fixture index failure'],
|
||||
attempts: 1,
|
||||
}))
|
||||
);
|
||||
});
|
||||
|
||||
test('ingestion startup propagates failure before later handlers or schedules can initialize', async () => {
|
||||
const result = await probe(String.raw`
|
||||
const {initializeAllHandlers} = await import('./apps/stock/data-ingestion/src/handlers/index.ts');
|
||||
const f=fixture('failed',{failIndexes:true});
|
||||
let error;
|
||||
try {await initializeAllHandlers(f.services,f.context);} catch (failure) {error=failure.message;}
|
||||
output({error,queues:[...f.queues.keys()],indexes:f.indexes.length,ttResolved:f.container.cache.has('tt')});
|
||||
`);
|
||||
expect(result.error).toBe('fixture index failure');
|
||||
expect(result.queues).toEqual(['webshare', 'te']);
|
||||
expect(result.indexes).toBe(1);
|
||||
expect(result.ttResolved).toBe(false);
|
||||
});
|
||||
|
||||
test('conflicting registration cannot replace an initialized singleton or leak service ownership', async () => {
|
||||
const result = await probe(String.raw`
|
||||
class Handler {
|
||||
static __handlerName='fixture';
|
||||
static __operations=[{name:'run',method:'run'}];
|
||||
async execute() {return 'original';}
|
||||
}
|
||||
class Conflict extends Handler {}
|
||||
class Next extends Handler {static __handlerName='next';}
|
||||
const f=fixture('one');
|
||||
f.scanner.registerHandlerClass(Handler);
|
||||
await f.scanner.initializeHandlers();
|
||||
const instance=f.container.resolve('fixture');
|
||||
let error;
|
||||
try {f.scanner.registerHandlerClass(Conflict,{serviceName:'other'});} catch(failure) {error=failure.message;}
|
||||
f.scanner.registerHandlerClass(Next);
|
||||
output({error,same:instance===f.container.resolve('fixture'),
|
||||
result:await f.registry.getOperation('fixture','run')(),service:f.registry.getHandlerService('next')});
|
||||
`);
|
||||
expect(result.error).toBe("Handler 'fixture' is already registered with a different class");
|
||||
expect(result.same).toBe(true);
|
||||
expect(result.result).toBe('original');
|
||||
expect(result.service).toBe('data-ingestion');
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue