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

@ -6,7 +6,7 @@
"type": "module",
"scripts": {
"dev": "bun --watch src/index.ts",
"build": "bun build src/index.ts --outdir dist --target node --external chromium-bidi --external electron --external playwright --external playwright-core",
"build": "bun build src/index.ts --outdir dist --target node",
"start": "bun dist/index.js",
"test": "bun test",
"clean": "rm -rf dist"

View file

@ -1,34 +0,0 @@
/**
* Service Container Setup for Web API
* Configures dependency injection for the web API service
*/
import type { UnifiedAppConfig } from '@stock-bot/config';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
const logger = getLogger('web-api-container');
/**
* Configure the service container for web API workloads
*/
export function setupServiceContainer(
config: UnifiedAppConfig,
container: IServiceContainer
): IServiceContainer {
logger.info('Configuring web API service container...');
// Web API specific configuration
// This service mainly reads data, so smaller pool sizes are fine
const poolSizes = {
mongodb: config.environment === 'production' ? 20 : 10,
postgres: config.environment === 'production' ? 30 : 15,
cache: config.environment === 'production' ? 20 : 10,
};
logger.info('Web API pool sizes configured', poolSizes);
// The container is already configured with connections
// Just return it with our logging
return container;
}

View file

@ -1,107 +1,18 @@
import { existsSync, readdirSync, readFileSync } from 'fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'path';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import { runPostgresMigrations } from '@stock-bot/postgres';
import type { IServiceContainer } from '@stock-bot/services';
const logger = getLogger('migration-runner');
export async function runMigrations(container: IServiceContainer): Promise<void> {
logger.info('Migration runner called');
logger.info('Container type', { type: typeof container });
logger.info('Container postgres available', { available: !!container.postgres });
if (!container.postgres) {
logger.warn('PostgreSQL not available, skipping migrations');
logger.info('Container keys:', Object.keys(container));
return;
}
try {
await container.postgres.transaction(async client => {
// All startup migrations share one database-scoped lock on this transaction's client.
// PostgreSQL releases it on commit/rollback, including when startup fails.
await client.query('SELECT pg_advisory_xact_lock($1, $2)', [0x53544254, 1]);
// Create migrations table if it doesn't exist
await client.query(`
CREATE TABLE IF NOT EXISTS migrations (
id SERIAL PRIMARY KEY,
filename VARCHAR(255) NOT NULL UNIQUE,
executed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
)
`);
// Get list of migration files from database/postgres/init while holding the lock.
let directory = dirname(fileURLToPath(import.meta.url));
while (!existsSync(join(directory, 'database', 'postgres', 'init'))) {
const parent = dirname(directory);
if (parent === directory) {
throw new Error('Cannot locate PostgreSQL migrations');
}
directory = parent;
}
const migrationsDir = join(directory, 'database', 'postgres', 'init');
logger.info('Looking for migrations', { directory: migrationsDir });
const files = readdirSync(migrationsDir)
.filter(
f =>
f.endsWith('.sql') &&
(f.startsWith('001_') ||
f === '09-backtest-run-contract.sql' ||
f === '10-durable-backtest-dispatch.sql' ||
f === '11-simulation-execution-ledger.sql' ||
f === '12-historical-datasets.sql' ||
f === '13-strategy-recovery.sql' ||
f === '14-backtest-submission.sql' ||
f === '15-canonical-paper-intents.sql' ||
f === '16-strategy-catalog.sql' ||
f === '17-research-retention.sql' ||
f === '18-backtest-strategy-versions.sql' ||
f === '19-canonical-research.sql' ||
f === '20-research-workspace.sql' ||
f === '21-run-reproduction.sql' ||
f === '22-experiments.sql' ||
f === '23-experiment-retries.sql' ||
f === '24-chronological-validation.sql' ||
f === '25-walk-forward.sql' ||
f === '26-cost-sensitivity.sql' ||
f === '27-research-evidence-sources.sql' ||
f === '28-research-agents.sql' ||
f === '29-isolated-candidates.sql' ||
f === '30-paper-deployments.sql' ||
f === '31-research-agent-project-links.sql' ||
f === '32-candidate-parameter-defaults.sql' ||
f === '33-candidate-decimal-normalization.sql')
) // Explicit additive migration allowlist; never replay destructive init migrations
.sort();
logger.info('Found migration files:', files);
for (const file of files) {
// Check and apply using the same locked client, not another pooled connection.
const result = await client.query('SELECT 1 FROM migrations WHERE filename = $1', [file]);
if (result.rows.length === 0) {
logger.info(`Running migration: ${file}`);
// Read and execute migration
const sql = readFileSync(join(migrationsDir, file), 'utf8');
await client.query(sql);
await client.query(
'INSERT INTO migrations (filename) VALUES ($1) ON CONFLICT (filename) DO NOTHING',
[file]
);
logger.info(`Migration applied: ${file}`);
} else {
logger.debug(`Migration already executed: ${file}`);
}
}
});
logger.info('All migrations completed successfully');
const applied = await runPostgresMigrations(container.postgres, { track: 'research' });
logger.info('All migrations completed successfully', { appliedCount: applied.length });
} catch (error) {
logger.error('Migration failed', { error });
throw error;

View file

@ -1,5 +0,0 @@
/**
* Routes index - exports all route modules
*/
export { createExchangeRoutes } from './exchange.routes';
export { healthRoutes } from './health.routes';

View file

@ -1,25 +0,0 @@
/**
* Web API Service Types
* Defines required services for web API handlers
*/
import type { ServiceTypes } from '@stock-bot/services';
/**
* Services required by web API handlers
* Makes specific services non-nullable since they're always enabled
*/
export type WebApiServices = ServiceTypes & {
// Always required services
logger: NonNullable<ServiceTypes['logger']>;
mongodb: NonNullable<ServiceTypes['mongodb']>;
postgres: NonNullable<ServiceTypes['postgres']>;
cache: NonNullable<ServiceTypes['cache']>;
queue: NonNullable<ServiceTypes['queue']>;
queueManager: NonNullable<ServiceTypes['queueManager']>;
// Optional services remain optional
browser: ServiceTypes['browser'];
proxy: ServiceTypes['proxy'];
questdb: ServiceTypes['questdb'];
globalCache: ServiceTypes['globalCache'];
};