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

@ -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>;

View file

@ -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>;

View file

@ -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>;

View file

@ -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>;

View file

@ -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 {

View file

@ -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:', {

View file

@ -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);
});
}
}