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

@ -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;
}
}
}