319 lines
9.5 KiB
TypeScript
319 lines
9.5 KiB
TypeScript
import {
|
|
asClass,
|
|
asFunction,
|
|
asValue,
|
|
createContainer,
|
|
InjectionMode,
|
|
type AwilixContainer,
|
|
} from 'awilix';
|
|
import type { BaseAppConfig as StockBotAppConfig, UnifiedAppConfig } from '@stock-bot/config';
|
|
import { toUnifiedConfig } from '@stock-bot/config';
|
|
import { HandlerRegistry } from '@stock-bot/handler-registry';
|
|
import type { QueueManagerDependencies } from '@stock-bot/queue';
|
|
import type { IServiceContainer } from '@stock-bot/services';
|
|
import { appConfigSchema, type AppConfig } from '../config/schemas';
|
|
import {
|
|
registerApplicationServices,
|
|
registerCacheServices,
|
|
registerCoreServices,
|
|
registerDatabaseServices,
|
|
} from '../registrations';
|
|
import { HandlerScanner } from '../scanner';
|
|
import { ServiceLifecycleManager } from '../utils/lifecycle';
|
|
import type { ContainerBuildOptions, ServiceDefinitions } from './types';
|
|
|
|
export interface ContainerRegistrationHelpers {
|
|
asClass: typeof asClass;
|
|
asFunction: typeof asFunction;
|
|
asValue: typeof asValue;
|
|
}
|
|
|
|
export type ContainerRegistrar = (
|
|
container: AwilixContainer<ServiceDefinitions>,
|
|
config: AppConfig,
|
|
helpers: ContainerRegistrationHelpers
|
|
) => void;
|
|
|
|
function extractMongoDatabaseFromUri(uri?: string): string | undefined {
|
|
const trimmed = uri?.trim();
|
|
if (!trimmed) {
|
|
return undefined;
|
|
}
|
|
|
|
const schemeMatch = /^mongodb(?:\+srv)?:\/\/(.*)$/i.exec(trimmed);
|
|
const rest = schemeMatch?.[1];
|
|
if (!rest) {
|
|
return undefined;
|
|
}
|
|
|
|
const delimiterMatch = /[/?#]/.exec(rest);
|
|
if (!delimiterMatch || delimiterMatch[0] !== '/') {
|
|
return undefined;
|
|
}
|
|
|
|
const pathPart = rest.slice(delimiterMatch.index).split(/[?#]/, 1)[0] ?? '';
|
|
const rawDb = pathPart.replace(/^\/+/, '').split('/')[0];
|
|
if (!rawDb) {
|
|
return undefined;
|
|
}
|
|
|
|
try {
|
|
return decodeURIComponent(rawDb);
|
|
} catch {
|
|
return rawDb;
|
|
}
|
|
}
|
|
|
|
function getInfluxPort(config: { influxPort?: number; ilpPort?: number }): number {
|
|
return config.influxPort ?? config.ilpPort ?? 9009;
|
|
}
|
|
|
|
export class ServiceContainerBuilder {
|
|
private config: Partial<AppConfig> = {};
|
|
private unifiedConfig: UnifiedAppConfig | null = null;
|
|
private customRegistrations: ContainerRegistrar[] = [];
|
|
private readonly deps?: { queueManagerDeps?: QueueManagerDependencies };
|
|
private options: ContainerBuildOptions = {
|
|
enableCache: true,
|
|
enableQueue: true,
|
|
enableMongoDB: true,
|
|
enablePostgres: true,
|
|
enableQuestDB: true,
|
|
enableBrowser: true,
|
|
enableProxy: true,
|
|
skipInitialization: false,
|
|
initializationTimeout: 30000,
|
|
};
|
|
|
|
constructor(deps?: { queueManagerDeps?: QueueManagerDependencies }) {
|
|
this.deps = deps;
|
|
}
|
|
|
|
withConfig(config: AppConfig | StockBotAppConfig | UnifiedAppConfig): this {
|
|
// Convert to unified config format
|
|
this.unifiedConfig = toUnifiedConfig(config);
|
|
this.config = this.transformStockBotConfig(this.unifiedConfig);
|
|
return this;
|
|
}
|
|
|
|
withOptions(options: Partial<ContainerBuildOptions>): this {
|
|
Object.assign(this.options, options);
|
|
return this;
|
|
}
|
|
|
|
withRegistrations(registrar: ContainerRegistrar): this {
|
|
this.customRegistrations.push(registrar);
|
|
return this;
|
|
}
|
|
|
|
enableService(
|
|
service: keyof Omit<ContainerBuildOptions, 'skipInitialization' | 'initializationTimeout'>,
|
|
enabled = true
|
|
): this {
|
|
this.options[service] = enabled;
|
|
return this;
|
|
}
|
|
|
|
skipInitialization(skip = true): this {
|
|
this.options.skipInitialization = skip;
|
|
return this;
|
|
}
|
|
|
|
async build(): Promise<AwilixContainer<ServiceDefinitions>> {
|
|
return (await this.buildOwned()).container;
|
|
}
|
|
|
|
/** Keep initialization and shutdown in one resource lifetime when the caller owns an app. */
|
|
async buildOwned() {
|
|
// Validate and prepare config
|
|
const validatedConfig = this.prepareConfig();
|
|
|
|
// Create container
|
|
const container = createContainer<ServiceDefinitions>({
|
|
injectionMode: InjectionMode.PROXY,
|
|
strict: true,
|
|
});
|
|
|
|
// Register services
|
|
this.registerServices(container, validatedConfig);
|
|
const helpers: ContainerRegistrationHelpers = { asClass, asFunction, asValue };
|
|
for (const registrar of this.customRegistrations) {
|
|
registrar(container, validatedConfig, helpers);
|
|
}
|
|
|
|
const lifecycleManager = new ServiceLifecycleManager();
|
|
// Initialize services if not skipped
|
|
if (!this.options.skipInitialization) {
|
|
await lifecycleManager.initializeServices(container, this.options.initializationTimeout);
|
|
}
|
|
|
|
let shutdown: Promise<void> | undefined;
|
|
return {
|
|
container,
|
|
shutdown: () =>
|
|
(shutdown ??= (async () => {
|
|
try {
|
|
await lifecycleManager.shutdownServices(container);
|
|
} finally {
|
|
await container.dispose();
|
|
}
|
|
})()),
|
|
};
|
|
}
|
|
|
|
private prepareConfig(): AppConfig {
|
|
const finalConfig = this.applyServiceOptions(this.config);
|
|
return appConfigSchema.parse(finalConfig);
|
|
}
|
|
|
|
private applyServiceOptions(config: Partial<AppConfig>) {
|
|
// Ensure questdb config has the right field names for DI
|
|
const questdbConfig = config.questdb
|
|
? {
|
|
...config.questdb,
|
|
influxPort: getInfluxPort(config.questdb),
|
|
}
|
|
: {
|
|
enabled: true,
|
|
host: 'localhost',
|
|
httpPort: 9000,
|
|
pgPort: 8812,
|
|
influxPort: 9009,
|
|
database: 'questdb',
|
|
};
|
|
|
|
return {
|
|
redis: {
|
|
...(config.redis || {
|
|
enabled: this.options.enableCache ?? true,
|
|
host: 'localhost',
|
|
port: 6379,
|
|
db: 0,
|
|
}),
|
|
enabled: this.options.enableCache !== false && (config.redis?.enabled ?? true),
|
|
},
|
|
mongodb: {
|
|
...(config.mongodb || {
|
|
enabled: this.options.enableMongoDB ?? true,
|
|
uri: 'mongodb://localhost:27017',
|
|
database: '',
|
|
}),
|
|
...(this.options.mongoReadOnly
|
|
? {
|
|
uri: config.mongodb?.readUri ?? config.mongodb?.uri ?? 'mongodb://localhost:27017',
|
|
database:
|
|
extractMongoDatabaseFromUri(config.mongodb?.readUri) ??
|
|
config.mongodb?.database ??
|
|
'',
|
|
readOnly: true,
|
|
}
|
|
: {}),
|
|
enabled: this.options.enableMongoDB !== false && (config.mongodb?.enabled ?? true),
|
|
},
|
|
postgres: {
|
|
...(config.postgres || {
|
|
enabled: this.options.enablePostgres ?? true,
|
|
host: 'localhost',
|
|
port: 5432,
|
|
database: 'postgres',
|
|
user: 'postgres',
|
|
password: 'postgres',
|
|
}),
|
|
enabled: this.options.enablePostgres !== false && (config.postgres?.enabled ?? true),
|
|
},
|
|
questdb: this.options.enableQuestDB ? questdbConfig : undefined,
|
|
proxy: this.options.enableProxy
|
|
? config.proxy || { enabled: false, cachePrefix: 'proxy:', ttl: 3600 }
|
|
: undefined,
|
|
browser: this.options.enableBrowser
|
|
? config.browser || { headless: true, timeout: 30000 }
|
|
: undefined,
|
|
queue: this.options.enableQueue
|
|
? config.queue || {
|
|
enabled: true,
|
|
workers: 1,
|
|
concurrency: 1,
|
|
enableScheduledJobs: false,
|
|
defaultJobOptions: {
|
|
attempts: 3,
|
|
backoff: { type: 'exponential' as const, delay: 1000 },
|
|
removeOnComplete: 100,
|
|
removeOnFail: 100,
|
|
},
|
|
}
|
|
: undefined,
|
|
service: config.service,
|
|
};
|
|
}
|
|
|
|
private registerServices(
|
|
container: AwilixContainer<ServiceDefinitions>,
|
|
config: AppConfig
|
|
): void {
|
|
// Register handler infrastructure first
|
|
container.register({
|
|
handlerRegistry: asClass(HandlerRegistry).singleton(),
|
|
handlerScanner: asFunction(({ handlerRegistry }) => {
|
|
return new HandlerScanner(handlerRegistry, container, {
|
|
serviceName: config.service?.serviceName || config.service?.name,
|
|
autoRegister: true,
|
|
});
|
|
}).singleton(),
|
|
});
|
|
|
|
registerCoreServices(container, config);
|
|
registerCacheServices(container, config);
|
|
registerDatabaseServices(container, config);
|
|
registerApplicationServices(container, config, {
|
|
delayWorkerStart: this.options.delayWorkerStart ?? false,
|
|
queueManagerDeps: this.deps?.queueManagerDeps,
|
|
});
|
|
|
|
// Register service container aggregate
|
|
container.register({
|
|
serviceContainer: asFunction<IServiceContainer>(
|
|
({
|
|
config: _config,
|
|
logger,
|
|
cache,
|
|
globalCache,
|
|
proxyManager,
|
|
browser,
|
|
queueManager,
|
|
mongoClient,
|
|
postgresClient,
|
|
questdbClient,
|
|
}: ServiceDefinitions) => ({
|
|
logger,
|
|
cache,
|
|
globalCache,
|
|
proxy: proxyManager, // Map proxyManager to proxy
|
|
browser,
|
|
queueManager, // Provide queueManager directly
|
|
mongodb: mongoClient, // Map mongoClient to mongodb
|
|
postgres: postgresClient, // Map postgresClient to postgres
|
|
questdb: questdbClient, // Map questdbClient to questdb
|
|
})
|
|
).singleton(),
|
|
});
|
|
}
|
|
|
|
private transformStockBotConfig(config: UnifiedAppConfig): Partial<AppConfig> {
|
|
// Keep the schema-normalized values intact; only the legacy port name
|
|
// differs at this adapter boundary.
|
|
const questdb = config.questdb
|
|
? { ...config.questdb, influxPort: getInfluxPort(config.questdb) }
|
|
: undefined;
|
|
|
|
return {
|
|
redis: config.redis,
|
|
mongodb: config.mongodb,
|
|
postgres: config.postgres,
|
|
questdb,
|
|
queue: config.queue,
|
|
browser: config.browser,
|
|
proxy: config.proxy,
|
|
service: config.service,
|
|
};
|
|
}
|
|
}
|