292 lines
10 KiB
TypeScript
292 lines
10 KiB
TypeScript
import { describe, expect, it, mock } from 'bun:test';
|
|
import { ZodError } from 'zod';
|
|
import { baseAppSchema } from '@stock-bot/config';
|
|
import type { Queue, QueueWorkerConfig } from '@stock-bot/queue';
|
|
import { ServiceContainerBuilder } from '../src/container/builder';
|
|
|
|
// Production schemas and registrations, with initialization disabled: no module
|
|
// mocks, environment credentials, sockets or a second config implementation.
|
|
function configuration() {
|
|
return baseAppSchema.parse({
|
|
name: 'di-test',
|
|
version: '1.0.0',
|
|
environment: 'test',
|
|
service: { name: 'TestService', port: 3000 },
|
|
log: { level: 'fatal' },
|
|
database: {
|
|
dragonfly: { enabled: false },
|
|
mongodb: { enabled: false, uri: 'mongodb://localhost/test', database: 'fixture' },
|
|
postgres: { enabled: false, database: 'fixture', user: 'fixture', password: 'fixture' },
|
|
questdb: { enabled: false, ilpPort: 19009 },
|
|
},
|
|
});
|
|
}
|
|
|
|
async function compose(config = configuration()) {
|
|
return new ServiceContainerBuilder().withConfig(config).skipInitialization().build();
|
|
}
|
|
|
|
describe('ServiceContainerBuilder production configuration', () => {
|
|
it('normalizes nested configuration and registers real services without connecting', async () => {
|
|
const container = await compose();
|
|
try {
|
|
const config = container.resolve('config');
|
|
expect(config.service?.serviceName).toBe('test-service');
|
|
expect(config.mongodb.database).toBe('fixture');
|
|
expect(config.postgres.database).toBe('fixture');
|
|
expect(config.questdb?.influxPort).toBe(19009);
|
|
for (const name of ['cache', 'mongoClient', 'postgresClient', 'questdbClient']) {
|
|
expect(container.resolve(name)).toBeNull();
|
|
}
|
|
expect(container.resolve('handlerRegistry')).toBeDefined();
|
|
expect(container.resolve('handlerScanner')).toBeDefined();
|
|
expect(container.hasRegistration('serviceContainer')).toBe(true);
|
|
} finally {
|
|
await container.dispose();
|
|
}
|
|
});
|
|
|
|
it('uses flat database settings in preference to nested ones', async () => {
|
|
const config = {
|
|
...configuration(),
|
|
redis: { enabled: false, host: 'flat.test', port: 16379, db: 2 },
|
|
};
|
|
const container = await compose(config);
|
|
try {
|
|
expect(container.resolve('config').redis).toMatchObject(config.redis);
|
|
} finally {
|
|
await container.dispose();
|
|
}
|
|
});
|
|
|
|
it('keeps optional service defaults and honors disabled optional services', async () => {
|
|
const defaults = await compose();
|
|
try {
|
|
expect(defaults.resolve('config').queue).toMatchObject({
|
|
enabled: true,
|
|
workers: 1,
|
|
concurrency: 1,
|
|
});
|
|
expect(defaults.resolve('config').browser).toMatchObject({ headless: true, timeout: 30000 });
|
|
} finally {
|
|
await defaults.dispose();
|
|
}
|
|
const container = await new ServiceContainerBuilder()
|
|
.withConfig(configuration())
|
|
.withOptions({
|
|
enableQueue: false,
|
|
enableBrowser: false,
|
|
enableProxy: false,
|
|
enableQuestDB: false,
|
|
})
|
|
.skipInitialization()
|
|
.build();
|
|
try {
|
|
const config = container.resolve('config');
|
|
expect(config.queue).toBeUndefined();
|
|
expect(config.browser).toBeUndefined();
|
|
expect(config.proxy).toBeUndefined();
|
|
expect(config.questdb).toBeUndefined();
|
|
} finally {
|
|
await container.dispose();
|
|
}
|
|
});
|
|
|
|
it('uses the last complete configuration when the builder is reused', async () => {
|
|
const builder = new ServiceContainerBuilder().withConfig(configuration());
|
|
const next = { ...configuration(), service: { name: 'replacement', port: 3100 } };
|
|
const container = await builder.withConfig(next).skipInitialization().build();
|
|
try {
|
|
expect(container.resolve('config').service?.name).toBe('replacement');
|
|
} finally {
|
|
await container.dispose();
|
|
}
|
|
});
|
|
|
|
it('allows service-specific capability overrides via withRegistrations', async () => {
|
|
const fakeBrowser = { close: async () => {} } as never;
|
|
const container = await new ServiceContainerBuilder()
|
|
.withConfig(configuration())
|
|
.withRegistrations((diContainer, _cfg, { asValue }) => {
|
|
diContainer.register({ browser: asValue(fakeBrowser) });
|
|
})
|
|
.skipInitialization()
|
|
.build();
|
|
try {
|
|
expect(container.resolve('browser')).toBe(fakeBrowser);
|
|
expect(container.resolve('serviceContainer').browser).toBe(fakeBrowser);
|
|
} finally {
|
|
await container.dispose();
|
|
}
|
|
});
|
|
|
|
it('extracts database from multi-host readUri when mongoReadOnly is enabled', async () => {
|
|
const config = {
|
|
...configuration(),
|
|
database: {
|
|
...configuration().database,
|
|
mongodb: {
|
|
enabled: true,
|
|
uri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin',
|
|
readUri:
|
|
'mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock?authSource=stock',
|
|
database: 'stock_dev',
|
|
},
|
|
},
|
|
};
|
|
const container = await new ServiceContainerBuilder()
|
|
.withConfig(config)
|
|
.withOptions({
|
|
enableMongoDB: true,
|
|
mongoReadOnly: true,
|
|
enablePostgres: false,
|
|
enableQuestDB: false,
|
|
enableCache: false,
|
|
enableQueue: false,
|
|
enableBrowser: false,
|
|
enableProxy: false,
|
|
})
|
|
.skipInitialization()
|
|
.build();
|
|
|
|
try {
|
|
const resolvedConfig = container.resolve('config');
|
|
expect(resolvedConfig.mongodb.readOnly).toBe(true);
|
|
expect(resolvedConfig.mongodb.database).toBe('stock');
|
|
|
|
const mongo = container.resolve('mongoClient');
|
|
expect(mongo).not.toBeNull();
|
|
expect(mongo!.isReadOnly()).toBe(true);
|
|
expect(mongo!.getDefaultDatabase()).toBe('stock');
|
|
} finally {
|
|
await container.dispose();
|
|
}
|
|
});
|
|
|
|
it('rejects invalid settings and missing required app fields with schema errors', () => {
|
|
expect(() =>
|
|
new ServiceContainerBuilder().withConfig({
|
|
...configuration(),
|
|
redis: { enabled: 'wrong' },
|
|
} as never)
|
|
).toThrow(ZodError);
|
|
expect(() =>
|
|
new ServiceContainerBuilder().withConfig({ service: { name: 'incomplete' } } as never)
|
|
).toThrow(ZodError);
|
|
});
|
|
|
|
it('defaults delayWorkerStart to false for orchestrator-style containers and enables it only when opted in', async () => {
|
|
const queueEnabledConfig = {
|
|
...configuration(),
|
|
service: { name: 'orchestrator', port: 3003 },
|
|
redis: { enabled: true, host: '127.0.0.1', port: 16379, db: 0 },
|
|
queue: {
|
|
enabled: true,
|
|
workers: 1,
|
|
concurrency: 1,
|
|
redis: { host: '127.0.0.1', port: 16379, db: 0 },
|
|
},
|
|
};
|
|
|
|
const createOfflineQueueDeps = () => {
|
|
const redisQuit = mock(async () => 'OK');
|
|
const createdQueues: Array<{
|
|
name: string;
|
|
workerConfig: QueueWorkerConfig;
|
|
close: ReturnType<typeof mock>;
|
|
}> = [];
|
|
const createRedis = mock(() => ({ quit: redisQuit, disconnect: mock(() => {}) }) as any);
|
|
const createQueue = mock(
|
|
(
|
|
name: string,
|
|
_redisConfig: unknown,
|
|
_defaultJobOptions: unknown,
|
|
workerConfig: QueueWorkerConfig
|
|
) => {
|
|
const workerCount = workerConfig.startWorker ? (workerConfig.workers ?? 0) : 0;
|
|
const close = mock(async () => {});
|
|
createdQueues.push({ name, workerConfig, close });
|
|
return {
|
|
getName: () => name,
|
|
getWorkerCount: () => workerCount,
|
|
close,
|
|
} as unknown as Queue;
|
|
}
|
|
);
|
|
return { deps: { createRedis, createQueue }, createdQueues, redisQuit };
|
|
};
|
|
|
|
// Orchestrator path (matching apps/stock/orchestrator/src/simple-container.ts): no delayWorkerStart
|
|
const orchestratorStubs = createOfflineQueueDeps();
|
|
const orchestratorContainer = await new ServiceContainerBuilder({
|
|
queueManagerDeps: orchestratorStubs.deps,
|
|
})
|
|
.withConfig(queueEnabledConfig)
|
|
.withOptions({
|
|
enableMongoDB: false,
|
|
enablePostgres: false,
|
|
enableCache: true,
|
|
enableQueue: true,
|
|
enableQuestDB: false,
|
|
enableBrowser: false,
|
|
enableProxy: false,
|
|
})
|
|
.skipInitialization()
|
|
.build();
|
|
|
|
const orchestratorQueueManager = orchestratorContainer.resolve('queueManager');
|
|
try {
|
|
expect(orchestratorQueueManager).not.toBeNull();
|
|
expect(orchestratorQueueManager!.getConfig().delayWorkerStart).toBe(false);
|
|
|
|
const queue = orchestratorQueueManager!.getQueue('orchestrator', {
|
|
workers: 1,
|
|
concurrency: 3,
|
|
});
|
|
expect(orchestratorStubs.createdQueues).toHaveLength(1);
|
|
expect(orchestratorStubs.createdQueues[0]?.workerConfig.startWorker).toBe(true);
|
|
expect(orchestratorStubs.createdQueues[0]?.workerConfig.workers).toBe(1);
|
|
expect(orchestratorStubs.createdQueues[0]?.workerConfig.concurrency).toBe(3);
|
|
expect(queue.getWorkerCount()).toBe(1);
|
|
} finally {
|
|
await orchestratorQueueManager?.shutdown();
|
|
await orchestratorContainer.dispose();
|
|
}
|
|
|
|
// Opt-in path (matching data-ingestion / data-pipeline): delayWorkerStart: true
|
|
const delayedStubs = createOfflineQueueDeps();
|
|
const delayedContainer = await new ServiceContainerBuilder({
|
|
queueManagerDeps: delayedStubs.deps,
|
|
})
|
|
.withConfig({
|
|
...queueEnabledConfig,
|
|
service: { name: 'data-ingestion', port: 3001 },
|
|
})
|
|
.withOptions({
|
|
enableMongoDB: false,
|
|
enablePostgres: false,
|
|
enableCache: true,
|
|
enableQueue: true,
|
|
delayWorkerStart: true,
|
|
enableQuestDB: false,
|
|
enableBrowser: false,
|
|
enableProxy: false,
|
|
})
|
|
.skipInitialization()
|
|
.build();
|
|
|
|
const delayedQueueManager = delayedContainer.resolve('queueManager');
|
|
try {
|
|
expect(delayedQueueManager).not.toBeNull();
|
|
expect(delayedQueueManager!.getConfig().delayWorkerStart).toBe(true);
|
|
|
|
const queue = delayedQueueManager!.getQueue('te');
|
|
expect(delayedStubs.createdQueues).toHaveLength(1);
|
|
expect(delayedStubs.createdQueues[0]?.workerConfig.startWorker).toBe(false);
|
|
expect(queue.getWorkerCount()).toBe(0);
|
|
} finally {
|
|
await delayedQueueManager?.shutdown();
|
|
await delayedContainer.dispose();
|
|
}
|
|
});
|
|
});
|