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
|
|
@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -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(),
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -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', {
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue