stock-bot/test/integration/store-configuration.test.ts

264 lines
9.1 KiB
TypeScript

import { asValue, createContainer } from 'awilix';
import { expect, mock, test } from 'bun:test';
import type { PoolConfig } from 'pg';
import { baseAppSchema } from '@stock-bot/config';
import { appConfigSchema } from '../../libs/core/di/src/config/schemas';
import { ServiceContainerBuilder } from '../../libs/core/di/src/container/builder';
import type { ServiceDefinitions } from '../../libs/core/di/src/container/types';
import { registerCacheServices } from '../../libs/core/di/src/registrations/cache.registration';
function configuration(enabled = true) {
return baseAppSchema.parse({
name: 'store-configuration',
version: '1.0.0',
service: { name: 'store-configuration', port: 3000 },
log: { level: 'fatal' },
database: {
dragonfly: { enabled, host: 'redis.test', password: 'fixture', db: 3 },
mongodb: {
enabled,
uri: 'mongodb://fixture:fixture@mongo.test:27017/store?authSource=admin',
database: 'store',
poolSize: 17,
},
postgres: {
enabled,
host: 'pg.test',
port: 15432,
database: 'store',
user: 'fixture',
password: 'fixture',
ssl: true,
poolSize: 19,
connectionTimeout: 4321,
idleTimeout: 8765,
},
questdb: { enabled: false },
},
});
}
for (const enabled of [true, false]) {
test(`explicit disable options win over enabled=${enabled} configuration`, async () => {
const c = await new ServiceContainerBuilder()
.withConfig(configuration(enabled))
.withOptions({ enableCache: false, enableMongoDB: false, enablePostgres: false })
.skipInitialization()
.build();
try {
for (const name of ['cache', 'mongoClient', 'postgresClient']) {
expect(c.resolve(name)).toBeNull();
}
const config = c.resolve('config');
expect(config.redis.enabled).toBe(false);
expect(config.mongodb.enabled).toBe(false);
expect(config.postgres.enabled).toBe(false);
} finally {
await c.dispose();
}
});
}
test('enable options do not override disabled configurations', async () => {
const c = await new ServiceContainerBuilder()
.withConfig(configuration(false))
.withOptions({ enableCache: true, enableMongoDB: true, enablePostgres: true })
.skipInitialization()
.build();
try {
for (const name of ['cache', 'mongoClient', 'postgresClient']) {
expect(c.resolve(name)).toBeNull();
}
} finally {
await c.dispose();
}
});
test('PostgreSQL nondefault fields reach wire configuration and Mongo retains URI/pool settings', async () => {
const c = await new ServiceContainerBuilder()
.withConfig(configuration())
.skipInitialization()
.build();
try {
const wire = (
c.resolve('postgresClient') as unknown as { buildPoolConfig(): PoolConfig }
).buildPoolConfig();
expect(wire).toMatchObject({
host: 'pg.test',
port: 15432,
database: 'store',
user: 'fixture',
password: 'fixture',
ssl: { rejectUnauthorized: true },
max: 19,
connectionTimeoutMillis: 4321,
idleTimeoutMillis: 8765,
});
for (const key of [
'query_timeout',
'statement_timeout',
'lock_timeout',
'idle_in_transaction_session_timeout',
] as const) {
expect(wire[key]).toBeUndefined();
}
const mongo = c.resolve('mongoClient') as unknown as {
config: { uri: string; poolSettings: { maxPoolSize: number } };
};
expect(mongo.config.uri).toBe(configuration().database!.mongodb!.uri);
expect(mongo.config.poolSettings.maxPoolSize).toBe(17);
} finally {
await c.dispose();
}
});
test('flat QuestDB alias and credentials reach the client; unsupported tuning is diagnosed', async () => {
const c = await new ServiceContainerBuilder()
.withConfig({
...configuration(false),
questdb: {
enabled: true,
host: 'quest.test',
ilpPort: 19009,
influxPort: 29009,
user: 'fixture',
password: 'fixture',
bufferSize: 1234,
flushInterval: 3456,
},
} as never)
.skipInitialization()
.build();
const logger = c.resolve('logger');
const originalWarn = logger.warn;
logger.warn = mock(() => {});
try {
expect(c.resolve('config').questdb).toMatchObject({
influxPort: 29009,
bufferSize: 1234,
flushInterval: 3456,
user: 'fixture',
password: 'fixture',
});
expect(c.resolve('questdbClient')!.configuration).toMatchObject({
influxPort: 29009,
user: 'fixture',
password: 'fixture',
});
expect(logger.warn).toHaveBeenCalledWith(
'QuestDB bufferSize/flushInterval are deprecated and have no effect; configure explicit writer batch options instead'
);
expect(logger.warn).toHaveBeenCalledTimes(1);
} finally {
logger.warn = originalWarn;
await c.dispose();
}
});
test('default QuestDB compatibility settings do not produce tuning diagnostics', async () => {
const c = await new ServiceContainerBuilder()
.withConfig({ ...configuration(false), questdb: { enabled: true } } as never)
.skipInitialization()
.build();
const logger = c.resolve('logger');
const originalWarn = logger.warn;
logger.warn = mock(() => {});
try {
expect(c.resolve('questdbClient')).not.toBeNull();
expect(logger.warn).not.toHaveBeenCalled();
} finally {
logger.warn = originalWarn;
await c.dispose();
}
});
// Existing offline examples compose the shared graph without an application config.
test('all-disabled default composition needs neither store settings nor connections', async () => {
const c = await new ServiceContainerBuilder()
.withOptions({
enableCache: false,
enableQueue: false,
enableMongoDB: false,
enablePostgres: false,
enableQuestDB: false,
enableBrowser: false,
enableProxy: false,
})
.build();
try {
for (const name of ['cache', 'mongoClient', 'postgresClient', 'questdbClient']) {
expect(c.resolve(name)).toBeNull();
}
} finally {
await c.dispose();
}
});
test('Redis ACL username reaches cache and both queue connection settings without opening sockets', async () => {
// Isolate the transport substitution: Bun module mocks otherwise leak between suites.
const child = Bun.spawn(
[
process.execPath,
'-e',
String.raw`
import {mock} from 'bun:test';
const captured=[];
class Redis {
constructor(options){captured.push(options);}
on(){return this;}
disconnect(){}
async quit(){}
}
mock.module('ioredis',()=>({default:Redis,Redis,Cluster:Redis}));
const {ServiceContainerBuilder}=await import('./libs/core/di/src/container/builder.ts');
const c=await new ServiceContainerBuilder().withConfig({
name:'redis-auth-test',version:'1.0.0',service:{name:'redis-auth-test',port:3000},log:{level:'fatal'},
database:{dragonfly:{enabled:true,host:'redis.fixture.test',username:'research-reader',password:'fixture-only'},
mongodb:{enabled:false,uri:'mongodb://localhost/test',database:'test'},
postgres:{enabled:false,database:'test',user:'test',password:'fixture-only'},questdb:{enabled:false}},
}).withOptions({enableBrowser:false,enableProxy:false}).skipInitialization().build();
c.resolve('cache');c.resolve('globalCache');
const queue=c.resolve('queueManager');
process.stdout.write('__redis_capture__'+JSON.stringify({captured,queue:queue.redisConnection})+'\n');
await c.dispose();
`,
],
{ stdout: 'pipe', stderr: 'pipe' }
);
const [stdout, stderr, code] = await Promise.all([
new Response(child.stdout).text(),
new Response(child.stderr).text(),
child.exited,
]);
if (code !== 0) {
throw new Error(`Redis transport probe failed: ${stderr}`);
}
const line = stdout.split('\n').find(line => line.startsWith('__redis_capture__'));
expect(line).toBeDefined();
const result = JSON.parse(line!.slice('__redis_capture__'.length));
expect(result.captured).toHaveLength(3);
for (const config of [...result.captured, result.queue]) {
expect(config).toMatchObject({
host: 'redis.fixture.test',
username: 'research-reader',
password: 'fixture-only',
});
}
});
test('deprecated DI cache prefixes produce a diagnostic without echoing supplied values', () => {
const logger = { warn: mock(() => {}) };
// Registration validates the compatibility setting without constructing Redis transports.
const container = createContainer<ServiceDefinitions>();
container.register('logger', asValue(logger as unknown as ServiceDefinitions['logger']));
const config = appConfigSchema.parse({
redis: { enabled: true, keyPrefix: 'private-operator-prefix' },
mongodb: { enabled: false, uri: 'mongodb://unused/test', database: 'test' },
postgres: { enabled: false, database: 'test', user: 'test', password: 'fixture-only' },
});
registerCacheServices(container, config);
expect(logger.warn).toHaveBeenCalledTimes(1);
expect(logger.warn).toHaveBeenCalledWith(
'Redis keyPrefix is deprecated at the DI boundary; service/global/proxy namespaces remain fixed'
);
});