- 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
318 lines
10 KiB
TypeScript
318 lines
10 KiB
TypeScript
import { readFileSync } from 'fs';
|
|
import { ConfigLoaderError } from '../errors';
|
|
import type { ConfigLoader } from '../types';
|
|
|
|
interface EnvLoaderOptions {
|
|
convertCase?: boolean;
|
|
parseJson?: boolean;
|
|
parseValues?: boolean;
|
|
nestedDelimiter?: string;
|
|
}
|
|
|
|
export class EnvLoader implements ConfigLoader {
|
|
readonly priority = 100;
|
|
|
|
constructor(
|
|
private prefix = '',
|
|
private options: EnvLoaderOptions = {}
|
|
) {
|
|
this.options = {
|
|
convertCase: false,
|
|
parseJson: true,
|
|
parseValues: true,
|
|
nestedDelimiter: '_',
|
|
...options,
|
|
};
|
|
}
|
|
|
|
load(): Record<string, unknown> {
|
|
try {
|
|
// Stop on the first .env file found so repo-root runs never traverse into parent directories
|
|
const possiblePaths = ['./.env', '../.env', '../../.env', '../../../.env'];
|
|
for (const path of possiblePaths) {
|
|
if (this.loadEnvFile(path)) {
|
|
break;
|
|
}
|
|
}
|
|
|
|
const config: Record<string, unknown> = {};
|
|
const envVars = process.env;
|
|
|
|
for (const [key, value] of Object.entries(envVars)) {
|
|
if (this.prefix && !key.startsWith(this.prefix)) {
|
|
continue;
|
|
}
|
|
|
|
const configKey = this.prefix ? key.slice(this.prefix.length) : key;
|
|
|
|
if (!this.options.convertCase && !this.options.nestedDelimiter) {
|
|
config[configKey] = this.parseValue(value || '');
|
|
} else {
|
|
this.setConfigValue(config, configKey, value || '');
|
|
}
|
|
}
|
|
|
|
return config;
|
|
} catch (error) {
|
|
throw new ConfigLoaderError(`Failed to load environment variables: ${error}`, 'EnvLoader');
|
|
}
|
|
}
|
|
|
|
private setConfigValue(config: Record<string, unknown>, key: string, value: string): void {
|
|
try {
|
|
if (!this.prefix && !this.options.convertCase) {
|
|
const providerMapping = this.getProviderMapping(key);
|
|
if (providerMapping) {
|
|
const shouldPreserveString = this.shouldPreserveStringForKey(key);
|
|
const parsedValue = shouldPreserveString ? value : this.parseValue(value);
|
|
this.setNestedValue(config, [...providerMapping.path], parsedValue);
|
|
return;
|
|
}
|
|
}
|
|
|
|
const parsedValue = this.shouldPreserveStringForKey(key) ? value : this.parseValue(value);
|
|
|
|
if (this.options.convertCase) {
|
|
const camelKey = this.toCamelCase(key);
|
|
config[camelKey] = parsedValue;
|
|
} else if (
|
|
this.options.nestedDelimiter &&
|
|
this.options.nestedDelimiter !== '_' &&
|
|
key.includes(this.options.nestedDelimiter)
|
|
) {
|
|
const parts = key.split(this.options.nestedDelimiter);
|
|
this.setNestedValue(config, parts, parsedValue);
|
|
} else if (key.includes('_')) {
|
|
const path = key.toLowerCase().split('_');
|
|
this.setNestedValue(config, path, parsedValue);
|
|
} else {
|
|
config[key] = parsedValue;
|
|
}
|
|
} catch {
|
|
// Skip environment variables that cannot be set on readonly target keys
|
|
}
|
|
}
|
|
|
|
private setNestedValue(obj: Record<string, unknown>, path: string[], value: unknown): boolean {
|
|
if (path.length === 0) {
|
|
return false;
|
|
}
|
|
const lastKey = path.pop();
|
|
if (!lastKey) {
|
|
return false;
|
|
}
|
|
|
|
try {
|
|
const target = path.reduce((acc, key) => {
|
|
if (!acc[key] || typeof acc[key] !== 'object') {
|
|
acc[key] = {};
|
|
}
|
|
return acc[key] as Record<string, unknown>;
|
|
}, obj);
|
|
|
|
(target as Record<string, unknown>)[lastKey] = value;
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private toCamelCase(str: string): string {
|
|
return str.toLowerCase().replace(/_([a-z])/g, (_, char) => char.toUpperCase());
|
|
}
|
|
|
|
private shouldPreserveStringForKey(key: string): boolean {
|
|
const preserveStringKeys = [
|
|
'QM_WEBMASTER_ID',
|
|
'IB_MARKET_DATA_TYPE',
|
|
'MONGODB_URI',
|
|
'MONGODB_READ_URI',
|
|
];
|
|
if (preserveStringKeys.includes(key)) {
|
|
return true;
|
|
}
|
|
return /(?:^|_)(?:PASSWORD|SECRET|TOKEN|API_KEY|URI)$/i.test(key);
|
|
}
|
|
|
|
private getProviderMapping(envKey: string): { path: string[] } | null {
|
|
const providerMappings: Record<string, string[]> = {
|
|
// Database mappings
|
|
MONGODB_URI: ['database', 'mongodb', 'uri'],
|
|
MONGODB_READ_URI: ['database', 'mongodb', 'readUri'],
|
|
MONGODB_READ_ONLY: ['database', 'mongodb', 'readOnly'],
|
|
MONGODB_DATABASE: ['database', 'mongodb', 'database'],
|
|
MONGODB_HOST: ['database', 'mongodb', 'host'],
|
|
MONGODB_PORT: ['database', 'mongodb', 'port'],
|
|
MONGODB_USERNAME: ['database', 'mongodb', 'user'],
|
|
MONGODB_PASSWORD: ['database', 'mongodb', 'password'],
|
|
POSTGRES_HOST: ['database', 'postgres', 'host'],
|
|
POSTGRES_PORT: ['database', 'postgres', 'port'],
|
|
POSTGRES_DATABASE: ['database', 'postgres', 'database'],
|
|
POSTGRES_USERNAME: ['database', 'postgres', 'user'],
|
|
POSTGRES_PASSWORD: ['database', 'postgres', 'password'],
|
|
POSTGRES_SSL: ['database', 'postgres', 'ssl'],
|
|
DRAGONFLY_HOST: ['database', 'dragonfly', 'host'],
|
|
DRAGONFLY_PORT: ['database', 'dragonfly', 'port'],
|
|
DRAGONFLY_PASSWORD: ['database', 'dragonfly', 'password'],
|
|
QUESTDB_ENABLED: ['database', 'questdb', 'enabled'],
|
|
QUESTDB_HOST: ['database', 'questdb', 'host'],
|
|
QUESTDB_PORT: ['database', 'questdb', 'httpPort'],
|
|
QUESTDB_HTTP_PORT: ['database', 'questdb', 'httpPort'],
|
|
QUESTDB_PG_PORT: ['database', 'questdb', 'pgPort'],
|
|
QUESTDB_ILP_PORT: ['database', 'questdb', 'ilpPort'],
|
|
QUESTDB_INFLUX_PORT: ['database', 'questdb', 'influxPort'],
|
|
QUESTDB_USER: ['database', 'questdb', 'user'],
|
|
QUESTDB_PASSWORD: ['database', 'questdb', 'password'],
|
|
|
|
// Queue mappings
|
|
QUEUE_ENABLED: ['queue', 'enabled'],
|
|
QUEUE_ENABLE_SCHEDULED_JOBS: ['queue', 'enableScheduledJobs'],
|
|
QUEUE_WORKERS: ['queue', 'workers'],
|
|
QUEUE_CONCURRENCY: ['queue', 'concurrency'],
|
|
QUEUE_REDIS_HOST: ['queue', 'redis', 'host'],
|
|
QUEUE_REDIS_PORT: ['queue', 'redis', 'port'],
|
|
QUEUE_REDIS_PASSWORD: ['queue', 'redis', 'password'],
|
|
QUEUE_REDIS_DB: ['queue', 'redis', 'db'],
|
|
|
|
// WebShare provider mappings
|
|
WEBSHARE_API_KEY: ['webshare', 'apiKey'],
|
|
WEBSHARE_API_URL: ['webshare', 'apiUrl'],
|
|
WEBSHARE_ENABLED: ['webshare', 'enabled'],
|
|
|
|
// EOD provider mappings
|
|
EOD_API_KEY: ['providers', 'eod', 'apiKey'],
|
|
EOD_BASE_URL: ['providers', 'eod', 'baseUrl'],
|
|
EOD_TIER: ['providers', 'eod', 'tier'],
|
|
EOD_ENABLED: ['providers', 'eod', 'enabled'],
|
|
EOD_PRIORITY: ['providers', 'eod', 'priority'],
|
|
|
|
// Interactive Brokers provider mappings
|
|
IB_GATEWAY_HOST: ['providers', 'ib', 'gateway', 'host'],
|
|
IB_GATEWAY_PORT: ['providers', 'ib', 'gateway', 'port'],
|
|
IB_CLIENT_ID: ['providers', 'ib', 'gateway', 'clientId'],
|
|
IB_ACCOUNT: ['providers', 'ib', 'account'],
|
|
IB_MARKET_DATA_TYPE: ['providers', 'ib', 'marketDataType'],
|
|
IB_ENABLED: ['providers', 'ib', 'enabled'],
|
|
IB_PRIORITY: ['providers', 'ib', 'priority'],
|
|
|
|
// QuoteMedia provider mappings
|
|
QM_USERNAME: ['providers', 'qm', 'username'],
|
|
QM_PASSWORD: ['providers', 'qm', 'password'],
|
|
QM_BASE_URL: ['providers', 'qm', 'baseUrl'],
|
|
QM_WEBMASTER_ID: ['providers', 'qm', 'webmasterId'],
|
|
QM_ENABLED: ['providers', 'qm', 'enabled'],
|
|
QM_PRIORITY: ['providers', 'qm', 'priority'],
|
|
|
|
// Yahoo Finance provider mappings
|
|
YAHOO_BASE_URL: ['providers', 'yahoo', 'baseUrl'],
|
|
YAHOO_COOKIE_JAR: ['providers', 'yahoo', 'cookieJar'],
|
|
YAHOO_CRUMB: ['providers', 'yahoo', 'crumb'],
|
|
YAHOO_ENABLED: ['providers', 'yahoo', 'enabled'],
|
|
YAHOO_PRIORITY: ['providers', 'yahoo', 'priority'],
|
|
|
|
// General application config mappings
|
|
NAME: ['name'],
|
|
VERSION: ['version'],
|
|
|
|
// Log mappings
|
|
LOG_LEVEL: ['log', 'level'],
|
|
LOG_FORMAT: ['log', 'format'],
|
|
LOG_HIDE_OBJECT: ['log', 'hideObject'],
|
|
LOG_LOKI_ENABLED: ['log', 'loki', 'enabled'],
|
|
LOG_LOKI_HOST: ['log', 'loki', 'host'],
|
|
LOG_LOKI_PORT: ['log', 'loki', 'port'],
|
|
|
|
DEBUG_MODE: ['debug'],
|
|
};
|
|
|
|
const mapping = providerMappings[envKey];
|
|
return mapping ? { path: mapping } : null;
|
|
}
|
|
|
|
private parseValue(value: string): unknown {
|
|
if (!this.options.parseValues && !this.options.parseJson) {
|
|
return value;
|
|
}
|
|
|
|
if (this.options.parseJson) {
|
|
try {
|
|
return JSON.parse(value);
|
|
} catch {
|
|
// Not JSON, continue
|
|
}
|
|
}
|
|
|
|
if (!this.options.parseValues) {
|
|
return value;
|
|
}
|
|
|
|
if (value.toLowerCase() === 'true') {
|
|
return true;
|
|
}
|
|
if (value.toLowerCase() === 'false') {
|
|
return false;
|
|
}
|
|
|
|
if (!/^[+-]/.test(value) && !/^0\d/.test(value)) {
|
|
const num = Number(value);
|
|
if (!isNaN(num) && value !== '') {
|
|
return num;
|
|
}
|
|
}
|
|
|
|
if (value.toLowerCase() === 'null') {
|
|
return null;
|
|
}
|
|
if (value.toLowerCase() === 'undefined') {
|
|
return undefined;
|
|
}
|
|
|
|
return value;
|
|
}
|
|
|
|
private loadEnvFile(filePath: string): boolean {
|
|
try {
|
|
const envContent = readFileSync(filePath, 'utf-8');
|
|
const lines = envContent.split('\n');
|
|
|
|
for (const line of lines) {
|
|
const trimmed = line.trim();
|
|
if (!trimmed || trimmed.startsWith('#')) {
|
|
continue;
|
|
}
|
|
|
|
const equalIndex = trimmed.indexOf('=');
|
|
if (equalIndex === -1) {
|
|
continue;
|
|
}
|
|
|
|
const key = trimmed.substring(0, equalIndex).trim();
|
|
if (!key) {
|
|
continue;
|
|
}
|
|
let value = trimmed.substring(equalIndex + 1).trim();
|
|
|
|
if (
|
|
(value.startsWith('"') && value.endsWith('"')) ||
|
|
(value.startsWith("'") && value.endsWith("'"))
|
|
) {
|
|
value = value.slice(1, -1);
|
|
}
|
|
|
|
if (!(key in process.env)) {
|
|
process.env[key] = value;
|
|
}
|
|
}
|
|
return true;
|
|
} catch (error: unknown) {
|
|
if (error && typeof error === 'object' && 'code' in error && error.code !== 'ENOENT') {
|
|
// eslint-disable-next-line no-console
|
|
console.warn(
|
|
`Warning: Could not load env file ${filePath}:`,
|
|
error instanceof Error ? error.message : String(error)
|
|
);
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
}
|