fix: clean up service configuration startup and development commands
This commit is contained in:
parent
4ddffa6b67
commit
805a9f8fd4
36 changed files with 627 additions and 596 deletions
|
|
@ -19,6 +19,7 @@ export const questdbConfigSchema = z.object({
|
|||
enabled: z.boolean().default(true),
|
||||
host: z.string().default('localhost'),
|
||||
ilpPort: z.number().default(9009),
|
||||
influxPort: z.number().optional(), // legacy flat alias; explicit alias wins at DI boundary
|
||||
httpPort: z.number().default(9000),
|
||||
pgPort: z.number().default(8812),
|
||||
database: z.string().default('questdb'),
|
||||
|
|
@ -50,6 +51,7 @@ export const dragonflyConfigSchema = z.object({
|
|||
port: z.number().default(6379),
|
||||
password: z.string().optional(),
|
||||
db: z.number().min(0).max(15).default(0),
|
||||
username: z.string().optional(),
|
||||
keyPrefix: z.string().optional(),
|
||||
ttl: z.number().optional(),
|
||||
maxRetries: z.number().default(3),
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ export const unifiedAppSchema = baseAppSchema
|
|||
// Handle the ilpPort -> influxPort mapping for DI system
|
||||
const questdbConfig = {
|
||||
...data.database.questdb,
|
||||
influxPort: data.database.questdb.ilpPort,
|
||||
influxPort: data.database.questdb.influxPort ?? data.database.questdb.ilpPort,
|
||||
};
|
||||
data.questdb = questdbConfig;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,5 @@
|
|||
import { z } from 'zod';
|
||||
import { mongodbConfigSchema as coreSchema } from '@stock-bot/config';
|
||||
|
||||
export const mongodbConfigSchema = z.object({
|
||||
enabled: z.boolean().optional().default(true),
|
||||
uri: z.string(),
|
||||
database: z.string(),
|
||||
});
|
||||
|
||||
export const mongodbConfigSchema = coreSchema;
|
||||
export type MongoDBConfig = z.infer<typeof mongodbConfigSchema>;
|
||||
|
|
|
|||
|
|
@ -1,12 +1,5 @@
|
|||
import { z } from 'zod';
|
||||
import { postgresConfigSchema as coreSchema } from '@stock-bot/config';
|
||||
|
||||
export const postgresConfigSchema = z.object({
|
||||
enabled: z.boolean().optional().default(true),
|
||||
host: z.string().default('localhost'),
|
||||
port: z.number().default(5432),
|
||||
database: z.string(),
|
||||
user: z.string(),
|
||||
password: z.string(),
|
||||
});
|
||||
|
||||
export const postgresConfigSchema = coreSchema;
|
||||
export type PostgresConfig = z.infer<typeof postgresConfigSchema>;
|
||||
|
|
|
|||
|
|
@ -1,14 +1,8 @@
|
|||
import { z } from 'zod';
|
||||
import { questdbConfigSchema as coreQuestdbConfigSchema } from '@stock-bot/config';
|
||||
|
||||
export const questdbConfigSchema = z.object({
|
||||
enabled: z.boolean().optional().default(true),
|
||||
host: z.string().default('localhost'),
|
||||
httpPort: z.number().optional().default(9000),
|
||||
pgPort: z.number().optional().default(8812),
|
||||
influxPort: z.number().optional().default(9009),
|
||||
database: z.string().optional().default('questdb'),
|
||||
user: z.string().optional(),
|
||||
password: z.string().optional(),
|
||||
// ilpPort is normalized once by the builder for the legacy client field name.
|
||||
export const questdbConfigSchema = coreQuestdbConfigSchema.extend({
|
||||
influxPort: z.number().default(9009),
|
||||
});
|
||||
|
||||
export type QuestDBConfig = z.infer<typeof questdbConfigSchema>;
|
||||
|
|
|
|||
|
|
@ -1,12 +1,5 @@
|
|||
import { z } from 'zod';
|
||||
import { dragonflyConfigSchema } from '@stock-bot/config';
|
||||
|
||||
export const redisConfigSchema = z.object({
|
||||
enabled: z.boolean().optional().default(true),
|
||||
host: z.string().default('localhost'),
|
||||
port: z.number().default(6379),
|
||||
password: z.string().optional(),
|
||||
username: z.string().optional(),
|
||||
db: z.number().optional().default(0),
|
||||
});
|
||||
|
||||
export const redisConfigSchema = dragonflyConfigSchema;
|
||||
export type RedisConfig = z.infer<typeof redisConfigSchema>;
|
||||
|
|
|
|||
|
|
@ -85,7 +85,7 @@ export class ServiceContainerBuilder {
|
|||
return appConfigSchema.parse(finalConfig);
|
||||
}
|
||||
|
||||
private applyServiceOptions(config: Partial<AppConfig>): AppConfig {
|
||||
private applyServiceOptions(config: Partial<AppConfig>) {
|
||||
// Ensure questdb config has the right field names for DI
|
||||
const questdbConfig = config.questdb
|
||||
? {
|
||||
|
|
@ -102,24 +102,33 @@ export class ServiceContainerBuilder {
|
|||
};
|
||||
|
||||
return {
|
||||
redis: config.redis || {
|
||||
enabled: this.options.enableCache ?? true,
|
||||
host: 'localhost',
|
||||
port: 6379,
|
||||
db: 0,
|
||||
redis: {
|
||||
...(config.redis || {
|
||||
enabled: this.options.enableCache ?? true,
|
||||
host: 'localhost',
|
||||
port: 6379,
|
||||
db: 0,
|
||||
}),
|
||||
enabled: this.options.enableCache !== false && (config.redis?.enabled ?? true),
|
||||
},
|
||||
mongodb: config.mongodb || {
|
||||
enabled: this.options.enableMongoDB ?? true,
|
||||
uri: '',
|
||||
database: '',
|
||||
mongodb: {
|
||||
...(config.mongodb || {
|
||||
enabled: this.options.enableMongoDB ?? true,
|
||||
uri: '',
|
||||
database: '',
|
||||
}),
|
||||
enabled: this.options.enableMongoDB !== false && (config.mongodb?.enabled ?? true),
|
||||
},
|
||||
postgres: config.postgres || {
|
||||
enabled: this.options.enablePostgres ?? true,
|
||||
host: 'localhost',
|
||||
port: 5432,
|
||||
database: 'postgres',
|
||||
user: 'postgres',
|
||||
password: 'postgres',
|
||||
postgres: {
|
||||
...(config.postgres || {
|
||||
enabled: this.options.enablePostgres ?? true,
|
||||
host: 'localhost',
|
||||
port: 5432,
|
||||
database: 'postgres',
|
||||
user: 'postgres',
|
||||
password: 'postgres',
|
||||
}),
|
||||
enabled: this.options.enablePostgres !== false && (config.postgres?.enabled ?? true),
|
||||
},
|
||||
questdb: this.options.enableQuestDB ? questdbConfig : undefined,
|
||||
proxy: this.options.enableProxy
|
||||
|
|
@ -196,19 +205,10 @@ export class ServiceContainerBuilder {
|
|||
}
|
||||
|
||||
private transformStockBotConfig(config: UnifiedAppConfig): Partial<AppConfig> {
|
||||
// Unified config already has flat structure, just extract what we need
|
||||
// Handle questdb field name mapping
|
||||
// Keep the schema-normalized values intact; only the legacy port name
|
||||
// differs at this adapter boundary.
|
||||
const questdb = config.questdb
|
||||
? {
|
||||
enabled: config.questdb.enabled ?? true,
|
||||
host: config.questdb.host || 'localhost',
|
||||
httpPort: config.questdb.httpPort || 9000,
|
||||
pgPort: config.questdb.pgPort || 8812,
|
||||
influxPort: getInfluxPort(config.questdb),
|
||||
database: config.questdb.database || 'questdb',
|
||||
user: config.questdb.user,
|
||||
password: config.questdb.password,
|
||||
}
|
||||
? { ...config.questdb, influxPort: getInfluxPort(config.questdb) }
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -14,18 +14,21 @@ export function registerDatabaseServices(
|
|||
if (config.mongodb?.enabled) {
|
||||
container.register({
|
||||
mongoClient: asFunction(({ logger }) => {
|
||||
// Parse MongoDB URI to extract components
|
||||
const uriMatch = config.mongodb.uri.match(
|
||||
/mongodb:\/\/(?:([^:]+):([^@]+)@)?([^:/]+):(\d+)\/([^?]+)(?:\?authSource=(.+))?/
|
||||
);
|
||||
// The driver parses URI credentials, SRV and query options. Do not
|
||||
// reconstruct them with an incomplete URI regular expression.
|
||||
const mongoConfig = {
|
||||
host: uriMatch?.[3] || 'localhost',
|
||||
port: parseInt(uriMatch?.[4] || '27017'),
|
||||
host: config.mongodb.host ?? 'localhost',
|
||||
port: config.mongodb.port ?? 27017,
|
||||
database: config.mongodb.database,
|
||||
username: uriMatch?.[1],
|
||||
password: uriMatch?.[2] ? String(uriMatch?.[2]) : undefined,
|
||||
authSource: uriMatch?.[6] || 'admin',
|
||||
username: config.mongodb.user,
|
||||
password: config.mongodb.password,
|
||||
authSource: config.mongodb.authSource,
|
||||
uri: config.mongodb.uri,
|
||||
poolSettings: {
|
||||
maxPoolSize: config.mongodb.poolSize,
|
||||
minPoolSize: 0,
|
||||
maxIdleTime: 10000,
|
||||
},
|
||||
};
|
||||
return new MongoDBClient(mongoConfig, logger);
|
||||
}).singleton(),
|
||||
|
|
@ -45,7 +48,20 @@ export function registerDatabaseServices(
|
|||
port: config.postgres.port,
|
||||
database: config.postgres.database,
|
||||
username: config.postgres.user,
|
||||
password: String(config.postgres.password), // Ensure password is a string
|
||||
password: config.postgres.password,
|
||||
ssl: { enabled: config.postgres.ssl, rejectUnauthorized: true },
|
||||
poolSettings: {
|
||||
min: 0,
|
||||
max: config.postgres.poolSize,
|
||||
idleTimeoutMillis: config.postgres.idleTimeout,
|
||||
},
|
||||
timeouts: {
|
||||
connection: config.postgres.connectionTimeout,
|
||||
query: 0,
|
||||
statement: 0,
|
||||
lock: 0,
|
||||
idleInTransaction: 0,
|
||||
},
|
||||
};
|
||||
|
||||
logger.debug('PostgreSQL config:', {
|
||||
|
|
|
|||
|
|
@ -25,42 +25,72 @@ export class ServiceLifecycleManager {
|
|||
container: AwilixContainer<ServiceDefinitions>,
|
||||
timeout = 30000
|
||||
): Promise<void> {
|
||||
const initPromises: Promise<void>[] = [];
|
||||
|
||||
for (const { name, key } of this.services) {
|
||||
const service = container.cradle[key] as ServiceWithLifecycle | null;
|
||||
|
||||
if (service) {
|
||||
const initPromise = this.initializeService(name, service);
|
||||
initPromises.push(
|
||||
Promise.race([
|
||||
initPromise,
|
||||
this.createTimeoutPromise(
|
||||
timeout,
|
||||
`${name} initialization timed out after ${timeout}ms`
|
||||
),
|
||||
])
|
||||
);
|
||||
}
|
||||
const started: { name: string; service: ServiceWithLifecycle; settled: boolean }[] = [];
|
||||
const cancelTimers: (() => void)[] = [];
|
||||
let failed = false;
|
||||
try {
|
||||
const work = this.services.map(async ({ name, key }) => {
|
||||
const service = container.cradle[key] as ServiceWithLifecycle | null;
|
||||
if (!service) {return Promise.resolve();}
|
||||
const entry = { name, service, settled: false };
|
||||
started.push(entry);
|
||||
// A timeout cannot cancel connect(). Keep ownership until it settles,
|
||||
// including resources allocated by an initializer that later rejects.
|
||||
const initialization = this.initializeService(name, service).finally(async () => {
|
||||
entry.settled = true;
|
||||
if (failed) {await this.cleanupOnce(name, service);}
|
||||
});
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const expired = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(
|
||||
() => reject(new Error(`${name} initialization timed out after ${timeout}ms`)),
|
||||
timeout
|
||||
);
|
||||
});
|
||||
const clear = () => clearTimeout(timer);
|
||||
cancelTimers.push(clear);
|
||||
return Promise.race([initialization, expired]).finally(clear);
|
||||
});
|
||||
await Promise.all(work);
|
||||
this.logger.info('All services initialized successfully');
|
||||
} catch (error) {
|
||||
failed = true;
|
||||
// Only settled work can be released finally. Pending work retains the
|
||||
// cleanup continuation above, so startup need not wait on a hung connect.
|
||||
await Promise.allSettled(
|
||||
started
|
||||
.filter(entry => entry.settled)
|
||||
.reverse()
|
||||
.map(({ name, service }) => this.cleanupOnce(name, service))
|
||||
);
|
||||
throw error;
|
||||
} finally {
|
||||
for (const clear of cancelTimers) {clear();}
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(initPromises);
|
||||
this.logger.info('All services initialized successfully');
|
||||
private readonly cleanup = new WeakMap<ServiceWithLifecycle, Promise<void>>();
|
||||
|
||||
private cleanupOnce(name: string, service: ServiceWithLifecycle): Promise<void> {
|
||||
let work = this.cleanup.get(service);
|
||||
if (!work) {
|
||||
work = this.shutdownService(name, service);
|
||||
this.cleanup.set(service, work);
|
||||
}
|
||||
return work;
|
||||
}
|
||||
|
||||
async shutdownServices(container: AwilixContainer<ServiceDefinitions>): Promise<void> {
|
||||
const shutdownPromises: Promise<void>[] = [];
|
||||
|
||||
// Shutdown in reverse order
|
||||
// Resolve and clean independently: one broken resolver must not prevent
|
||||
// other, already connected resources from being released.
|
||||
for (const { name, key } of [...this.services].reverse()) {
|
||||
const service = container.cradle[key] as ServiceWithLifecycle | null;
|
||||
|
||||
if (service) {
|
||||
shutdownPromises.push(this.shutdownService(name, service));
|
||||
try {
|
||||
const service = container.cradle[key] as ServiceWithLifecycle | null;
|
||||
if (service) {await this.cleanupOnce(name, service);}
|
||||
} catch (error) {
|
||||
this.logger.error(`Error resolving ${name} during shutdown:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.allSettled(shutdownPromises);
|
||||
this.logger.info('All services shut down');
|
||||
}
|
||||
|
||||
|
|
@ -93,10 +123,4 @@ export class ServiceLifecycleManager {
|
|||
this.logger.error(`Error shutting down ${name}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
private createTimeoutPromise(timeout: number, message: string): Promise<never> {
|
||||
return new Promise((_, reject) => {
|
||||
setTimeout(() => reject(new Error(message)), timeout);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,443 +1,116 @@
|
|||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import type { AppConfig } from '../src/config/schemas';
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { ZodError } from 'zod';
|
||||
import { baseAppSchema } from '@stock-bot/config';
|
||||
import { ServiceContainerBuilder } from '../src/container/builder';
|
||||
|
||||
// Mock the external dependencies
|
||||
mock.module('@stock-bot/config', () => ({
|
||||
toUnifiedConfig: (config: any) => {
|
||||
const result: any = { ...config };
|
||||
// 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 },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Ensure service.serviceName is set
|
||||
if (result.service && !result.service.serviceName) {
|
||||
result.service.serviceName = result.service.name
|
||||
.replace(/([A-Z])/g, '-$1')
|
||||
.toLowerCase()
|
||||
.replace(/^-/, '');
|
||||
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();
|
||||
}
|
||||
|
||||
// Handle questdb field mapping
|
||||
if (result.questdb && result.questdb.ilpPort && !result.questdb.influxPort) {
|
||||
result.questdb.influxPort = result.questdb.ilpPort;
|
||||
}
|
||||
|
||||
// Set default environment if not provided
|
||||
if (!result.environment) {
|
||||
result.environment = 'test';
|
||||
}
|
||||
|
||||
// Ensure database object exists
|
||||
if (!result.database) {
|
||||
result.database = {};
|
||||
}
|
||||
|
||||
// Copy flat configs to nested if they exist
|
||||
if (result.redis) {
|
||||
result.database.dragonfly = result.redis;
|
||||
}
|
||||
if (result.mongodb) {
|
||||
result.database.mongodb = result.mongodb;
|
||||
}
|
||||
if (result.postgres) {
|
||||
result.database.postgres = result.postgres;
|
||||
}
|
||||
if (result.questdb) {
|
||||
result.database.questdb = result.questdb;
|
||||
}
|
||||
|
||||
return result;
|
||||
},
|
||||
}));
|
||||
|
||||
mock.module('@stock-bot/handler-registry', () => ({
|
||||
HandlerRegistry: class {
|
||||
private handlers = new Map();
|
||||
private metadata = new Map();
|
||||
|
||||
register(name: string, handler: any) {
|
||||
this.handlers.set(name, handler);
|
||||
}
|
||||
|
||||
get(name: string) {
|
||||
return this.handlers.get(name);
|
||||
}
|
||||
|
||||
has(name: string) {
|
||||
return this.handlers.has(name);
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.handlers.clear();
|
||||
this.metadata.clear();
|
||||
}
|
||||
|
||||
getAll() {
|
||||
return Array.from(this.handlers.entries());
|
||||
}
|
||||
|
||||
getAllMetadata() {
|
||||
return Array.from(this.metadata.entries());
|
||||
}
|
||||
|
||||
setMetadata(key: string, meta: any) {
|
||||
this.metadata.set(key, meta);
|
||||
}
|
||||
|
||||
getMetadata(key: string) {
|
||||
return this.metadata.get(key);
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
describe('ServiceContainerBuilder', () => {
|
||||
let builder: ServiceContainerBuilder;
|
||||
|
||||
beforeEach(() => {
|
||||
builder = new ServiceContainerBuilder();
|
||||
});
|
||||
|
||||
describe('configuration', () => {
|
||||
it('should accept AppConfig format', async () => {
|
||||
const config: AppConfig = {
|
||||
redis: { enabled: true, host: 'localhost', port: 6379, db: 0 },
|
||||
mongodb: { enabled: true, uri: 'mongodb://localhost', database: 'test' },
|
||||
postgres: {
|
||||
enabled: true,
|
||||
host: 'localhost',
|
||||
port: 5432,
|
||||
database: 'test',
|
||||
user: 'user',
|
||||
password: 'pass',
|
||||
},
|
||||
service: { name: 'test-service', serviceName: 'test-service' },
|
||||
};
|
||||
|
||||
try {
|
||||
const container = await builder.withConfig(config).skipInitialization().build();
|
||||
expect(container).toBeDefined();
|
||||
expect(container.hasRegistration('config')).toBe(true);
|
||||
} catch (error: any) {
|
||||
// If validation fails, that's OK for this test
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('should merge partial config with defaults', async () => {
|
||||
const partialConfig = {
|
||||
service: { name: 'test-service', serviceName: 'test-service' },
|
||||
};
|
||||
|
||||
try {
|
||||
const container = await builder.withConfig(partialConfig).skipInitialization().build();
|
||||
const resolvedConfig = container.resolve('config');
|
||||
expect(resolvedConfig.redis).toBeDefined();
|
||||
expect(resolvedConfig.mongodb).toBeDefined();
|
||||
expect(resolvedConfig.postgres).toBeDefined();
|
||||
} catch (error: any) {
|
||||
// If validation fails, that's OK for this test
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('should handle questdb field name mapping', async () => {
|
||||
const config = {
|
||||
questdb: {
|
||||
enabled: true,
|
||||
host: 'localhost',
|
||||
httpPort: 9000,
|
||||
pgPort: 8812,
|
||||
ilpPort: 9009, // Should be mapped to influxPort
|
||||
database: 'questdb',
|
||||
},
|
||||
service: { name: 'test-service', serviceName: 'test-service' },
|
||||
};
|
||||
|
||||
try {
|
||||
const container = await builder.withConfig(config).skipInitialization().build();
|
||||
const resolvedConfig = container.resolve('config');
|
||||
expect(resolvedConfig.questdb?.influxPort).toBe(9009);
|
||||
} catch (error: any) {
|
||||
// If validation fails, that's OK for this test
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
});
|
||||
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();
|
||||
}
|
||||
});
|
||||
|
||||
describe('service options', () => {
|
||||
it('should enable/disable services based on options', async () => {
|
||||
try {
|
||||
const container = await builder
|
||||
.withConfig({ service: { name: 'test' } })
|
||||
.enableService('enableCache', false)
|
||||
.enableService('enableMongoDB', false)
|
||||
.skipInitialization()
|
||||
.build();
|
||||
|
||||
const config = container.resolve('config');
|
||||
expect(config.redis.enabled).toBe(false);
|
||||
expect(config.mongodb.enabled).toBe(false);
|
||||
} catch (error: any) {
|
||||
// If validation fails, that's OK for this test
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('should apply options using withOptions', async () => {
|
||||
const options = {
|
||||
enableCache: false,
|
||||
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,
|
||||
skipInitialization: true,
|
||||
initializationTimeout: 60000,
|
||||
};
|
||||
|
||||
try {
|
||||
const container = await builder
|
||||
.withConfig({ service: { name: 'test' } })
|
||||
.withOptions(options)
|
||||
.build();
|
||||
|
||||
const config = container.resolve('config');
|
||||
expect(config.redis.enabled).toBe(false);
|
||||
expect(config.queue).toBeUndefined();
|
||||
expect(config.browser).toBeUndefined();
|
||||
} catch (error: any) {
|
||||
// If validation fails, that's OK for this test
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('should handle all service toggles', async () => {
|
||||
try {
|
||||
const container = await builder
|
||||
.withConfig({ service: { name: 'test' } })
|
||||
.enableService('enablePostgres', false)
|
||||
.enableService('enableQuestDB', false)
|
||||
.enableService('enableProxy', false)
|
||||
.skipInitialization()
|
||||
.build();
|
||||
|
||||
const config = container.resolve('config');
|
||||
expect(config.postgres.enabled).toBe(false);
|
||||
expect(config.questdb).toBeUndefined();
|
||||
expect(config.proxy).toBeUndefined();
|
||||
} catch (error: any) {
|
||||
// If validation fails, that's OK for this test
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
});
|
||||
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();
|
||||
}
|
||||
});
|
||||
|
||||
describe('initialization', () => {
|
||||
it('should skip initialization when requested', async () => {
|
||||
try {
|
||||
const container = await builder
|
||||
.withConfig({ service: { name: 'test' } })
|
||||
.skipInitialization()
|
||||
.build();
|
||||
|
||||
// Container should be built without initialization
|
||||
expect(container).toBeDefined();
|
||||
} catch (error: any) {
|
||||
// If validation fails, that's OK for this test
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('should initialize services by default', async () => {
|
||||
// This test would require full service setup which might fail
|
||||
// So we'll just test that it attempts initialization
|
||||
try {
|
||||
await builder.withConfig({ service: { name: 'test' } }).build();
|
||||
// If it succeeds, that's fine
|
||||
expect(true).toBe(true);
|
||||
} catch (error: any) {
|
||||
// Expected - services might not be available in test env
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
});
|
||||
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();
|
||||
}
|
||||
});
|
||||
|
||||
describe('container registration', () => {
|
||||
it('should register handler infrastructure', async () => {
|
||||
try {
|
||||
const container = await builder
|
||||
.withConfig({ service: { name: 'test-service' } })
|
||||
.skipInitialization()
|
||||
.build();
|
||||
|
||||
expect(container.hasRegistration('handlerRegistry')).toBe(true);
|
||||
expect(container.hasRegistration('handlerScanner')).toBe(true);
|
||||
} catch (error: any) {
|
||||
// If validation fails, that's OK for this test
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('should register service container aggregate', async () => {
|
||||
try {
|
||||
const container = await builder
|
||||
.withConfig({ service: { name: 'test' } })
|
||||
.skipInitialization()
|
||||
.build();
|
||||
|
||||
expect(container.hasRegistration('serviceContainer')).toBe(true);
|
||||
} catch (error: any) {
|
||||
// If validation fails, that's OK for this test
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('config defaults', () => {
|
||||
it('should provide sensible defaults for redis', async () => {
|
||||
try {
|
||||
const container = await builder
|
||||
.withConfig({ service: { name: 'test' } })
|
||||
.skipInitialization()
|
||||
.build();
|
||||
|
||||
const config = container.resolve('config');
|
||||
expect(config.redis).toEqual({
|
||||
enabled: true,
|
||||
host: 'localhost',
|
||||
port: 6379,
|
||||
db: 0,
|
||||
});
|
||||
} catch (error: any) {
|
||||
// If validation fails, that's OK for this test
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('should provide sensible defaults for queue', async () => {
|
||||
try {
|
||||
const container = await builder
|
||||
.withConfig({ service: { name: 'test' } })
|
||||
.skipInitialization()
|
||||
.build();
|
||||
|
||||
const config = container.resolve('config');
|
||||
expect(config.queue).toEqual({
|
||||
enabled: true,
|
||||
workers: 1,
|
||||
concurrency: 1,
|
||||
enableScheduledJobs: true,
|
||||
defaultJobOptions: {
|
||||
attempts: 3,
|
||||
backoff: { type: 'exponential', delay: 1000 },
|
||||
removeOnComplete: 100,
|
||||
removeOnFail: 100,
|
||||
},
|
||||
});
|
||||
} catch (error: any) {
|
||||
// If validation fails, that's OK for this test
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('should provide sensible defaults for browser', async () => {
|
||||
try {
|
||||
const container = await builder
|
||||
.withConfig({ service: { name: 'test' } })
|
||||
.skipInitialization()
|
||||
.build();
|
||||
|
||||
const config = container.resolve('config');
|
||||
expect(config.browser).toEqual({
|
||||
headless: true,
|
||||
timeout: 30000,
|
||||
});
|
||||
} catch (error: any) {
|
||||
// If validation fails, that's OK for this test
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('builder chaining', () => {
|
||||
it('should support method chaining', async () => {
|
||||
try {
|
||||
const container = await builder
|
||||
.withConfig({ service: { name: 'test' } })
|
||||
.enableService('enableCache', true)
|
||||
.enableService('enableQueue', false)
|
||||
.withOptions({ initializationTimeout: 45000 })
|
||||
.skipInitialization(true)
|
||||
.build();
|
||||
|
||||
expect(container).toBeDefined();
|
||||
const config = container.resolve('config');
|
||||
expect(config.redis.enabled).toBe(true);
|
||||
expect(config.queue).toBeUndefined();
|
||||
} catch (error: any) {
|
||||
// If validation fails, that's OK for this test
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('should allow multiple withConfig calls with last one winning', async () => {
|
||||
const config1 = {
|
||||
service: { name: 'service1' },
|
||||
redis: { enabled: true, host: 'host1', port: 6379, db: 0 },
|
||||
};
|
||||
const config2 = {
|
||||
service: { name: 'service2' },
|
||||
redis: { enabled: true, host: 'host2', port: 6380, db: 1 },
|
||||
};
|
||||
|
||||
try {
|
||||
const container = await builder
|
||||
.withConfig(config1)
|
||||
.withConfig(config2)
|
||||
.skipInitialization()
|
||||
.build();
|
||||
|
||||
const config = container.resolve('config');
|
||||
expect(config.service.name).toBe('service2');
|
||||
expect(config.redis.host).toBe('host2');
|
||||
expect(config.redis.port).toBe(6380);
|
||||
} catch (error: any) {
|
||||
// If validation fails, that's OK for this test
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('error handling', () => {
|
||||
it('should validate config before building', async () => {
|
||||
const invalidConfig = {
|
||||
redis: { enabled: 'not-a-boolean' }, // Invalid type
|
||||
service: { name: 'test' },
|
||||
};
|
||||
|
||||
try {
|
||||
await builder.withConfig(invalidConfig as any).build();
|
||||
// If we get here without error, that's fine in test env
|
||||
expect(true).toBe(true);
|
||||
} catch (error: any) {
|
||||
// Schema validation error is expected
|
||||
expect(error.name).toBe('ZodError');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('service container resolution', () => {
|
||||
it('should properly map services in serviceContainer', async () => {
|
||||
try {
|
||||
const container = await builder
|
||||
.withConfig({ service: { name: 'test' } })
|
||||
.skipInitialization()
|
||||
.build();
|
||||
|
||||
// We need to check that serviceContainer would properly map services
|
||||
// but we can't resolve it without all dependencies
|
||||
// So we'll just verify the registration exists
|
||||
const registrations = container.registrations;
|
||||
expect(registrations.serviceContainer).toBeDefined();
|
||||
} catch (error: any) {
|
||||
// If validation fails, that's OK for this test
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
});
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -18,6 +18,9 @@ describe('Dependency Injection', () => {
|
|||
const config = {
|
||||
name: 'test-service',
|
||||
version: '1.0.0',
|
||||
database: {
|
||||
mongodb: { enabled: false, uri: 'mongodb://localhost/test', database: 'test' },
|
||||
},
|
||||
service: {
|
||||
name: 'test-service',
|
||||
type: 'WORKER' as const,
|
||||
|
|
@ -41,6 +44,9 @@ describe('Dependency Injection', () => {
|
|||
const config = {
|
||||
name: 'test-service',
|
||||
version: '1.0.0',
|
||||
database: {
|
||||
mongodb: { enabled: false, uri: 'mongodb://localhost/test', database: 'test' },
|
||||
},
|
||||
service: {
|
||||
name: 'test-service',
|
||||
type: 'WORKER' as const,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue