fix: clean up service configuration startup and development commands

This commit is contained in:
Boki 2026-10-26 13:23:49 -04:00
parent 4ddffa6b67
commit 805a9f8fd4
36 changed files with 627 additions and 596 deletions

View file

@ -0,0 +1,96 @@
import type { AwilixContainer } from 'awilix';
import { expect, mock, test } from 'bun:test';
import { ServiceLifecycleManager } from '../../libs/core/di/src/utils/lifecycle';
function container(cradle: object) {
return { cradle } as AwilixContainer;
}
function deferred() {
let resolve!: () => void;
let reject!: (error: Error) => void;
const promise = new Promise<void>((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
test('failed startup rolls back settled resources and preserves the original error', async () => {
const failure = new Error('mongo failed');
const disconnect = mock(async () => {});
const manager = new ServiceLifecycleManager();
const c = container({
cache: { connect: async () => {}, disconnect },
mongoClient: {
connect: async () => {
throw failure;
},
disconnect: async () => {
throw new Error('cleanup failed');
},
},
});
await expect(manager.initializeServices(c)).rejects.toBe(failure);
expect(disconnect).toHaveBeenCalledTimes(1);
await manager.shutdownServices(c);
expect(disconnect).toHaveBeenCalledTimes(1);
});
test('resolver failure retains ownership of initialization already in flight', async () => {
const late = deferred();
const disconnect = mock(async () => {});
const failure = new Error('resolver failed');
const c = container({
cache: { connect: () => late.promise, disconnect },
get mongoClient() {
throw failure;
},
});
await expect(new ServiceLifecycleManager().initializeServices(c)).rejects.toBe(failure);
expect(disconnect).not.toHaveBeenCalled();
late.resolve();
await Bun.sleep(0);
expect(disconnect).toHaveBeenCalledTimes(1);
});
test('timeout returns promptly and cleans up a late successful initializer', async () => {
const late = deferred();
const disconnect = mock(async () => {});
const c = container({ cache: { connect: () => late.promise, disconnect } });
await expect(new ServiceLifecycleManager().initializeServices(c, 5)).rejects.toThrow(
'cache initialization timed out'
);
late.resolve();
await Bun.sleep(0);
expect(disconnect).toHaveBeenCalledTimes(1);
});
test('late failed initialization also releases resources allocated before failure', async () => {
const late = deferred();
const disconnect = mock(async () => {});
const c = container({ cache: { connect: () => late.promise, disconnect } });
await expect(new ServiceLifecycleManager().initializeServices(c, 5)).rejects.toThrow('timed out');
late.reject(new Error('late failure'));
await Bun.sleep(0);
expect(disconnect).toHaveBeenCalledTimes(1);
});
test('successful initialization clears timeout handles immediately', async () => {
const child = Bun.spawn(
[
process.execPath,
'-e',
`
import {ServiceLifecycleManager} from './libs/core/di/src/utils/lifecycle.ts';
await new ServiceLifecycleManager().initializeServices({cradle:{cache:{connect:async()=>{}}}}, 30000);
`,
],
{ stdout: 'ignore', stderr: 'pipe' }
);
const timer = setTimeout(() => child.kill(), 3000);
try {
expect(await child.exited).toBe(0);
} finally {
clearTimeout(timer);
}
});

View file

@ -0,0 +1,129 @@
import { expect, test } from 'bun:test';
import type { PoolConfig } from 'pg';
import { baseAppSchema } from '@stock-bot/config';
import { ServiceContainerBuilder } from '../../libs/core/di/src/container/builder';
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,
});
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 takes precedence without discarding credentials or schema settings', 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();
try {
expect(c.resolve('config').questdb).toMatchObject({
influxPort: 29009,
bufferSize: 1234,
flushInterval: 3456,
user: 'fixture',
password: 'fixture',
});
} finally {
await c.dispose();
}
});