stock-bot/libs/core/di/src/utils/lifecycle.ts

134 lines
4.8 KiB
TypeScript

import type { AwilixContainer } from 'awilix';
import { getLogger } from '@stock-bot/logger';
import type { ServiceDefinitions } from '../container/types';
interface ServiceWithLifecycle {
connect?: () => Promise<void>;
disconnect?: () => Promise<void>;
close?: () => Promise<void>;
initialize?: () => Promise<void>;
shutdown?: () => Promise<void>;
}
export class ServiceLifecycleManager {
private readonly logger = getLogger('service-lifecycle');
private readonly services = [
{ name: 'cache', key: 'cache' as const },
{ name: 'mongoClient', key: 'mongoClient' as const },
{ name: 'postgresClient', key: 'postgresClient' as const },
{ name: 'questdbClient', key: 'questdbClient' as const },
{ name: 'proxyManager', key: 'proxyManager' as const },
{ name: 'queueManager', key: 'queueManager' as const },
];
async initializeServices(
container: AwilixContainer<ServiceDefinitions>,
timeout = 30000
): Promise<void> {
const started: { name: string; service: ServiceWithLifecycle; settled: boolean }[] = [];
const cancelTimers: (() => void)[] = [];
let failed = false;
try {
const work = this.services.map(async ({ name, key }) => {
const service = container.cradle[key] as ServiceWithLifecycle | null;
if (!service) {
return Promise.resolve();
}
const entry = { name, service, settled: false };
started.push(entry);
// A timeout cannot cancel connect(). Keep ownership until it settles,
// including resources allocated by an initializer that later rejects.
const initialization = this.initializeService(name, service).finally(async () => {
entry.settled = true;
if (failed) {
await this.cleanupOnce(name, service);
}
});
let timer: ReturnType<typeof setTimeout>;
const expired = new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new Error(`${name} initialization timed out after ${timeout}ms`)),
timeout
);
});
const clear = () => clearTimeout(timer);
cancelTimers.push(clear);
return Promise.race([initialization, expired]).finally(clear);
});
await Promise.all(work);
this.logger.info('All services initialized successfully');
} catch (error) {
failed = true;
// Only settled work can be released finally. Pending work retains the
// cleanup continuation above, so startup need not wait on a hung connect.
await Promise.allSettled(
started
.filter(entry => entry.settled)
.reverse()
.map(({ name, service }) => this.cleanupOnce(name, service))
);
throw error;
} finally {
for (const clear of cancelTimers) {
clear();
}
}
}
private readonly cleanup = new WeakMap<ServiceWithLifecycle, Promise<void>>();
private cleanupOnce(name: string, service: ServiceWithLifecycle): Promise<void> {
let work = this.cleanup.get(service);
if (!work) {
work = this.shutdownService(name, service);
this.cleanup.set(service, work);
}
return work;
}
async shutdownServices(container: AwilixContainer<ServiceDefinitions>): Promise<void> {
// Resolve and clean independently: one broken resolver must not prevent
// other, already connected resources from being released.
for (const { name, key } of [...this.services].reverse()) {
try {
const service = container.cradle[key] as ServiceWithLifecycle | null;
if (service) {
await this.cleanupOnce(name, service);
}
} catch (error) {
this.logger.error(`Error resolving ${name} during shutdown:`, error);
}
}
this.logger.info('All services shut down');
}
private async initializeService(name: string, service: ServiceWithLifecycle): Promise<void> {
try {
if (typeof service.connect === 'function') {
await service.connect();
this.logger.info(`${name} connected`);
} else if (typeof service.initialize === 'function') {
await service.initialize();
this.logger.info(`${name} initialized`);
}
} catch (error) {
this.logger.error(`Failed to initialize ${name}:`, error);
throw error;
}
}
private async shutdownService(name: string, service: ServiceWithLifecycle): Promise<void> {
try {
if (typeof service.disconnect === 'function') {
await service.disconnect();
} else if (typeof service.close === 'function') {
await service.close();
} else if (typeof service.shutdown === 'function') {
await service.shutdown();
}
this.logger.info(`${name} shut down`);
} catch (error) {
this.logger.error(`Error shutting down ${name}:`, error);
}
}
}