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,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 },
];