import { asFunction, asValue, createContainer as createDiContainer } from 'awilix'; import { afterEach, describe, expect, test } from 'bun:test'; import { ServiceContainerBuilder, type ServiceCradle } from '@stock-bot/di'; import type { StockAppConfig } from '@stock-bot/stock-config'; import { stockAppSchema } from '../../apps/stock/config/src/schemas/stock-app.schema'; import { ResearchBacktestPool } from '../../apps/stock/orchestrator/src/backtest/ResearchBacktestPool'; import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container'; import { createRoutes } from '../../apps/stock/orchestrator/src/routes/create-routes'; import { createContainer } from '../../apps/stock/orchestrator/src/simple-container'; import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types'; import { logger } from '../fixtures/execution'; const cleanup: (() => Promise)[] = []; afterEach(async () => { for (const close of cleanup.splice(0).reverse()) { await close(); } }); async function compose( options: Parameters[1] = {}, queues?: unknown[] ) { const container = await new ServiceContainerBuilder() .withOptions({ enableCache: false, enableQueue: false, enableMongoDB: false, enablePostgres: false, enableQuestDB: false, enableBrowser: false, enableProxy: false, }) .build(); const services: OrchestratorServices = { logger }; if (queues) { Object.defineProperty(services, 'queueManager', { value: { getQueue: (name: string, options: unknown) => queues.push({ name, options }) }, }); } container.register({ serviceContainer: asValue(services) }); await registerOrchestratorServices(container, options); cleanup.push(async () => { await services.custom!.BacktestRunner!.shutdown(); await container.dispose(); }); return { services, container }; } describe('canonical research-only default composition', () => { test.each(['paper', 'research-only'] as const)( '%s refuses retired TypeScript financial execution before resolving services', async role => { let resolved = 0; const container = createDiContainer(); container.register({ serviceContainer: asFunction(() => { resolved++; throw new Error('must not resolve'); }), }); await expect( registerOrchestratorServices(container, { role, useRustEngine: false }) ).rejects.toThrow('Legacy financial execution is retired'); expect(resolved).toBe(0); } ); test('paper requires explicit canonical configuration before connections, including initializeMode false', async () => { const container = createDiContainer(); await expect( registerOrchestratorServices(container, { role: 'paper', initializeMode: false }) ).rejects.toThrow('explicit canonicalPaper'); await expect( createContainer({ services: { orchestrator: { defaultMode: 'paper' } } } as StockAppConfig) ).rejects.toThrow('explicit canonicalPaper'); await expect( createContainer({ services: { orchestrator: { backtesting: { useRustEngine: false } } }, } as StockAppConfig) ).rejects.toThrow('Legacy financial execution is retired'); }); test('unchecked role and backend options fail closed before service resolution', async () => { const container = createDiContainer(); for (const options of [ { role: 'research' }, { role: null }, { useRustEngine: 'false' }, { useRustEngine: null }, ]) { await expect( registerOrchestratorServices( container, options as unknown as Parameters[1] ) ).rejects.toThrow('role' in options ? 'Unsupported runtime role' : 'must be a boolean'); } }); test.each([{}, { role: 'research-only' as const }])( 'default and explicit research compose one canonical engine without any account/feed/mode gateway', async options => { const { services, container } = await compose(options); expect(services.custom!.BacktestRunner).toBeInstanceOf(ResearchBacktestPool); for (const key of [ 'BacktestEngine', 'ModeManager', 'ExecutionService', 'MarketDataService', 'StrategyManager', 'PaperTradingManager', 'CanonicalPaperRuntime', ]) { expect(services.custom).not.toHaveProperty(key); expect(container.hasRegistration(key)).toBe(false); } const app = createRoutes(services); expect(await (await app.request('/health')).json()).toMatchObject({ mode: 'research-only', execution: 'canonical-research', }); expect((await app.request('/api/recovery')).status).toBe(503); for (const path of ['/api/orders', '/api/positions']) { expect((await app.request(path, { method: 'POST' })).status).toBe(409); } expect(await (await app.request('/api/paper/readiness')).json()).toMatchObject({ configured: false, active: false, ready: false, operatorHalted: true, accountId: null, }); } ); test.each([1, 2, 4] as const)( 'composition uses one BullMQ consumer with concurrency %s', async maxConcurrent => { const calls: unknown[] = []; const { services } = await compose({ maxConcurrent }, calls); expect(calls).toEqual([ { name: 'orchestrator', options: { workers: 1, concurrency: maxConcurrent } }, ]); expect(services.custom!.BacktestRunner!.getStatus().isRunning).toBe(false); } ); test('default composition and schema select one slot; invalid values fail before resolving services/connections', async () => { const calls: unknown[] = []; await compose({}, calls); expect(calls).toEqual([{ name: 'orchestrator', options: { workers: 1, concurrency: 1 } }]); const schema = stockAppSchema.shape.services .unwrap() .shape.orchestrator.unwrap() .shape.backtesting.unwrap(); expect(schema.parse({}).maxConcurrent).toBe(1); for (const maxConcurrent of [null, 0, 3, 5, 1.5, '2', NaN, Infinity]) { expect(schema.safeParse({ maxConcurrent }).success).toBe(false); const container = createDiContainer(); await expect( registerOrchestratorServices(container, { maxConcurrent } as never) ).rejects.toThrow('1, 2, or 4'); await expect( createContainer({ services: { orchestrator: { backtesting: { maxConcurrent } } } } as never) ).rejects.toThrow('1, 2, or 4'); } }); test('cannot overlay the canonical graph on a legacy account runtime', async () => { const container = createDiContainer(); container.register({ serviceContainer: asValue({ logger, custom: { ExecutionService: {} } }) }); await expect(registerOrchestratorServices(container)).rejects.toThrow( 'fresh runtime composition' ); }); });