fix(ingestion): await container-owned handler initialization (CL27)

This commit is contained in:
Boki 2026-10-28 13:56:31 -04:00
parent cd1aa61481
commit 5c9e32d0ef
11 changed files with 424 additions and 317 deletions

View file

@ -43,27 +43,14 @@ import { createEODOperationRegistry } from './shared';
],
})
export class EodHandler extends BaseHandler<DataIngestionServices> {
static operationRegistry?: OperationRegistry;
public operationRegistry!: OperationRegistry;
constructor(services: IServiceContainer) {
super(resolveIngestionServices(services, 'eod'));
}
// Use pre-initialized registry if available, otherwise create new one
if (EodHandler.operationRegistry) {
this.operationRegistry = EodHandler.operationRegistry;
this.logger.info('Using pre-initialized EOD operation registry');
} else {
// Fallback: Initialize operation registry with EOD provider
createEODOperationRegistry(this.mongodb, this.logger)
.then(registry => {
this.operationRegistry = registry;
this.logger.info('EOD operation registry initialized successfully');
})
.catch(error => {
this.logger.error('Failed to initialize EOD operations', { error });
});
}
override async onInit(): Promise<void> {
this.operationRegistry = await createEODOperationRegistry(this.mongodb, this.logger);
}
/**

View file

@ -4,143 +4,39 @@ import type { HandlerInitializationContext } from '@stock-bot/di';
* Uses explicit imports for bundling compatibility
*/
import { getLogger } from '@stock-bot/logger';
import type { IServiceContainer } from '@stock-bot/services';
import type { DecoratedHandlerClass } from '@stock-bot/types';
import type { OperationRegistry } from '../shared/operation-manager';
// Import handlers explicitly for bundling (ensures they're included in the build)
// These imports trigger the decorator metadata to be set
import { CeoHandler } from './ceo/ceo.handler';
import { EodHandler } from './eod/eod.handler';
import { createEODOperationRegistry } from './eod/shared';
import { IbHandler } from './ib/ib.handler';
import { QMHandler } from './qm/qm.handler';
import { createQMOperationRegistry } from './qm/shared/operation-provider';
import { TeHandler } from './te/te.handler';
import { TradingViewHandler } from './tradingview/tradingview.handler';
import { TtHandler } from './tt/tt.handler';
import { WebShareHandler } from './webshare/webshare.handler';
// Add more handler imports as needed
const handlers = [
CeoHandler,
IbHandler,
QMHandler,
WebShareHandler,
TradingViewHandler,
TeHandler,
EodHandler,
TtHandler,
];
const logger = getLogger('handler-init');
// Global operation registries that handlers will reference
let eodOperationRegistry: OperationRegistry | undefined;
let qmOperationRegistry: OperationRegistry | undefined;
/**
* Initialize and register all handlers
* Note: The actual registration is now handled by the HandlerScanner in the DI container
* This function is kept for backward compatibility and explicit handler imports
*/
/** Register enabled handlers, then await their container-owned executing instances. */
export async function initializeAllHandlers(
serviceContainer: IServiceContainer,
context: HandlerInitializationContext
): Promise<void> {
try {
// Initialize operation registries first
logger.info('Initializing operation registries');
const mongodb = serviceContainer.mongodb;
const operationLogger = serviceContainer.logger;
// Create operation registries
try {
eodOperationRegistry = await createEODOperationRegistry(mongodb, operationLogger);
logger.info('EOD operation registry created');
// Attach to handler class so instances can access it
EodHandler.operationRegistry = eodOperationRegistry;
} catch (error) {
logger.error('Failed to create EOD operation registry', { error });
}
try {
qmOperationRegistry = await createQMOperationRegistry(mongodb, operationLogger);
logger.info('QM operation registry created');
// Attach to handler class so instances can access it
QMHandler.operationRegistry = qmOperationRegistry;
} catch (error) {
logger.error('Failed to create QM operation registry', { error });
}
// The HandlerScanner in the DI container will handle the actual registration
// We just need to ensure handlers are imported so their decorators run
const handlers = [
CeoHandler,
IbHandler,
QMHandler,
WebShareHandler,
TradingViewHandler,
TeHandler,
EodHandler,
TtHandler,
];
logger.info('Handler imports loaded', {
count: handlers.length,
handlers: handlers.map(h => (h as DecoratedHandlerClass).__handlerName || h.name),
});
// Log what metadata the handlers have
for (const HandlerClass of handlers) {
const metadata = HandlerClass.extractMetadata();
logger.info(`Handler ${HandlerClass.name} metadata`, {
hasMetadata: !!metadata,
handlerName: metadata?.name,
operationCount: metadata?.operations?.length || 0,
scheduledJobCount: metadata?.scheduledJobs?.length || 0,
});
}
// Get the DI container from the service container
const diContainer = context;
if (diContainer) {
// Get handler scanner from DI container
const scanner = context.handlerScanner;
if (scanner?.registerHandlerClass) {
for (const HandlerClass of handlers) {
scanner.registerHandlerClass(HandlerClass, { serviceName: 'data-ingestion' });
}
logger.info('Handlers registered with scanner');
} else {
logger.warn('Handler scanner not found or missing registerHandlerClass method');
}
// Also check the handler registry directly
const handlerRegistry = context.handlerRegistry;
if (handlerRegistry) {
logger.info('Handler registry state after registration', {
registeredHandlers: handlerRegistry.getHandlerNames(),
handlersWithSchedule: handlerRegistry.getAllHandlersWithSchedule().size,
});
// Initialize handlers that have onInit method
// We need to instantiate handlers and call their onInit
for (const HandlerClass of handlers) {
try {
// Create handler instance with service container
const handlerInstance = new HandlerClass(serviceContainer);
if (handlerInstance && typeof handlerInstance.onInit === 'function') {
const handlerName =
(HandlerClass as DecoratedHandlerClass).__handlerName || HandlerClass.name;
logger.info(`Calling onInit for handler: ${handlerName}`);
await handlerInstance.onInit();
}
} catch (error) {
logger.error(`Failed to initialize handler ${HandlerClass.name}:`, error);
}
}
}
} else {
logger.error('Could not access DI container from service container');
}
} catch (error) {
logger.error('Handler initialization failed', { error });
throw error;
for (const HandlerClass of handlers) {
context.handlerScanner.registerHandlerClass(HandlerClass, { serviceName: 'data-ingestion' });
}
await context.handlerScanner.initializeHandlers();
serviceContainer.logger.info('Ingestion handlers initialized', {
handlers: context.handlerRegistry.getHandlerNames(),
});
}

View file

@ -31,26 +31,14 @@ import {
@Handler('qm')
@Disabled() // Disable by default, enable specific operations as needed
export class QMHandler extends BaseHandler<DataIngestionServices> {
static operationRegistry?: OperationRegistry;
public operationRegistry!: OperationRegistry;
constructor(services: IServiceContainer) {
super(resolveIngestionServices(services, 'qm')); // Handler name read from @Handler decorator
super(resolveIngestionServices(services, 'qm'));
}
// Use pre-initialized registry if available, otherwise create new one
if (QMHandler.operationRegistry) {
this.operationRegistry = QMHandler.operationRegistry;
this.logger.info('Using pre-initialized QM operation registry');
} else {
// Fallback: Initialize operation registry with QM provider
createQMOperationRegistry(this.mongodb, this.logger)
.then(registry => {
this.operationRegistry = registry;
})
.catch(error => {
this.logger.error('Failed to initialize QM operations', { error });
});
}
override async onInit(): Promise<void> {
this.operationRegistry = await createQMOperationRegistry(this.mongodb, this.logger);
}
/**

View file

@ -30,154 +30,129 @@ export class TeHandler extends BaseHandler<DataIngestionServices> {
override async onInit(): Promise<void> {
this.logger.info('Initializing TeHandler and creating indexes');
if (!this.mongodb) {
this.logger.warn('MongoDB not available, skipping index creation');
return;
// Create indexes for teUrls collection
const indexes: { indexSpec: IndexSpecification; options: CreateIndexesOptions }[] = [
// Compound index for finding URLs to crawl
{
indexSpec: { lastCrawled: 1, url: 1 },
options: {
name: 'crawl_status_idx',
background: true,
},
},
// Unique index on URL to prevent duplicates
{
indexSpec: { url: 1 },
options: {
name: 'url_unique_idx',
unique: true,
background: true,
},
},
// Index for finding URLs by symbol
{
indexSpec: { teSymbol: 1 },
options: {
name: 'symbol_idx',
sparse: true,
background: true,
},
},
// Index for skip reason filtering
{
indexSpec: { skipReason: 1 },
options: {
name: 'skip_reason_idx',
sparse: true,
background: true,
},
},
// Compound index for efficient batch queries
{
indexSpec: { lastCrawled: 1, skipReason: 1 },
options: {
name: 'batch_query_idx',
background: true,
},
},
// Index for finding URLs with chart data
{
indexSpec: { teChartUrl: 1 },
options: {
name: 'chart_url_idx',
sparse: true,
background: true,
},
},
// Index for data-scheduler: filter by teType + sort by lastDataFetch
{
indexSpec: { teType: 1, lastDataFetch: 1 },
options: {
name: 'data_fetch_schedule_idx',
background: true,
},
},
];
for (const index of indexes) {
await this.mongodb.createIndex('teUrls', index.indexSpec, index.options);
this.logger.info(`Created/verified index: ${index.options.name}`);
}
try {
// Create indexes for teUrls collection
const indexes: { indexSpec: IndexSpecification; options: CreateIndexesOptions }[] = [
// Compound index for finding URLs to crawl
{
indexSpec: { lastCrawled: 1, url: 1 },
options: {
name: 'crawl_status_idx',
background: true,
},
// Indexes for teData collection (one doc per symbol with data array)
const teDataIndexes: { indexSpec: IndexSpecification; options: CreateIndexesOptions }[] = [
{
indexSpec: { teSymbol: 1 },
options: {
name: 'symbol_unique_idx',
unique: true,
background: true,
},
// Unique index on URL to prevent duplicates
{
indexSpec: { url: 1 },
options: {
name: 'url_unique_idx',
unique: true,
background: true,
},
},
{
indexSpec: { country: 1, category: 1 },
options: {
name: 'country_category_idx',
background: true,
},
// Index for finding URLs by symbol
{
indexSpec: { teSymbol: 1 },
options: {
name: 'symbol_idx',
sparse: true,
background: true,
},
},
// Index for skip reason filtering
{
indexSpec: { skipReason: 1 },
options: {
name: 'skip_reason_idx',
sparse: true,
background: true,
},
},
// Compound index for efficient batch queries
{
indexSpec: { lastCrawled: 1, skipReason: 1 },
options: {
name: 'batch_query_idx',
background: true,
},
},
// Index for finding URLs with chart data
{
indexSpec: { teChartUrl: 1 },
options: {
name: 'chart_url_idx',
sparse: true,
background: true,
},
},
// Index for data-scheduler: filter by teType + sort by lastDataFetch
{
indexSpec: { teType: 1, lastDataFetch: 1 },
options: {
name: 'data_fetch_schedule_idx',
background: true,
},
},
];
},
];
for (const index of indexes) {
try {
await this.mongodb.createIndex('teUrls', index.indexSpec, index.options);
this.logger.info(`Created/verified index: ${index.options.name}`);
} catch (error) {
// Index might already exist, that's OK
this.logger.debug(`Index ${index.options.name} may already exist:`, { error });
}
}
// Indexes for teData collection (one doc per symbol with data array)
const teDataIndexes: { indexSpec: IndexSpecification; options: CreateIndexesOptions }[] = [
{
indexSpec: { teSymbol: 1 },
options: {
name: 'symbol_unique_idx',
unique: true,
background: true,
},
},
{
indexSpec: { country: 1, category: 1 },
options: {
name: 'country_category_idx',
background: true,
},
},
];
for (const index of teDataIndexes) {
try {
await this.mongodb.createIndex('teData', index.indexSpec, index.options);
this.logger.info(`Created/verified teData index: ${index.options.name}`);
} catch (error) {
this.logger.debug(`teData index ${index.options.name} may already exist:`, { error });
}
}
// Indexes for teMarketData collection
const teMarketDataIndexes: {
indexSpec: IndexSpecification;
options: CreateIndexesOptions;
}[] = [
{
indexSpec: { teSymbol: 1 },
options: {
name: 'symbol_unique_idx',
unique: true,
background: true,
},
},
{
indexSpec: { category: 1 },
options: {
name: 'category_idx',
background: true,
},
},
];
for (const index of teMarketDataIndexes) {
try {
await this.mongodb.createIndex('teMarketData', index.indexSpec, index.options);
this.logger.info(`Created/verified teMarketData index: ${index.options.name}`);
} catch (error) {
this.logger.debug(`teMarketData index ${index.options.name} may already exist:`, {
error,
});
}
}
// Check collection stats
const count = await this.mongodb.countDocuments('teUrls', {});
this.logger.info(`TeUrls collection has ${count} documents`);
} catch (error) {
this.logger.error('Error creating indexes for TeHandler:', error);
// Don't throw - allow handler to continue even if indexes fail
for (const index of teDataIndexes) {
await this.mongodb.createIndex('teData', index.indexSpec, index.options);
this.logger.info(`Created/verified teData index: ${index.options.name}`);
}
// Indexes for teMarketData collection
const teMarketDataIndexes: {
indexSpec: IndexSpecification;
options: CreateIndexesOptions;
}[] = [
{
indexSpec: { teSymbol: 1 },
options: {
name: 'symbol_unique_idx',
unique: true,
background: true,
},
},
{
indexSpec: { category: 1 },
options: {
name: 'category_idx',
background: true,
},
},
];
for (const index of teMarketDataIndexes) {
await this.mongodb.createIndex('teMarketData', index.indexSpec, index.options);
this.logger.info(`Created/verified teMarketData index: ${index.options.name}`);
}
// Check collection stats
const count = await this.mongodb.countDocuments('teUrls', {});
this.logger.info(`TeUrls collection has ${count} documents`);
}
@ScheduledOperation('te-countries', '0 0 * * 0', {

View file

@ -12,10 +12,6 @@ export class TtHandler extends BaseHandler<DataIngestionServices> {
}
override async onInit(): Promise<void> {
if (!this.mongodb) {
return;
}
const indexes: { indexSpec: IndexSpecification; options: CreateIndexesOptions }[] = [
{
indexSpec: { contract: 1, date: 1 },
@ -32,11 +28,7 @@ export class TtHandler extends BaseHandler<DataIngestionServices> {
];
for (const index of indexes) {
try {
await this.mongodb.createIndex('ttFutures', index.indexSpec, index.options);
} catch (error) {
this.logger.debug(`ttFutures index ${index.options.name} may already exist:`, { error });
}
await this.mongodb.createIndex('ttFutures', index.indexSpec, index.options);
}
}

View file

@ -13,3 +13,7 @@ Agents use root-reserved disjoint files in the integration worktree. Root alone
- **CL22:** Queue library tsc build passed; independent root queue-lifecycle and cache-ownership suites passed (see /tmp/stock-bot-cl22-root.log). Scoped lint/format passed. Pending payload ownership, drain behavior, and connection cleanup covered without service mutation.
- **CL23:** Independent root retired-backtest-api, catalog-backtest-contract and backtest-result-mapping suites: 16 passed, 125 assertions. Scoped lint/format passed. Regression verifies no writes on retired V1/implicit autostart, explicit save-only behavior and preserved historical read/cancellation.
- **CL27:** Root rebuilt DI and independently ran ingestion-handler-initialization: 6 passed, 27 assertions. Enabled-instance identity, two-container isolation, failure propagation, operations waiting for init, unchanged schedules and duplicate registration covered. Scoped lint/format passed.
- **CL34:** Independent provider normalization suite: 6 passed, 10 assertions. Disposable PostgreSQL pipeline safety: 8 passed, 28 assertions, including verified mapping preservation, unverified update and replay identity. Scoped lint/format passed; active QM session manager preserved.

View file

@ -1,6 +1,6 @@
# Canonical development backlog
**Active: E13 architecture cleanup, CL22–CL35 (3/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md).
**Active: E13 architecture cleanup, CL22–CL35 (5/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md).
**Current scheduled backlog: 99/99 complete.** The owner resumed performance and authorized review of all seven conditions. P08 and O02 are implemented; five optional extensions remain deliberately deferred, and four merged IDs are redirects. This is not a claim that all 108 retained IDs were implemented. [Decisions, measurements and validation](../conditional-review.md).

View file

@ -3777,7 +3777,7 @@
"complexity": "M",
"assignment": null,
"write_locks": ["CL23"],
"completed_commit": null,
"completed_commit": "cd1aa6148119ea364de52bcfb4cfa1bac8259ca9",
"blocker": null,
"release_gates": [],
"completion_evidence": "architecture-cleanup-execution.md",
@ -3846,7 +3846,7 @@
"epic": "E13",
"priority": "P1",
"severity": "High",
"status": "ready",
"status": "done",
"dependencies": [],
"decision_dependencies": [],
"task_file": "backlog/tasks/CL27.md",
@ -3856,7 +3856,9 @@
"completed_commit": null,
"blocker": null,
"release_gates": [],
"completion_evidence": "architecture-cleanup-execution.md"
"completion_evidence": "architecture-cleanup-execution.md",
"integration_state": "accepted",
"validation": "Root rebuilt DI and independently ran ingestion-handler-initialization: 6 passed, 27 assertions. Enabled-instance identity, two-container isolation, failure propagation, operations waiting for init, unchanged schedules and duplicate registration covered. Scoped lint/format passed."
},
{
"id": "CL28",
@ -3972,7 +3974,7 @@
"epic": "E13",
"priority": "P2",
"severity": "Medium",
"status": "ready",
"status": "done",
"dependencies": [],
"decision_dependencies": [],
"task_file": "backlog/tasks/CL34.md",
@ -3982,7 +3984,9 @@
"completed_commit": null,
"blocker": null,
"release_gates": [],
"completion_evidence": "architecture-cleanup-execution.md"
"completion_evidence": "architecture-cleanup-execution.md",
"integration_state": "accepted",
"validation": "Independent provider normalization suite: 6 passed, 10 assertions. Disposable PostgreSQL pipeline safety: 8 passed, 28 assertions, including verified mapping preservation, unverified update and replay identity. Scoped lint/format passed; active QM session manager preserved."
},
{
"id": "CL35",
@ -10387,7 +10391,7 @@
],
"work_policy": "Root integrates/commits reviewed tasks; agents own disjoint explicit files in the root integration worktree. Only root builds shared outputs and runs combined gates. No isolated native agent build claim.",
"first_wave": ["CL22", "CL23", "CL24"],
"completed": 3,
"last_verification": "Independent root retired-backtest-api, catalog-backtest-contract and backtest-result-mapping suites: 16 passed, 125 assertions. Scoped lint/format passed. Regression verifies no writes on retired V1/implicit autostart, explicit save-only behavior and preserved historical read/cancellation."
"completed": 5,
"last_verification": "Independent provider normalization suite: 6 passed, 10 assertions. Disposable PostgreSQL pipeline safety: 8 passed, 28 assertions, including verified mapping preservation, unverified update and replay identity. Scoped lint/format passed; active QM session manager preserved."
}
}

View file

@ -18,3 +18,7 @@ Two-container isolation, disabled providers, failure/order, instance identity, s
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
Root rebuilt DI and independently ran ingestion-handler-initialization: 6 passed, 27 assertions. Enabled-instance identity, two-container isolation, failure propagation, operations waiting for init, unchanged schedules and duplicate registration covered. Scoped lint/format passed.

View file

@ -27,6 +27,7 @@ export interface HandlerScannerOptions {
export class HandlerScanner {
private logger = getLogger('handler-scanner');
private discoveredHandlers = new Map<string, DecoratedHandlerClass>();
private initializations = new Map<string, Promise<IHandler>>();
constructor(
private registry: HandlerRegistry,
@ -120,6 +121,13 @@ export class HandlerScanner {
this.logger.debug('Skipping disabled handler', { handlerName });
return;
}
const existing = this.discoveredHandlers.get(handlerName);
if (existing === HandlerClass) {
return;
}
if (existing) {
throw new Error(`Handler '${handlerName}' is already registered with a different class`);
}
// Filter out disabled operations
const enabledOperations = operations.filter(op => {
@ -170,7 +178,7 @@ export class HandlerScanner {
const operationHandlers: Record<string, JobHandler> = {};
for (const op of enabledOperations) {
operationHandlers[op.name] = async (payload: unknown) => {
const handler = this.container.resolve<IHandler>(handlerName);
const handler = await this.initializeHandler(handlerName);
const context: ExecutionContext = {
type: 'queue',
metadata: { source: 'queue', timestamp: Date.now() },
@ -230,6 +238,30 @@ export class HandlerScanner {
return new Map(this.discoveredHandlers);
}
/** Initialize the same container-owned instances used by registered operations. */
async initializeHandlers(): Promise<void> {
for (const handlerName of this.discoveredHandlers.keys()) {
await this.initializeHandler(handlerName);
}
}
private initializeHandler(handlerName: string): Promise<IHandler> {
let initialization = this.initializations.get(handlerName);
if (!initialization) {
// Publish the promise before construction: a constructor can create queue
// workers, whose operations must wait for initialization to finish too.
initialization = Promise.resolve().then(async () => {
const handler = this.container.resolve<IHandler & { onInit?(): Promise<void> }>(
handlerName
);
await handler.onInit?.();
return handler;
});
this.initializations.set(handlerName, initialization);
}
return initialization;
}
/**
* Manually register a handler class
*/
@ -245,9 +277,10 @@ export class HandlerScanner {
this.options.serviceName = serviceName;
}
this.registerHandler(HandlerClass, HandlerClass.name, 'manual');
// Restore original service name
this.options.serviceName = originalServiceName;
try {
this.registerHandler(HandlerClass, HandlerClass.name, 'manual');
} finally {
this.options.serviceName = originalServiceName;
}
}
}

View 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');
});