import { asValue, type AwilixContainer } from 'awilix'; import { z } from 'zod'; import type { ServiceCradle as ServiceDefinitions } from '@stock-bot/di'; import { BacktestRunner } from './backtest/BacktestRunner'; import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRepository'; import { assertResearchConcurrency, ResearchBacktestPool } from './backtest/ResearchBacktestPool'; import { UnavailableBacktestRunRepository } from './backtest/run-repository'; import { RustBacktestAdapter } from './backtest/RustBacktestAdapter'; import type { PaperConfigurationInput, PaperRuntime } from '@stock-bot/stock-config/paper-runtime'; import { PostgresCanonicalExecutionRepository } from './execution/PostgresCanonicalExecutionRepository'; import { BacktestHandler } from './handlers/backtest/backtest.handler'; import { CanonicalPaperRuntime } from './paper/CanonicalPaperRuntime'; import { validatePaperConfiguration } from './paper/feed'; import { PaperDeploymentHost } from './paper/PaperDeploymentHost'; import { StorageService } from '@stock-bot/trading-runtime/historical-storage'; import { createBuiltinStrategy } from './strategies/canonical-builtins'; import { stopOrchestratorWork } from './runtime'; import type { OrchestratorServices as IServiceContainer } from './types'; export type OrchestratorRole = 'paper' | 'research-only'; export function assertSupportedComposition(role: OrchestratorRole, useRustEngine: boolean): void { if (role !== 'paper' && role !== 'research-only') { throw new Error('Unsupported runtime role: expected paper or research-only'); } if (typeof useRustEngine !== 'boolean') { throw new Error('Runtime useRustEngine option must be a boolean'); } if (!useRustEngine) { throw new Error('Legacy financial execution is retired; the canonical Rust engine is required'); } } /** Validate before opening resources as well as before registering runtime services. */ export function resolvePaperComposition( role: OrchestratorRole, canonicalInput?: PaperConfigurationInput, deploymentInput?: unknown ) { if ((canonicalInput !== undefined || deploymentInput !== undefined) && role !== 'paper') { throw new Error('Canonical paper configuration requires a paper composition'); } if (canonicalInput !== undefined && deploymentInput !== undefined) { throw new Error('Choose canonicalPaper or paperDeploymentHost, never two account owners'); } const canonicalPaper = canonicalInput === undefined ? undefined : validatePaperConfiguration(canonicalInput); if (canonicalPaper && canonicalPaper.version !== 1) { throw new Error('Promoted paper strategies require an explicitly reviewed deployment host'); } const paperDeploymentHost = deploymentInput === undefined ? undefined : z .object({ enabled: z.literal(true), deploymentId: z .string() .uuid() .transform(id => id.toLowerCase()) .optional(), }) .strict() .parse(deploymentInput); if (role === 'paper' && !canonicalPaper && !paperDeploymentHost) { throw new Error( 'Paper composition requires explicit canonicalPaper or paperDeploymentHost configuration; accounts are never migrated automatically' ); } return { canonicalPaper, paperDeploymentHost }; } /** * Register orchestrator-specific services in the DI container */ export async function registerOrchestratorServices( container: AwilixContainer, options: { role?: OrchestratorRole; initializeMode?: boolean; useRustEngine?: boolean; allowSyntheticData?: boolean; syntheticSeed?: number; nativeExecutionTimeoutMs?: number; maxConcurrent?: number; canonicalPaper?: PaperConfigurationInput; paperDeploymentHost?: { enabled: true; deploymentId?: string }; } = {} ): Promise { const role = options.role === undefined ? 'research-only' : options.role; const useRustEngine = options.useRustEngine === undefined ? true : options.useRustEngine; assertSupportedComposition(role, useRustEngine); const maxConcurrent = options.maxConcurrent === undefined ? 1 : options.maxConcurrent; assertResearchConcurrency(maxConcurrent); const { canonicalPaper, paperDeploymentHost } = resolvePaperComposition( role, options.canonicalPaper, options.paperDeploymentHost ); // Create a service adapter that provides the expected interface const services = container.resolve('serviceContainer') as IServiceContainer; const custom = services.custom ?? {}; if (!services.custom) { Object.defineProperty(services, 'custom', { value: custom, enumerable: true }); } if ( [ 'CanonicalPaperRuntime', 'PaperDeploymentHost', 'ModeManager', 'ExecutionService', 'MarketDataService', 'StrategyManager', 'PaperTradingManager', 'BacktestEngine', 'BacktestRunner', ].some(key => custom[key as keyof typeof custom] || container.hasRegistration(key)) ) { throw new Error('Canonical execution requires a fresh runtime composition'); } // Create storage service first as it's needed by other services const storageService = new StorageService( services.logger, services.mongodb, services.questdb || null, options ); if ((canonicalPaper || paperDeploymentHost) && !services.postgres) { throw new Error('Canonical paper requires durable PostgreSQL custody'); } const paper = canonicalPaper && services.postgres ? new CanonicalPaperRuntime({ repository: new PostgresCanonicalExecutionRepository(services.postgres), programs: canonicalPaper.strategies.map(createBuiltinStrategy), }) : undefined; const deploymentHost = paperDeploymentHost && services.postgres ? new PaperDeploymentHost({ database: services.postgres, repository: new PostgresCanonicalExecutionRepository(services.postgres), }) : undefined; const runner = new ResearchBacktestPool({ runners: Array.from( { length: maxConcurrent }, () => new BacktestRunner({ engine: new RustBacktestAdapter( { logger: services.logger }, { timeoutMs: options.nativeExecutionTimeoutMs } ), repository: services.postgres ? new PostgresBacktestRunRepository(services.postgres) : new UnavailableBacktestRunRepository(), logger: services.logger, }) ), logger: services.logger, }); // Both roles share canonical research. Only an explicitly configured paper // composition owns account custody; startup never activates it. Object.assign(custom, { StorageService: storageService, BacktestRunner: runner, ...(paper ? { CanonicalPaperRuntime: paper } : {}), ...(deploymentHost ? { PaperDeploymentHost: deploymentHost } : {}), }); const canonicalContainer = container as AwilixContainer< ServiceDefinitions & { StorageService: StorageService; CanonicalPaperRuntime: PaperRuntime; PaperDeploymentHost: PaperDeploymentHost; BacktestRunner: ResearchBacktestPool; orchestratorServices: IServiceContainer; } >; canonicalContainer.register({ StorageService: asValue(storageService), BacktestRunner: asValue(runner), orchestratorServices: asValue(services), ...(paper ? { CanonicalPaperRuntime: asValue(paper) } : {}), ...(deploymentHost ? { PaperDeploymentHost: asValue(deploymentHost) } : {}), }); container .resolve('handlerScanner') .registerHandlerClass(BacktestHandler, { serviceName: 'orchestrator' }); try { if (paper && canonicalPaper && options.initializeMode !== false) { await paper.initialize(canonicalPaper); } if (deploymentHost && paperDeploymentHost?.deploymentId && options.initializeMode !== false) { await deploymentHost.bind(paperDeploymentHost.deploymentId); } services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: maxConcurrent }); } catch (error) { await stopOrchestratorWork(services).catch(cleanupError => { services.logger.error('Orchestrator registration cleanup failed', { cleanupError }); }); throw error; } } // Kept only as an explicit diagnostic for obsolete integration code. export function getContainer(): IServiceContainer { throw new Error( 'Container should be accessed through ServiceApplication. Update your code to use dependency injection.' ); }