- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
223 lines
5.9 KiB
TypeScript
223 lines
5.9 KiB
TypeScript
import { join } from 'path';
|
|
import { z } from 'zod';
|
|
import { getLogger } from '@stock-bot/logger';
|
|
import { ConfigError, ConfigValidationError } from './errors';
|
|
import { EnvLoader } from './loaders/env.loader';
|
|
import { FileLoader } from './loaders/file.loader';
|
|
import type {
|
|
ConfigLoader,
|
|
ConfigManagerOptions,
|
|
ConfigSchema,
|
|
DeepPartial,
|
|
Environment,
|
|
} from './types';
|
|
|
|
export type { ConfigManagerOptions } from './types';
|
|
|
|
export class ConfigManager<T = Record<string, unknown>> {
|
|
private readonly logger = getLogger('config-manager');
|
|
private config: T | null = null;
|
|
private loaders: ConfigLoader[];
|
|
private environment: Environment;
|
|
private schema?: ConfigSchema;
|
|
|
|
constructor(options: ConfigManagerOptions = {}, defaultSchema?: ConfigSchema) {
|
|
this.environment = options.environment || this.detectEnvironment();
|
|
this.schema = defaultSchema;
|
|
|
|
if (options.loaders) {
|
|
this.loaders = options.loaders;
|
|
} else {
|
|
const configPath = options.configPath || join(process.cwd(), 'config');
|
|
this.loaders = [new FileLoader(configPath, this.environment), new EnvLoader('')];
|
|
}
|
|
}
|
|
|
|
initialize(schema?: ConfigSchema): T {
|
|
if (this.config) {
|
|
return this.config;
|
|
}
|
|
|
|
if (schema) {
|
|
this.schema = schema;
|
|
}
|
|
|
|
const sortedLoaders = [...this.loaders].sort((a, b) => a.priority - b.priority);
|
|
|
|
const configs: Record<string, unknown>[] = [];
|
|
for (const loader of sortedLoaders) {
|
|
const config = loader.load();
|
|
if (config && Object.keys(config).length > 0) {
|
|
configs.push(config);
|
|
}
|
|
}
|
|
|
|
const mergedConfig = this.merge(...configs) as T;
|
|
|
|
if (
|
|
typeof mergedConfig === 'object' &&
|
|
mergedConfig !== null &&
|
|
!('environment' in mergedConfig)
|
|
) {
|
|
(mergedConfig as Record<string, unknown>)['environment'] = this.environment;
|
|
}
|
|
|
|
if (this.schema) {
|
|
try {
|
|
this.config = this.schema.parse(mergedConfig) as T;
|
|
} catch (error) {
|
|
if (error instanceof z.ZodError) {
|
|
const errorDetails = error.errors.map(err => ({
|
|
path: err.path.join('.'),
|
|
message: err.message,
|
|
code: err.code,
|
|
}));
|
|
|
|
this.logger.error('Configuration validation failed:', errorDetails);
|
|
throw new ConfigValidationError('Configuration validation failed', error.errors);
|
|
}
|
|
throw error;
|
|
}
|
|
} else {
|
|
this.config = mergedConfig;
|
|
}
|
|
|
|
return this.config;
|
|
}
|
|
|
|
get(): T {
|
|
if (!this.config) {
|
|
throw new ConfigError('Configuration not initialized. Call initialize() first.');
|
|
}
|
|
return this.config;
|
|
}
|
|
|
|
getValue<R = unknown>(path: string): R {
|
|
const config = this.get();
|
|
const keys = path.split('.');
|
|
let value: unknown = config;
|
|
|
|
for (const key of keys) {
|
|
if (value && typeof value === 'object' && key in value) {
|
|
value = (value as Record<string, unknown>)[key];
|
|
} else {
|
|
throw new ConfigError(`Configuration key not found: ${path}`);
|
|
}
|
|
}
|
|
|
|
return value as R;
|
|
}
|
|
|
|
has(path: string): boolean {
|
|
try {
|
|
this.getValue(path);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
set(updates: DeepPartial<T>): void {
|
|
if (!this.config) {
|
|
throw new ConfigError('Configuration not initialized. Call initialize() first.');
|
|
}
|
|
|
|
const updated = this.merge(
|
|
this.config as Record<string, unknown>,
|
|
updates as Record<string, unknown>
|
|
) as T;
|
|
|
|
if (this.schema) {
|
|
try {
|
|
this.config = this.schema.parse(updated) as T;
|
|
} catch (error) {
|
|
if (error instanceof z.ZodError) {
|
|
throw new ConfigValidationError(
|
|
'Configuration validation failed after update',
|
|
error.errors
|
|
);
|
|
}
|
|
throw error;
|
|
}
|
|
} else {
|
|
this.config = updated;
|
|
}
|
|
}
|
|
|
|
getEnvironment(): Environment {
|
|
return this.environment;
|
|
}
|
|
|
|
reset(): void {
|
|
this.config = null;
|
|
}
|
|
|
|
validate<S extends ConfigSchema>(schema: S): z.infer<S> {
|
|
const config = this.get();
|
|
return schema.parse(config);
|
|
}
|
|
|
|
private detectEnvironment(): Environment {
|
|
const env = process.env.NODE_ENV?.toLowerCase();
|
|
switch (env) {
|
|
case 'production':
|
|
case 'prod':
|
|
return 'production';
|
|
case 'qa':
|
|
return 'qa';
|
|
case 'test':
|
|
return 'test';
|
|
case 'development':
|
|
case 'dev':
|
|
default:
|
|
return 'development';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Deep merge tracking only active ancestor objects so valid shared DAG references
|
|
* (e.g. redis = database.dragonfly) are preserved rather than replaced with '[Circular]'.
|
|
*/
|
|
private merge(...objects: Record<string, unknown>[]): Record<string, unknown> {
|
|
const ancestors = new WeakSet<object>();
|
|
|
|
const mergeRecursive = (...objs: Record<string, unknown>[]): Record<string, unknown> => {
|
|
const result: Record<string, unknown> = {};
|
|
|
|
for (const obj of objs) {
|
|
for (const [key, value] of Object.entries(obj)) {
|
|
if (value === null || value === undefined) {
|
|
result[key] = value;
|
|
} else if (
|
|
typeof value === 'object' &&
|
|
!Array.isArray(value) &&
|
|
!(value instanceof Date) &&
|
|
!(value instanceof RegExp)
|
|
) {
|
|
if (ancestors.has(value)) {
|
|
result[key] = '[Circular]';
|
|
continue;
|
|
}
|
|
ancestors.add(value);
|
|
try {
|
|
result[key] = mergeRecursive(
|
|
(result[key] && typeof result[key] === 'object' && !Array.isArray(result[key])
|
|
? (result[key] as Record<string, unknown>)
|
|
: {}),
|
|
value as Record<string, unknown>
|
|
);
|
|
} finally {
|
|
ancestors.delete(value);
|
|
}
|
|
} else {
|
|
result[key] = value;
|
|
}
|
|
}
|
|
}
|
|
|
|
return result;
|
|
};
|
|
|
|
return mergeRecursive(...objects);
|
|
}
|
|
}
|