refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack

- 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
This commit is contained in:
Boki 2026-11-27 00:11:50 -05:00
parent ce9e2df67c
commit 4cd6038063
432 changed files with 1247 additions and 44469 deletions

View file

@ -1,83 +0,0 @@
export class CacheKeyGenerator {
/**
* Generate cache key for market data
*/
static marketData(symbol: string, timeframe: string, date?: Date): string {
const dateStr = date ? date.toISOString().split('T')[0] : 'latest';
return `market:${symbol.toLowerCase()}:${timeframe}:${dateStr}`;
}
/**
* Generate cache key for technical indicators
*/
static indicator(symbol: string, indicator: string, period: number, dataHash: string): string {
return `indicator:${symbol.toLowerCase()}:${indicator}:${period}:${dataHash}`;
}
/**
* Generate cache key for backtest results
*/
static backtest(strategyName: string, params: Record<string, unknown>): string {
const paramHash = this.hashObject(params);
return `backtest:${strategyName}:${paramHash}`;
}
/**
* Generate cache key for strategy results
*/
static strategy(strategyName: string, symbol: string, timeframe: string): string {
return `strategy:${strategyName}:${symbol.toLowerCase()}:${timeframe}`;
}
/**
* Generate cache key for user sessions
*/
static userSession(userId: string): string {
return `session:${userId}`;
}
/**
* Generate cache key for portfolio data
*/
static portfolio(userId: string, portfolioId: string): string {
return `portfolio:${userId}:${portfolioId}`;
}
/**
* Generate cache key for real-time prices
*/
static realtimePrice(symbol: string): string {
return `price:realtime:${symbol.toLowerCase()}`;
}
/**
* Generate cache key for order book data
*/
static orderBook(symbol: string, depth: number = 10): string {
return `orderbook:${symbol.toLowerCase()}:${depth}`;
}
/**
* Create a simple hash from object for cache keys
*/
private static hashObject(obj: Record<string, unknown>): string {
const str = JSON.stringify(obj, Object.keys(obj).sort());
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash; // Convert to 32-bit integer
}
return Math.abs(hash).toString(36);
}
}
/**
* Simple key generator function
*/
export function generateKey(...parts: (string | number | boolean | undefined)[]): string {
return parts
.filter(part => part !== undefined)
.map(part => String(part))
.join(':');
}

View file

@ -41,7 +41,7 @@ export class NamespacedCache implements CacheProvider {
// Clear only keys with this namespace prefix
const keys = await this.cache.keys(`${this.prefix}*`);
if (keys.length > 0) {
await Promise.all(keys.map(key => this.cache.del(key.substring(this.prefix.length))));
await Promise.all(keys.map(key => this.cache.del(key)));
}
}

View file

@ -1,6 +1,5 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { CacheFactory, createNamespacedCache } from '../src/cache-factory';
import { generateKey } from '../src/key-generator';
import type { ICache } from '../src/types';
describe('CacheFactory', () => {
@ -89,25 +88,3 @@ describe('NamespacedCache', () => {
expect(keys).toEqual(['key1', 'key2']);
});
});
describe('KeyGenerator', () => {
it('should generate key from parts', () => {
const key = generateKey('part1', 'part2', 'part3');
expect(key).toBe('part1:part2:part3');
});
it('should handle empty parts', () => {
const key = generateKey();
expect(key).toBe('');
});
it('should skip undefined parts', () => {
const key = generateKey('part1', undefined, 'part3');
expect(key).toBe('part1:part3');
});
it('should convert non-string parts', () => {
const key = generateKey('prefix', 123, true);
expect(key).toBe('prefix:123:true');
});
});

View file

@ -1,220 +0,0 @@
import { describe, expect, it } from 'bun:test';
import { CacheKeyGenerator, generateKey } from '../src/key-generator';
describe('CacheKeyGenerator', () => {
describe('marketData', () => {
it('should generate key with symbol, timeframe and date', () => {
const date = new Date('2024-01-15T10:30:00Z');
const key = CacheKeyGenerator.marketData('AAPL', '1h', date);
expect(key).toBe('market:aapl:1h:2024-01-15');
});
it('should generate key with "latest" when no date provided', () => {
const key = CacheKeyGenerator.marketData('MSFT', '1d');
expect(key).toBe('market:msft:1d:latest');
});
it('should lowercase the symbol', () => {
const key = CacheKeyGenerator.marketData('GOOGL', '5m');
expect(key).toBe('market:googl:5m:latest');
});
it('should handle different timeframes', () => {
expect(CacheKeyGenerator.marketData('TSLA', '1m')).toBe('market:tsla:1m:latest');
expect(CacheKeyGenerator.marketData('TSLA', '15m')).toBe('market:tsla:15m:latest');
expect(CacheKeyGenerator.marketData('TSLA', '1w')).toBe('market:tsla:1w:latest');
});
});
describe('indicator', () => {
it('should generate key with all parameters', () => {
const key = CacheKeyGenerator.indicator('AAPL', 'RSI', 14, 'abc123');
expect(key).toBe('indicator:aapl:RSI:14:abc123');
});
it('should lowercase the symbol but not indicator name', () => {
const key = CacheKeyGenerator.indicator('META', 'MACD', 20, 'hash456');
expect(key).toBe('indicator:meta:MACD:20:hash456');
});
it('should handle different period values', () => {
expect(CacheKeyGenerator.indicator('AMZN', 'SMA', 50, 'hash1')).toBe(
'indicator:amzn:SMA:50:hash1'
);
expect(CacheKeyGenerator.indicator('AMZN', 'SMA', 200, 'hash2')).toBe(
'indicator:amzn:SMA:200:hash2'
);
});
});
describe('backtest', () => {
it('should generate key with strategy name and hashed params', () => {
const params = { stopLoss: 0.02, takeProfit: 0.05 };
const key = CacheKeyGenerator.backtest('MomentumStrategy', params);
expect(key).toMatch(/^backtest:MomentumStrategy:[a-z0-9]+$/);
});
it('should generate same hash for same params regardless of order', () => {
const params1 = { a: 1, b: 2, c: 3 };
const params2 = { c: 3, a: 1, b: 2 };
const key1 = CacheKeyGenerator.backtest('Strategy', params1);
const key2 = CacheKeyGenerator.backtest('Strategy', params2);
expect(key1).toBe(key2);
});
it('should generate different hashes for different params', () => {
const params1 = { threshold: 0.01 };
const params2 = { threshold: 0.02 };
const key1 = CacheKeyGenerator.backtest('Strategy', params1);
const key2 = CacheKeyGenerator.backtest('Strategy', params2);
expect(key1).not.toBe(key2);
});
it('should handle complex nested params', () => {
const params = {
indicators: { rsi: { period: 14 }, macd: { fast: 12, slow: 26 } },
risk: { maxDrawdown: 0.1 },
};
const key = CacheKeyGenerator.backtest('ComplexStrategy', params);
expect(key).toMatch(/^backtest:ComplexStrategy:[a-z0-9]+$/);
});
});
describe('strategy', () => {
it('should generate key with strategy name, symbol and timeframe', () => {
const key = CacheKeyGenerator.strategy('TrendFollowing', 'NVDA', '4h');
expect(key).toBe('strategy:TrendFollowing:nvda:4h');
});
it('should lowercase the symbol but not strategy name', () => {
const key = CacheKeyGenerator.strategy('MeanReversion', 'AMD', '1d');
expect(key).toBe('strategy:MeanReversion:amd:1d');
});
});
describe('userSession', () => {
it('should generate key with userId', () => {
const key = CacheKeyGenerator.userSession('user123');
expect(key).toBe('session:user123');
});
it('should handle different userId formats', () => {
expect(CacheKeyGenerator.userSession('uuid-123-456')).toBe('session:uuid-123-456');
expect(CacheKeyGenerator.userSession('email@example.com')).toBe('session:email@example.com');
});
});
describe('portfolio', () => {
it('should generate key with userId and portfolioId', () => {
const key = CacheKeyGenerator.portfolio('user123', 'portfolio456');
expect(key).toBe('portfolio:user123:portfolio456');
});
it('should handle UUID format IDs', () => {
const key = CacheKeyGenerator.portfolio(
'550e8400-e29b-41d4-a716-446655440000',
'6ba7b810-9dad-11d1-80b4-00c04fd430c8'
);
expect(key).toBe(
'portfolio:550e8400-e29b-41d4-a716-446655440000:6ba7b810-9dad-11d1-80b4-00c04fd430c8'
);
});
});
describe('realtimePrice', () => {
it('should generate key with symbol', () => {
const key = CacheKeyGenerator.realtimePrice('BTC');
expect(key).toBe('price:realtime:btc');
});
it('should lowercase the symbol', () => {
const key = CacheKeyGenerator.realtimePrice('ETH-USD');
expect(key).toBe('price:realtime:eth-usd');
});
});
describe('orderBook', () => {
it('should generate key with symbol and default depth', () => {
const key = CacheKeyGenerator.orderBook('BTC');
expect(key).toBe('orderbook:btc:10');
});
it('should generate key with custom depth', () => {
const key = CacheKeyGenerator.orderBook('ETH', 20);
expect(key).toBe('orderbook:eth:20');
});
it('should lowercase the symbol', () => {
const key = CacheKeyGenerator.orderBook('USDT', 5);
expect(key).toBe('orderbook:usdt:5');
});
});
describe('hashObject', () => {
it('should generate consistent hashes', () => {
const params = { x: 1, y: 2 };
const key1 = CacheKeyGenerator.backtest('Test', params);
const key2 = CacheKeyGenerator.backtest('Test', params);
expect(key1).toBe(key2);
});
it('should handle empty objects', () => {
const key = CacheKeyGenerator.backtest('Empty', {});
expect(key).toMatch(/^backtest:Empty:[a-z0-9]+$/);
});
it('should handle arrays in objects', () => {
const params = { symbols: ['AAPL', 'MSFT'], periods: [10, 20, 30] };
const key = CacheKeyGenerator.backtest('ArrayTest', params);
expect(key).toMatch(/^backtest:ArrayTest:[a-z0-9]+$/);
});
it('should handle null and undefined values', () => {
const params = { a: null, b: undefined, c: 'value' };
const key = CacheKeyGenerator.backtest('NullTest', params);
expect(key).toMatch(/^backtest:NullTest:[a-z0-9]+$/);
});
});
});
describe('generateKey', () => {
it('should join parts with colons', () => {
const key = generateKey('user', 123, 'data');
expect(key).toBe('user:123:data');
});
it('should filter undefined values', () => {
const key = generateKey('prefix', undefined, 'suffix');
expect(key).toBe('prefix:suffix');
});
it('should convert all types to strings', () => {
const key = generateKey('bool', true, 'num', 42, 'str', 'text');
expect(key).toBe('bool:true:num:42:str:text');
});
it('should handle empty input', () => {
const key = generateKey();
expect(key).toBe('');
});
it('should handle single part', () => {
const key = generateKey('single');
expect(key).toBe('single');
});
it('should handle all undefined values', () => {
const key = generateKey(undefined, undefined, undefined);
expect(key).toBe('');
});
it('should handle boolean false', () => {
const key = generateKey('flag', false, 'end');
expect(key).toBe('flag:false:end');
});
it('should handle zero', () => {
const key = generateKey('count', 0, 'items');
expect(key).toBe('count:0:items');
});
});

View file

@ -189,9 +189,9 @@ describe('NamespacedCache', () => {
expect(mockCache.keys).toHaveBeenCalledWith('test-namespace:*');
expect(mockCache.del).toHaveBeenCalledTimes(3);
expect(mockCache.del).toHaveBeenCalledWith('key1');
expect(mockCache.del).toHaveBeenCalledWith('key2');
expect(mockCache.del).toHaveBeenCalledWith('key3');
expect(mockCache.del).toHaveBeenCalledWith('test-namespace:key1');
expect(mockCache.del).toHaveBeenCalledWith('test-namespace:key2');
expect(mockCache.del).toHaveBeenCalledWith('test-namespace:key3');
});
it('should handle empty namespace', async () => {

View file

@ -1,50 +0,0 @@
# Environment
NODE_ENV=development
# Service Configuration
STOCKBOT_SERVICE_NAME=stock-bot-service
STOCKBOT_SERVICE_PORT=3000
# Database Configuration
STOCKBOT_DATABASE_POSTGRES_HOST=localhost
STOCKBOT_DATABASE_POSTGRES_PORT=5432
STOCKBOT_DATABASE_POSTGRES_DATABASE=stockbot
STOCKBOT_DATABASE_POSTGRES_USER=postgres
STOCKBOT_DATABASE_POSTGRES_PASSWORD=postgres
STOCKBOT_DATABASE_QUESTDB_HOST=localhost
STOCKBOT_DATABASE_QUESTDB_ILP_PORT=9009
STOCKBOT_DATABASE_QUESTDB_HTTP_PORT=9000
STOCKBOT_DATABASE_MONGODB_HOST=localhost
STOCKBOT_DATABASE_MONGODB_PORT=27017
STOCKBOT_DATABASE_MONGODB_DATABASE=stockbot
STOCKBOT_DATABASE_DRAGONFLY_HOST=localhost
STOCKBOT_DATABASE_DRAGONFLY_PORT=6379
# Provider Configuration
STOCKBOT_PROVIDERS_EOD_API_KEY=your_eod_api_key
STOCKBOT_PROVIDERS_EOD_ENABLED=true
STOCKBOT_PROVIDERS_IB_ENABLED=false
STOCKBOT_PROVIDERS_IB_GATEWAY_HOST=localhost
STOCKBOT_PROVIDERS_IB_GATEWAY_PORT=5000
STOCKBOT_PROVIDERS_IB_ACCOUNT=your_account_id
STOCKBOT_PROVIDERS_QM_ENABLED=false
STOCKBOT_PROVIDERS_QM_USERNAME=your_username
STOCKBOT_PROVIDERS_QM_PASSWORD=your_password
STOCKBOT_PROVIDERS_QM_WEBMASTER_ID=your_webmaster_id
# Logging
STOCKBOT_LOGGING_LEVEL=info
STOCKBOT_LOGGING_LOKI_ENABLED=false
STOCKBOT_LOGGING_LOKI_HOST=localhost
STOCKBOT_LOGGING_LOKI_PORT=3100
# HTTP Proxy (optional)
STOCKBOT_HTTP_PROXY_ENABLED=false
STOCKBOT_HTTP_PROXY_URL=http://proxy.example.com:8080
STOCKBOT_HTTP_PROXY_AUTH_USERNAME=username
STOCKBOT_HTTP_PROXY_AUTH_PASSWORD=password

View file

@ -1,94 +0,0 @@
{
"name": "stock-bot",
"version": "1.0.0",
"debug": false,
"service": {
"name": "stock-bot-service",
"port": 3000,
"host": "0.0.0.0",
"healthCheckPath": "/health",
"metricsPath": "/metrics",
"shutdownTimeout": 30000,
"cors": {
"enabled": true,
"origin": "*",
"credentials": true
}
},
"logging": {
"level": "info",
"format": "json",
"loki": {
"enabled": false,
"host": "localhost",
"port": 3100,
"labels": {}
}
},
"database": {
"postgres": {
"host": "localhost",
"port": 5432,
"database": "stockbot",
"user": "postgres",
"password": "postgres",
"ssl": false,
"poolSize": 10,
"connectionTimeout": 30000,
"idleTimeout": 10000
},
"questdb": {
"host": "localhost",
"ilpPort": 9009,
"httpPort": 9000,
"pgPort": 8812,
"database": "questdb",
"user": "admin",
"password": "quest",
"bufferSize": 65536,
"flushInterval": 1000
},
"mongodb": {
"host": "localhost",
"port": 27017,
"database": "stockbot",
"authSource": "admin",
"poolSize": 10
},
"dragonfly": {
"host": "localhost",
"port": 6379,
"db": 0,
"maxRetries": 3,
"retryDelay": 100
}
},
"queue": {
"redis": {
"host": "localhost",
"port": 6379,
"db": 0
},
"defaultJobOptions": {
"attempts": 3,
"backoff": {
"type": "exponential",
"delay": 1000
},
"removeOnComplete": 100,
"removeOnFail": 100
}
},
"http": {
"timeout": 30000,
"retries": 3,
"retryDelay": 1000,
"proxy": {
"enabled": false
}
},
"webshare": {
"apiKey": "",
"apiUrl": "https://proxy.webshare.io/api/v2/"
}
}

View file

@ -1,48 +0,0 @@
{
"debug": true,
"logging": {
"level": "debug",
"format": "pretty"
},
"providers": {
"eod": {
"name": "eod-historical-data",
"enabled": true,
"priority": 1,
"apiKey": "demo",
"tier": "free",
"rateLimit": {
"maxRequests": 20,
"windowMs": 60000
}
},
"yahoo": {
"name": "yahoo-finance",
"enabled": true,
"priority": 2,
"rateLimit": {
"maxRequests": 100,
"windowMs": 60000
}
},
"ib": {
"name": "interactive-brokers",
"enabled": false,
"priority": 0,
"gateway": {
"host": "localhost",
"port": 5000,
"clientId": 1
},
"marketDataType": "delayed"
},
"qm": {
"name": "quotemedia",
"enabled": false,
"priority": 3,
"username": "",
"password": "",
"webmasterId": ""
}
}
}

View file

@ -1,32 +0,0 @@
{
"debug": false,
"logging": {
"level": "warn",
"format": "json",
"loki": {
"enabled": true,
"labels": {
"app": "stock-bot",
"env": "production"
}
}
},
"database": {
"postgres": {
"ssl": true,
"poolSize": 20
},
"questdb": {
"bufferSize": 131072,
"flushInterval": 500
},
"mongodb": {
"poolSize": 20
}
},
"http": {
"timeout": 60000,
"retries": 5,
"retryDelay": 2000
}
}

View file

@ -1,42 +0,0 @@
{
"debug": true,
"logging": {
"level": "error",
"format": "json"
},
"service": {
"port": 0,
"shutdownTimeout": 5000
},
"database": {
"postgres": {
"database": "stockbot_test",
"poolSize": 5
},
"questdb": {
"database": "questdb_test"
},
"mongodb": {
"database": "stockbot_test",
"poolSize": 5
},
"dragonfly": {
"db": 15,
"keyPrefix": "test:"
}
},
"queue": {
"redis": {
"db": 15
},
"defaultJobOptions": {
"attempts": 1,
"removeOnComplete": 100,
"removeOnFail": 100
}
},
"http": {
"timeout": 5000,
"retries": 1
}
}

View file

@ -14,13 +14,7 @@
"build": "tsc",
"dev": "tsc --watch",
"test": "bun test",
"clean": "rm -rf dist",
"cli": "bun run src/cli.ts",
"validate": "bun run src/cli.ts --validate",
"check": "bun run src/cli.ts --check"
},
"bin": {
"config-cli": "./dist/cli.js"
"clean": "rm -rf dist"
},
"dependencies": {
"@stock-bot/logger": "workspace:*",

View file

@ -1,175 +0,0 @@
#!/usr/bin/env bun
/* eslint-disable no-console */
import { join } from 'path';
import { parseArgs } from 'util';
import { redactSecrets } from './utils/secrets';
import {
checkRequiredEnvVars,
formatValidationResult,
validateCompleteness,
validateConfig,
} from './utils/validation';
import { ConfigManager } from './config-manager';
import { baseAppSchema } from './schemas';
import type { Environment } from './types';
interface CliOptions {
config?: string;
env?: string;
validate?: boolean;
show?: boolean;
check?: boolean;
json?: boolean;
help?: boolean;
}
const REQUIRED_PATHS = [
'service.name',
'service.port',
'database.postgres.host',
'database.postgres.database',
];
const REQUIRED_ENV_VARS = ['NODE_ENV'];
const SECRET_PATHS = [
'database.postgres.password',
'database.mongodb.uri',
'providers.quoteMedia.apiKey',
'providers.interactiveBrokers.clientId',
];
function printUsage() {
console.log(`
Stock Bot Configuration CLI
Usage: bun run config-cli [options]
Options:
--config <path> Path to config directory (default: ./config)
--env <env> Environment to use (development, test, production)
--validate Validate configuration against schema
--show Show current configuration (secrets redacted)
--check Run all configuration checks
--json Output in JSON format
--help Show this help message
Examples:
# Validate configuration
bun run config-cli --validate
# Show configuration for production
bun run config-cli --env production --show
# Run all checks
bun run config-cli --check
# Output configuration as JSON
bun run config-cli --show --json
`);
}
async function main() {
const { values } = parseArgs({
args: process.argv.slice(2),
options: {
config: { type: 'string' },
env: { type: 'string' },
validate: { type: 'boolean' },
show: { type: 'boolean' },
check: { type: 'boolean' },
json: { type: 'boolean' },
help: { type: 'boolean' },
},
}) as { values: CliOptions };
if (values.help) {
printUsage();
process.exit(0);
}
const configPath = values.config || join(process.cwd(), 'config');
const environment = values.env as Environment;
try {
const manager = new ConfigManager({
configPath,
environment,
});
const config = await manager.initialize(baseAppSchema);
if (values.validate) {
const result = validateConfig(config, baseAppSchema);
if (values.json) {
console.log(JSON.stringify(result, null, 2));
} else {
console.log(formatValidationResult(result));
}
process.exit(result.valid ? 0 : 1);
}
if (values.show) {
const redacted = redactSecrets(config, SECRET_PATHS);
if (values.json) {
console.log(JSON.stringify(redacted, null, 2));
} else {
console.log('Current Configuration:');
console.log(JSON.stringify(redacted, null, 2));
}
}
if (values.check) {
console.log('Running configuration checks...\n');
// Schema validation
console.log('1. Schema Validation:');
const schemaResult = validateConfig(config, baseAppSchema);
console.log(formatValidationResult(schemaResult));
console.log();
// Environment variables
console.log('2. Required Environment Variables:');
const envResult = checkRequiredEnvVars(REQUIRED_ENV_VARS);
console.log(formatValidationResult(envResult));
console.log();
// Required paths
console.log('3. Required Configuration Paths:');
const pathResult = validateCompleteness(config, REQUIRED_PATHS);
console.log(formatValidationResult(pathResult));
console.log();
// Overall result
const allValid = schemaResult.valid && envResult.valid && pathResult.valid;
if (allValid) {
console.log('✅ All configuration checks passed!');
process.exit(0);
} else {
console.log('❌ Some configuration checks failed');
process.exit(1);
}
}
if (!values.validate && !values.show && !values.check) {
console.log('No action specified. Use --help for usage information.');
process.exit(1);
}
} catch (error) {
if (values.json) {
console.error(JSON.stringify({ error: String(error) }));
} else {
console.error('Error:', error);
}
process.exit(1);
}
}
// Run CLI
if (import.meta.main) {
main();
}

View file

@ -1,9 +1,9 @@
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 { ConfigError, ConfigValidationError } from './errors';
import type {
ConfigLoader,
ConfigManagerOptions,
@ -21,8 +21,9 @@ export class ConfigManager<T = Record<string, unknown>> {
private environment: Environment;
private schema?: ConfigSchema;
constructor(options: ConfigManagerOptions = {}) {
constructor(options: ConfigManagerOptions = {}, defaultSchema?: ConfigSchema) {
this.environment = options.environment || this.detectEnvironment();
this.schema = defaultSchema;
if (options.loaders) {
this.loaders = options.loaders;
@ -32,20 +33,17 @@ export class ConfigManager<T = Record<string, unknown>> {
}
}
/**
* Initialize the configuration by loading from all sources
*/
initialize(schema?: ConfigSchema): T {
if (this.config) {
return this.config;
}
this.schema = schema;
if (schema) {
this.schema = schema;
}
// Sort loaders by priority (higher priority last)
const sortedLoaders = [...this.loaders].sort((a, b) => a.priority - b.priority);
// Load configurations from all sources
const configs: Record<string, unknown>[] = [];
for (const loader of sortedLoaders) {
const config = loader.load();
@ -54,10 +52,8 @@ export class ConfigManager<T = Record<string, unknown>> {
}
}
// Merge all configurations
const mergedConfig = this.merge(...configs) as T;
// Add environment if not present
if (
typeof mergedConfig === 'object' &&
mergedConfig !== null &&
@ -66,7 +62,6 @@ export class ConfigManager<T = Record<string, unknown>> {
(mergedConfig as Record<string, unknown>)['environment'] = this.environment;
}
// Validate if schema provided
if (this.schema) {
try {
this.config = this.schema.parse(mergedConfig) as T;
@ -90,9 +85,6 @@ export class ConfigManager<T = Record<string, unknown>> {
return this.config;
}
/**
* Get the current configuration
*/
get(): T {
if (!this.config) {
throw new ConfigError('Configuration not initialized. Call initialize() first.');
@ -100,9 +92,6 @@ export class ConfigManager<T = Record<string, unknown>> {
return this.config;
}
/**
* Get a specific configuration value by path
*/
getValue<R = unknown>(path: string): R {
const config = this.get();
const keys = path.split('.');
@ -119,9 +108,6 @@ export class ConfigManager<T = Record<string, unknown>> {
return value as R;
}
/**
* Check if a configuration path exists
*/
has(path: string): boolean {
try {
this.getValue(path);
@ -131,9 +117,6 @@ export class ConfigManager<T = Record<string, unknown>> {
}
}
/**
* Update configuration at runtime
*/
set(updates: DeepPartial<T>): void {
if (!this.config) {
throw new ConfigError('Configuration not initialized. Call initialize() first.');
@ -161,23 +144,14 @@ export class ConfigManager<T = Record<string, unknown>> {
}
}
/**
* Get the current environment
*/
getEnvironment(): Environment {
return this.environment;
}
/**
* Reset configuration
*/
reset(): void {
this.config = null;
}
/**
* Validate configuration against a schema
*/
validate<S extends ConfigSchema>(schema: S): z.infer<S> {
const config = this.get();
return schema.parse(config);
@ -201,11 +175,12 @@ export class ConfigManager<T = Record<string, unknown>> {
}
/**
* Deep merge with circular reference handling
* 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 seen = new WeakSet();
const ancestors = new WeakSet<object>();
const mergeRecursive = (...objs: Record<string, unknown>[]): Record<string, unknown> => {
const result: Record<string, unknown> = {};
@ -219,17 +194,21 @@ export class ConfigManager<T = Record<string, unknown>> {
!(value instanceof Date) &&
!(value instanceof RegExp)
) {
// Check for circular reference
if (seen.has(value)) {
if (ancestors.has(value)) {
result[key] = '[Circular]';
continue;
}
seen.add(value);
result[key] = mergeRecursive(
(result[key] as Record<string, unknown>) || {},
value as Record<string, unknown>
);
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;
}
@ -238,7 +217,7 @@ export class ConfigManager<T = Record<string, unknown>> {
return result;
};
return mergeRecursive(...objects);
}
}

View file

@ -1,14 +1,10 @@
import { ConfigManager, type ConfigManagerOptions } from './config-manager';
import type { ConfigSchema } from './types';
// Export only what's actually used
export { ConfigManager } from './config-manager';
export type { ConfigManagerOptions } from './config-manager';
export { toUnifiedConfig } from './schemas/unified-app.schema';
// Export used types
export type { BaseAppConfig, UnifiedAppConfig } from './schemas';
// Export schemas that are used by apps
export {
baseAppSchema,
dragonflyConfigSchema,
@ -24,33 +20,13 @@ export {
type ProviderName,
} from './schemas';
// createAppConfig function for apps/stock
export function createAppConfig<T>(
schema: unknown,
options?: ConfigManagerOptions
): ConfigManager<T> {
return new ConfigManager<T>(options);
const zodSchema =
schema && typeof schema === 'object' && 'parse' in schema
? (schema as ConfigSchema)
: undefined;
return new ConfigManager<T>(options, zodSchema);
}
// Export utilities
export {
SecretValue,
secret,
isSecret,
isSecretEnvVar,
COMMON_SECRET_PATTERNS,
redactSecrets,
wrapSecretEnvVars,
secretSchema,
secretStringSchema
} from './utils/secrets';
export {
checkRequiredEnvVars,
createStrictSchema,
formatValidationResult,
mergeSchemas,
validateConfig,
validateCompleteness,
type ValidationResult
} from './utils/validation';

View file

@ -10,7 +10,7 @@ interface EnvLoaderOptions {
}
export class EnvLoader implements ConfigLoader {
readonly priority = 100; // Highest priority
readonly priority = 100;
constructor(
private prefix = '',
@ -27,10 +27,12 @@ export class EnvLoader implements ConfigLoader {
load(): Record<string, unknown> {
try {
// Load root .env file - try multiple possible locations
// 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) {
this.loadEnvFile(path);
if (this.loadEnvFile(path)) {
break;
}
}
const config: Record<string, unknown> = {};
@ -44,10 +46,8 @@ export class EnvLoader implements ConfigLoader {
const configKey = this.prefix ? key.slice(this.prefix.length) : key;
if (!this.options.convertCase && !this.options.nestedDelimiter) {
// Simple case - just keep the key as is
config[configKey] = this.parseValue(value || '');
} else {
// Handle nested structure or case conversion
this.setConfigValue(config, configKey, value || '');
}
}
@ -60,22 +60,19 @@ export class EnvLoader implements ConfigLoader {
private setConfigValue(config: Record<string, unknown>, key: string, value: string): void {
try {
// Handle provider-specific environment variables (only for application usage, not tests)
if (!this.prefix && !this.options.convertCase) {
const providerMapping = this.getProviderMapping(key);
if (providerMapping) {
// For certain fields, we need to preserve the string value
const shouldPreserveString = this.shouldPreserveStringForKey(key);
const parsedValue = shouldPreserveString ? value : this.parseValue(value);
this.setNestedValue(config, providerMapping.path, parsedValue);
this.setNestedValue(config, [...providerMapping.path], parsedValue);
return;
}
}
const parsedValue = this.parseValue(value);
const parsedValue = this.shouldPreserveStringForKey(key) ? value : this.parseValue(value);
if (this.options.convertCase) {
// Convert to camelCase
const camelKey = this.toCamelCase(key);
config[camelKey] = parsedValue;
} else if (
@ -83,32 +80,26 @@ export class EnvLoader implements ConfigLoader {
this.options.nestedDelimiter !== '_' &&
key.includes(this.options.nestedDelimiter)
) {
// Handle nested delimiter (e.g., APP__NAME -> { APP: { NAME: value } })
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 {
// Convert to nested structure based on underscores, or keep as-is if no underscores
if (key.includes('_')) {
const path = key.toLowerCase().split('_');
this.setNestedValue(config, path, parsedValue);
} else {
// Single key without underscores - keep original case
config[key] = parsedValue;
}
config[key] = parsedValue;
}
} catch {
// Skip environment variables that can't be set (readonly properties)
// This is expected behavior for system environment variables
// 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; // Cannot set value on empty path
return false;
}
const lastKey = path.pop();
if (!lastKey) {
return false; // This should never happen due to length check above
return false;
}
try {
@ -122,7 +113,6 @@ export class EnvLoader implements ConfigLoader {
(target as Record<string, unknown>)[lastKey] = value;
return true;
} catch {
// If we can't assign to any property (readonly), skip this env var silently
return false;
}
}
@ -132,22 +122,19 @@ export class EnvLoader implements ConfigLoader {
}
private shouldPreserveStringForKey(key: string): boolean {
// Keys that should preserve string values even if they look like numbers
const preserveStringKeys = [
'QM_WEBMASTER_ID',
'IB_MARKET_DATA_TYPE',
'MONGODB_URI',
'MONGODB_READ_URI',
'MONGODB_PASSWORD',
'POSTGRES_PASSWORD',
'DRAGONFLY_PASSWORD',
'QUESTDB_PASSWORD',
];
return preserveStringKeys.includes(key);
if (preserveStringKeys.includes(key)) {
return true;
}
return /(?:^|_)(?:PASSWORD|SECRET|TOKEN|API_KEY|URI)$/i.test(key);
}
private getProviderMapping(envKey: string): { path: string[] } | null {
// Provider-specific and special environment variable mappings
const providerMappings: Record<string, string[]> = {
// Database mappings
MONGODB_URI: ['database', 'mongodb', 'uri'],
@ -167,8 +154,25 @@ export class EnvLoader implements ConfigLoader {
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'],
@ -210,7 +214,7 @@ export class EnvLoader implements ConfigLoader {
NAME: ['name'],
VERSION: ['version'],
// Log mappings (using LOG_ prefix for all)
// Log mappings
LOG_LEVEL: ['log', 'level'],
LOG_FORMAT: ['log', 'format'],
LOG_HIDE_OBJECT: ['log', 'hideObject'],
@ -218,7 +222,6 @@ export class EnvLoader implements ConfigLoader {
LOG_LOKI_HOST: ['log', 'loki', 'host'],
LOG_LOKI_PORT: ['log', 'loki', 'port'],
// Special mappings to avoid conflicts
DEBUG_MODE: ['debug'],
};
@ -231,12 +234,11 @@ export class EnvLoader implements ConfigLoader {
return value;
}
// Try to parse as JSON first if enabled
if (this.options.parseJson) {
try {
return JSON.parse(value);
} catch {
// Not JSON, continue with other parsing
// Not JSON, continue
}
}
@ -244,7 +246,6 @@ export class EnvLoader implements ConfigLoader {
return value;
}
// Handle booleans
if (value.toLowerCase() === 'true') {
return true;
}
@ -252,7 +253,6 @@ export class EnvLoader implements ConfigLoader {
return false;
}
// Handle numbers (but preserve strings with leading zeros or plus signs)
if (!/^[+-]/.test(value) && !/^0\d/.test(value)) {
const num = Number(value);
if (!isNaN(num) && value !== '') {
@ -260,7 +260,6 @@ export class EnvLoader implements ConfigLoader {
}
}
// Handle null/undefined
if (value.toLowerCase() === 'null') {
return null;
}
@ -268,11 +267,10 @@ export class EnvLoader implements ConfigLoader {
return undefined;
}
// Return as string
return value;
}
private loadEnvFile(filePath: string): void {
private loadEnvFile(filePath: string): boolean {
try {
const envContent = readFileSync(filePath, 'utf-8');
const lines = envContent.split('\n');
@ -280,18 +278,20 @@ export class EnvLoader implements ConfigLoader {
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) {
continue; // Skip empty lines and comments
continue;
}
const equalIndex = trimmed.indexOf('=');
if (equalIndex === -1) {
continue; // Skip lines without =
continue;
}
const key = trimmed.substring(0, equalIndex).trim();
if (!key) {
continue;
}
let value = trimmed.substring(equalIndex + 1).trim();
// Remove surrounding quotes if present
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
@ -299,13 +299,12 @@ export class EnvLoader implements ConfigLoader {
value = value.slice(1, -1);
}
// Only set if not already set (allows override precedence)
if (!(key in process.env)) {
process.env[key] = value;
}
}
return true;
} catch (error: unknown) {
// File not found is not an error (env files are optional)
if (error && typeof error === 'object' && 'code' in error && error.code !== 'ENOENT') {
// eslint-disable-next-line no-console
console.warn(
@ -313,6 +312,7 @@ export class EnvLoader implements ConfigLoader {
error instanceof Error ? error.message : String(error)
);
}
return false;
}
}
}

View file

@ -1,178 +0,0 @@
import { z } from 'zod';
/**
* Secret value wrapper to prevent accidental logging
*/
export class SecretValue<T = string> {
private readonly value: T;
private readonly masked: string;
constructor(value: T, mask: string = '***') {
this.value = value;
this.masked = mask;
}
/**
* Get the actual secret value
* @param reason - Required reason for accessing the secret
*/
reveal(reason: string): T {
if (!reason) {
throw new Error('Reason required for revealing secret value');
}
return this.value;
}
/**
* Get masked representation
*/
toString(): string {
return this.masked;
}
/**
* Prevent JSON serialization of actual value
*/
toJSON(): string {
return this.masked;
}
/**
* Check if value matches without revealing it
*/
equals(other: T): boolean {
return this.value === other;
}
/**
* Transform the secret value
*/
map<R>(fn: (value: T) => R, reason: string): SecretValue<R> {
return new SecretValue(fn(this.reveal(reason)));
}
}
/**
* Zod schema for secret values
*/
export const secretSchema = <T extends z.ZodTypeAny>(_schema: T) => {
return z.custom<SecretValue<z.infer<T>>>(val => val instanceof SecretValue, {
message: 'Expected SecretValue instance',
});
};
/**
* Transform string to SecretValue in Zod schema
*/
export const secretStringSchema = z.string().transform(val => new SecretValue(val));
/**
* Create a secret value
*/
export function secret<T = string>(value: T, mask?: string): SecretValue<T> {
return new SecretValue(value, mask);
}
/**
* Check if a value is a secret
*/
export function isSecret(value: unknown): value is SecretValue {
return value instanceof SecretValue;
}
/**
* Redact secrets from an object
*/
export function redactSecrets<T extends Record<string, unknown>>(
obj: T,
secretPaths: string[] = []
): T {
const result = redactSecretValues(obj) as T;
// Redact known secret paths
for (const path of secretPaths) {
const keys = path.split('.');
let current: Record<string, unknown> = result;
for (let i = 0; i < keys.length - 1; i++) {
const key = keys[i];
if (key && current[key] && typeof current[key] === 'object') {
current = current[key] as Record<string, unknown>;
} else {
break;
}
}
const lastKey = keys[keys.length - 1];
if (current && lastKey && lastKey in current) {
current[lastKey] = '***REDACTED***';
}
}
// Recursively redact SecretValue instances
function redactSecretValues(obj: unknown): unknown {
if (obj === null || obj === undefined) {
return obj;
}
if (isSecret(obj)) {
return obj.toString();
}
if (Array.isArray(obj)) {
return obj.map(redactSecretValues);
}
if (typeof obj === 'object') {
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(obj)) {
result[key] = redactSecretValues(value);
}
return result;
}
return obj;
}
return result;
}
/**
* Environment variable names that should be treated as secrets
*/
export const COMMON_SECRET_PATTERNS = [
/password/i,
/secret/i,
/key/i,
/token/i,
/credential/i,
/private/i,
/auth/i,
/api[-_]?key/i,
];
/**
* Check if an environment variable name indicates a secret
*/
export function isSecretEnvVar(name: string): boolean {
return COMMON_SECRET_PATTERNS.some(pattern => pattern.test(name));
}
/**
* Wrap environment variables that look like secrets
*/
export function wrapSecretEnvVars(
env: Record<string, string | undefined>
): Record<string, string | SecretValue | undefined> {
const result: Record<string, string | SecretValue | undefined> = {};
for (const [key, value] of Object.entries(env)) {
if (value !== undefined && isSecretEnvVar(key)) {
result[key] = new SecretValue(value, `***${key}***`);
} else {
result[key] = value;
}
}
return result;
}

View file

@ -1,155 +0,0 @@
import { z } from 'zod';
import { defined } from '@stock-bot/invariants';
export interface ValidationResult {
valid: boolean;
errors?: Array<{
path: string;
message: string;
expected?: string;
received?: string;
}>;
warnings?: Array<{
path: string;
message: string;
}>;
}
/**
* Validate configuration against a schema
*/
export function validateConfig<T>(config: unknown, schema: z.ZodSchema<T>): ValidationResult {
try {
schema.parse(config);
return { valid: true };
} catch (error) {
if (error instanceof z.ZodError) {
const errors = error.errors.map(err => ({
path: err.path.join('.'),
message: err.message,
expected: 'expected' in err ? String(err.expected) : undefined,
received: 'received' in err ? String(err.received) : undefined,
}));
return { valid: false, errors };
}
throw error;
}
}
/**
* Check for required environment variables
*/
export function checkRequiredEnvVars(required: string[]): ValidationResult {
const errors: ValidationResult['errors'] = [];
for (const envVar of required) {
if (!process.env[envVar]) {
errors.push({
path: `env.${envVar}`,
message: `Required environment variable ${envVar} is not set`,
});
}
}
return {
valid: errors.length === 0,
errors: errors.length > 0 ? errors : undefined,
};
}
/**
* Validate configuration completeness
*/
export function validateCompleteness(
config: Record<string, unknown>,
required: string[]
): ValidationResult {
const errors: ValidationResult['errors'] = [];
for (const path of required) {
const keys = path.split('.');
let current: unknown = config;
let found = true;
for (const key of keys) {
if (current && typeof current === 'object' && key in current) {
current = (current as Record<string, unknown>)[key];
} else {
found = false;
break;
}
}
if (!found || current === undefined || current === null) {
errors.push({
path,
message: `Required configuration value is missing`,
});
}
}
return {
valid: errors.length === 0,
errors: errors.length > 0 ? errors : undefined,
};
}
/**
* Format validation result for display
*/
export function formatValidationResult(result: ValidationResult): string {
const lines: string[] = [];
if (result.valid) {
lines.push('✅ Configuration is valid');
} else {
lines.push('❌ Configuration validation failed');
}
if (result.errors && result.errors.length > 0) {
lines.push('\nErrors:');
for (const error of result.errors) {
lines.push(` - ${error.path}: ${error.message}`);
if (error.expected && error.received) {
lines.push(` Expected: ${error.expected}, Received: ${error.received}`);
}
}
}
if (result.warnings && result.warnings.length > 0) {
lines.push('\nWarnings:');
for (const warning of result.warnings) {
lines.push(` - ${warning.path}: ${warning.message}`);
}
}
return lines.join('\n');
}
/**
* Create a strict schema that doesn't allow extra properties
*/
export function createStrictSchema<T extends z.ZodRawShape>(shape: T): z.ZodObject<T, 'strict'> {
return z.object(shape).strict();
}
/**
* Merge multiple schemas
*/
export function mergeSchemas<T extends z.ZodSchema[]>(
...schemas: T
): z.ZodIntersection<T[0], T[1]> {
if (schemas.length < 2) {
throw new Error('At least two schemas required for merge');
}
let result: z.ZodTypeAny = defined(schemas[0]).and(defined(schemas[1]));
for (let i = 2; i < schemas.length; i++) {
result = result.and(defined(schemas[i]));
}
return result as z.ZodIntersection<T[0], T[1]>;
}

View file

@ -1,518 +0,0 @@
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { z } from 'zod';
import {
checkRequiredEnvVars,
COMMON_SECRET_PATTERNS,
createStrictSchema,
formatValidationResult,
isSecret,
isSecretEnvVar,
mergeSchemas,
redactSecrets,
secret,
secretSchema,
secretStringSchema,
SecretValue,
validateCompleteness,
validateConfig,
wrapSecretEnvVars,
type ValidationResult,
} from '../src';
describe('Config Utils', () => {
describe('SecretValue', () => {
it('should create a secret value', () => {
const secret = new SecretValue('my-secret');
expect(secret).toBeInstanceOf(SecretValue);
expect(secret.toString()).toBe('***');
});
it('should use custom mask', () => {
const secret = new SecretValue('my-secret', 'HIDDEN');
expect(secret.toString()).toBe('HIDDEN');
});
it('should reveal value with reason', () => {
const secret = new SecretValue('my-secret');
expect(secret.reveal('testing')).toBe('my-secret');
});
it('should throw when revealing without reason', () => {
const secret = new SecretValue('my-secret');
expect(() => secret.reveal('')).toThrow('Reason required for revealing secret value');
});
it('should mask value in JSON', () => {
const secret = new SecretValue('my-secret');
expect(JSON.stringify(secret)).toBe('"***"');
expect(secret.toJSON()).toBe('***');
});
it('should compare values without revealing', () => {
const secret = new SecretValue('my-secret');
expect(secret.equals('my-secret')).toBe(true);
expect(secret.equals('other-secret')).toBe(false);
});
it('should map secret values', () => {
const secret = new SecretValue('hello');
const mapped = secret.map(val => val.toUpperCase(), 'testing transformation');
expect(mapped.reveal('checking result')).toBe('HELLO');
expect(mapped.toString()).toBe('***');
});
it('should work with non-string types', () => {
const numberSecret = new SecretValue(12345, 'XXX');
expect(numberSecret.reveal('test')).toBe(12345);
expect(numberSecret.toString()).toBe('XXX');
const objectSecret = new SecretValue({ key: 'value' }, '[OBJECT]');
expect(objectSecret.reveal('test')).toEqual({ key: 'value' });
expect(objectSecret.toString()).toBe('[OBJECT]');
});
});
describe('secret helper function', () => {
it('should create secret values', () => {
const s = secret('my-secret');
expect(s).toBeInstanceOf(SecretValue);
expect(s.reveal('test')).toBe('my-secret');
});
it('should accept custom mask', () => {
const s = secret('my-secret', 'REDACTED');
expect(s.toString()).toBe('REDACTED');
});
});
describe('isSecret', () => {
it('should identify secret values', () => {
expect(isSecret(new SecretValue('test'))).toBe(true);
expect(isSecret(secret('test'))).toBe(true);
expect(isSecret('test')).toBe(false);
expect(isSecret(null)).toBe(false);
expect(isSecret(undefined)).toBe(false);
expect(isSecret({})).toBe(false);
});
});
describe('secretSchema', () => {
it('should validate SecretValue instances', () => {
const schema = secretSchema(z.string());
const secretVal = new SecretValue('test');
expect(() => schema.parse(secretVal)).not.toThrow();
expect(() => schema.parse('test')).toThrow();
expect(() => schema.parse(null)).toThrow();
});
});
describe('secretStringSchema', () => {
it('should transform string to SecretValue', () => {
const result = secretStringSchema.parse('my-secret');
expect(result).toBeInstanceOf(SecretValue);
expect(result.reveal('test')).toBe('my-secret');
});
it('should reject non-strings', () => {
expect(() => secretStringSchema.parse(123)).toThrow();
expect(() => secretStringSchema.parse(null)).toThrow();
});
});
describe('redactSecrets', () => {
it('should redact specified paths', () => {
const obj = {
username: 'admin',
password: 'secret123',
nested: {
apiKey: 'key123',
public: 'visible',
},
};
const redacted = redactSecrets(obj, ['password', 'nested.apiKey']);
expect(redacted).toEqual({
username: 'admin',
password: '***REDACTED***',
nested: {
apiKey: '***REDACTED***',
public: 'visible',
},
});
});
it('should redact SecretValue instances', () => {
const obj = {
normal: 'value',
secret: new SecretValue('hidden', 'MASKED'),
nested: {
anotherSecret: secret('also-hidden'),
},
};
const redacted = redactSecrets(obj);
expect(redacted).toEqual({
normal: 'value',
secret: 'MASKED',
nested: {
anotherSecret: '***',
},
});
});
it('should handle arrays', () => {
const obj = {
items: [
{ name: 'item1', secret: new SecretValue('s1') },
{ name: 'item2', secret: new SecretValue('s2') },
],
};
const redacted = redactSecrets(obj);
expect(redacted.items).toEqual([
{ name: 'item1', secret: '***' },
{ name: 'item2', secret: '***' },
]);
});
it('should handle null and undefined', () => {
const obj = {
nullValue: null,
undefinedValue: undefined,
secret: new SecretValue('test'),
};
const redacted = redactSecrets(obj);
expect(redacted).toEqual({
nullValue: null,
undefinedValue: undefined,
secret: '***',
});
});
it('should handle non-existent paths gracefully', () => {
const obj = { a: 'value' };
const redacted = redactSecrets(obj, ['b.c.d']);
expect(redacted).toEqual({ a: 'value' });
});
it('should not modify original object', () => {
const obj = { password: 'secret', nested: { token: 'nested-secret' } };
const original = { password: 'secret', nested: { token: 'nested-secret' } };
const redacted = redactSecrets(obj, ['password', 'nested.token']);
expect(redacted.nested.token).toBe('***REDACTED***');
expect(obj).toEqual(original);
});
});
describe('isSecretEnvVar', () => {
it('should identify common secret patterns', () => {
// Positive cases
expect(isSecretEnvVar('PASSWORD')).toBe(true);
expect(isSecretEnvVar('DB_PASSWORD')).toBe(true);
expect(isSecretEnvVar('API_KEY')).toBe(true);
expect(isSecretEnvVar('API-KEY')).toBe(true);
expect(isSecretEnvVar('SECRET_TOKEN')).toBe(true);
expect(isSecretEnvVar('AUTH_TOKEN')).toBe(true);
expect(isSecretEnvVar('PRIVATE_KEY')).toBe(true);
expect(isSecretEnvVar('CREDENTIAL')).toBe(true);
expect(isSecretEnvVar('password')).toBe(true); // Case insensitive
// Negative cases
expect(isSecretEnvVar('USERNAME')).toBe(false);
expect(isSecretEnvVar('PORT')).toBe(false);
expect(isSecretEnvVar('DEBUG')).toBe(false);
expect(isSecretEnvVar('NODE_ENV')).toBe(false);
});
});
describe('wrapSecretEnvVars', () => {
it('should wrap secret environment variables', () => {
const env = {
USERNAME: 'admin',
PASSWORD: 'secret123',
API_KEY: 'key123',
PORT: '3000',
};
const wrapped = wrapSecretEnvVars(env);
expect(wrapped.USERNAME).toBe('admin');
expect(wrapped.PORT).toBe('3000');
expect(isSecret(wrapped.PASSWORD)).toBe(true);
expect(isSecret(wrapped.API_KEY)).toBe(true);
const passwordSecret = wrapped.PASSWORD as SecretValue;
expect(passwordSecret.reveal('test')).toBe('secret123');
expect(passwordSecret.toString()).toBe('***PASSWORD***');
});
it('should handle undefined values', () => {
const env = {
PASSWORD: undefined,
USERNAME: 'admin',
};
const wrapped = wrapSecretEnvVars(env);
expect(wrapped.PASSWORD).toBeUndefined();
expect(wrapped.USERNAME).toBe('admin');
});
});
describe('validateConfig', () => {
const schema = z.object({
name: z.string(),
port: z.number(),
optional: z.string().optional(),
});
it('should validate valid config', () => {
const result = validateConfig({ name: 'app', port: 3000 }, schema);
expect(result.valid).toBe(true);
expect(result.errors).toBeUndefined();
});
it('should return errors for invalid config', () => {
const result = validateConfig({ name: 'app', port: 'invalid' }, schema);
expect(result.valid).toBe(false);
expect(result.errors).toBeDefined();
expect(result.errors![0].path).toBe('port');
expect(result.errors![0].message).toContain('Expected number');
});
it('should handle missing required fields', () => {
const result = validateConfig({ port: 3000 }, schema);
expect(result.valid).toBe(false);
expect(result.errors).toBeDefined();
expect(result.errors![0].path).toBe('name');
});
it('should rethrow non-Zod errors', () => {
const badSchema = {
parse: () => {
throw new Error('Not a Zod error');
},
} as any;
expect(() => validateConfig({}, badSchema)).toThrow('Not a Zod error');
});
});
describe('checkRequiredEnvVars', () => {
const originalEnv = { ...process.env };
beforeEach(() => {
// Clear environment
for (const key in process.env) {
delete process.env[key];
}
});
afterEach(() => {
// Restore environment
for (const key in process.env) {
delete process.env[key];
}
Object.assign(process.env, originalEnv);
});
it('should pass when all required vars are set', () => {
process.env.API_KEY = 'key123';
process.env.DATABASE_URL = 'postgres://...';
const result = checkRequiredEnvVars(['API_KEY', 'DATABASE_URL']);
expect(result.valid).toBe(true);
expect(result.errors).toBeUndefined();
});
it('should fail when required vars are missing', () => {
process.env.API_KEY = 'key123';
const result = checkRequiredEnvVars(['API_KEY', 'DATABASE_URL', 'MISSING_VAR']);
expect(result.valid).toBe(false);
expect(result.errors).toHaveLength(2);
expect(result.errors![0].path).toBe('env.DATABASE_URL');
expect(result.errors![1].path).toBe('env.MISSING_VAR');
});
it('should handle empty required list', () => {
const result = checkRequiredEnvVars([]);
expect(result.valid).toBe(true);
expect(result.errors).toBeUndefined();
});
});
describe('validateCompleteness', () => {
it('should validate complete config', () => {
const config = {
database: {
host: 'localhost',
port: 5432,
credentials: {
username: 'admin',
password: 'secret',
},
},
};
const result = validateCompleteness(config, [
'database.host',
'database.port',
'database.credentials.username',
]);
expect(result.valid).toBe(true);
expect(result.errors).toBeUndefined();
});
it('should detect missing values', () => {
const config = {
database: {
host: 'localhost',
credentials: {},
},
};
const result = validateCompleteness(config, [
'database.host',
'database.port',
'database.credentials.username',
]);
expect(result.valid).toBe(false);
expect(result.errors).toHaveLength(2);
expect(result.errors![0].path).toBe('database.port');
expect(result.errors![1].path).toBe('database.credentials.username');
});
it('should handle null and undefined as missing', () => {
const config = {
a: null,
b: undefined,
c: 'value',
};
const result = validateCompleteness(config, ['a', 'b', 'c']);
expect(result.valid).toBe(false);
expect(result.errors).toHaveLength(2);
});
it('should handle non-existent paths', () => {
const config = { a: 'value' };
const result = validateCompleteness(config, ['b.c.d']);
expect(result.valid).toBe(false);
expect(result.errors![0].path).toBe('b.c.d');
});
});
describe('formatValidationResult', () => {
it('should format valid result', () => {
const result: ValidationResult = { valid: true };
const formatted = formatValidationResult(result);
expect(formatted).toBe('✅ Configuration is valid');
});
it('should format errors', () => {
const result: ValidationResult = {
valid: false,
errors: [
{ path: 'port', message: 'Expected number' },
{
path: 'database.host',
message: 'Invalid value',
expected: 'string',
received: 'number',
},
],
};
const formatted = formatValidationResult(result);
expect(formatted).toContain('❌ Configuration validation failed');
expect(formatted).toContain('Errors:');
expect(formatted).toContain('- port: Expected number');
expect(formatted).toContain('- database.host: Invalid value');
expect(formatted).toContain('Expected: string, Received: number');
});
it('should format warnings', () => {
const result: ValidationResult = {
valid: true,
warnings: [{ path: 'deprecated.feature', message: 'This feature is deprecated' }],
};
const formatted = formatValidationResult(result);
expect(formatted).toContain('✅ Configuration is valid');
expect(formatted).toContain('Warnings:');
expect(formatted).toContain('- deprecated.feature: This feature is deprecated');
});
});
describe('createStrictSchema', () => {
it('should create strict schema', () => {
const schema = createStrictSchema({
name: z.string(),
age: z.number(),
});
expect(() => schema.parse({ name: 'John', age: 30 })).not.toThrow();
expect(() => schema.parse({ name: 'John', age: 30, extra: 'field' })).toThrow();
});
});
describe('mergeSchemas', () => {
it('should merge two schemas', () => {
const schema1 = z.object({ a: z.string() });
const schema2 = z.object({ b: z.number() });
const merged = mergeSchemas(schema1, schema2);
const result = merged.parse({ a: 'test', b: 123 });
expect(result).toEqual({ a: 'test', b: 123 });
});
it('should merge multiple schemas', () => {
const schema1 = z.object({ a: z.string() });
const schema2 = z.object({ b: z.number() });
const schema3 = z.object({ c: z.boolean() });
const merged = mergeSchemas(schema1, schema2, schema3);
const result = merged.parse({ a: 'test', b: 123, c: true });
expect(result).toEqual({ a: 'test', b: 123, c: true });
});
it('should throw with less than two schemas', () => {
expect(() => mergeSchemas(z.object({}))).toThrow('At least two schemas required');
expect(() => mergeSchemas()).toThrow('At least two schemas required');
});
it('should handle overlapping fields', () => {
const schema1 = z.object({ a: z.string(), shared: z.string() });
const schema2 = z.object({ b: z.number(), shared: z.string() });
const merged = mergeSchemas(schema1, schema2);
// Both schemas require 'shared' to be a string
expect(() => merged.parse({ a: 'test', b: 123, shared: 'value' })).not.toThrow();
expect(() => merged.parse({ a: 'test', b: 123, shared: 123 })).toThrow();
});
});
describe('COMMON_SECRET_PATTERNS', () => {
it('should be an array of RegExp', () => {
expect(Array.isArray(COMMON_SECRET_PATTERNS)).toBe(true);
expect(COMMON_SECRET_PATTERNS.length).toBeGreaterThan(0);
for (const pattern of COMMON_SECRET_PATTERNS) {
expect(pattern).toBeInstanceOf(RegExp);
}
});
});
});

View file

@ -1,8 +1,21 @@
{
"name": "@stock-bot/di",
"version": "1.0.0",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"default": "./dist/index.js"
},
"./http-security": {
"types": "./dist/http/security.d.ts",
"import": "./dist/http/security.js",
"default": "./dist/http/security.js"
}
},
"scripts": {
"build": "tsc",
"clean": "rm -rf dist",
@ -13,11 +26,10 @@
"@stock-bot/config": "workspace:*",
"@stock-bot/logger": "workspace:*",
"@stock-bot/types": "workspace:*",
"@stock-bot/browser": "workspace:*",
"@stock-bot/cache": "workspace:*",
"@stock-bot/proxy": "workspace:*",
"@stock-bot/mongodb": "workspace:*",
"@stock-bot/postgres": "workspace:*",
"@stock-bot/proxy": "workspace:*",
"@stock-bot/questdb": "workspace:*",
"@stock-bot/queue": "workspace:*",
"@stock-bot/shutdown": "workspace:*",

View file

@ -1,7 +0,0 @@
import type { AwilixContainer } from 'awilix';
import type { ServiceDefinitions } from './container/types';
// Compatibility exports use the same composition contract as the active builder.
export type { AppConfig } from './config/schemas';
export type { ServiceCradle, ServiceDefinitions, ServiceContainerOptions } from './container/types';
export type ServiceContainer = AwilixContainer<ServiceDefinitions>;

View file

@ -1,4 +1,11 @@
import { asClass, asFunction, createContainer, InjectionMode, type AwilixContainer } from 'awilix';
import {
asClass,
asFunction,
asValue,
createContainer,
InjectionMode,
type AwilixContainer,
} from 'awilix';
import type { BaseAppConfig as StockBotAppConfig, UnifiedAppConfig } from '@stock-bot/config';
import { toUnifiedConfig } from '@stock-bot/config';
import { HandlerRegistry } from '@stock-bot/handler-registry';
@ -14,8 +21,22 @@ import { HandlerScanner } from '../scanner';
import { ServiceLifecycleManager } from '../utils/lifecycle';
import type { ContainerBuildOptions, ServiceDefinitions } from './types';
export interface ContainerRegistrationHelpers {
asClass: typeof asClass;
asFunction: typeof asFunction;
asValue: typeof asValue;
}
export type ContainerRegistrar = (
container: AwilixContainer<ServiceDefinitions>,
config: AppConfig,
helpers: ContainerRegistrationHelpers
) => void;
function extractMongoDatabaseFromUri(uri?: string): string | undefined {
if (!uri) return undefined;
if (!uri) {
return undefined;
}
try {
const db = new URL(uri).pathname.replace(/^\/+/, '').split('/')[0];
return db || undefined;
@ -31,6 +52,7 @@ function getInfluxPort(config: { influxPort?: number; ilpPort?: number }): numbe
export class ServiceContainerBuilder {
private config: Partial<AppConfig> = {};
private unifiedConfig: UnifiedAppConfig | null = null;
private customRegistrations: ContainerRegistrar[] = [];
private options: ContainerBuildOptions = {
enableCache: true,
enableQueue: true,
@ -55,6 +77,11 @@ export class ServiceContainerBuilder {
return this;
}
withRegistrations(registrar: ContainerRegistrar): this {
this.customRegistrations.push(registrar);
return this;
}
enableService(
service: keyof Omit<ContainerBuildOptions, 'skipInitialization' | 'initializationTimeout'>,
enabled = true
@ -85,6 +112,10 @@ export class ServiceContainerBuilder {
// Register services
this.registerServices(container, validatedConfig);
const helpers: ContainerRegistrationHelpers = { asClass, asFunction, asValue };
for (const registrar of this.customRegistrations) {
registrar(container, validatedConfig, helpers);
}
const lifecycleManager = new ServiceLifecycleManager();
// Initialize services if not skipped

View file

@ -1,26 +1,21 @@
import type { Browser } from '@stock-bot/browser';
import type { CacheProvider } from '@stock-bot/cache';
import type { HandlerRegistry } from '@stock-bot/handler-registry';
import type { Logger } from '@stock-bot/logger';
import type { MongoDBClient } from '@stock-bot/mongodb';
import type { PostgreSQLClient } from '@stock-bot/postgres';
import type { ProxyManager } from '@stock-bot/proxy';
import type { QuestDBClient } from '@stock-bot/questdb';
import type { QueueManager } from '@stock-bot/queue';
import type { IServiceContainer } from '@stock-bot/services';
import type { Browser, IServiceContainer, ProxyManager } from '@stock-bot/services';
import type { AppConfig } from '../config/schemas';
import type { HandlerScanner } from '../scanner';
export interface ServiceDefinitions {
// Configuration
config: AppConfig;
logger: Logger;
// Handler infrastructure
handlerRegistry: HandlerRegistry;
handlerScanner: HandlerScanner;
// Core services
cache: CacheProvider | null;
globalCache: CacheProvider | null;
proxyCache: CacheProvider | null;
@ -28,12 +23,10 @@ export interface ServiceDefinitions {
browser: Browser | null;
queueManager: QueueManager | null;
// Database clients
mongoClient: MongoDBClient | null;
postgresClient: PostgreSQLClient | null;
questdbClient: QuestDBClient | null;
// Aggregate service container
serviceContainer: IServiceContainer;
}

View file

@ -1 +0,0 @@
// This directory is reserved for future factory implementations

View file

@ -1,7 +1,6 @@
// Export only what's actually used
export { ServiceApplication } from './service-application';
export { ServiceContainerBuilder } from './container/builder';
export { OperationContext } from './operation-context';
export type { ContainerRegistrar, ContainerRegistrationHelpers } from './container/builder';
export {
createHttpSecurity,
httpSecurityOptions,
@ -11,12 +10,10 @@ export {
getResearchHttpPrincipal,
} from './http/security';
export type { HttpSecurity, HttpSecurityOptions } from './http/security';
export { calculatePoolSize, getServicePoolSize, getHandlerPoolSize } from './pool-size-calculator';
export { ServiceLifecycleManager } from './utils/lifecycle';
export { HandlerScanner } from './scanner/handler-scanner';
export type { IServiceContainer } from '@stock-bot/services';
// Export schemas
export {
appConfigSchema,
redisConfigSchema,
@ -29,5 +26,4 @@ export {
} from './config/schemas';
export type { ServiceDefinitions, ServiceCradle } from './container/types';
export type { HandlerInitializationContext } from './service-application';

View file

@ -1,144 +0,0 @@
/**
* OperationContext - Unified context for handler operations
*/
import { getLogger, type Logger } from '@stock-bot/logger';
interface ServiceResolver {
resolve<T>(serviceName: string): T;
resolveAsync<T>(serviceName: string): Promise<T>;
}
export interface OperationContextOptions {
handlerName: string;
operationName: string;
parentLogger?: Logger;
container?: ServiceResolver;
metadata?: Record<string, unknown>;
traceId?: string;
}
export class OperationContext {
public readonly logger: Logger;
public readonly traceId: string;
public readonly metadata: Record<string, unknown>;
private readonly container?: ServiceResolver;
private readonly startTime: Date;
constructor(options: OperationContextOptions) {
this.container = options.container;
this.metadata = options.metadata || {};
this.traceId = options.traceId || this.generateTraceId();
this.startTime = new Date();
this.logger =
options.parentLogger ||
getLogger(`${options.handlerName}:${options.operationName}`, {
traceId: this.traceId,
metadata: this.metadata,
});
}
/**
* Creates a new OperationContext with automatic resource management
*/
static create(
handlerName: string,
operationName: string,
options: {
container?: ServiceResolver;
parentLogger?: Logger;
metadata?: Record<string, unknown>;
traceId?: string;
} = {}
): OperationContext {
return new OperationContext({
handlerName,
operationName,
...options,
});
}
/**
* Resolve a service from the container
*/
resolve<T>(serviceName: string): T {
if (!this.container) {
throw new Error('No service container available');
}
return this.container.resolve<T>(serviceName);
}
/**
* Resolve a service asynchronously from the container
*/
async resolveAsync<T>(serviceName: string): Promise<T> {
if (!this.container) {
throw new Error('No service container available');
}
return this.container.resolveAsync<T>(serviceName);
}
/**
* Add metadata to the context
*/
addMetadata(key: string, value: unknown): void {
this.metadata[key] = value;
}
/**
* Get execution time in milliseconds
*/
getExecutionTime(): number {
return Date.now() - this.startTime.getTime();
}
/**
* Log operation completion with metrics
*/
logCompletion(success: boolean, error?: Error): void {
const executionTime = this.getExecutionTime();
if (success) {
this.logger.info('Operation completed successfully', {
executionTime,
metadata: this.metadata,
});
} else {
this.logger.error('Operation failed', {
executionTime,
error: error?.message,
stack: error?.stack,
metadata: this.metadata,
});
}
}
/**
* Cleanup method
*/
async dispose(): Promise<void> {
this.logCompletion(true);
}
/**
* Create child context
*/
createChild(operationName: string, metadata?: Record<string, unknown>): OperationContext {
return new OperationContext({
handlerName: 'child',
operationName,
parentLogger: this.logger,
container: this.container,
traceId: this.traceId,
metadata: { ...this.metadata, ...metadata },
});
}
/**
* Generate a unique trace ID
*/
private generateTraceId(): string {
return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
}

View file

@ -1,102 +0,0 @@
import type { ConnectionPoolConfig } from './types';
export interface PoolSizeRecommendation {
min: number;
max: number;
idle: number;
}
export class PoolSizeCalculator {
private static readonly DEFAULT_SIZES: Record<string, PoolSizeRecommendation> = {
// Service-level defaults
'data-ingestion': { min: 5, max: 50, idle: 10 },
'data-pipeline': { min: 3, max: 30, idle: 5 },
'processing-service': { min: 2, max: 20, idle: 3 },
'web-api': { min: 2, max: 10, idle: 2 },
'portfolio-service': { min: 2, max: 15, idle: 3 },
'strategy-service': { min: 3, max: 25, idle: 5 },
'execution-service': { min: 2, max: 10, idle: 2 },
// Handler-level defaults
'batch-import': { min: 10, max: 100, idle: 20 },
'real-time': { min: 2, max: 10, idle: 3 },
analytics: { min: 5, max: 30, idle: 10 },
reporting: { min: 3, max: 20, idle: 5 },
};
static calculate(
serviceName: string,
handlerName?: string,
customConfig?: Partial<ConnectionPoolConfig>
): PoolSizeRecommendation {
// Check for custom configuration first
if (customConfig?.minConnections && customConfig?.maxConnections) {
return {
min: customConfig.minConnections,
max: customConfig.maxConnections,
idle: Math.floor((customConfig.minConnections + customConfig.maxConnections) / 4),
};
}
// Try handler-specific sizes first, then service-level
const key = handlerName || serviceName;
const recommendation = this.DEFAULT_SIZES[key] || this.DEFAULT_SIZES[serviceName];
if (recommendation) {
return { ...recommendation };
}
// Fall back to generic defaults
return {
min: 2,
max: 10,
idle: 3,
};
}
static getOptimalPoolSize(
expectedConcurrency: number,
averageQueryTimeMs: number,
targetLatencyMs: number
): number {
// Little's Law: L = λ * W
// L = number of connections needed
// λ = arrival rate (requests per second)
// W = average time in system (seconds)
const requestsPerSecond = expectedConcurrency;
const averageTimeInSystem = averageQueryTimeMs / 1000;
const minConnections = Math.ceil(requestsPerSecond * averageTimeInSystem);
// Add buffer for burst traffic (20% overhead)
const recommendedSize = Math.ceil(minConnections * 1.2);
// Ensure we meet target latency
const latencyBasedSize = Math.ceil(
expectedConcurrency * (averageQueryTimeMs / targetLatencyMs)
);
return Math.max(recommendedSize, latencyBasedSize, 2); // Minimum 2 connections
}
}
// Export convenience functions
export function calculatePoolSize(
serviceName: string,
handlerName?: string,
customConfig?: Partial<ConnectionPoolConfig>
): PoolSizeRecommendation {
return PoolSizeCalculator.calculate(serviceName, handlerName, customConfig);
}
export function getServicePoolSize(serviceName: string): PoolSizeRecommendation {
return PoolSizeCalculator.calculate(serviceName);
}
export function getHandlerPoolSize(
serviceName: string,
handlerName: string
): PoolSizeRecommendation {
return PoolSizeCalculator.calculate(serviceName, handlerName);
}

View file

@ -1,7 +1,8 @@
import { asClass, asFunction, asValue, type AwilixContainer } from 'awilix';
import { Browser } from '@stock-bot/browser';
import { asFunction, asValue, type AwilixContainer } from 'awilix';
import { createCache } from '@stock-bot/cache';
import { defined } from '@stock-bot/invariants';
import { ProxyManager } from '@stock-bot/proxy';
import { QueueManager } from '@stock-bot/queue';
import type { AppConfig } from '../config/schemas';
import type { ServiceDefinitions } from '../container/types';
@ -9,52 +10,40 @@ export function registerApplicationServices(
container: AwilixContainer<ServiceDefinitions>,
config: AppConfig
): void {
// Browser
if (config.browser) {
container.register({
browser: asClass(Browser)
.singleton()
.inject(() => ({
options: {
headless: defined(config.browser).headless,
timeout: defined(config.browser).timeout,
},
})),
});
} else {
container.register({
browser: asValue(null), // Required field
});
}
// Browser is an ingestion-only capability registered by apps/stock/data-ingestion
// via ServiceContainerBuilder.withRegistrations() so non-ingestion apps never pull Playwright.
container.register({
browser: asValue(null),
});
// Proxy Manager
// Proxy Manager (pure TypeScript + Redis cache; zero browser dependencies)
if (config.proxy && config.redis?.enabled) {
const redisConfig = config.redis;
const proxyConfig = config.proxy;
container.register({
proxyCache: asFunction(({ logger }) => {
// Create a separate cache instance for proxy with global prefix
const { createCache } = require('@stock-bot/cache');
return createCache({
redisConfig: {
host: config.redis.host,
port: config.redis.port,
password: config.redis.password,
username: config.redis.username,
maxRetriesPerRequest: config.redis.maxRetries,
retryDelay: config.redis.retryDelay,
db: 1, // Use cache DB (usually DB 1)
host: redisConfig.host,
port: redisConfig.port,
password: redisConfig.password,
username: redisConfig.username,
maxRetriesPerRequest: redisConfig.maxRetries,
retryDelay: redisConfig.retryDelay,
db: 1,
},
shared: false,
keyPrefix: 'cache:proxy:',
ttl: 86400, // 24 hours default
ttl: 86400,
enableMetrics: true,
logger,
});
})
.singleton()
.disposer(cache => cache.disconnect?.()),
proxyManager: asFunction(
({ logger, proxyCache }) => new ProxyManager(defined(proxyCache), config.proxy, logger)
).singleton(),
proxyManager: asFunction(({ logger, proxyCache }) => {
return new ProxyManager(defined(proxyCache), proxyConfig, logger);
}).singleton(),
});
} else {
container.register({
@ -67,8 +56,6 @@ export function registerApplicationServices(
if (config.queue?.enabled && config.redis?.enabled) {
container.register({
queueManager: asFunction(({ logger, handlerRegistry }) => {
const { QueueManager } = require('@stock-bot/queue');
const queueConfig = {
serviceName: config.service?.serviceName || config.service?.name || 'unknown',
redis: {

View file

@ -168,6 +168,25 @@ export class ServiceApplication {
return app;
}
private resolveOptional<K extends keyof ServiceDefinitions>(
name: K
): ServiceDefinitions[K] | null {
if (!this.container) {
return null;
}
if (
typeof this.container.hasRegistration === 'function' &&
!this.container.hasRegistration(name)
) {
return null;
}
try {
return this.container.resolve(name);
} catch {
return null;
}
}
/**
* Register graceful shutdown handlers
*/
@ -178,30 +197,26 @@ export class ServiceApplication {
timeout: this.serviceConfig.shutdownTimeout,
});
// Priority 1: Queue system (highest priority)
if (this.serviceConfig.enableScheduledJobs) {
this.shutdown.onShutdown(
async () => {
this.logger.info('Shutting down queue system...');
const startTime = Date.now();
try {
const queueManager = this.container?.resolve('queueManager');
if (queueManager) {
await queueManager.shutdown();
const duration = Date.now() - startTime;
this.logger.info('Queue system shut down successfully', { duration });
} else {
this.logger.warn('No queue manager found to shut down');
}
} catch (error) {
// Priority 1: Queue system (always register so active workers drain even when scheduled cron jobs are disabled)
this.shutdown.onShutdown(
async () => {
const startTime = Date.now();
try {
const queueManager = this.resolveOptional('queueManager');
if (queueManager) {
this.logger.info('Shutting down queue system...');
await queueManager.shutdown();
const duration = Date.now() - startTime;
this.logger.error('Error shutting down queue system', { error, duration });
this.logger.info('Queue system shut down successfully', { duration });
}
},
SHUTDOWN_DEFAULTS.HIGH_PRIORITY,
'Queue System'
);
}
} catch (error) {
const duration = Date.now() - startTime;
this.logger.error('Error shutting down queue system', { error, duration });
}
},
SHUTDOWN_DEFAULTS.HIGH_PRIORITY,
'Queue System'
);
// Priority 1: HTTP Server (high priority)
this.shutdown.onShutdown(
@ -251,7 +266,7 @@ export class ServiceApplication {
try {
if (this.container) {
// Disconnect database clients
const mongoClient = this.container.resolve('mongoClient');
const mongoClient = this.resolveOptional('mongoClient');
if (mongoClient?.disconnect) {
try {
const mongoStart = Date.now();
@ -263,7 +278,7 @@ export class ServiceApplication {
}
}
const postgresClient = this.container.resolve('postgresClient');
const postgresClient = this.resolveOptional('postgresClient');
if (postgresClient?.disconnect) {
try {
const pgStart = Date.now();
@ -275,7 +290,7 @@ export class ServiceApplication {
}
}
const questdbClient = this.container.resolve('questdbClient');
const questdbClient = this.resolveOptional('questdbClient');
if (questdbClient?.disconnect) {
try {
const questStart = Date.now();
@ -287,6 +302,13 @@ export class ServiceApplication {
}
}
if (typeof this.container.dispose === 'function') {
await this.container.dispose().catch(error => {
this.logger.error('Failed to dispose DI container resources', { error });
failed.push('Container');
});
}
const duration = Date.now() - startTime;
this.logger.info('Service disposal completed', {
duration,
@ -326,10 +348,7 @@ export class ServiceApplication {
this.logger.info('All shutdown handlers registered', {
service: this.serviceConfig.serviceName,
handlerCount:
3 +
(this.serviceConfig.enableScheduledJobs ? 1 : 0) +
(this.hooks.onBeforeShutdown ? 1 : 0),
handlerCount: 4 + (this.hooks.onBeforeShutdown ? 1 : 0),
});
}
@ -377,10 +396,10 @@ export class ServiceApplication {
this.logger.info('Handlers initialized');
// After handlers are initialized, add rate limit rules to queue manager
const queueManager = this.container.resolve('queueManager');
const handlerRegistry = this.container.resolve<HandlerRegistry>('handlerRegistry');
const queueManager = this.resolveOptional('queueManager');
const handlerRegistry = this.resolveOptional('handlerRegistry');
if (queueManager && handlerRegistry) {
if (queueManager && typeof handlerRegistry?.getAllMetadata === 'function') {
const rateLimitRules = [];
const allMetadata = handlerRegistry.getAllMetadata();
@ -420,9 +439,17 @@ export class ServiceApplication {
const routes = routeFactory(this.serviceContainer);
this.app.route('/', routes);
// Initialize scheduled jobs if enabled
if (this.serviceConfig.enableScheduledJobs) {
// Initialize scheduled jobs if enabled in both serviceConfig and runtime queue config
const scheduledJobsEnabled =
this.serviceConfig.enableScheduledJobs && (this.config.queue?.enableScheduledJobs ?? true);
if (scheduledJobsEnabled) {
await this.initializeScheduledJobs();
} else {
const queueManager = this.resolveOptional('queueManager');
if (queueManager?.startAllWorkers) {
queueManager.startAllWorkers();
this.logger.info('Queue workers started (scheduled cron jobs disabled)');
}
}
// Call before start hook

View file

@ -1,71 +0,0 @@
// Generic types to avoid circular dependencies
export interface GenericClientConfig {
[key: string]: unknown;
}
export interface ConnectionPoolConfig {
name: string;
poolSize?: number;
minConnections?: number;
maxConnections?: number;
idleTimeoutMillis?: number;
connectionTimeoutMillis?: number;
enableMetrics?: boolean;
}
export interface MongoDBPoolConfig extends ConnectionPoolConfig {
config: GenericClientConfig;
}
export interface PostgreSQLPoolConfig extends ConnectionPoolConfig {
config: GenericClientConfig;
}
export interface CachePoolConfig extends ConnectionPoolConfig {
config: GenericClientConfig;
}
export interface QueuePoolConfig extends ConnectionPoolConfig {
config: GenericClientConfig;
}
export interface ConnectionFactoryConfig {
service: string;
environment: 'development' | 'qa' | 'production' | 'test';
pools?: {
mongodb?: Partial<MongoDBPoolConfig>;
postgres?: Partial<PostgreSQLPoolConfig>;
cache?: Partial<CachePoolConfig>;
queue?: Partial<QueuePoolConfig>;
};
}
export interface ConnectionPool<T> {
name: string;
client: T;
metrics: PoolMetrics;
health(): Promise<boolean>;
dispose(): Promise<void>;
}
export interface PoolMetrics {
created: Date;
totalConnections: number;
activeConnections: number;
idleConnections: number;
waitingRequests: number;
errors: number;
}
export interface ConnectionFactory {
createMongoDB(config: MongoDBPoolConfig): Promise<ConnectionPool<unknown>>;
createPostgreSQL(config: PostgreSQLPoolConfig): Promise<ConnectionPool<unknown>>;
createCache(config: CachePoolConfig): Promise<ConnectionPool<unknown>>;
createQueue(config: QueuePoolConfig): Promise<ConnectionPool<unknown>>;
getPool(
type: 'mongodb' | 'postgres' | 'cache' | 'queue',
name: string
): ConnectionPool<unknown> | undefined;
listPools(): Array<{ type: string; name: string; metrics: PoolMetrics }>;
disposeAll(): Promise<void>;
}

View file

@ -20,6 +20,7 @@ export class ServiceLifecycleManager {
{ name: 'postgresClient', key: 'postgresClient' as const },
{ name: 'questdbClient', key: 'questdbClient' as const },
{ name: 'proxyManager', key: 'proxyManager' as const },
{ name: 'browser', key: 'browser' as const },
{ name: 'queueManager', key: 'queueManager' as const },
];

View file

@ -1,76 +0,0 @@
import { describe, expect, it } from 'bun:test';
import type {
ServiceContainer,
ServiceContainerOptions,
ServiceCradle,
ServiceDefinitions,
} from '../src/awilix-container';
describe('Awilix Container Types', () => {
it('should export ServiceDefinitions interface', () => {
// Type test - if this compiles, the type exists
const testDefinitions: Partial<ServiceDefinitions> = {
config: {} as any,
logger: {} as any,
cache: null,
proxyManager: null,
browser: {} as any,
queueManager: null,
mongoClient: null,
postgresClient: null,
questdbClient: null,
serviceContainer: {} as any,
};
expect(testDefinitions).toBeDefined();
});
it('should export ServiceContainer type', () => {
// Type test - if this compiles, the type exists
const testContainer: ServiceContainer | null = null;
expect(testContainer).toBeNull();
});
it('should export ServiceCradle type', () => {
// Type test - if this compiles, the type exists
const testCradle: Partial<ServiceCradle> = {
config: {} as any,
logger: {} as any,
};
expect(testCradle).toBeDefined();
});
it('should export ServiceContainerOptions interface', () => {
// Type test - if this compiles, the type exists
const testOptions: ServiceContainerOptions = {
enableQuestDB: true,
enableMongoDB: true,
enablePostgres: true,
enableCache: true,
enableQueue: true,
enableBrowser: true,
enableProxy: true,
};
expect(testOptions).toBeDefined();
expect(testOptions.enableQuestDB).toBe(true);
expect(testOptions.enableMongoDB).toBe(true);
expect(testOptions.enablePostgres).toBe(true);
expect(testOptions.enableCache).toBe(true);
expect(testOptions.enableQueue).toBe(true);
expect(testOptions.enableBrowser).toBe(true);
expect(testOptions.enableProxy).toBe(true);
});
it('should allow partial ServiceContainerOptions', () => {
const partialOptions: ServiceContainerOptions = {
enableCache: true,
enableQueue: false,
};
expect(partialOptions.enableCache).toBe(true);
expect(partialOptions.enableQueue).toBe(false);
expect(partialOptions.enableQuestDB).toBeUndefined();
});
});

View file

@ -102,6 +102,23 @@ describe('ServiceContainerBuilder production configuration', () => {
}
});
it('allows service-specific capability overrides via withRegistrations', async () => {
const fakeBrowser = { close: async () => {} } as never;
const container = await new ServiceContainerBuilder()
.withConfig(configuration())
.withRegistrations((diContainer, _cfg, { asValue }) => {
diContainer.register({ browser: asValue(fakeBrowser) });
})
.skipInitialization()
.build();
try {
expect(container.resolve('browser')).toBe(fakeBrowser);
expect(container.resolve('serviceContainer').browser).toBe(fakeBrowser);
} finally {
await container.dispose();
}
});
it('rejects invalid settings and missing required app fields with schema errors', () => {
expect(() =>
new ServiceContainerBuilder().withConfig({

View file

@ -1,8 +1,6 @@
import { asClass, asFunction, asValue, createContainer, InjectionMode } from 'awilix';
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { ServiceContainerBuilder } from '../src/container/builder';
import { OperationContext } from '../src/operation-context';
import { PoolSizeCalculator } from '../src/pool-size-calculator';
import { HandlerScanner } from '../src/scanner/handler-scanner';
import { ServiceApplication } from '../src/service-application';
@ -124,55 +122,6 @@ describe('Dependency Injection', () => {
});
});
describe('OperationContext', () => {
it('should create operation context', () => {
const context = new OperationContext({
handlerName: 'test-handler',
operationName: 'test-op',
});
expect(context.traceId).toBeDefined();
expect(context.logger).toBeDefined();
expect(context.metadata).toEqual({});
});
it('should include metadata', () => {
const metadata = { userId: '123', source: 'api' };
const context = new OperationContext({
handlerName: 'test-handler',
operationName: 'test-op',
metadata,
});
expect(context.metadata).toEqual(metadata);
});
it('should track execution time', async () => {
const context = new OperationContext({
handlerName: 'test-handler',
operationName: 'test-op',
});
await new Promise(resolve => setTimeout(resolve, 10));
const executionTime = context.getExecutionTime();
expect(executionTime).toBeGreaterThanOrEqual(10);
});
it('should create child context', () => {
const parentContext = new OperationContext({
handlerName: 'parent-handler',
operationName: 'parent-op',
metadata: { parentId: '123' },
});
const childContext = parentContext.createChild('child-op', { childId: '456' });
expect(childContext.traceId).toBe(parentContext.traceId);
expect(childContext.metadata).toEqual({ parentId: '123', childId: '456' });
});
});
describe('HandlerScanner', () => {
it('should create scanner instance', () => {
const mockRegistry = {
@ -219,52 +168,4 @@ describe('Dependency Injection', () => {
expect(app.stop).toBeDefined();
});
});
describe('Pool Size Calculator', () => {
it('should calculate pool size for services', () => {
const recommendation = PoolSizeCalculator.calculate('web-api');
expect(recommendation.min).toBe(2);
expect(recommendation.max).toBe(10);
expect(recommendation.idle).toBe(2);
});
it('should calculate pool size for handlers', () => {
const recommendation = PoolSizeCalculator.calculate('data-ingestion', 'batch-import');
expect(recommendation.min).toBe(10);
expect(recommendation.max).toBe(100);
expect(recommendation.idle).toBe(20);
});
it('should use custom configuration', () => {
const recommendation = PoolSizeCalculator.calculate('custom', undefined, {
minConnections: 5,
maxConnections: 50,
});
expect(recommendation.min).toBe(5);
expect(recommendation.max).toBe(50);
expect(recommendation.idle).toBe(13); // (5+50)/4 = 13.75 -> 13
});
it('should fall back to defaults', () => {
const recommendation = PoolSizeCalculator.calculate('unknown-service');
expect(recommendation.min).toBe(2);
expect(recommendation.max).toBe(10);
expect(recommendation.idle).toBe(3);
});
it('should calculate optimal pool size', () => {
const size = PoolSizeCalculator.getOptimalPoolSize(
100, // 100 requests per second
50, // 50ms average query time
100 // 100ms target latency
);
expect(size).toBeGreaterThan(0);
expect(size).toBe(50); // max(100*0.05*1.2, 100*50/100, 2) = max(6, 50, 2) = 50
});
});
});

View file

@ -2,16 +2,6 @@ import { describe, expect, it } from 'bun:test';
import * as diExports from '../src/index';
describe('DI Package Exports', () => {
it('should export OperationContext', () => {
expect(diExports.OperationContext).toBeDefined();
});
it('should export pool size calculator', () => {
expect(diExports.calculatePoolSize).toBeDefined();
expect(diExports.getServicePoolSize).toBeDefined();
expect(diExports.getHandlerPoolSize).toBeDefined();
});
it('should export ServiceContainerBuilder', () => {
expect(diExports.ServiceContainerBuilder).toBeDefined();
});

View file

@ -1,273 +0,0 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { OperationContext } from '../src/operation-context';
import type { OperationContextOptions } from '../src/operation-context';
describe('OperationContext', () => {
const mockLogger = {
info: mock(() => {}),
error: mock(() => {}),
warn: mock(() => {}),
debug: mock(() => {}),
trace: mock(() => {}),
child: mock(() => mockLogger),
};
const mockContainer = {
resolve: mock((name: string) => ({ name })),
resolveAsync: mock(async (name: string) => ({ name })),
};
beforeEach(() => {
// Reset mocks
Object.keys(mockLogger).forEach(key => {
if (typeof mockLogger[key as keyof typeof mockLogger] === 'function') {
(mockLogger as any)[key] = mock(() => (key === 'child' ? mockLogger : undefined));
}
});
mockContainer.resolve = mock((name: string) => ({ name }));
mockContainer.resolveAsync = mock(async (name: string) => ({ name }));
});
describe('constructor', () => {
it('should create context with required options', () => {
const options: OperationContextOptions = {
handlerName: 'test-handler',
operationName: 'test-op',
};
const context = new OperationContext(options);
expect(context).toBeDefined();
expect(context.traceId).toBeDefined();
expect(context.metadata).toEqual({});
expect(context.logger).toBeDefined();
});
it('should create context with all options', () => {
const options: OperationContextOptions = {
handlerName: 'test-handler',
operationName: 'test-op',
parentLogger: mockLogger,
container: mockContainer,
metadata: { key: 'value' },
traceId: 'custom-trace-id',
};
const context = new OperationContext(options);
expect(context.traceId).toBe('custom-trace-id');
expect(context.metadata).toEqual({ key: 'value' });
expect(context.logger).toBe(mockLogger);
});
});
describe('static create', () => {
it('should create context using static method', () => {
const context = OperationContext.create('handler', 'operation', {
metadata: { foo: 'bar' },
});
expect(context).toBeDefined();
expect(context.metadata).toEqual({ foo: 'bar' });
});
});
describe('service resolution', () => {
it('should resolve services from container', () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
container: mockContainer,
});
const service = context.resolve('myService');
expect(service).toEqual({ name: 'myService' });
expect(mockContainer.resolve).toHaveBeenCalledWith('myService');
});
it('should resolve services asynchronously', async () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
container: mockContainer,
});
const service = await context.resolveAsync('myService');
expect(service).toEqual({ name: 'myService' });
expect(mockContainer.resolveAsync).toHaveBeenCalledWith('myService');
});
it('should throw error when no container available', () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
});
expect(() => context.resolve('service')).toThrow('No service container available');
});
it('should throw error when no container available for async', async () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
});
await expect(context.resolveAsync('service')).rejects.toThrow(
'No service container available'
);
});
});
describe('metadata', () => {
it('should add metadata', () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
});
context.addMetadata('userId', '12345');
context.addMetadata('correlationId', 'corr-456');
expect(context.metadata.userId).toBe('12345');
expect(context.metadata.correlationId).toBe('corr-456');
});
it('should preserve initial metadata', () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
metadata: { initial: 'value' },
});
context.addMetadata('added', 'new-value');
expect(context.metadata.initial).toBe('value');
expect(context.metadata.added).toBe('new-value');
});
});
describe('execution time', () => {
it('should track execution time', async () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
});
// Wait a bit
await new Promise(resolve => setTimeout(resolve, 50));
const executionTime = context.getExecutionTime();
expect(executionTime).toBeGreaterThan(40);
expect(executionTime).toBeLessThan(100);
});
});
describe('logging', () => {
it('should log successful completion', () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
parentLogger: mockLogger,
});
context.logCompletion(true);
expect(mockLogger.info).toHaveBeenCalledWith(
'Operation completed successfully',
expect.objectContaining({
executionTime: expect.any(Number),
metadata: {},
})
);
});
it('should log failed completion with error', () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
parentLogger: mockLogger,
});
const error = new Error('Test error');
context.logCompletion(false, error);
expect(mockLogger.error).toHaveBeenCalledWith(
'Operation failed',
expect.objectContaining({
executionTime: expect.any(Number),
error: 'Test error',
stack: expect.any(String),
metadata: {},
})
);
});
});
describe('child context', () => {
it('should create child context', () => {
const parent = new OperationContext({
handlerName: 'parent',
operationName: 'parent-op',
parentLogger: mockLogger,
container: mockContainer,
traceId: 'parent-trace',
metadata: { parentKey: 'parentValue' },
});
const child = parent.createChild('child-op', { childKey: 'childValue' });
expect(child.traceId).toBe('parent-trace'); // Inherits trace ID
expect(child.metadata).toEqual({
parentKey: 'parentValue',
childKey: 'childValue',
});
expect(child.logger).toBe(mockLogger); // Inherits logger
});
it('should create child without additional metadata', () => {
const parent = new OperationContext({
handlerName: 'parent',
operationName: 'parent-op',
metadata: { key: 'value' },
});
const child = parent.createChild('child-op');
expect(child.metadata).toEqual({ key: 'value' });
});
});
describe('dispose', () => {
it('should log completion on dispose', async () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
parentLogger: mockLogger,
});
await context.dispose();
expect(mockLogger.info).toHaveBeenCalledWith(
'Operation completed successfully',
expect.any(Object)
);
});
});
describe('trace ID generation', () => {
it('should generate unique trace IDs', () => {
const context1 = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
});
const context2 = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
});
expect(context1.traceId).not.toBe(context2.traceId);
expect(context1.traceId).toMatch(/^\d+-[a-z0-9]+$/);
});
});
});

View file

@ -1,165 +0,0 @@
import { describe, expect, it } from 'bun:test';
import { PoolSizeCalculator } from '../src/pool-size-calculator';
import type { ConnectionPoolConfig } from '../src/types';
describe('PoolSizeCalculator', () => {
describe('calculate', () => {
it('should return service-level defaults for known services', () => {
const result = PoolSizeCalculator.calculate('data-ingestion');
expect(result).toEqual({ min: 5, max: 50, idle: 10 });
});
it('should return handler-level defaults when handler name is provided', () => {
const result = PoolSizeCalculator.calculate('any-service', 'batch-import');
expect(result).toEqual({ min: 10, max: 100, idle: 20 });
});
it('should prefer handler-level over service-level defaults', () => {
const result = PoolSizeCalculator.calculate('data-ingestion', 'real-time');
expect(result).toEqual({ min: 2, max: 10, idle: 3 });
});
it('should return generic defaults for unknown services', () => {
const result = PoolSizeCalculator.calculate('unknown-service');
expect(result).toEqual({ min: 2, max: 10, idle: 3 });
});
it('should use custom configuration when provided', () => {
const customConfig: Partial<ConnectionPoolConfig> = {
minConnections: 15,
maxConnections: 75,
};
const result = PoolSizeCalculator.calculate('data-ingestion', undefined, customConfig);
expect(result).toEqual({
min: 15,
max: 75,
idle: Math.floor((15 + 75) / 4), // 22
});
});
it('should ignore partial custom configuration', () => {
const customConfig: Partial<ConnectionPoolConfig> = {
minConnections: 15,
// maxConnections not provided
};
const result = PoolSizeCalculator.calculate('data-ingestion', undefined, customConfig);
// Should fall back to defaults
expect(result).toEqual({ min: 5, max: 50, idle: 10 });
});
it('should handle all predefined service types', () => {
const services = [
{ name: 'data-pipeline', expected: { min: 3, max: 30, idle: 5 } },
{ name: 'processing-service', expected: { min: 2, max: 20, idle: 3 } },
{ name: 'web-api', expected: { min: 2, max: 10, idle: 2 } },
{ name: 'portfolio-service', expected: { min: 2, max: 15, idle: 3 } },
{ name: 'strategy-service', expected: { min: 3, max: 25, idle: 5 } },
{ name: 'execution-service', expected: { min: 2, max: 10, idle: 2 } },
];
services.forEach(({ name, expected }) => {
const result = PoolSizeCalculator.calculate(name);
expect(result).toEqual(expected);
});
});
it('should handle all predefined handler types', () => {
const handlers = [
{ name: 'analytics', expected: { min: 5, max: 30, idle: 10 } },
{ name: 'reporting', expected: { min: 3, max: 20, idle: 5 } },
];
handlers.forEach(({ name, expected }) => {
const result = PoolSizeCalculator.calculate('any-service', name);
expect(result).toEqual(expected);
});
});
it('should return a new object each time', () => {
const result1 = PoolSizeCalculator.calculate('data-ingestion');
const result2 = PoolSizeCalculator.calculate('data-ingestion');
expect(result1).not.toBe(result2);
expect(result1).toEqual(result2);
});
});
describe('getOptimalPoolSize', () => {
it("should calculate pool size based on Little's Law", () => {
// 10 requests/second, 100ms average query time, 50ms target latency
const result = PoolSizeCalculator.getOptimalPoolSize(10, 100, 50);
// Little's Law: L = λ * W = 10 * 0.1 = 1
// With 20% buffer: 1 * 1.2 = 1.2, ceil = 2
// Latency based: 10 * (100/50) = 20
// Max of (2, 20, 2) = 20
expect(result).toBe(20);
});
it('should return minimum 2 connections', () => {
// Very low concurrency
const result = PoolSizeCalculator.getOptimalPoolSize(0.1, 10, 1000);
expect(result).toBe(2);
});
it('should handle high concurrency scenarios', () => {
// 100 requests/second, 500ms average query time, 100ms target latency
const result = PoolSizeCalculator.getOptimalPoolSize(100, 500, 100);
// Little's Law: L = 100 * 0.5 = 50
// With 20% buffer: 50 * 1.2 = 60
// Latency based: 100 * (500/100) = 500
// Max of (60, 500, 2) = 500
expect(result).toBe(500);
});
it('should handle scenarios where latency target is already met', () => {
// 10 requests/second, 50ms average query time, 200ms target latency
const result = PoolSizeCalculator.getOptimalPoolSize(10, 50, 200);
// Little's Law: L = 10 * 0.05 = 0.5
// With 20% buffer: 0.5 * 1.2 = 0.6, ceil = 1
// Latency based: 10 * (50/200) = 2.5, ceil = 3
// Max of (1, 3, 2) = 3
expect(result).toBe(3);
});
it('should handle edge cases with zero values', () => {
expect(PoolSizeCalculator.getOptimalPoolSize(0, 100, 100)).toBe(2);
expect(PoolSizeCalculator.getOptimalPoolSize(10, 0, 100)).toBe(2);
});
it('should handle fractional calculations correctly', () => {
// 15 requests/second, 75ms average query time, 150ms target latency
const result = PoolSizeCalculator.getOptimalPoolSize(15, 75, 150);
// Little's Law: L = 15 * 0.075 = 1.125
// With 20% buffer: 1.125 * 1.2 = 1.35, ceil = 2
// Latency based: 15 * (75/150) = 7.5, ceil = 8
// Max of (2, 8, 2) = 8
expect(result).toBe(8);
});
it('should prioritize latency-based sizing when it requires more connections', () => {
// Scenario where latency requirements demand more connections than throughput
const result = PoolSizeCalculator.getOptimalPoolSize(5, 200, 50);
// Little's Law: L = 5 * 0.2 = 1
// With 20% buffer: 1 * 1.2 = 1.2, ceil = 2
// Latency based: 5 * (200/50) = 20
// Max of (2, 20, 2) = 20
expect(result).toBe(20);
});
it('should handle very high query times', () => {
// 50 requests/second, 2000ms average query time, 500ms target latency
const result = PoolSizeCalculator.getOptimalPoolSize(50, 2000, 500);
// Little's Law: L = 50 * 2 = 100
// With 20% buffer: 100 * 1.2 = 120
// Latency based: 50 * (2000/500) = 200
// Max of (120, 200, 2) = 200
expect(result).toBe(200);
});
});
});

View file

@ -231,44 +231,20 @@ describe('DI Registrations', () => {
});
describe('registerApplicationServices', () => {
it('should register browser when config exists', () => {
it('should register default null browser outside ingestion and register proxy when redis enabled', () => {
const container = createContainer();
// Mock browser factory
const mockBrowser = {
launch: mock(() => Promise.resolve()),
close: mock(() => Promise.resolve()),
};
mock.module('@stock-bot/browser', () => ({
createBrowser: () => mockBrowser,
}));
const config = {
browser: {
headless: true,
timeout: 30000,
},
} as any;
registerApplicationServices(container, config);
expect(container.hasRegistration('browser')).toBe(true);
});
it('should register proxy when config exists', () => {
const container = createContainer();
// Mock proxy factory
const mockProxy = {
getProxy: mock(() => 'http://proxy:8080'),
};
mock.module('@stock-bot/proxy', () => ({
createProxyManager: () => mockProxy,
}));
const config = {
redis: {
enabled: true,
host: 'localhost',
port: 6379,
db: 0,
},
proxy: {
enabled: true,
url: 'http://proxy:8080',
@ -277,10 +253,14 @@ describe('DI Registrations', () => {
registerApplicationServices(container, config);
expect(container.hasRegistration('browser')).toBe(true);
expect(container.hasRegistration('proxyCache')).toBe(true);
expect(container.hasRegistration('proxyManager')).toBe(true);
expect(container.resolve('browser')).toBeNull();
expect(container.getRegistration('proxyManager')?.lifetime).toBe('SINGLETON');
});
it('should register queue manager when queue config exists', () => {
it('should register queue manager when queue and redis configs exist', () => {
const container = createContainer();
// Mock dependencies
@ -321,6 +301,12 @@ describe('DI Registrations', () => {
name: 'test-service',
serviceName: 'test-service',
},
redis: {
enabled: true,
host: 'localhost',
port: 6379,
db: 0,
},
queue: {
enabled: true,
workers: 2,
@ -394,20 +380,26 @@ describe('DI Registrations', () => {
});
describe('registration options', () => {
it('should register services as singletons', () => {
it('should register queueManager as singleton when enabled', () => {
const container = createContainer();
const config = {
browser: {
headless: true,
timeout: 30000,
redis: {
enabled: true,
host: 'localhost',
port: 6379,
db: 0,
},
queue: {
enabled: true,
workers: 1,
concurrency: 1,
},
} as any;
registerApplicationServices(container, config);
// Check that browser was registered as singleton
const registration = container.getRegistration('browser');
const registration = container.getRegistration('queueManager');
expect(registration).toBeDefined();
expect(registration?.lifetime).toBe('SINGLETON');
});

View file

@ -263,9 +263,9 @@ describe('ServiceApplication', () => {
await app.start(mockContainerFactory, mockRouteFactory, mockHandlerInitializer);
expect(mockHandlerInitializer).toHaveBeenCalledWith(
{ test: 'container' },
expect.objectContaining({
test: 'container',
_diContainer: mockContainer,
handlerRegistry: expect.anything(),
})
);
expect(mockLogger.info).toHaveBeenCalledWith('Handlers initialized');

View file

@ -1,270 +0,0 @@
import { describe, expect, it } from 'bun:test';
import type {
CachePoolConfig,
ConnectionFactory,
ConnectionFactoryConfig,
ConnectionPool,
ConnectionPoolConfig,
GenericClientConfig,
MongoDBPoolConfig,
PoolMetrics,
PostgreSQLPoolConfig,
QueuePoolConfig,
} from '../src/types';
describe('DI Types', () => {
describe('GenericClientConfig', () => {
it('should allow any key-value pairs', () => {
const config: GenericClientConfig = {
host: 'localhost',
port: 5432,
username: 'test',
password: 'test',
customOption: true,
};
expect(config.host).toBe('localhost');
expect(config.port).toBe(5432);
expect(config.customOption).toBe(true);
});
});
describe('ConnectionPoolConfig', () => {
it('should have required and optional fields', () => {
const config: ConnectionPoolConfig = {
name: 'test-pool',
poolSize: 10,
minConnections: 2,
maxConnections: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 5000,
enableMetrics: true,
};
expect(config.name).toBe('test-pool');
expect(config.poolSize).toBe(10);
expect(config.enableMetrics).toBe(true);
});
it('should allow minimal configuration', () => {
const config: ConnectionPoolConfig = {
name: 'minimal-pool',
};
expect(config.name).toBe('minimal-pool');
expect(config.poolSize).toBeUndefined();
});
});
describe('Specific Pool Configs', () => {
it('should extend ConnectionPoolConfig for MongoDB', () => {
const config: MongoDBPoolConfig = {
name: 'mongo-pool',
poolSize: 5,
config: {
uri: 'mongodb://localhost:27017',
database: 'test',
},
};
expect(config.name).toBe('mongo-pool');
expect(config.config.uri).toBe('mongodb://localhost:27017');
});
it('should extend ConnectionPoolConfig for PostgreSQL', () => {
const config: PostgreSQLPoolConfig = {
name: 'postgres-pool',
config: {
host: 'localhost',
port: 5432,
database: 'test',
},
};
expect(config.name).toBe('postgres-pool');
expect(config.config.host).toBe('localhost');
});
it('should extend ConnectionPoolConfig for Cache', () => {
const config: CachePoolConfig = {
name: 'cache-pool',
config: {
host: 'localhost',
port: 6379,
},
};
expect(config.name).toBe('cache-pool');
expect(config.config.port).toBe(6379);
});
it('should extend ConnectionPoolConfig for Queue', () => {
const config: QueuePoolConfig = {
name: 'queue-pool',
config: {
redis: {
host: 'localhost',
port: 6379,
},
},
};
expect(config.name).toBe('queue-pool');
expect(config.config.redis.host).toBe('localhost');
});
});
describe('ConnectionFactoryConfig', () => {
it('should define factory configuration', () => {
const config: ConnectionFactoryConfig = {
service: 'test-service',
environment: 'development',
pools: {
mongodb: {
poolSize: 10,
},
postgres: {
maxConnections: 20,
},
cache: {
idleTimeoutMillis: 60000,
},
queue: {
enableMetrics: true,
},
},
};
expect(config.service).toBe('test-service');
expect(config.environment).toBe('development');
expect(config.pools?.mongodb?.poolSize).toBe(10);
expect(config.pools?.postgres?.maxConnections).toBe(20);
});
it('should allow minimal factory config', () => {
const config: ConnectionFactoryConfig = {
service: 'minimal-service',
environment: 'test',
};
expect(config.service).toBe('minimal-service');
expect(config.pools).toBeUndefined();
});
});
describe('ConnectionPool', () => {
it('should define connection pool interface', () => {
const mockPool: ConnectionPool<any> = {
name: 'test-pool',
client: { connected: true },
metrics: {
created: new Date(),
totalConnections: 10,
activeConnections: 5,
idleConnections: 5,
waitingRequests: 0,
errors: 0,
},
health: async () => true,
dispose: async () => {},
};
expect(mockPool.name).toBe('test-pool');
expect(mockPool.client.connected).toBe(true);
expect(mockPool.metrics.totalConnections).toBe(10);
});
});
describe('PoolMetrics', () => {
it('should define pool metrics structure', () => {
const metrics: PoolMetrics = {
created: new Date('2024-01-01'),
totalConnections: 100,
activeConnections: 25,
idleConnections: 75,
waitingRequests: 2,
errors: 3,
};
expect(metrics.totalConnections).toBe(100);
expect(metrics.activeConnections).toBe(25);
expect(metrics.idleConnections).toBe(75);
expect(metrics.waitingRequests).toBe(2);
expect(metrics.errors).toBe(3);
});
});
describe('ConnectionFactory', () => {
it('should define connection factory interface', () => {
const mockFactory: ConnectionFactory = {
createMongoDB: async config => ({
name: config.name,
client: {},
metrics: {
created: new Date(),
totalConnections: 0,
activeConnections: 0,
idleConnections: 0,
waitingRequests: 0,
errors: 0,
},
health: async () => true,
dispose: async () => {},
}),
createPostgreSQL: async config => ({
name: config.name,
client: {},
metrics: {
created: new Date(),
totalConnections: 0,
activeConnections: 0,
idleConnections: 0,
waitingRequests: 0,
errors: 0,
},
health: async () => true,
dispose: async () => {},
}),
createCache: async config => ({
name: config.name,
client: {},
metrics: {
created: new Date(),
totalConnections: 0,
activeConnections: 0,
idleConnections: 0,
waitingRequests: 0,
errors: 0,
},
health: async () => true,
dispose: async () => {},
}),
createQueue: async config => ({
name: config.name,
client: {},
metrics: {
created: new Date(),
totalConnections: 0,
activeConnections: 0,
idleConnections: 0,
waitingRequests: 0,
errors: 0,
},
health: async () => true,
dispose: async () => {},
}),
getPool: (_type, _name) => undefined,
listPools: () => [],
disposeAll: async () => {},
};
expect(mockFactory.createMongoDB).toBeDefined();
expect(mockFactory.createPostgreSQL).toBeDefined();
expect(mockFactory.createCache).toBeDefined();
expect(mockFactory.createQueue).toBeDefined();
expect(mockFactory.getPool).toBeDefined();
expect(mockFactory.listPools).toBeDefined();
expect(mockFactory.disposeAll).toBeDefined();
});
});
});

View file

@ -1,191 +0,0 @@
# @stock-bot/event-bus
Lightweight event bus for inter-service communication in the Stock Bot platform.
## Overview
This library provides a simple pub/sub event system using Redis, designed for real-time event distribution between microservices. It focuses on simplicity and reliability for event-driven communication.
## Features
- Simple pub/sub pattern using Redis
- Automatic reconnection and resubscription
- Local event emission (works even without Redis)
- TypeScript support with predefined trading event types
- Lightweight with minimal dependencies
## Installation
```bash
bun add @stock-bot/event-bus
```
## Usage
### Basic Setup
```typescript
import { createEventBus, TradingEventType } from '@stock-bot/event-bus';
const eventBus = createEventBus({
serviceName: 'data-ingestion',
redisConfig: {
host: 'localhost',
port: 6379,
},
enableLogging: true,
});
// Wait for connection
await eventBus.waitForConnection();
```
### Publishing Events
```typescript
// Publish a price update
await eventBus.publish(TradingEventType.PRICE_UPDATE, {
symbol: 'AAPL',
price: 150.25,
volume: 1000000,
timestamp: Date.now(),
});
// Publish with metadata
await eventBus.publish(TradingEventType.ORDER_FILLED,
{
orderId: '12345',
symbol: 'TSLA',
side: 'buy',
quantity: 100,
price: 250.50,
},
{ source: 'ib-gateway', region: 'us' }
);
```
### Subscribing to Events
```typescript
// Subscribe to price updates
await eventBus.subscribe(TradingEventType.PRICE_UPDATE, async (message) => {
console.log(`Price update for ${message.data.symbol}: $${message.data.price}`);
});
// Subscribe to order events
await eventBus.subscribe(TradingEventType.ORDER_FILLED, async (message) => {
const { orderId, symbol, quantity, price } = message.data;
console.log(`Order ${orderId} filled: ${quantity} ${symbol} @ $${price}`);
});
```
### Event Types
The library includes predefined event types for common trading operations:
```typescript
enum TradingEventType {
// Market data events
PRICE_UPDATE = 'market.price.update',
ORDERBOOK_UPDATE = 'market.orderbook.update',
TRADE_EXECUTED = 'market.trade.executed',
// Order events
ORDER_CREATED = 'order.created',
ORDER_FILLED = 'order.filled',
ORDER_CANCELLED = 'order.cancelled',
ORDER_REJECTED = 'order.rejected',
// Position events
POSITION_OPENED = 'position.opened',
POSITION_CLOSED = 'position.closed',
POSITION_UPDATED = 'position.updated',
// Strategy events
STRATEGY_SIGNAL = 'strategy.signal',
STRATEGY_STARTED = 'strategy.started',
STRATEGY_STOPPED = 'strategy.stopped',
// Risk events
RISK_LIMIT_BREACH = 'risk.limit.breach',
RISK_WARNING = 'risk.warning',
// System events
SERVICE_STARTED = 'system.service.started',
SERVICE_STOPPED = 'system.service.stopped',
SERVICE_ERROR = 'system.service.error',
}
```
### Typed Events
Use TypeScript generics for type-safe event handling:
```typescript
import type { PriceUpdateEvent, OrderEvent } from '@stock-bot/event-bus';
// Type-safe subscription
await eventBus.subscribe<PriceUpdateEvent>(
TradingEventType.PRICE_UPDATE,
async (message) => {
// message.data is typed as PriceUpdateEvent
const { symbol, price, volume } = message.data;
}
);
```
### Cleanup
```typescript
// Unsubscribe from specific event
await eventBus.unsubscribe(TradingEventType.PRICE_UPDATE);
// Close all connections
await eventBus.close();
```
## Architecture Notes
This library is designed for lightweight, real-time event distribution. For reliable job processing, retries, and persistence, use the `@stock-bot/queue` library with BullMQ instead.
### When to Use Event Bus
- Real-time notifications (price updates, trade executions)
- Service coordination (strategy signals, risk alerts)
- System monitoring (service status, errors)
### When to Use Queue
- Data processing jobs
- Batch operations
- Tasks requiring persistence and retries
- Scheduled operations
## Error Handling
The event bus handles connection failures gracefully:
```typescript
try {
await eventBus.publish(TradingEventType.PRICE_UPDATE, data);
} catch (error) {
// Event will still be emitted locally
console.error('Failed to publish to Redis:', error);
}
```
## Development
```bash
# Install dependencies
bun install
# Build
bun run build
# Run tests
bun test
# Clean build artifacts
bun run clean
```

View file

@ -1,40 +0,0 @@
{
"name": "@stock-bot/event-bus",
"version": "1.0.0",
"description": "Event bus library for inter-service communication",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"scripts": {
"build": "tsc",
"test": "bun test",
"clean": "rimraf dist"
},
"dependencies": {
"@stock-bot/logger": "*",
"ioredis": "^5.3.2",
"eventemitter3": "^5.0.1",
"@stock-bot/invariants": "workspace:*"
},
"devDependencies": {
"@types/node": "^20.11.0",
"typescript": "^5.3.0",
"bun-types": "^1.2.15"
},
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"./types": {
"import": "./dist/types.js",
"require": "./dist/types.js",
"types": "./dist/types.d.ts"
}
},
"files": [
"dist",
"README.md"
]
}

View file

@ -1,246 +0,0 @@
import { EventEmitter } from 'eventemitter3';
import Redis from 'ioredis';
import { getLogger } from '@stock-bot/logger';
import type { EventBusConfig, EventBusMessage, EventHandler, EventSubscription } from './types';
/**
* Lightweight Event Bus for inter-service communication
* Uses Redis pub/sub for simple, real-time event distribution
*/
export class EventBus extends EventEmitter {
private publisher: Redis;
private subscriber: Redis;
private readonly serviceName: string;
private readonly logger: ReturnType<typeof getLogger>;
private subscriptions: Map<string, EventSubscription> = new Map();
private isConnected: boolean = false;
constructor(config: EventBusConfig) {
super();
this.serviceName = config.serviceName;
this.logger = getLogger(`event-bus:${this.serviceName}`);
// Create Redis connections
const redisOptions = {
host: config.redisConfig.host,
port: config.redisConfig.port,
password: config.redisConfig.password,
db: config.redisConfig.db || 0,
lazyConnect: false,
enableOfflineQueue: true,
reconnectOnError: (err: Error) => {
this.logger.error('Redis connection error:', err);
return true;
},
};
this.publisher = new Redis(redisOptions);
this.subscriber = new Redis(redisOptions);
this.setupRedisHandlers();
}
private setupRedisHandlers(): void {
// Publisher handlers
this.publisher.on('connect', () => {
this.logger.info('Publisher connected to Redis');
this.isConnected = true;
});
this.publisher.on('error', error => {
this.logger.error('Publisher Redis error:', error);
});
// Subscriber handlers
this.subscriber.on('connect', () => {
this.logger.info('Subscriber connected to Redis');
// Resubscribe to all channels on reconnect
this.resubscribeAll();
});
this.subscriber.on('error', error => {
this.logger.error('Subscriber Redis error:', error);
});
// Handle incoming messages
this.subscriber.on('message', this.handleMessage.bind(this));
}
private handleMessage(channel: string, message: string): void {
try {
const eventMessage: EventBusMessage = JSON.parse(message);
// Skip messages from self
if (eventMessage.source === this.serviceName) {
return;
}
// Extract event type from channel (remove 'events:' prefix)
const eventType = channel.replace('events:', '');
// Emit locally
this.emit(eventType, eventMessage);
// Call registered handler if exists
const subscription = this.subscriptions.get(eventType);
if (subscription?.handler) {
Promise.resolve(subscription.handler(eventMessage)).catch(error => {
this.logger.error(`Handler error for event ${eventType}:`, error);
});
}
this.logger.debug(`Received event: ${eventType} from ${eventMessage.source}`);
} catch (error) {
this.logger.error('Failed to handle message:', { error, channel, message });
}
}
/**
* Publish an event
*/
async publish<T = unknown>(
type: string,
data: T,
metadata?: Record<string, unknown>
): Promise<void> {
const message: EventBusMessage<T> = {
id: this.generateId(),
type,
source: this.serviceName,
timestamp: Date.now(),
data,
metadata,
};
// Emit locally first
this.emit(type, message);
// Publish to Redis
if (this.isConnected) {
try {
const channel = `events:${type}`;
await this.publisher.publish(channel, JSON.stringify(message));
this.logger.debug(`Published event: ${type}`, { messageId: message.id });
} catch (error) {
this.logger.error(`Failed to publish event: ${type}`, { error, messageId: message.id });
throw error;
}
} else {
this.logger.warn(`Not connected to Redis, event ${type} only emitted locally`);
}
}
/**
* Subscribe to an event
*/
async subscribe<T = unknown>(eventType: string, handler: EventHandler<T>): Promise<void> {
// Register handler
this.subscriptions.set(eventType, {
channel: `events:${eventType}`,
handler: message => handler(message as EventBusMessage<T>),
});
// Add local listener
this.on(eventType, handler);
// Subscribe to Redis channel
try {
const channel = `events:${eventType}`;
await this.subscriber.subscribe(channel);
this.logger.debug(`Subscribed to event: ${eventType}`);
} catch (error) {
this.logger.error(`Failed to subscribe to event: ${eventType}`, error);
throw error;
}
}
/**
* Unsubscribe from an event
*/
async unsubscribe(eventType: string, handler?: EventHandler): Promise<void> {
// Remove specific handler or all handlers
if (handler) {
this.off(eventType, handler);
} else {
this.removeAllListeners(eventType);
}
// Remove from subscriptions
this.subscriptions.delete(eventType);
// Unsubscribe from Redis
try {
const channel = `events:${eventType}`;
await this.subscriber.unsubscribe(channel);
this.logger.debug(`Unsubscribed from event: ${eventType}`);
} catch (error) {
this.logger.error(`Failed to unsubscribe from event: ${eventType}`, error);
}
}
/**
* Resubscribe to all channels (used on reconnect)
*/
private async resubscribeAll(): Promise<void> {
for (const [eventType, subscription] of this.subscriptions.entries()) {
try {
await this.subscriber.subscribe(subscription.channel);
this.logger.debug(`Resubscribed to event: ${eventType}`);
} catch (error) {
this.logger.error(`Failed to resubscribe to event: ${eventType}`, error);
}
}
}
/**
* Wait for connection to be established
*/
async waitForConnection(timeout: number = 5000): Promise<void> {
const startTime = Date.now();
while (!this.isConnected && Date.now() - startTime < timeout) {
await new Promise(resolve => setTimeout(resolve, 100));
}
if (!this.isConnected) {
throw new Error(`Failed to connect to Redis within ${timeout}ms`);
}
}
/**
* Close all connections
*/
async close(): Promise<void> {
this.isConnected = false;
// Clear all subscriptions
this.subscriptions.clear();
this.removeAllListeners();
// Close Redis connections
await Promise.all([this.publisher.quit(), this.subscriber.quit()]);
this.logger.info('Event bus closed');
}
/**
* Generate unique message ID
*/
private generateId(): string {
return `${this.serviceName}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
/**
* Check if connected to Redis
*/
get connected(): boolean {
return this.isConnected;
}
/**
* Get service name
*/
get service(): string {
return this.serviceName;
}
}

View file

@ -1,13 +0,0 @@
import { EventBus } from './event-bus';
import type { EventBusConfig } from './types';
/**
* Create a new event bus instance
*/
export function createEventBus(config: EventBusConfig): EventBus {
return new EventBus(config);
}
// Re-export everything
export { EventBus } from './event-bus';
export * from './types';

View file

@ -1,205 +0,0 @@
import { defined } from '@stock-bot/invariants';
import type { EventBusMessage, EventHandler, EventSubscription } from './types';
/**
* Simple in-memory event bus for testing
*/
export class SimpleEventBus {
private subscriptions = new Map<string, Set<{ id: string; handler: EventHandler }>>();
private subscriptionById = new Map<
string,
{ id: string; channel: string; handler: EventHandler }
>();
private nextId = 1;
subscribe(channel: string, handler: EventHandler): EventSubscription {
const id = `sub-${this.nextId++}`;
const subscription = { id, handler };
if (!this.subscriptions.has(channel)) {
this.subscriptions.set(channel, new Set());
}
defined(this.subscriptions.get(channel)).add(subscription);
this.subscriptionById.set(id, { id, channel, handler });
return { channel, handler };
}
unsubscribe(idOrSubscription: string | EventSubscription): boolean {
if (typeof idOrSubscription === 'string') {
const subscription = this.subscriptionById.get(idOrSubscription);
if (!subscription) {
return false;
}
const channelSubs = this.subscriptions.get(subscription.channel);
if (channelSubs) {
channelSubs.forEach(sub => {
if (sub.id === idOrSubscription) {
channelSubs.delete(sub);
}
});
if (channelSubs.size === 0) {
this.subscriptions.delete(subscription.channel);
}
}
this.subscriptionById.delete(idOrSubscription);
return true;
} else {
// Unsubscribe by matching handler and channel
const channelSubs = this.subscriptions.get(idOrSubscription.channel);
if (channelSubs) {
let removed = false;
channelSubs.forEach(sub => {
if (sub.handler === idOrSubscription.handler) {
channelSubs.delete(sub);
this.subscriptionById.delete(sub.id);
removed = true;
}
});
if (channelSubs.size === 0) {
this.subscriptions.delete(idOrSubscription.channel);
}
return removed;
}
return false;
}
}
async publish(event: string, data: unknown): Promise<void> {
const message: EventBusMessage = {
id: `msg-${this.nextId++}`,
type: event,
source: 'simple-event-bus',
timestamp: Date.now(),
data,
};
const handlers: EventHandler[] = [];
// Direct matches
const directSubs = this.subscriptions.get(event);
if (directSubs) {
handlers.push(...Array.from(directSubs).map(s => s.handler));
}
// Pattern matches
for (const [pattern, subs] of this.subscriptions) {
if (pattern.includes('*') && this.matchPattern(pattern, event)) {
handlers.push(...Array.from(subs).map(s => s.handler));
}
}
// Execute all handlers
await Promise.all(
handlers.map(handler =>
Promise.resolve(handler(message)).catch(_err => {
// Silently catch errors
})
)
);
}
publishSync(event: string, data: unknown): void {
const message: EventBusMessage = {
id: `msg-${this.nextId++}`,
type: event,
source: 'simple-event-bus',
timestamp: Date.now(),
data,
};
const handlers: EventHandler[] = [];
// Direct matches
const directSubs = this.subscriptions.get(event);
if (directSubs) {
handlers.push(...Array.from(directSubs).map(s => s.handler));
}
// Pattern matches
for (const [pattern, subs] of this.subscriptions) {
if (pattern.includes('*') && this.matchPattern(pattern, event)) {
handlers.push(...Array.from(subs).map(s => s.handler));
}
}
// Execute all handlers synchronously
handlers.forEach(handler => {
try {
handler(message);
} catch {
// Silently catch errors
}
});
}
once(event: string, handler: EventHandler): EventSubscription {
let subId: string;
const wrappedHandler: EventHandler = async message => {
await handler(message);
this.unsubscribe(subId);
};
const subscription = this.subscribe(event, wrappedHandler);
// Find the subscription ID
this.subscriptionById.forEach((value, key) => {
if (value.handler === wrappedHandler) {
subId = key;
}
});
return subscription;
}
off(event: string, handler?: EventHandler): void {
if (!handler) {
// Remove all handlers for this event
const subs = this.subscriptions.get(event);
if (subs) {
for (const sub of subs) {
this.subscriptionById.delete(sub.id);
}
this.subscriptions.delete(event);
}
} else {
// Remove specific handler
const subs = this.subscriptions.get(event);
if (subs) {
const toRemove: string[] = [];
subs.forEach(sub => {
if (sub.handler === handler) {
toRemove.push(sub.id);
}
});
toRemove.forEach(id => {
subs.forEach(sub => {
if (sub.id === id) {
subs.delete(sub);
}
});
this.subscriptionById.delete(id);
});
if (subs.size === 0) {
this.subscriptions.delete(event);
}
}
}
}
hasSubscribers(event: string): boolean {
return this.subscriptions.has(event) && defined(this.subscriptions.get(event)).size > 0;
}
clear(): void {
this.subscriptions.clear();
this.subscriptionById.clear();
}
private matchPattern(pattern: string, event: string): boolean {
// Simple pattern matching: user.* matches user.created, user.updated, etc.
const regex = new RegExp('^' + pattern.replace(/\*/g, '.*') + '$');
return regex.test(event);
}
}

View file

@ -1,111 +0,0 @@
export interface EventBusMessage<T = unknown> {
id: string;
type: string;
source: string;
timestamp: number;
data: T;
metadata?: Record<string, unknown>;
}
export interface EventHandler<T = unknown> {
(message: EventBusMessage<T>): Promise<void> | void;
}
export interface EventBusConfig {
serviceName: string;
redisConfig: {
host: string;
port: number;
password?: string;
db?: number;
};
enableLogging?: boolean;
}
export interface EventSubscription {
channel: string;
handler: EventHandler;
}
// Trading-specific event types
export enum TradingEventType {
// Market data events
PRICE_UPDATE = 'market.price.update',
ORDERBOOK_UPDATE = 'market.orderbook.update',
TRADE_EXECUTED = 'market.trade.executed',
// Order events
ORDER_CREATED = 'order.created',
ORDER_FILLED = 'order.filled',
ORDER_CANCELLED = 'order.cancelled',
ORDER_REJECTED = 'order.rejected',
// Position events
POSITION_OPENED = 'position.opened',
POSITION_CLOSED = 'position.closed',
POSITION_UPDATED = 'position.updated',
// Strategy events
STRATEGY_SIGNAL = 'strategy.signal',
STRATEGY_STARTED = 'strategy.started',
STRATEGY_STOPPED = 'strategy.stopped',
// Risk events
RISK_LIMIT_BREACH = 'risk.limit.breach',
RISK_WARNING = 'risk.warning',
// System events
SERVICE_STARTED = 'system.service.started',
SERVICE_STOPPED = 'system.service.stopped',
SERVICE_ERROR = 'system.service.error',
}
// Event data types
export interface PriceUpdateEvent {
symbol: string;
price: number;
volume: number;
timestamp: number;
}
export interface OrderEvent {
orderId: string;
symbol: string;
side: 'buy' | 'sell';
quantity: number;
price?: number;
type: 'market' | 'limit' | 'stop' | 'stop_limit';
status: string;
portfolioId: string;
strategyId?: string;
}
export interface PositionEvent {
positionId: string;
symbol: string;
quantity: number;
averageCost: number;
currentPrice: number;
unrealizedPnl: number;
realizedPnl: number;
portfolioId: string;
}
export interface StrategySignalEvent {
strategyId: string;
signal: 'buy' | 'sell' | 'hold';
symbol: string;
confidence: number;
indicators: Record<string, number>;
timestamp: number;
}
export interface RiskEvent {
type: 'position_size' | 'daily_loss' | 'max_drawdown' | 'concentration';
severity: 'warning' | 'critical';
currentValue: number;
limit: number;
portfolioId?: string;
strategyId?: string;
message: string;
}

View file

@ -1,17 +0,0 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"composite": true
},
"include": ["src/**/*"],
"references": [
{
"path": "../../core/logger"
},
{
"path": "../../../libs/core/invariants"
}
]
}

View file

@ -12,7 +12,6 @@
"dependencies": {
"@stock-bot/services": "workspace:*",
"@stock-bot/cache": "workspace:*",
"@stock-bot/config": "workspace:*",
"@stock-bot/handler-registry": "workspace:*",
"@stock-bot/logger": "workspace:*",
"@stock-bot/types": "workspace:*",

View file

@ -11,7 +11,6 @@
"test": "bun test"
},
"dependencies": {
"got": "^14.4.7",
"pino": "^9.7.0",
"pino-loki": "^2.6.0",
"pino-pretty": "^13.0.0"

View file

@ -346,6 +346,7 @@ async function addJobsInChunks(
chunkSize: chunk.length,
error,
});
throw error;
}
}

View file

@ -1,257 +0,0 @@
import { Queue, type Job } from 'bullmq';
import type { DLQConfig, RedisConfig } from './types';
import { getRedisConnection } from './utils';
// Logger interface for type safety
interface Logger {
info(message: string, meta?: Record<string, unknown>): void;
error(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
debug(message: string, meta?: Record<string, unknown>): void;
}
export class DeadLetterQueueHandler {
private dlq: Queue;
private config: Required<DLQConfig>;
private failureCount = new Map<string, number>();
private readonly logger: Logger;
constructor(
private mainQueue: Queue,
connection: RedisConfig,
config: DLQConfig = {},
logger?: Logger
) {
this.logger = logger || console;
this.config = {
maxRetries: config.maxRetries ?? 3,
retryDelay: config.retryDelay ?? 60000, // 1 minute
alertThreshold: config.alertThreshold ?? 100,
cleanupAge: config.cleanupAge ?? 168, // 7 days
};
// Create DLQ with same name but -dlq suffix
const dlqName = `${mainQueue.name}-dlq`;
this.dlq = new Queue(dlqName, { connection: getRedisConnection(connection) });
}
/**
* Process a failed job - either retry or move to DLQ
*/
async handleFailedJob(job: Job, error: Error): Promise<void> {
const jobKey = `${job.name}:${job.id}`;
const currentFailures = (this.failureCount.get(jobKey) || 0) + 1;
this.failureCount.set(jobKey, currentFailures);
this.logger.warn('Job failed', {
jobId: job.id,
jobName: job.name,
attempt: job.attemptsMade,
maxAttempts: job.opts.attempts,
error: error.message,
failureCount: currentFailures,
});
// Check if job should be moved to DLQ
if (job.attemptsMade >= (job.opts.attempts || this.config.maxRetries)) {
await this.moveToDeadLetterQueue(job, error);
this.failureCount.delete(jobKey);
}
}
/**
* Move job to dead letter queue
*/
private async moveToDeadLetterQueue(job: Job, error: Error): Promise<void> {
try {
const dlqData = {
originalJob: {
id: job.id,
name: job.name,
data: job.data,
opts: job.opts,
attemptsMade: job.attemptsMade,
failedReason: job.failedReason,
processedOn: job.processedOn,
timestamp: job.timestamp,
},
error: {
message: error.message,
stack: error.stack,
name: error.name,
},
movedToDLQAt: new Date().toISOString(),
};
await this.dlq.add('failed-job', dlqData, {
removeOnComplete: 100,
removeOnFail: 100,
});
this.logger.error('Job moved to DLQ', {
jobId: job.id,
jobName: job.name,
error: error.message,
});
// Check if we need to alert
await this.checkAlertThreshold();
} catch (dlqError) {
this.logger.error('Failed to move job to DLQ', {
jobId: job.id,
error: dlqError,
});
}
}
/**
* Retry jobs from DLQ
*/
async retryDLQJobs(limit = 10): Promise<number> {
const jobs = await this.dlq.getCompleted(0, limit);
let retriedCount = 0;
for (const dlqJob of jobs) {
try {
const { originalJob } = dlqJob.data;
// Re-add to main queue with delay
await this.mainQueue.add(originalJob.name, originalJob.data, {
...originalJob.opts,
delay: this.config.retryDelay,
attempts: this.config.maxRetries,
});
// Remove from DLQ
await dlqJob.remove();
retriedCount++;
this.logger.info('Job retried from DLQ', {
originalJobId: originalJob.id,
jobName: originalJob.name,
});
} catch (error) {
this.logger.error('Failed to retry DLQ job', {
dlqJobId: dlqJob.id,
error,
});
}
}
return retriedCount;
}
/**
* Get DLQ statistics
*/
async getStats(): Promise<{
total: number;
recent: number;
byJobName: Record<string, number>;
oldestJob: Date | null;
}> {
const [completed, failed, waiting] = await Promise.all([
this.dlq.getCompleted(),
this.dlq.getFailed(),
this.dlq.getWaiting(),
]);
const allJobs = [...completed, ...failed, ...waiting];
const byJobName: Record<string, number> = {};
let oldestTimestamp: number | null = null;
for (const job of allJobs) {
const jobName = job.data.originalJob?.name || 'unknown';
byJobName[jobName] = (byJobName[jobName] || 0) + 1;
if (!oldestTimestamp || job.timestamp < oldestTimestamp) {
oldestTimestamp = job.timestamp;
}
}
// Count recent jobs (last 24 hours)
const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000;
const recent = allJobs.filter(job => job.timestamp > oneDayAgo).length;
return {
total: allJobs.length,
recent,
byJobName,
oldestJob: oldestTimestamp ? new Date(oldestTimestamp) : null,
};
}
/**
* Clean up old DLQ entries
*/
async cleanup(): Promise<number> {
const ageInMs = this.config.cleanupAge * 60 * 60 * 1000;
const cutoffTime = Date.now() - ageInMs;
const jobs = await this.dlq.getCompleted();
let removedCount = 0;
for (const job of jobs) {
if (job.timestamp < cutoffTime) {
await job.remove();
removedCount++;
}
}
this.logger.info('DLQ cleanup completed', {
removedCount,
cleanupAge: `${this.config.cleanupAge} hours`,
});
return removedCount;
}
/**
* Check if alert threshold is exceeded
*/
private async checkAlertThreshold(): Promise<void> {
const stats = await this.getStats();
if (stats.total >= this.config.alertThreshold) {
this.logger.error('DLQ alert threshold exceeded', {
threshold: this.config.alertThreshold,
currentCount: stats.total,
byJobName: stats.byJobName,
});
// In a real implementation, this would trigger alerts
}
}
/**
* Get failed jobs for inspection
*/
async inspectFailedJobs(limit = 10): Promise<
Array<{
id: string;
name: string;
data: unknown;
error: unknown;
failedAt: string;
attempts: number;
}>
> {
const jobs = await this.dlq.getCompleted(0, limit);
return jobs.map(job => ({
id: job.data.originalJob.id,
name: job.data.originalJob.name,
data: job.data.originalJob.data,
error: job.data.error,
failedAt: job.data.movedToDLQAt,
attempts: job.data.originalJob.attemptsMade,
}));
}
/**
* Shutdown DLQ handler
*/
async shutdown(): Promise<void> {
await this.dlq.close();
this.failureCount.clear();
}
}

View file

@ -1,67 +1,32 @@
// Core exports
export { Queue } from './queue';
export { QueueManager } from './queue-manager';
export { ServiceCache, createServiceCache } from './service-cache';
// Service utilities
export {
normalizeServiceName,
generateCachePrefix,
getFullQueueName,
parseQueueName,
} from './service-utils';
// Batch processing
export { processBatchJob, processItems } from './batch-processor';
// DLQ handling
export { DeadLetterQueueHandler } from './dlq-handler';
// Metrics
export { QueueMetricsCollector } from './queue-metrics';
// Rate limiting
export { QueueRateLimiter } from './rate-limiter';
// Types
export type {
// Core types
JobData,
JobOptions,
QueueOptions,
GlobalStats,
// Batch processing types
BatchResult,
ProcessOptions,
BatchJobData,
// Handler types
JobHandler,
TypedJobHandler,
HandlerConfig,
HandlerConfigWithSchedule,
HandlerInitializer,
QueueStats,
QueueWorkerConfig,
// Configuration types
RedisConfig,
QueueConfig,
QueueManagerConfig,
// Rate limiting types
RateLimitConfig,
RateLimitRule,
// DLQ types
DLQConfig,
DLQJobInfo,
// Scheduled job types
ScheduledJob,
ScheduleConfig,
// Smart Queue types
SmartQueueConfig,
QueueRoute,
} from './types';

View file

@ -1,318 +0,0 @@
import { Queue, QueueEvents } from 'bullmq';
// import { getLogger } from '@stock-bot/logger';
// const logger = getLogger('queue-metrics');
interface QueueMetrics {
// Job counts
waiting: number;
active: number;
completed: number;
failed: number;
delayed: number;
paused?: number;
// Performance metrics
processingTime: {
avg: number;
min: number;
max: number;
p95: number;
p99: number;
};
// Throughput
throughput: {
completedPerMinute: number;
failedPerMinute: number;
totalPerMinute: number;
};
// Job age
oldestWaitingJob: Date | null;
// Health
isHealthy: boolean;
healthIssues: string[];
}
export class QueueMetricsCollector {
private processingTimes: number[] = [];
private completedTimestamps: number[] = [];
private failedTimestamps: number[] = [];
private jobStartTimes = new Map<string, number>();
private readonly maxSamples = 1000;
private readonly metricsInterval = 60000; // 1 minute
constructor(
private queue: Queue,
private queueEvents: QueueEvents
) {
this.setupEventListeners();
}
/**
* Setup event listeners for metrics collection
*/
private setupEventListeners(): void {
this.queueEvents.on('completed', () => {
// Record completion
this.completedTimestamps.push(Date.now());
this.cleanupOldTimestamps();
});
this.queueEvents.on('failed', () => {
// Record failure
this.failedTimestamps.push(Date.now());
this.cleanupOldTimestamps();
});
// Track processing times
this.queueEvents.on('active', ({ jobId }) => {
this.jobStartTimes.set(jobId, Date.now());
});
this.queueEvents.on('completed', ({ jobId }) => {
const startTime = this.jobStartTimes.get(jobId);
if (startTime) {
const processingTime = Date.now() - startTime;
this.recordProcessingTime(processingTime);
this.jobStartTimes.delete(jobId);
}
});
}
/**
* Record processing time
*/
private recordProcessingTime(time: number): void {
this.processingTimes.push(time);
// Keep only recent samples
if (this.processingTimes.length > this.maxSamples) {
this.processingTimes = this.processingTimes.slice(-this.maxSamples);
}
}
/**
* Clean up old timestamps
*/
private cleanupOldTimestamps(): void {
const cutoff = Date.now() - this.metricsInterval;
this.completedTimestamps = this.completedTimestamps.filter(ts => ts > cutoff);
this.failedTimestamps = this.failedTimestamps.filter(ts => ts > cutoff);
}
/**
* Collect current metrics
*/
async collect(): Promise<QueueMetrics> {
// Get job counts
const [waiting, active, completed, failed, delayed] = await Promise.all([
this.queue.getWaitingCount(),
this.queue.getActiveCount(),
this.queue.getCompletedCount(),
this.queue.getFailedCount(),
this.queue.getDelayedCount(),
]);
// BullMQ doesn't have getPausedCount, check if queue is paused
const paused = (await this.queue.isPaused()) ? waiting : 0;
// Calculate processing time metrics
const processingTime = this.calculateProcessingTimeMetrics();
// Calculate throughput
const throughput = this.calculateThroughput();
// Get oldest waiting job
const oldestWaitingJob = await this.getOldestWaitingJob();
// Check health
const { isHealthy, healthIssues } = this.checkHealth({
waiting,
active,
failed,
processingTime,
});
return {
waiting,
active,
completed,
failed,
delayed,
paused,
processingTime,
throughput,
oldestWaitingJob,
isHealthy,
healthIssues,
};
}
/**
* Calculate processing time metrics
*/
private calculateProcessingTimeMetrics(): QueueMetrics['processingTime'] {
if (this.processingTimes.length === 0) {
return { avg: 0, min: 0, max: 0, p95: 0, p99: 0 };
}
const sorted = [...this.processingTimes].sort((a, b) => a - b);
const sum = sorted.reduce((acc, val) => acc + val, 0);
return {
avg: sorted.length > 0 ? Math.round(sum / sorted.length) : 0,
min: sorted[0] || 0,
max: sorted[sorted.length - 1] || 0,
p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
};
}
/**
* Calculate throughput metrics
*/
private calculateThroughput(): QueueMetrics['throughput'] {
const now = Date.now();
const oneMinuteAgo = now - 60000;
const completedPerMinute = this.completedTimestamps.filter(ts => ts > oneMinuteAgo).length;
const failedPerMinute = this.failedTimestamps.filter(ts => ts > oneMinuteAgo).length;
return {
completedPerMinute,
failedPerMinute,
totalPerMinute: completedPerMinute + failedPerMinute,
};
}
/**
* Get oldest waiting job
*/
private async getOldestWaitingJob(): Promise<Date | null> {
const waitingJobs = await this.queue.getWaiting(0, 1);
if (waitingJobs.length > 0) {
return new Date(waitingJobs[0].timestamp);
}
return null;
}
/**
* Check queue health
*/
private checkHealth(metrics: {
waiting: number;
active: number;
failed: number;
processingTime: QueueMetrics['processingTime'];
}): { isHealthy: boolean; healthIssues: string[] } {
const issues: string[] = [];
// Check for high failure rate
const failureRate = metrics.failed / (metrics.failed + this.completedTimestamps.length);
if (failureRate > 0.1) {
issues.push(`High failure rate: ${(failureRate * 100).toFixed(1)}%`);
}
// Check for queue backlog
if (metrics.waiting > 1000) {
issues.push(`Large queue backlog: ${metrics.waiting} jobs waiting`);
}
// Check for slow processing
if (metrics.processingTime.avg > 30000) {
// 30 seconds
issues.push(
`Slow average processing time: ${(metrics.processingTime.avg / 1000).toFixed(1)}s`
);
}
// Check for stalled active jobs
if (metrics.active > 100) {
issues.push(`High number of active jobs: ${metrics.active}`);
}
return {
isHealthy: issues.length === 0,
healthIssues: issues,
};
}
/**
* Get formatted metrics report
*/
async getReport(): Promise<string> {
const metrics = await this.collect();
return `
Queue Metrics Report
===================
Status: ${metrics.isHealthy ? '✅ Healthy' : '⚠️ Issues Detected'}
Job Counts:
- Waiting: ${metrics.waiting}
- Active: ${metrics.active}
- Completed: ${metrics.completed}
- Failed: ${metrics.failed}
- Delayed: ${metrics.delayed}
- Paused: ${metrics.paused}
Performance:
- Avg Processing Time: ${(metrics.processingTime.avg / 1000).toFixed(2)}s
- Min/Max: ${(metrics.processingTime.min / 1000).toFixed(2)}s / ${(metrics.processingTime.max / 1000).toFixed(2)}s
- P95/P99: ${(metrics.processingTime.p95 / 1000).toFixed(2)}s / ${(metrics.processingTime.p99 / 1000).toFixed(2)}s
Throughput:
- Completed/min: ${metrics.throughput.completedPerMinute}
- Failed/min: ${metrics.throughput.failedPerMinute}
- Total/min: ${metrics.throughput.totalPerMinute}
${metrics.oldestWaitingJob ? `Oldest Waiting Job: ${metrics.oldestWaitingJob.toISOString()}` : 'No waiting jobs'}
${metrics.healthIssues.length > 0 ? `\nHealth Issues:\n${metrics.healthIssues.map(issue => `- ${issue}`).join('\n')}` : ''}
`.trim();
}
/**
* Export metrics in Prometheus format
*/
async getPrometheusMetrics(): Promise<string> {
const metrics = await this.collect();
const queueName = this.queue.name;
return `
# HELP queue_jobs_total Total number of jobs by status
# TYPE queue_jobs_total gauge
queue_jobs_total{queue="${queueName}",status="waiting"} ${metrics.waiting}
queue_jobs_total{queue="${queueName}",status="active"} ${metrics.active}
queue_jobs_total{queue="${queueName}",status="completed"} ${metrics.completed}
queue_jobs_total{queue="${queueName}",status="failed"} ${metrics.failed}
queue_jobs_total{queue="${queueName}",status="delayed"} ${metrics.delayed}
queue_jobs_total{queue="${queueName}",status="paused"} ${metrics.paused}
# HELP queue_processing_time_seconds Job processing time in seconds
# TYPE queue_processing_time_seconds summary
queue_processing_time_seconds{queue="${queueName}",quantile="0.5"} ${(metrics.processingTime.avg / 1000).toFixed(3)}
queue_processing_time_seconds{queue="${queueName}",quantile="0.95"} ${(metrics.processingTime.p95 / 1000).toFixed(3)}
queue_processing_time_seconds{queue="${queueName}",quantile="0.99"} ${(metrics.processingTime.p99 / 1000).toFixed(3)}
queue_processing_time_seconds_sum{queue="${queueName}"} ${((metrics.processingTime.avg * this.processingTimes.length) / 1000).toFixed(3)}
queue_processing_time_seconds_count{queue="${queueName}"} ${this.processingTimes.length}
# HELP queue_throughput_per_minute Jobs processed per minute
# TYPE queue_throughput_per_minute gauge
queue_throughput_per_minute{queue="${queueName}",status="completed"} ${metrics.throughput.completedPerMinute}
queue_throughput_per_minute{queue="${queueName}",status="failed"} ${metrics.throughput.failedPerMinute}
queue_throughput_per_minute{queue="${queueName}",status="total"} ${metrics.throughput.totalPerMinute}
# HELP queue_health Queue health status
# TYPE queue_health gauge
queue_health{queue="${queueName}"} ${metrics.isHealthy ? 1 : 0}
`.trim();
}
}

View file

@ -84,16 +84,6 @@ export interface GlobalStats {
uptime: number;
}
// Legacy type for backward compatibility
export interface QueueConfig extends QueueManagerConfig {
queueName?: string;
workers?: number;
concurrency?: number;
handlers?: HandlerInitializer[];
dlqConfig?: DLQConfig;
enableMetrics?: boolean;
}
// Extended batch job data for queue implementation
export interface BatchJobData {
payloadKey: string;
@ -103,10 +93,6 @@ export interface BatchJobData {
totalDelayHours: number; // Total time to distribute all batches
}
export interface HandlerInitializer {
(): void | Promise<void>;
}
// Rate limiting types
export type RateLimitWindow = import('@stock-bot/types').RateLimitWindow;
@ -120,40 +106,6 @@ export interface RateLimitRule {
config: RateLimitConfig;
}
// DLQ types
export interface DLQConfig {
maxRetries?: number;
retryDelay?: number;
alertThreshold?: number;
cleanupAge?: number;
}
export interface DLQJobInfo {
id: string;
name: string;
failedReason: string;
attemptsMade: number;
timestamp: number;
data: unknown;
}
export interface ScheduleConfig {
pattern: string;
jobName: string;
data?: unknown;
options?: ExtendedJobOptions;
}
// Smart Queue Types
export interface SmartQueueConfig extends QueueManagerConfig {
/** Name of the current service */
serviceName: string;
/** Whether to auto-discover handlers from registry */
autoDiscoverHandlers?: boolean;
/** Custom service registry (defaults to built-in) */
serviceRegistry?: Record<string, unknown>;
}
export interface QueueRoute {
/** Full queue name (now just the handler name, e.g., 'ceo') */
fullName: string;

View file

@ -120,15 +120,17 @@ describe('Batch Processor', () => {
throw new Error('Failed to add jobs');
});
// processBatchJob should still complete even if addBulk fails
const _result = await processBatchJob(
batchData,
'test-queue',
mockQueueManager as unknown as QueueManager
);
// processBatchJob rethrows chunk errors and retains the cached payload for retry
await expect(
processBatchJob(
batchData,
'test-queue',
mockQueueManager as unknown as QueueManager
)
).rejects.toThrow('Failed to add jobs');
expect(mockQueue.addBulk).toHaveBeenCalled();
// The error is logged in addJobsInChunks, not in processBatchJob
expect(mockCache.del).not.toHaveBeenCalled();
expect(mockLogger.error).toHaveBeenCalledWith('Failed to add job chunk', expect.any(Object));
});
@ -273,15 +275,15 @@ describe('Batch Processor', () => {
throw new Error('Process error');
});
// processItems catches errors and continues, so it won't reject
const result = await processItems(
items,
'test-queue',
options,
mockQueueManager as unknown as QueueManager
);
await expect(
processItems(
items,
'test-queue',
options,
mockQueueManager as unknown as QueueManager
)
).rejects.toThrow('Process error');
expect(result.jobsCreated).toBe(0);
expect(mockQueue.addBulk).toHaveBeenCalled();
expect(mockLogger.error).toHaveBeenCalledWith('Failed to add job chunk', expect.any(Object));
});

View file

@ -1,278 +0,0 @@
import type { Job, Queue } from 'bullmq';
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { DeadLetterQueueHandler } from '../src/dlq-handler';
import type { RedisConfig } from '../src/types';
describe('DeadLetterQueueHandler', () => {
// Mock the DLQ Queue that will be created
const mockDLQQueue = {
name: 'test-queue-dlq',
add: mock(() => Promise.resolve({})),
getCompleted: mock(() => Promise.resolve([])),
getFailed: mock(() => Promise.resolve([])),
getWaiting: mock(() => Promise.resolve([])),
close: mock(() => Promise.resolve()),
} as unknown as Queue;
const mockLogger = {
info: mock(() => {}),
error: mock(() => {}),
warn: mock(() => {}),
debug: mock(() => {}),
trace: mock(() => {}),
};
const mockQueue = {
name: 'test-queue',
add: mock(() => Promise.resolve({})),
getCompleted: mock(() => Promise.resolve([])),
getFailed: mock(() => Promise.resolve([])),
getWaiting: mock(() => Promise.resolve([])),
} as unknown as Queue;
const mockRedisConfig: RedisConfig = {
host: 'localhost',
port: 6379,
};
let dlqHandler: DeadLetterQueueHandler;
beforeEach(() => {
// Reset DLQ queue mocks
mockDLQQueue.add = mock(() => Promise.resolve({}));
mockDLQQueue.getCompleted = mock(() => Promise.resolve([]));
mockDLQQueue.getFailed = mock(() => Promise.resolve([]));
mockDLQQueue.getWaiting = mock(() => Promise.resolve([]));
mockDLQQueue.close = mock(() => Promise.resolve());
// Create handler with mocked DLQ queue
dlqHandler = new DeadLetterQueueHandler(mockQueue, mockRedisConfig, {}, mockLogger);
// Override the dlq property to use our mock
(dlqHandler as any).dlq = mockDLQQueue;
// Reset mocks
mockLogger.info = mock(() => {});
mockLogger.error = mock(() => {});
mockLogger.warn = mock(() => {});
});
describe('handleFailedJob', () => {
it('should log failed job details', async () => {
const mockJob = {
id: 'job-123',
name: 'test-job',
queueName: 'test-queue',
data: {
handler: 'testHandler',
operation: 'testOp',
payload: { test: true },
},
attemptsMade: 3,
opts: { attempts: 3 },
failedReason: 'Test error',
finishedOn: Date.now(),
processedOn: Date.now() - 5000,
timestamp: Date.now() - 10000,
} as Job;
const error = new Error('Job processing failed');
await dlqHandler.handleFailedJob(mockJob, error);
expect(mockLogger.error).toHaveBeenCalledWith(
'Job moved to DLQ',
expect.objectContaining({
jobId: 'job-123',
jobName: 'test-job',
error: 'Job processing failed',
})
);
});
it('should handle jobs without data gracefully', async () => {
const mockJob = {
id: 'job-123',
name: 'test-job',
queueName: 'test-queue',
data: null,
attemptsMade: 3,
opts: { attempts: 3 },
timestamp: Date.now() - 10000,
processedOn: Date.now() - 5000,
} as any;
const error = new Error('No data');
await dlqHandler.handleFailedJob(mockJob, error);
expect(mockLogger.error).toHaveBeenCalled();
});
it('should check alert threshold', async () => {
const mockJob = {
id: 'job-123',
name: 'critical-job',
queueName: 'critical-queue',
data: { handler: 'critical', operation: 'process' },
attemptsMade: 3,
opts: { attempts: 3 },
} as Job;
const error = new Error('Critical failure');
await dlqHandler.handleFailedJob(mockJob, error);
expect(mockLogger.warn).toHaveBeenCalled();
});
});
describe('getStats', () => {
it('should return DLQ statistics', async () => {
const mockJobs = [
{
id: 'job-1',
data: { originalJob: { name: 'process' } },
timestamp: Date.now(),
},
{
id: 'job-2',
data: { originalJob: { name: 'process' } },
timestamp: Date.now() - 100000,
},
{
id: 'job-3',
data: { originalJob: { name: 'validate' } },
timestamp: Date.now() - 200000,
},
];
mockDLQQueue.getCompleted = mock(() => Promise.resolve(mockJobs));
mockDLQQueue.getFailed = mock(() => Promise.resolve([]));
mockDLQQueue.getWaiting = mock(() => Promise.resolve([]));
const stats = await dlqHandler.getStats();
expect(stats.total).toBe(3);
expect(stats.byJobName['process']).toBe(2);
expect(stats.byJobName['validate']).toBe(1);
expect(stats.oldestJob).toBeDefined();
});
it('should handle empty DLQ', async () => {
const stats = await dlqHandler.getStats();
expect(stats.total).toBe(0);
expect(stats.byJobName).toEqual({});
expect(stats.oldestJob).toBeNull();
});
});
describe('retryDLQJobs', () => {
it('should retry jobs from DLQ', async () => {
const mockDLQJobs = [
{
id: 'dlq-1',
data: {
originalJob: {
id: 'orig-1',
name: 'retry-job',
data: { test: true },
opts: {},
},
},
remove: mock(() => Promise.resolve()),
},
];
(dlqHandler as any).dlq = {
getCompleted: mock(() => Promise.resolve(mockDLQJobs)),
};
const retriedCount = await dlqHandler.retryDLQJobs(1);
expect(retriedCount).toBe(1);
expect(mockQueue.add).toHaveBeenCalledWith(
'retry-job',
{ test: true },
expect.objectContaining({ delay: expect.any(Number) })
);
expect(mockDLQJobs[0].remove).toHaveBeenCalled();
});
});
describe('cleanup', () => {
it('should clean up old DLQ entries', async () => {
const oldJob = {
id: 'old-1',
timestamp: Date.now() - 8 * 24 * 60 * 60 * 1000, // 8 days old
remove: mock(() => Promise.resolve()),
};
const newJob = {
id: 'new-1',
timestamp: Date.now() - 1 * 24 * 60 * 60 * 1000, // 1 day old
remove: mock(() => Promise.resolve()),
};
(dlqHandler as any).dlq = {
getCompleted: mock(() => Promise.resolve([oldJob, newJob])),
};
const removedCount = await dlqHandler.cleanup();
expect(removedCount).toBe(1);
expect(oldJob.remove).toHaveBeenCalled();
expect(newJob.remove).not.toHaveBeenCalled();
});
});
describe('inspectFailedJobs', () => {
it('should return formatted failed jobs', async () => {
const mockDLQJobs = [
{
data: {
originalJob: {
id: 'orig-1',
name: 'test-job',
data: { test: true },
attemptsMade: 3,
},
error: {
message: 'Test error',
stack: 'Error stack',
},
movedToDLQAt: '2024-01-01T00:00:00Z',
},
},
];
(dlqHandler as any).dlq = {
getCompleted: mock(() => Promise.resolve(mockDLQJobs)),
};
const inspected = await dlqHandler.inspectFailedJobs(10);
expect(inspected).toHaveLength(1);
expect(inspected[0]).toEqual({
id: 'orig-1',
name: 'test-job',
data: { test: true },
error: { message: 'Test error', stack: 'Error stack' },
failedAt: '2024-01-01T00:00:00Z',
attempts: 3,
});
});
});
describe('shutdown', () => {
it('should close DLQ and clear state', async () => {
const mockClose = mock(() => Promise.resolve());
(dlqHandler as any).dlq = {
close: mockClose,
};
await dlqHandler.shutdown();
expect(mockClose).toHaveBeenCalled();
});
});
});

View file

@ -1,233 +0,0 @@
import type { Job, Queue, QueueEvents } from 'bullmq';
import { beforeEach, describe, expect, it, mock, type Mock } from 'bun:test';
import { QueueMetricsCollector } from '../src/queue-metrics';
describe('QueueMetricsCollector', () => {
let metrics: QueueMetricsCollector;
let mockQueue: {
name: string;
getWaitingCount: Mock<() => Promise<number>>;
getActiveCount: Mock<() => Promise<number>>;
getCompletedCount: Mock<() => Promise<number>>;
getFailedCount: Mock<() => Promise<number>>;
getDelayedCount: Mock<() => Promise<number>>;
isPaused: Mock<() => Promise<boolean>>;
getWaiting: Mock<() => Promise<Job[]>>;
};
let mockQueueEvents: {
on: Mock<(event: string, handler: Function) => void>;
};
beforeEach(() => {
mockQueue = {
name: 'test-queue',
getWaitingCount: mock(() => Promise.resolve(0)),
getActiveCount: mock(() => Promise.resolve(0)),
getCompletedCount: mock(() => Promise.resolve(0)),
getFailedCount: mock(() => Promise.resolve(0)),
getDelayedCount: mock(() => Promise.resolve(0)),
isPaused: mock(() => Promise.resolve(false)),
getWaiting: mock(() => Promise.resolve([])),
};
mockQueueEvents = {
on: mock(() => {}),
};
metrics = new QueueMetricsCollector(
mockQueue as unknown as Queue,
mockQueueEvents as unknown as QueueEvents
);
});
describe('collect metrics', () => {
it('should collect current metrics', async () => {
mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(5));
mockQueue.getActiveCount.mockImplementation(() => Promise.resolve(2));
mockQueue.getCompletedCount.mockImplementation(() => Promise.resolve(100));
mockQueue.getFailedCount.mockImplementation(() => Promise.resolve(3));
mockQueue.getDelayedCount.mockImplementation(() => Promise.resolve(1));
// Add some completed timestamps to avoid 100% failure rate
const completedHandler = mockQueueEvents.on.mock.calls.find(
call => call[0] === 'completed'
)?.[1];
if (completedHandler) {
for (let i = 0; i < 50; i++) {
completedHandler();
}
}
const result = await metrics.collect();
expect(result.waiting).toBe(5);
expect(result.active).toBe(2);
expect(result.completed).toBe(100);
expect(result.failed).toBe(3);
expect(result.delayed).toBe(1);
expect(result.isHealthy).toBe(true);
});
it('should detect health issues', async () => {
mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(2000)); // High backlog
mockQueue.getActiveCount.mockImplementation(() => Promise.resolve(150)); // High active
mockQueue.getFailedCount.mockImplementation(() => Promise.resolve(50));
const result = await metrics.collect();
expect(result.isHealthy).toBe(false);
expect(result.healthIssues.length).toBeGreaterThan(0);
expect(result.healthIssues.some(issue => issue.includes('queue backlog'))).toBe(true);
expect(result.healthIssues.some(issue => issue.includes('active jobs'))).toBe(true);
});
it('should handle paused queue', async () => {
mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(10));
mockQueue.isPaused.mockImplementation(() => Promise.resolve(true));
const result = await metrics.collect();
expect(result.paused).toBe(10);
});
});
describe('processing time metrics', () => {
it('should calculate processing time metrics', async () => {
// Access private property for testing
const metricsWithPrivate = metrics as QueueMetricsCollector & {
processingTimes: number[];
};
metricsWithPrivate.processingTimes = [1000, 2000, 3000, 4000, 5000];
const result = await metrics.collect();
expect(result.processingTime.avg).toBe(3000);
expect(result.processingTime.min).toBe(1000);
expect(result.processingTime.max).toBe(5000);
expect(result.processingTime.p95).toBe(5000);
});
it('should handle no processing times', async () => {
const result = await metrics.collect();
expect(result.processingTime.avg).toBe(0);
expect(result.processingTime.min).toBe(0);
expect(result.processingTime.max).toBe(0);
});
});
describe('throughput metrics', () => {
it('should calculate throughput', async () => {
// Access private properties for testing
const metricsWithPrivate = metrics as QueueMetricsCollector & {
completedTimestamps: number[];
failedTimestamps: number[];
};
const now = Date.now();
metricsWithPrivate.completedTimestamps = [
now - 30000, // 30 seconds ago
now - 20000,
now - 10000,
];
metricsWithPrivate.failedTimestamps = [now - 25000, now - 5000];
const result = await metrics.collect();
expect(result.throughput.completedPerMinute).toBe(3);
expect(result.throughput.failedPerMinute).toBe(2);
expect(result.throughput.totalPerMinute).toBe(5);
});
});
describe('getReport', () => {
it('should generate formatted report', async () => {
mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(5));
mockQueue.getActiveCount.mockImplementation(() => Promise.resolve(2));
mockQueue.getCompletedCount.mockImplementation(() => Promise.resolve(100));
mockQueue.getFailedCount.mockImplementation(() => Promise.resolve(3));
// Add some completed timestamps to make it healthy
const completedHandler = mockQueueEvents.on.mock.calls.find(
call => call[0] === 'completed'
)?.[1];
if (completedHandler) {
for (let i = 0; i < 50; i++) {
completedHandler();
}
}
const report = await metrics.getReport();
expect(report).toContain('Queue Metrics Report');
expect(report).toContain('✅ Healthy');
expect(report).toContain('Waiting: 5');
expect(report).toContain('Active: 2');
expect(report).toContain('Completed: 100');
expect(report).toContain('Failed: 3');
});
});
describe('getPrometheusMetrics', () => {
it('should generate Prometheus formatted metrics', async () => {
mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(5));
mockQueue.getActiveCount.mockImplementation(() => Promise.resolve(2));
mockQueue.getCompletedCount.mockImplementation(() => Promise.resolve(100));
mockQueue.getFailedCount.mockImplementation(() => Promise.resolve(3));
const prometheusMetrics = await metrics.getPrometheusMetrics();
expect(prometheusMetrics).toContain('# HELP queue_jobs_total');
expect(prometheusMetrics).toContain(
'queue_jobs_total{queue="test-queue",status="waiting"} 5'
);
expect(prometheusMetrics).toContain('queue_jobs_total{queue="test-queue",status="active"} 2');
expect(prometheusMetrics).toContain(
'queue_jobs_total{queue="test-queue",status="completed"} 100'
);
expect(prometheusMetrics).toContain('# HELP queue_processing_time_seconds');
expect(prometheusMetrics).toContain('# HELP queue_throughput_per_minute');
expect(prometheusMetrics).toContain('# HELP queue_health');
});
});
describe('event listeners', () => {
it('should setup event listeners on construction', () => {
const newMockQueueEvents = {
on: mock<(event: string, handler: Function) => void>(() => {}),
};
new QueueMetricsCollector(
mockQueue as unknown as Queue,
newMockQueueEvents as unknown as QueueEvents
);
expect(newMockQueueEvents.on).toHaveBeenCalledWith('completed', expect.any(Function));
expect(newMockQueueEvents.on).toHaveBeenCalledWith('failed', expect.any(Function));
expect(newMockQueueEvents.on).toHaveBeenCalledWith('active', expect.any(Function));
});
});
describe('oldest waiting job', () => {
it('should get oldest waiting job date', async () => {
const oldJob = {
timestamp: Date.now() - 60000, // 1 minute ago
} as Job;
mockQueue.getWaiting.mockImplementation(() => Promise.resolve([oldJob]));
const result = await metrics.collect();
expect(result.oldestWaitingJob).toBeDefined();
expect(result.oldestWaitingJob).toBeInstanceOf(Date);
});
it('should return null when no waiting jobs', async () => {
mockQueue.getWaiting.mockImplementation(() => Promise.resolve([]));
const result = await metrics.collect();
expect(result.oldestWaitingJob).toBeNull();
});
});
});

View file

@ -23,7 +23,6 @@
"@stock-bot/postgres": "workspace:*",
"@stock-bot/proxy": "workspace:*",
"@stock-bot/questdb": "workspace:*",
"@stock-bot/queue": "workspace:*",
"playwright": "^1.40.0"
"@stock-bot/queue": "workspace:*"
}
}

View file

@ -22,7 +22,6 @@ export type QuestDBClient = Public<QuestDBImplementation>;
export type Browser = Public<BrowserImplementation>;
export type ProxyManager = Public<ProxyImplementation>;
export type { CacheProvider, CacheStats } from '@stock-bot/cache';
export type { BrowserContext, Page } from 'playwright';
export type { ProxyInfo, ProxyStats } from '@stock-bot/proxy';
/** Disabled adapters are null; omitted capabilities are undefined. */

View file

@ -1,34 +0,0 @@
/**
* Backtesting & Strategy Types
* Types for strategy backtesting and analysis
*/
import type { PortfolioAnalysis } from './portfolio';
import type { DrawdownAnalysis, RiskMetrics } from './risk-metrics';
import type { TradeExecution, TradePerformance } from './trading';
/**
* Backtesting results
*/
export interface BacktestResults {
/** All trades executed */
trades: TradeExecution[];
/** Equity curve over time */
equityCurve: Array<{ value: number; date: Date }>;
/** Performance metrics */
performance: PortfolioAnalysis;
/** Risk metrics */
riskMetrics: RiskMetrics;
/** Drawdown analysis */
drawdownAnalysis: DrawdownAnalysis;
/** Trade performance */
tradePerformance: TradePerformance;
/** Start date */
startDate: Date;
/** End date */
endDate: Date;
/** Initial capital */
initialCapital: number;
/** Final value */
finalValue: number;
}

View file

@ -1,45 +1,3 @@
/**
* Decorator Type Definitions
* Type definitions for handler decorators
*/
/**
* Schedule configuration for operations
*/
export interface ScheduleConfig {
cronPattern: string;
priority?: number;
immediately?: boolean;
description?: string;
}
/**
* Decorator metadata stored on classes
*/
export interface DecoratorMetadata {
handlerName?: string;
operations?: Array<{
name: string;
methodName: string;
schedules?: ScheduleConfig[];
}>;
disabled?: boolean;
}
/**
* Type for decorator factories
*/
export type DecoratorFactory<T = object> = (target: T, context?: unknown) => T | void;
/**
* Type for method decorators
*/
export type MethodDecoratorFactory = (
target: object,
propertyKey: string,
descriptor?: PropertyDescriptor
) => void | PropertyDescriptor;
/** Metadata shared by decorators, discovery, and handler dispatch. */
export interface RateLimitWindow {
points: number;

View file

@ -1,197 +0,0 @@
/**
* Financial Statements Types
* Types for fundamental financial statement data
*/
/**
* Balance Sheet data structure
*/
export interface BalanceSheet {
/** Reporting period date */
date: string;
/** Fiscal period (Q1, Q2, Q3, Q4, FY) */
period: string;
/** Currency */
currency: string;
// Assets
/** Total current assets */
totalCurrentAssets: number;
/** Cash and cash equivalents */
cashAndEquivalents: number;
/** Short-term investments */
shortTermInvestments?: number;
/** Accounts receivable */
accountsReceivable: number;
/** Inventory */
inventory: number;
/** Prepaid expenses */
prepaidExpenses?: number;
/** Other current assets */
otherCurrentAssets?: number;
/** Total non-current assets */
totalNonCurrentAssets: number;
/** Property, plant & equipment (net) */
propertyPlantEquipmentNet: number;
/** Intangible assets */
intangibleAssets?: number;
/** Goodwill */
goodwill?: number;
/** Long-term investments */
longTermInvestments?: number;
/** Other non-current assets */
otherNonCurrentAssets?: number;
/** Total assets */
totalAssets: number;
// Liabilities
/** Total current liabilities */
totalCurrentLiabilities: number;
/** Accounts payable */
accountsPayable: number;
/** Short-term debt */
shortTermDebt: number;
/** Accrued liabilities */
accruedLiabilities?: number;
/** Other current liabilities */
otherCurrentLiabilities?: number;
/** Total non-current liabilities */
totalNonCurrentLiabilities: number;
/** Long-term debt */
longTermDebt: number;
/** Deferred tax liabilities */
deferredTaxLiabilities?: number;
/** Other non-current liabilities */
otherNonCurrentLiabilities?: number;
/** Total liabilities */
totalLiabilities: number;
// Equity
/** Total stockholders' equity */
totalStockholdersEquity: number;
/** Common stock */
commonStock: number;
/** Retained earnings */
retainedEarnings: number;
/** Additional paid-in capital */
additionalPaidInCapital?: number;
/** Treasury stock */
treasuryStock?: number;
/** Accumulated other comprehensive income */
accumulatedOtherComprehensiveIncome?: number;
}
/**
* Income Statement data structure
*/
export interface IncomeStatement {
/** Reporting period date */
date: string;
/** Fiscal period (Q1, Q2, Q3, Q4, FY) */
period: string;
/** Currency */
currency: string;
/** Total revenue/net sales */
totalRevenue: number;
/** Cost of goods sold */
costOfGoodsSold: number;
/** Gross profit */
grossProfit: number;
/** Operating expenses */
operatingExpenses: number;
/** Research and development */
researchAndDevelopment?: number;
/** Selling, general & administrative */
sellingGeneralAdministrative?: number;
/** Depreciation and amortization */
depreciationAmortization?: number;
/** Other operating expenses */
otherOperatingExpenses?: number;
/** Operating income */
operatingIncome: number;
/** Interest income */
interestIncome?: number;
/** Interest expense */
interestExpense?: number;
/** Other income/expense */
otherIncomeExpense?: number;
/** Income before taxes */
incomeBeforeTaxes: number;
/** Income tax expense */
incomeTaxExpense: number;
/** Net income */
netIncome: number;
/** Earnings per share (basic) */
earningsPerShareBasic: number;
/** Earnings per share (diluted) */
earningsPerShareDiluted: number;
/** Weighted average shares outstanding (basic) */
sharesOutstandingBasic: number;
/** Weighted average shares outstanding (diluted) */
sharesOutstandingDiluted: number;
}
/**
* Cash Flow Statement data structure
*/
export interface CashFlowStatement {
/** Reporting period date */
date: string;
/** Fiscal period (Q1, Q2, Q3, Q4, FY) */
period: string;
/** Currency */
currency: string;
// Operating Activities
/** Net income */
netIncome: number;
/** Depreciation and amortization */
depreciationAmortization: number;
/** Changes in working capital */
changesInWorkingCapital: number;
/** Other operating activities */
otherOperatingActivities?: number;
/** Net cash from operating activities */
netCashFromOperatingActivities: number;
// Investing Activities
/** Capital expenditures */
capitalExpenditures: number;
/** Acquisitions */
acquisitions?: number;
/** Investments */
investments?: number;
/** Other investing activities */
otherInvestingActivities?: number;
/** Net cash from investing activities */
netCashFromInvestingActivities: number;
// Financing Activities
/** Debt issuance/repayment */
debtIssuanceRepayment?: number;
/** Equity issuance/repurchase */
equityIssuanceRepurchase?: number;
/** Dividends paid */
dividendsPaid?: number;
/** Other financing activities */
otherFinancingActivities?: number;
/** Net cash from financing activities */
netCashFromFinancingActivities: number;
/** Net change in cash */
netChangeInCash: number;
/** Cash at beginning of period */
cashAtBeginningOfPeriod: number;
/** Cash at end of period */
cashAtEndOfPeriod: number;
}

View file

@ -1,19 +1,7 @@
/**
* Helper Types
* Generic utility types for making functions work across different data types
*/
/**
* Interface for data that has a close price
* Used to make functions generic across different data types
*/
export interface HasClose {
close: number;
}
/**
* Interface for data that has OHLC prices
*/
export interface HasOHLC {
open: number;
high: number;
@ -21,16 +9,6 @@ export interface HasOHLC {
close: number;
}
/**
* Interface for data that has volume
*/
export interface HasVolume {
volume: number;
}
/**
* Interface for data that has timestamp
*/
export interface HasTimestamp {
timestamp: number;
}

View file

@ -1,49 +1,9 @@
/**
* Stock Bot Types Library
* Standardized type definitions for the entire trading platform
* Standardized type definitions for the trading and research platform
*/
// Export all market data types
export type {
LiquidityMetrics,
MarketData,
MarketRegime,
OHLCV,
OHLCVWithMetadata,
} from './market-data';
// Export all portfolio & position types
export type {
AssetAllocation,
KellyParams,
PortfolioAnalysis,
PortfolioPosition,
PositionSizeParams,
} from './portfolio';
// Export all trading & execution types
export type { TradeExecution, TradePerformance } from './trading';
// Export all risk & performance metrics
export type { DrawdownAnalysis, ReturnAnalysis, RiskMetrics } from './risk-metrics';
// Export all options pricing types
export type { GreeksCalculation, OptionParameters, OptionPricing } from './options';
// Export all financial statement types
export type { BalanceSheet, CashFlowStatement, IncomeStatement } from './financial-statements';
// Export all technical analysis types
export type {
CorrelationMatrix,
CorrelationResult,
GARCHParameters,
TechnicalIndicators,
VolatilityEstimates,
} from './technical-analysis';
// Export backtesting types
export type { BacktestResults } from './backtesting';
export type { OHLCV } from './market-data';
export type {
BacktestRunConfiguration,
BacktestRunMetrics,
@ -59,11 +19,7 @@ export type {
CanonicalMetrics,
CanonicalBacktestAnalytics,
} from './canonical-analytics';
// Export helper types
export type { HasClose, HasOHLC, HasTimestamp, HasVolume } from './helpers';
// Export handler types
export type { HasClose, HasOHLC, HasVolume } from './helpers';
export type {
ExecutionContext,
HandlerConfig,
@ -75,18 +31,7 @@ export type {
ScheduledJob,
TypedJobHandler,
} from './handlers';
// Export decorator types
export type {
ScheduleConfig,
DecoratorMetadata,
DecoratorFactory,
MethodDecoratorFactory,
} from './decorators';
// Export queue types
export type { JobData, JobOptions, QueueStats, BatchJobData, QueueWorkerConfig } from './queue';
export type {
DecoratedHandlerClass,
DecoratedHandlerMetadata,

View file

@ -1,11 +1,6 @@
/**
* Market Data Types
* Standard types for market data and pricing information
*/
/**
* Standard OHLCV (Open, High, Low, Close, Volume) data structure
* Used for candlestick/bar chart data across all market data providers
* Used for candlestick/bar chart data across market data adapters
*/
export interface OHLCV {
/** Opening price for the time period */
@ -25,83 +20,3 @@ export interface OHLCV {
/** Time interval (e.g., '1m', '5m', '1h', '1d') */
interval?: string;
}
/**
* OHLCV data with additional metadata
*/
export interface OHLCVWithMetadata extends OHLCV {
/** Source of the data (e.g., 'yahoo', 'ib', 'quotemedia') */
source: string;
/** Whether this is adjusted data */
adjusted?: boolean;
/** Number of trades during the period */
trades?: number;
/** Volume weighted average price */
vwap?: number;
}
/**
* Market data structure
*/
export interface MarketData {
/** Security symbol */
symbol: string;
/** Current price */
price: number;
/** Trading volume */
volume: number;
/** Timestamp */
timestamp: number;
/** Bid price */
bid?: number;
/** Ask price */
ask?: number;
/** Bid size */
bidSize?: number;
/** Ask size */
askSize?: number;
/** Previous close */
previousClose?: number;
/** Day's high */
high?: number;
/** Day's low */
low?: number;
/** Day's open */
open?: number;
}
/**
* Market liquidity metrics
*/
export interface LiquidityMetrics {
/** Bid-ask spread */
bidAskSpread: number;
/** Bid-ask spread percentage */
bidAskSpreadPercent: number;
/** Market depth */
marketDepth: number;
/** Average daily volume */
averageDailyVolume: number;
/** Volume rate */
volumeRate: number;
/** Price impact */
priceImpact: number;
/** Liquidity score */
liquidityScore: number;
}
/**
* Market regime classification
*/
export interface MarketRegime {
/** Current regime */
regime: 'trending' | 'ranging' | 'volatile' | 'quiet';
/** Regime strength (0-1) */
strength: number;
/** Regime duration (periods) */
duration: number;
/** Trend direction (if trending) */
trendDirection?: 'up' | 'down';
/** Volatility level */
volatilityLevel: 'low' | 'medium' | 'high';
}

View file

@ -1,58 +0,0 @@
/**
* Options Pricing Types
* Types for options pricing and derivatives
*/
/**
* Options pricing parameters
*/
export interface OptionParameters {
/** Underlying asset price */
spotPrice: number;
/** Strike price */
strikePrice: number;
/** Time to expiration (in years) */
timeToExpiry: number;
/** Risk-free interest rate */
riskFreeRate: number;
/** Volatility */
volatility: number;
/** Dividend yield */
dividendYield?: number;
/** Option type */
optionType: 'call' | 'put';
}
/**
* Option pricing results
*/
export interface OptionPricing {
/** Call option price */
callPrice: number;
/** Put option price */
putPrice: number;
/** Call intrinsic value */
callIntrinsic: number;
/** Put intrinsic value */
putIntrinsic: number;
/** Call time value */
callTimeValue: number;
/** Put time value */
putTimeValue: number;
}
/**
* Option Greeks calculation
*/
export interface GreeksCalculation {
/** Delta - price sensitivity */
delta: number;
/** Gamma - delta sensitivity */
gamma: number;
/** Theta - time decay */
theta: number;
/** Vega - volatility sensitivity */
vega: number;
/** Rho - interest rate sensitivity */
rho: number;
}

View file

@ -1,108 +0,0 @@
/**
* Portfolio & Position Types
* Types for portfolio management and position tracking
*/
/**
* Individual portfolio position
*/
export interface PortfolioPosition {
/** Security symbol/ticker */
symbol: string;
/** Number of shares/units */
shares: number;
/** Average entry price */
averagePrice: number;
/** Current market price */
currentPrice: number;
/** Current market value */
marketValue: number;
/** Unrealized P&L */
unrealizedPnL: number;
/** Unrealized P&L percentage */
unrealizedPnLPercent: number;
/** Weight in portfolio */
weight: number;
/** Security type (stock, bond, option, etc.) */
securityType?: string;
/** Currency */
currency?: string;
}
/**
* Portfolio analysis metrics
*/
export interface PortfolioAnalysis {
/** Total portfolio value */
totalValue: number;
/** Total cash balance */
cash: number;
/** Total invested amount */
invested: number;
/** Total unrealized P&L */
unrealizedPnL: number;
/** Total unrealized P&L percentage */
unrealizedPnLPercent: number;
/** Total return */
totalReturn: number;
/** Total return percentage */
totalReturnPercent: number;
/** Annualized return */
annualizedReturn: number;
/** Portfolio volatility (annualized) */
volatility: number;
/** Sharpe ratio */
sharpeRatio: number;
/** Maximum drawdown */
maxDrawdown: number;
/** Number of positions */
positionCount: number;
/** Portfolio concentration (largest position weight) */
concentration: number;
}
/**
* Asset allocation breakdown
*/
export interface AssetAllocation {
/** Asset class or category */
category: string;
/** Allocation value */
value: number;
/** Allocation percentage */
percentage: number;
/** Target allocation percentage */
target?: number;
/** Deviation from target */
deviation?: number;
}
/**
* Position sizing parameters
*/
export interface PositionSizeParams {
/** Account size */
accountSize: number;
/** Risk percentage per trade */
riskPercent: number;
/** Entry price */
entryPrice: number;
/** Stop loss price */
stopPrice: number;
/** Commission per share */
commission?: number;
}
/**
* Kelly Criterion parameters
*/
export interface KellyParams {
/** Win rate (0-1) */
winRate: number;
/** Average winning trade */
averageWin: number;
/** Average losing trade */
averageLoss: number;
/** Risk-free rate */
riskFreeRate?: number;
}

View file

@ -1,86 +0,0 @@
/**
* Risk & Performance Metrics Types
* Types for risk measurement and performance analysis
*/
/**
* Comprehensive risk metrics
*/
export interface RiskMetrics {
/** Value at Risk 95% */
var95: number;
/** Value at Risk 99% */
var99: number;
/** Conditional VaR 95% */
cvar95: number;
/** Maximum drawdown */
maxDrawdown: number;
/** Volatility (annualized) */
volatility: number;
/** Downside deviation */
downside_deviation: number;
/** Calmar ratio */
calmar_ratio: number;
/** Sortino ratio */
sortino_ratio: number;
/** Beta (vs benchmark) */
beta: number;
/** Alpha (vs benchmark) */
alpha: number;
/** Sharpe ratio */
sharpeRatio: number;
/** Treynor ratio */
treynorRatio: number;
/** Tracking error */
trackingError: number;
/** Information ratio */
informationRatio: number;
}
/**
* Drawdown analysis
*/
export interface DrawdownAnalysis {
/** Maximum drawdown percentage */
maxDrawdown: number;
/** Maximum drawdown duration (days) */
maxDrawdownDuration: number;
/** Current drawdown percentage */
currentDrawdown: number;
/** Current drawdown duration (days) */
currentDrawdownDuration: number;
/** Average drawdown percentage */
averageDrawdown: number;
/** Average drawdown duration (days) */
averageDrawdownDuration: number;
/** Number of drawdown periods */
drawdownPeriods: number;
/** Recovery factor */
recoveryFactor: number;
}
/**
* Return analysis statistics
*/
export interface ReturnAnalysis {
/** Total return */
totalReturn: number;
/** Annualized return */
annualizedReturn: number;
/** Volatility (annualized) */
volatility: number;
/** Skewness */
skewness: number;
/** Kurtosis */
kurtosis: number;
/** Best period return */
bestPeriod: number;
/** Worst period return */
worstPeriod: number;
/** Positive periods percentage */
positivePeriods: number;
/** Average positive return */
averagePositiveReturn: number;
/** Average negative return */
averageNegativeReturn: number;
}

View file

@ -1,109 +0,0 @@
/**
* Technical Analysis Types
* Types for technical indicators and market analysis
*/
/**
* Technical indicators collection
*/
export interface TechnicalIndicators {
/** Simple Moving Average */
sma: number[];
/** Exponential Moving Average */
ema: number[];
/** Relative Strength Index */
rsi: number[];
/** MACD indicator */
macd: {
macd: number[];
signal: number[];
histogram: number[];
};
/** Bollinger Bands */
bollinger: {
upper: number[];
middle: number[];
lower: number[];
};
/** Average True Range */
atr: number[];
/** Stochastic Oscillator */
stochastic: {
k: number[];
d: number[];
};
/** Williams %R */
williams_r: number[];
/** Commodity Channel Index */
cci: number[];
/** Momentum */
momentum: number[];
/** Rate of Change */
roc: number[];
}
/**
* Correlation analysis result
*/
export interface CorrelationResult {
/** Correlation coefficient */
correlation: number;
/** P-value for statistical significance */
pValue: number;
/** Is statistically significant */
isSignificant: boolean;
/** Confidence interval */
confidenceInterval: [number, number];
/** Sample size */
sampleSize: number;
}
/**
* Correlation matrix
*/
export interface CorrelationMatrix {
/** Asset symbols */
symbols: string[];
/** Correlation matrix values */
matrix: number[][];
/** Eigenvalues */
eigenvalues: number[];
/** Condition number */
conditionNumber: number;
/** Is positive definite */
isPositiveDefinite: boolean;
}
/**
* Volatility estimates using different models
*/
export interface VolatilityEstimates {
/** Close-to-close volatility */
closeToClose: number;
/** Parkinson volatility */
parkinson: number;
/** Garman-Klass volatility */
garmanKlass: number;
/** Rogers-Satchell volatility */
rogersSatchell: number;
/** Yang-Zhang volatility */
yangZhang: number;
}
/**
* GARCH model parameters
*/
export interface GARCHParameters {
/** Alpha parameter */
alpha: number;
/** Beta parameter */
beta: number;
/** Omega parameter */
omega: number;
/** Log likelihood */
logLikelihood: number;
/** AIC (Akaike Information Criterion) */
aic: number;
/** BIC (Bayesian Information Criterion) */
bic: number;
}

View file

@ -1,62 +0,0 @@
/**
* Trading & Execution Types
* Types for trade execution and performance analysis
*/
/**
* Trade execution record
*/
export interface TradeExecution {
/** Trade ID */
id?: string;
/** Security symbol */
symbol: string;
/** Trade type */
type: 'buy' | 'sell' | 'short' | 'cover';
/** Number of shares/units */
quantity: number;
/** Execution price */
price: number;
/** Total trade value */
value: number;
/** Commission/fees */
commission?: number;
/** Execution timestamp */
timestamp: number;
/** Order ID reference */
orderId?: string;
/** Execution venue */
venue?: string;
}
/**
* Trade performance analysis
*/
export interface TradePerformance {
/** Total number of trades */
totalTrades: number;
/** Number of winning trades */
winningTrades: number;
/** Number of losing trades */
losingTrades: number;
/** Win rate percentage */
winRate: number;
/** Average winning trade */
averageWin: number;
/** Average losing trade */
averageLoss: number;
/** Largest winning trade */
largestWin: number;
/** Largest losing trade */
largestLoss: number;
/** Profit factor (gross profit / gross loss) */
profitFactor: number;
/** Mathematical expectancy */
expectancy: number;
/** Total gross profit */
grossProfit: number;
/** Total gross loss */
grossLoss: number;
/** Net profit */
netProfit: number;
}