From c3cb36c8d66115248e9171cce75b785223e17b7b Mon Sep 17 00:00:00 2001 From: Boki Date: Tue, 20 Oct 2026 18:36:19 -0400 Subject: [PATCH] safety --- .env.example | 16 + .gitignore | 8 + .gitlab-ci.yml | 9 + README.md | 86 ++- apps/stock/data-ingestion/src/index.ts | 11 +- apps/stock/data-pipeline/package.json | 1 + .../handlers/exchanges/exchanges.handler.ts | 3 +- .../clear-postgresql-data.operations.ts | 66 +- .../sync-all-exchanges.operations.ts | 325 ++------- .../sync-qm-provider-mappings.operations.ts | 226 +----- .../sync-symbols-from-provider.operations.ts | 278 +------- apps/stock/data-pipeline/src/index.ts | 11 +- .../repositories/PipelineSyncRepository.ts | 180 +++++ .../src/routes/enhanced-sync.routes.ts | 14 +- .../stock/engine/src/indicators/stochastic.rs | 643 ++++++++++-------- apps/stock/orchestrator/src/index.ts | 6 +- apps/stock/web-api/src/index.ts | 6 +- .../stock/web-api/src/routes/create-routes.ts | 28 +- .../web-api/src/routes/pipeline.routes.ts | 14 +- .../web-api/src/routes/websocket.routes.ts | 10 +- .../web-api/src/server-with-websocket.ts | 18 +- .../src/services/backtest-v2.service.ts | 3 +- .../web-api/src/services/pipeline.service.ts | 10 +- apps/stock/web-app/src/app/App.tsx | 78 ++- apps/stock/web-app/src/app/AuthGate.tsx | 118 ++++ .../backtest/services/backtestApiV2.ts | 3 +- .../charts/services/chartDataService.ts | 3 +- .../exchanges/services/exchangeApi.ts | 3 +- .../monitoring/services/monitoringApi.ts | 2 +- .../src/features/pipeline/PipelinePage.tsx | 31 +- .../features/pipeline/hooks/usePipeline.ts | 4 +- .../features/pipeline/services/pipelineApi.ts | 13 +- apps/stock/web-app/src/hooks/useWebSocket.ts | 6 +- apps/stock/web-app/src/lib/api.ts | 14 + apps/stock/web-app/vite.config.ts | 2 +- bun.lock | 1 + docker-compose.dev.yml | 64 +- docker-compose.yml | 474 ++++++------- libs/core/di/src/http/security.ts | 277 ++++++++ libs/core/di/src/index.ts | 6 + libs/core/di/src/service-application.ts | 3 + libs/core/logger/src/logger.ts | 5 +- libs/core/logger/src/redact.ts | 52 ++ libs/core/types/src/index.ts | 5 + libs/core/types/src/reference-data.ts | 23 + package.json | 3 + scripts/audit-secrets.ts | 32 + scripts/check.ts | 2 + scripts/test-postgres.ts | 12 + scripts/test/security.test.ts | 318 +++++++++ test/postgres/pipeline-safety.test.ts | 231 +++++++ 51 files changed, 2290 insertions(+), 1467 deletions(-) create mode 100644 .env.example create mode 100644 apps/stock/data-pipeline/src/repositories/PipelineSyncRepository.ts create mode 100644 apps/stock/web-app/src/app/AuthGate.tsx create mode 100644 apps/stock/web-app/src/lib/api.ts create mode 100644 libs/core/di/src/http/security.ts create mode 100644 libs/core/logger/src/redact.ts create mode 100644 libs/core/types/src/reference-data.ts create mode 100644 scripts/audit-secrets.ts create mode 100644 scripts/test-postgres.ts create mode 100644 scripts/test/security.test.ts create mode 100644 test/postgres/pipeline-safety.test.ts diff --git a/.env.example b/.env.example new file mode 100644 index 00000000..3bffb1c8 --- /dev/null +++ b/.env.example @@ -0,0 +1,16 @@ +# Generate each token independently: openssl rand -hex 32 +# Tokens stay on the server; never put them in VITE_* variables or URLs. +STOCK_BOT_ADMIN_TOKEN= +STOCK_BOT_SERVICE_TOKEN= +# Optional read-only dashboard/API access. +STOCK_BOT_READ_TOKEN= +STOCK_BOT_HTTP_HOST=127.0.0.1 +STOCK_BOT_ALLOWED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000 +# Explicit loopback-only development escape hatch. Forbidden in production. +STOCK_BOT_AUTH_DISABLED=false +NODE_ENV=development +# Provider credentials are optional; configure only the providers you enable. +EOD_API_KEY= +QM_USERNAME= +QM_PASSWORD= +IB_ACCOUNT= diff --git a/.gitignore b/.gitignore index 90f3ea04..e3ebee38 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,11 @@ +# Environment files (the two private local-development configs are intentionally tracked) +.env +.env.* +!/.env +!/apps/stock/web-app/.env +!.env.example +!.env.*.example + # Dependencies node_modules/ .pnp diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 3c3fbb4a..4e9074a8 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -21,6 +21,14 @@ include: repository-check: stage: test image: rust:1.88-bookworm + services: + - name: postgres:16-alpine + alias: postgres + variables: + POSTGRES_DB: stock_bot_safety + POSTGRES_USER: fixture + POSTGRES_PASSWORD: fixture + PIPELINE_TEST_DATABASE_URL: postgres://fixture:fixture@postgres:5432/stock_bot_safety before_script: - apt-get update && apt-get install -y --no-install-recommends nodejs unzip - curl -fsSL https://bun.sh/install | bash -s "bun-v1.2.17" @@ -28,3 +36,4 @@ repository-check: - bun install --frozen-lockfile script: - bun run check + - bun run test:postgres diff --git a/README.md b/README.md index b123558c..b1139585 100644 --- a/README.md +++ b/README.md @@ -19,16 +19,16 @@ bun run check The root build selects every buildable leaf workspace, including all stock services and the native engine. `bun run build --dry=json` shows the actual Turbo task plan. -| Command | Scope | -| ------------------------ | ------------------------------------------------------------------------------------------- | -| `bun run build:libs` | Build shared libraries in dependency order | -| `bun run build --clean` | Force every workspace build without cached results | -| `bun run typecheck` | Check library, stock application, and tool source directly | -| `bun run test:contracts` | Compile positive and negative service-contract assertions | -| `bun run test:tooling` | Run workspace and service-consumer regression tests without infrastructure | -| `bun run test:integration` | Replay fixed prices through ingestion, storage, and the real native backtest engine | -| `bun run lint:check` | Lint stock applications, libraries, and tools with zero warnings allowed | -| `bun run check` | Run build, type checking, contract tests, tooling/integration tests, and lint; report every failed gate | +| Command | Scope | +| -------------------------- | ------------------------------------------------------------------------------------------------------- | +| `bun run build:libs` | Build shared libraries in dependency order | +| `bun run build --clean` | Force every workspace build without cached results | +| `bun run typecheck` | Check library, stock application, and tool source directly | +| `bun run test:contracts` | Compile positive and negative service-contract assertions | +| `bun run test:tooling` | Run workspace and service-consumer regression tests without infrastructure | +| `bun run test:integration` | Replay fixed prices through ingestion, storage, and the real native backtest engine | +| `bun run lint:check` | Lint stock applications, libraries, and tools with zero warnings allowed | +| `bun run check` | Run build, type checking, contract tests, tooling/integration tests, and lint; report every failed gate | `check` exits nonzero if any gate fails. Type/lint errors are not suppressed or baselined. The larger existing `bun run test` suite is separate: @@ -136,3 +136,69 @@ reads, missing data, duplicate/concurrent requests, failed persistence/rollback, responsive requests/streams, worker crashes, deadlines, cancellation, and cleanup. SQL tests use an in-process PostgreSQL emulator and the real transaction manager, not a live database. Durable queued dispatch and recovery after an orchestrator crash remain follow-up work. + +## HTTP access and secrets + +HTTP services now fail closed unless server-side access tokens are configured. Use the +root `.env` (`.env.example` documents the settings) and set independent `STOCK_BOT_ADMIN_TOKEN` and +`STOCK_BOT_SERVICE_TOKEN` values (at least 32 characters; generate each with +`openssl rand -hex 32`). An optional distinct `STOCK_BOT_READ_TOKEN` permits read-only +access. The same service token must be available to internal HTTP clients and servers. +Never put these tokens in `VITE_*` settings, URLs, source files, or logs. + +CLI clients use `Authorization: Bearer `. The dashboard sign-in exchanges an +admin/read token for a signed one-hour HttpOnly, SameSite=Strict cookie; it does not store +the token in localStorage or include it in the bundle. Production cookies require HTTPS. +Read-only access cannot mutate data; all mutation/admin operations require admin/service +access. Internal services do not accept browser cookies. WebSocket upgrades authenticate +and validate browser Origin. Session-key rotation invalidates issued cookies; logout clears +the browser cookie (copied cookies remain valid until expiry or key rotation). This is an +operator-access boundary, not a multi-user identity/tenant system. + +Dashboard/API URLs must be same-site for the strict cookie policy. In local development, +use matching hostnames (`localhost` for both, or `127.0.0.1` for both), not a mixture. + +`STOCK_BOT_HTTP_HOST` defaults to `127.0.0.1`. Set it explicitly for containers. Set +`STOCK_BOT_ALLOWED_ORIGINS` to an exact comma-separated list of trusted frontend origins; +production same-origin requests are supported, and reverse-proxy deployments must include +the public HTTPS origin. Wildcard/null origins are rejected. For isolated local demos only, +`STOCK_BOT_AUTH_DISABLED=true` is allowed on a loopback development/test listener, never +in production. Health endpoints remain public. TLS termination and external rate limiting +belong at the deployment boundary; do not expose development services directly. + +The root `.env` and `apps/stock/web-app/.env` are intentionally tracked for this private, +local-development repository. Other environment files remain ignored; +`bun run audit:secrets` rejects unexpected tracked environment files outside these two +explicit exceptions (WCAG excluded). It is not a complete secret scanner. Keep production +credentials out of these files. Committed values remain in Git history; rotate any real +credentials before sharing the repository or if access changes. Logging still redacts +sensitive fields, bearer tokens, credentialed URLs, and sensitive URL query parameters. +Development database/admin-UI Compose ports bind to loopback; existing containers must +be recreated for changed port bindings to take effect. + +## Pipeline safety + +Routine exchange/symbol/provider-mapping syncs are non-destructive. Legacy +`clearFirst: true` requests are rejected; scheduled exchange syncs no longer reset data. +The transactional sync paths share one checked-out PostgreSQL connection and one +transaction-scoped advisory lock. SQL errors roll back the whole batch and sync status, +and existing curated exchange/provider mappings are preserved. Do not add pooled +`query('BEGIN')` calls: use a transaction-scoped repository. + +Reference-data reset is a separate admin maintenance operation. Send a JSON body to +`POST /api/pipeline/clear/postgresql` with an explicit `type` (`provider_mappings`, +`exchanges`, or `all`) and `confirmation: "DELETE STOCK REFERENCE DATA:"`. +There is no default scope. A mapping-only reset deletes symbol-provider mappings only; +an exchange-only reset fails atomically if symbols still reference exchanges; `all` +deletes reference mappings, symbols, and exchanges in foreign-key order. These resets do +not delete backtest history, prices, or trading records. The dashboard requires typing +the matching confirmation. Generic queue access remains administrator-only. + +`bun run test:native` is part of `bun run check`. The stochastic tests explicitly cover +warm-up (14-bar K plus 3-value D needs 16 bars), invalid periods, golden values, and +incremental/batch parity; no synthetic D values are produced before warm-up completes. +`bun run test:postgres` additionally requires `PIPELINE_TEST_DATABASE_URL` pointing to a +**disposable database whose name starts with `stock_bot_safety`**. It creates/drops isolated +test schemas and verifies real rollback, foreign-key constraints, idempotency, and competing +transaction locking. CI provisions that database and runs this additional gate. It is +separate from the infrastructure-free `check`; never point tests at production. diff --git a/apps/stock/data-ingestion/src/index.ts b/apps/stock/data-ingestion/src/index.ts index 867d33df..39af9675 100644 --- a/apps/stock/data-ingestion/src/index.ts +++ b/apps/stock/data-ingestion/src/index.ts @@ -3,7 +3,7 @@ * Simplified entry point using ServiceApplication framework */ -import { ServiceApplication } from '@stock-bot/di'; +import { createHttpSecurity, httpSecurityOptions, ServiceApplication } from '@stock-bot/di'; import { getLogger } from '@stock-bot/logger'; import { initializeStockConfig } from '@stock-bot/stock-config'; import { createRoutes } from './routes/create-routes'; @@ -12,16 +12,22 @@ import { initializeAllHandlers } from './handlers'; // Initialize configuration with service-specific overrides const config = initializeStockConfig('dataIngestion'); +const security = createHttpSecurity({ ...httpSecurityOptions(), environment: config.environment }); // Log the full configuration const logger = getLogger('data-ingestion'); -logger.info('Service configuration:', config); +logger.info('Service configuration:', { + service: 'data-ingestion', + port: config.service.port, + environment: config.environment, +}); // Create service application const app = new ServiceApplication( config, { serviceName: 'data-ingestion', + hostname: security.hostname, enableHandlers: true, enableScheduledJobs: true, corsConfig: { @@ -41,6 +47,7 @@ const app = new ServiceApplication( }, { // Lifecycle hooks if needed + onAppReady: app => security.mount(app), onStarted: _port => { const logger = getLogger('data-ingestion'); logger.info('Data ingestion service startup initiated with ServiceApplication framework'); diff --git a/apps/stock/data-pipeline/package.json b/apps/stock/data-pipeline/package.json index 1e0ebde8..c351beb3 100644 --- a/apps/stock/data-pipeline/package.json +++ b/apps/stock/data-pipeline/package.json @@ -12,6 +12,7 @@ "clean": "rm -rf dist" }, "dependencies": { + "@stock-bot/types": "workspace:*", "@stock-bot/services": "workspace:*", "@stock-bot/cache": "*", "@stock-bot/config": "*", diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts b/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts index 0146f531..01d6fbb3 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts @@ -24,7 +24,7 @@ class ExchangesHandler extends BaseHandler { description: 'Weekly full exchange sync on Sunday at midnight', }) async syncAllExchanges(payload?: { clearFirst?: boolean }): Promise { - const finalPayload = payload || { clearFirst: true }; + const finalPayload = payload ?? {}; this.log('info', 'Starting sync of all exchanges', finalPayload); return syncAllExchanges(finalPayload, this); } @@ -74,6 +74,7 @@ class ExchangesHandler extends BaseHandler { @Operation('clear-postgresql-data') async clearPostgreSQLData(payload: { type?: 'exchanges' | 'provider_mappings' | 'all'; + confirmation?: string; }): Promise { this.log('warn', 'Clearing PostgreSQL data', payload); return clearPostgreSQLData(payload, this); diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/operations/clear-postgresql-data.operations.ts b/apps/stock/data-pipeline/src/handlers/exchanges/operations/clear-postgresql-data.operations.ts index 401bcf84..19589437 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/operations/clear-postgresql-data.operations.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/operations/clear-postgresql-data.operations.ts @@ -1,62 +1,12 @@ -import { at } from '@stock-bot/invariants'; -import { getLogger } from '@stock-bot/logger'; import { requireServices, type IServiceContainer } from '@stock-bot/services'; +import { + parseResetRequest, + PipelineSyncRepository, +} from '../../../repositories/PipelineSyncRepository'; import type { JobPayload } from '../../../types/job-payloads'; -const logger = getLogger('enhanced-sync-clear-postgresql-data'); - -export async function clearPostgreSQLData( - payload: JobPayload, - container: IServiceContainer -): Promise<{ - exchangesCleared: number; - symbolsCleared: number; - mappingsCleared: number; -}> { - logger.info('Clearing existing PostgreSQL data...'); - - try { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - - // Start transaction for atomic operations - await postgresClient.query('BEGIN'); - - // Get counts before clearing - const exchangeCountResult = await postgresClient.query( - 'SELECT COUNT(*) as count FROM exchanges' - ); - const symbolCountResult = await postgresClient.query('SELECT COUNT(*) as count FROM symbols'); - const mappingCountResult = await postgresClient.query( - 'SELECT COUNT(*) as count FROM provider_mappings' - ); - - const exchangesCleared = parseInt(at(exchangeCountResult.rows, 0).count); - const symbolsCleared = parseInt(at(symbolCountResult.rows, 0).count); - const mappingsCleared = parseInt(at(mappingCountResult.rows, 0).count); - - // Clear data in correct order (respect foreign keys) - await postgresClient.query('DELETE FROM provider_mappings'); - await postgresClient.query('DELETE FROM symbols'); - await postgresClient.query('DELETE FROM exchanges'); - - // Reset sync status - await postgresClient.query( - 'UPDATE sync_status SET last_sync_at = NULL, last_sync_count = 0, sync_errors = NULL' - ); - - await postgresClient.query('COMMIT'); - - logger.info('PostgreSQL data cleared successfully', { - exchangesCleared, - symbolsCleared, - mappingsCleared, - }); - - return { exchangesCleared, symbolsCleared, mappingsCleared }; - } catch (error) { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - await postgresClient.query('ROLLBACK'); - logger.error('Failed to clear PostgreSQL data', { error }); - throw error; - } +export async function clearPostgreSQLData(payload: JobPayload, container: IServiceContainer) { + const scope = parseResetRequest(payload); + const { postgres } = requireServices(container, 'postgres'); + return PipelineSyncRepository.transaction(postgres, repository => repository.reset(scope)); } diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-all-exchanges.operations.ts b/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-all-exchanges.operations.ts index 4eeb8cc2..a8105817 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-all-exchanges.operations.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-all-exchanges.operations.ts @@ -1,293 +1,52 @@ -import { getLogger } from '@stock-bot/logger'; -import type { PostgresClient } from '@stock-bot/services'; import { requireServices, type IServiceContainer } from '@stock-bot/services'; +import { + PipelineSyncRepository, + rejectDestructiveSync, +} from '../../../repositories/PipelineSyncRepository'; import type { JobPayload, SyncResult } from '../../../types/job-payloads'; -const logger = getLogger('enhanced-sync-all-exchanges'); - export async function syncAllExchanges( payload: JobPayload, container: IServiceContainer ): Promise { - const clearFirst = payload.clearFirst || true; - logger.info('Starting comprehensive exchange sync...', { clearFirst }); - - const result: SyncResult = { - processed: 0, - created: 0, - updated: 0, - skipped: 0, - errors: 0, - }; - - try { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - - // Clear existing data if requested - if (clearFirst) { - await clearPostgreSQLData(postgresClient); + rejectDestructiveSync(payload); + const { mongodb, postgres } = requireServices(container, 'mongodb', 'postgres'); + // Fetch first: no SQL connection or write lock is held across provider-storage reads. + const [eod, ib] = await Promise.all([ + mongodb.find('eodExchanges', { active: true }), + mongodb.find('ibExchanges', {}), + ]); + return PipelineSyncRepository.transaction(postgres, async repository => { + const result: SyncResult = { processed: 0, created: 0, updated: 0, skipped: 0, errors: 0 }; + const rows = [ + ...eod.map(row => ({ + provider: 'eod', + code: row.Code, + name: row.Name, + country: row.CountryISO2, + currency: row.Currency, + confidence: 0.95, + })), + ...ib.map(row => ({ + provider: 'ib', + code: row.exchange_id, + name: row.name, + country: row.country_code, + currency: row.currency, + confidence: 0.85, + })), + ]; + for (const row of rows) { + result.processed++; + if (!row.code) { + result.skipped++; + continue; + } + const outcome = await repository.syncExchange(row); + result[outcome]++; } - - // Start transaction for atomic operations - await postgresClient.query('BEGIN'); - - // 1. Sync from EOD exchanges (comprehensive global data) - const eodResult = await syncEODExchanges(container); - mergeResults(result, eodResult); - - // 2. Sync from IB exchanges (detailed asset information) - const ibResult = await syncIBExchanges(container); - mergeResults(result, ibResult); - - // 3. Update sync status - await updateSyncStatus('all', 'exchanges', result.processed, postgresClient); - - await postgresClient.query('COMMIT'); - - logger.info('Comprehensive exchange sync completed', result); + // Any SQL failure aborts the entire sync, including status; never swallow errors in a transaction. + await repository.updateStatus('all', 'exchanges', result.processed); return result; - } catch (error) { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - await postgresClient.query('ROLLBACK'); - logger.error('Comprehensive exchange sync failed', { error }); - throw error; - } -} - -async function clearPostgreSQLData(postgresClient: PostgresClient): Promise { - logger.info('Clearing existing PostgreSQL data...'); - - // Clear data in correct order (respect foreign keys) - await postgresClient.query('DELETE FROM provider_mappings'); - await postgresClient.query('DELETE FROM symbols'); - await postgresClient.query('DELETE FROM exchanges'); - - // Reset sync status - await postgresClient.query( - 'UPDATE sync_status SET last_sync_at = NULL, last_sync_count = 0, sync_errors = NULL' - ); - - logger.info('PostgreSQL data cleared successfully'); -} - -async function syncEODExchanges(container: IServiceContainer): Promise { - const { mongodb: mongoClient } = requireServices(container, 'mongodb'); - const exchanges = await mongoClient.find('eodExchanges', { active: true }); - const result: SyncResult = { processed: 0, created: 0, updated: 0, skipped: 0, errors: 0 }; - - for (const exchange of exchanges) { - try { - // Create provider exchange mapping for EOD - await createProviderExchangeMapping( - 'eod', // provider - exchange.Code, - exchange.Name, - exchange.CountryISO2, - exchange.Currency, - 0.95, // very high confidence for EOD data - container - ); - - result.processed++; - result.created++; // Count as created mapping - } catch (error) { - logger.error('Failed to process EOD exchange', { error, exchange }); - result.errors++; - } - } - - return result; -} - -async function syncIBExchanges(container: IServiceContainer): Promise { - const { mongodb: mongoClient } = requireServices(container, 'mongodb'); - const exchanges = await mongoClient.find('ibExchanges', {}); - const result: SyncResult = { processed: 0, created: 0, updated: 0, skipped: 0, errors: 0 }; - - for (const exchange of exchanges) { - try { - // Create provider exchange mapping for IB - await createProviderExchangeMapping( - 'ib', // provider - exchange.exchange_id, - exchange.name, - exchange.country_code, - 'USD', // IB doesn't specify currency, default to USD - 0.85, // good confidence for IB data - container - ); - - result.processed++; - result.created++; // Count as created mapping - } catch (error) { - logger.error('Failed to process IB exchange', { error, exchange }); - result.errors++; - } - } - - return result; -} - -async function createProviderExchangeMapping( - provider: string, - providerExchangeCode: string, - providerExchangeName: string, - countryCode: string | null, - currency: string | null, - confidence: number, - container: IServiceContainer -): Promise { - if (!providerExchangeCode) { - return; - } - - const { postgres: postgresClient } = requireServices(container, 'postgres'); - - // Check if mapping already exists - const existingMapping = await findProviderExchangeMapping( - provider, - providerExchangeCode, - container - ); - if (existingMapping) { - // Don't override existing mappings to preserve manual work - return; - } - - // Find or create master exchange - const masterExchange = await findOrCreateMasterExchange( - providerExchangeCode, - providerExchangeName, - countryCode, - currency, - container - ); - - if (!masterExchange) { - throw new Error('Master exchange was not created or resolved'); - } - - // Create the provider exchange mapping - const query = ` - INSERT INTO provider_exchange_mappings - (provider, provider_exchange_code, provider_exchange_name, master_exchange_id, - country_code, currency, confidence, active, auto_mapped) - VALUES ($1, $2, $3, $4, $5, $6, $7, false, true) - ON CONFLICT (provider, provider_exchange_code) DO NOTHING - `; - - await postgresClient.query(query, [ - provider, - providerExchangeCode, - providerExchangeName, - masterExchange.id, - countryCode, - currency, - confidence, - ]); -} - -async function findOrCreateMasterExchange( - providerCode: string, - providerName: string, - countryCode: string | null, - currency: string | null, - container: IServiceContainer -) { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - - // First, try to find exact match - let masterExchange = await findExchangeByCode(providerCode, container); - - if (masterExchange) { - return masterExchange; - } - - // Try to find by similar codes (basic mapping) - const basicMapping = getBasicExchangeMapping(providerCode); - if (basicMapping) { - masterExchange = await findExchangeByCode(basicMapping, container); - if (masterExchange) { - return masterExchange; - } - } - - // Create new master exchange (inactive by default) - const query = ` - INSERT INTO exchanges (code, name, country, currency, active) - VALUES ($1, $2, $3, $4, false) - ON CONFLICT (code) DO UPDATE SET - name = COALESCE(EXCLUDED.name, exchanges.name), - country = COALESCE(EXCLUDED.country, exchanges.country), - currency = COALESCE(EXCLUDED.currency, exchanges.currency) - RETURNING id, code, name, country, currency - `; - - const result = await postgresClient.query(query, [ - providerCode, - providerName || providerCode, - countryCode || 'US', - currency || 'USD', - ]); - - return result.rows[0]; -} - -function getBasicExchangeMapping(providerCode: string): string | null { - const mappings: Record = { - NYE: 'NYSE', - NAS: 'NASDAQ', - TO: 'TSX', - LN: 'LSE', - LON: 'LSE', - }; - - return mappings[providerCode.toUpperCase()] || null; -} - -async function findProviderExchangeMapping( - provider: string, - providerExchangeCode: string, - container: IServiceContainer -) { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - const query = - 'SELECT * FROM provider_exchange_mappings WHERE provider = $1 AND provider_exchange_code = $2'; - const result = await postgresClient.query(query, [provider, providerExchangeCode]); - return result.rows[0] || null; -} - -async function findExchangeByCode(code: string, container: IServiceContainer) { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - const query = 'SELECT * FROM exchanges WHERE code = $1'; - const result = await postgresClient.query(query, [code]); - return result.rows[0] || null; -} - -async function updateSyncStatus( - provider: string, - dataType: string, - count: number, - postgresClient: PostgresClient -): Promise { - const query = ` - INSERT INTO sync_status (provider, data_type, last_sync_at, last_sync_count, sync_errors) - VALUES ($1, $2, NOW(), $3, NULL) - ON CONFLICT (provider, data_type) - DO UPDATE SET - last_sync_at = NOW(), - last_sync_count = EXCLUDED.last_sync_count, - sync_errors = NULL, - updated_at = NOW() - `; - - await postgresClient.query(query, [provider, dataType, count]); -} - -function mergeResults(target: SyncResult, source: SyncResult): void { - target.processed += source.processed; - target.created += source.created; - target.updated += source.updated; - target.skipped += source.skipped; - target.errors += source.errors; + }); } diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-qm-provider-mappings.operations.ts b/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-qm-provider-mappings.operations.ts index 8b045a20..7661e2f1 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-qm-provider-mappings.operations.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-qm-provider-mappings.operations.ts @@ -1,33 +1,20 @@ -import { getLogger } from '@stock-bot/logger'; import { requireServices, type IServiceContainer } from '@stock-bot/services'; +import { + PipelineSyncRepository, + rejectDestructiveSync, +} from '../../../repositories/PipelineSyncRepository'; import type { JobPayload, SyncResult } from '../../../types/job-payloads'; -const logger = getLogger('enhanced-sync-qm-provider-mappings'); - export async function syncQMProviderMappings( payload: JobPayload, container: IServiceContainer ): Promise { - logger.info('Starting QM provider exchange mappings sync...'); - - const result: SyncResult = { - processed: 0, - created: 0, - updated: 0, - skipped: 0, - errors: 0, - }; - - try { - const { mongodb: mongoClient } = requireServices(container, 'mongodb'); - const { postgres: postgresClient } = requireServices(container, 'postgres'); - - // Start transaction - await postgresClient.query('BEGIN'); - - // Get unique exchange combinations from QM symbols - const db = mongoClient.getDatabase(); - const pipeline = [ + rejectDestructiveSync(payload); + const { mongodb, postgres } = requireServices(container, 'mongodb', 'postgres'); + const rows = await mongodb + .getDatabase() + .collection('qmSymbols') + .aggregate([ { $group: { _id: { @@ -35,8 +22,6 @@ export async function syncQMProviderMappings( exchange: '$exchange', countryCode: '$countryCode', }, - count: { $sum: 1 }, - sampleExchange: { $first: '$exchange' }, }, }, { @@ -44,180 +29,29 @@ export async function syncQMProviderMappings( exchangeCode: '$_id.exchangeCode', exchange: '$_id.exchange', countryCode: '$_id.countryCode', - count: 1, - sampleExchange: 1, }, }, - ]; - - const qmExchanges = await db.collection('qmSymbols').aggregate(pipeline).toArray(); - logger.info(`Found ${qmExchanges.length} unique QM exchange combinations`); - - for (const exchange of qmExchanges) { - try { - // Create provider exchange mapping for QM - await createProviderExchangeMapping( - 'qm', // provider - exchange.exchangeCode, - exchange.sampleExchange || exchange.exchangeCode, - exchange.countryCode, - exchange.countryCode === 'CA' ? 'CAD' : 'USD', // Simple currency mapping - 0.8, // good confidence for QM data - container - ); - - result.processed++; - result.created++; - } catch (error) { - logger.error('Failed to process QM exchange mapping', { error, exchange }); - result.errors++; + ]) + .toArray(); + return PipelineSyncRepository.transaction(postgres, async repository => { + const result: SyncResult = { processed: 0, created: 0, updated: 0, skipped: 0, errors: 0 }; + for (const row of rows) { + result.processed++; + if (!row.exchangeCode) { + result.skipped++; + continue; } + const outcome = await repository.syncExchange({ + provider: 'qm', + code: row.exchangeCode, + name: row.exchange || row.exchangeCode, + country: row.countryCode, + currency: row.countryCode === 'CA' ? 'CAD' : 'USD', + confidence: 0.8, + }); + result[outcome]++; } - - await postgresClient.query('COMMIT'); - - logger.info('QM provider exchange mappings sync completed', result); + await repository.updateStatus('qm', 'exchange_mappings', result.processed); return result; - } catch (error) { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - await postgresClient.query('ROLLBACK'); - logger.error('QM provider exchange mappings sync failed', { error }); - throw error; - } -} - -async function createProviderExchangeMapping( - provider: string, - providerExchangeCode: string, - providerExchangeName: string, - countryCode: string | null, - currency: string | null, - confidence: number, - container: IServiceContainer -): Promise { - if (!providerExchangeCode) { - return; - } - - const { postgres: postgresClient } = requireServices(container, 'postgres'); - - // Check if mapping already exists - const existingMapping = await findProviderExchangeMapping( - provider, - providerExchangeCode, - container - ); - if (existingMapping) { - // Don't override existing mappings to preserve manual work - return; - } - - // Find or create master exchange - const masterExchange = await findOrCreateMasterExchange( - providerExchangeCode, - providerExchangeName, - countryCode, - currency, - container - ); - - if (!masterExchange) { - throw new Error('Master exchange was not created or resolved'); - } - - // Create the provider exchange mapping - const query = ` - INSERT INTO provider_exchange_mappings - (provider, provider_exchange_code, provider_exchange_name, master_exchange_id, - country_code, currency, confidence, active, auto_mapped) - VALUES ($1, $2, $3, $4, $5, $6, $7, false, true) - ON CONFLICT (provider, provider_exchange_code) DO NOTHING - `; - - await postgresClient.query(query, [ - provider, - providerExchangeCode, - providerExchangeName, - masterExchange.id, - countryCode, - currency, - confidence, - ]); -} - -async function findProviderExchangeMapping( - provider: string, - providerExchangeCode: string, - container: IServiceContainer -) { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - const query = - 'SELECT * FROM provider_exchange_mappings WHERE provider = $1 AND provider_exchange_code = $2'; - const result = await postgresClient.query(query, [provider, providerExchangeCode]); - return result.rows[0] || null; -} - -async function findOrCreateMasterExchange( - providerCode: string, - providerName: string, - countryCode: string | null, - currency: string | null, - container: IServiceContainer -) { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - - // First, try to find exact match - let masterExchange = await findExchangeByCode(providerCode, container); - - if (masterExchange) { - return masterExchange; - } - - // Try to find by similar codes (basic mapping) - const basicMapping = getBasicExchangeMapping(providerCode); - if (basicMapping) { - masterExchange = await findExchangeByCode(basicMapping, container); - if (masterExchange) { - return masterExchange; - } - } - - // Create new master exchange (inactive by default) - const query = ` - INSERT INTO exchanges (code, name, country, currency, active) - VALUES ($1, $2, $3, $4, false) - ON CONFLICT (code) DO UPDATE SET - name = COALESCE(EXCLUDED.name, exchanges.name), - country = COALESCE(EXCLUDED.country, exchanges.country), - currency = COALESCE(EXCLUDED.currency, exchanges.currency) - RETURNING id, code, name, country, currency - `; - - const result = await postgresClient.query(query, [ - providerCode, - providerName || providerCode, - countryCode || 'US', - currency || 'USD', - ]); - - return result.rows[0]; -} - -function getBasicExchangeMapping(providerCode: string): string | null { - const mappings: Record = { - NYE: 'NYSE', - NAS: 'NASDAQ', - TO: 'TSX', - LN: 'LSE', - LON: 'LSE', - }; - - return mappings[providerCode.toUpperCase()] || null; -} - -async function findExchangeByCode(code: string, container: IServiceContainer) { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - const query = 'SELECT * FROM exchanges WHERE code = $1'; - const result = await postgresClient.query(query, [code]); - return result.rows[0] || null; + }); } diff --git a/apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts b/apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts index 032edb23..c28e6390 100644 --- a/apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts +++ b/apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts @@ -1,261 +1,39 @@ -import type { Document } from 'mongodb'; -import { at } from '@stock-bot/invariants'; -import { getLogger } from '@stock-bot/logger'; -import type { PostgresClient } from '@stock-bot/services'; import { requireServices, type IServiceContainer } from '@stock-bot/services'; +import { + PipelineSyncRepository, + rejectDestructiveSync, +} from '../../../repositories/PipelineSyncRepository'; import type { JobPayload, SyncResult } from '../../../types/job-payloads'; -const logger = getLogger('enhanced-sync-symbols-from-provider'); - export async function syncSymbolsFromProvider( payload: JobPayload, container: IServiceContainer ): Promise { - const provider = payload.provider; - const clearFirst = payload.clearFirst || false; - - if (!provider) { - throw new Error('Provider is required in payload'); - } - - logger.info(`Starting ${provider} symbols sync...`, { clearFirst }); - - const result: SyncResult = { - processed: 0, - created: 0, - updated: 0, - skipped: 0, - errors: 0, + rejectDestructiveSync(payload); + const provider = payload.provider?.toLowerCase(); + const collections: Record = { + qm: 'qmSymbols', + eod: 'eodSymbols', + ib: 'ibSymbols', }; - - try { - const { mongodb: mongoClient } = requireServices(container, 'mongodb'); - const { postgres: postgresClient } = requireServices(container, 'postgres'); - - // Clear existing data if requested (only symbols and mappings, keep exchanges) - if (clearFirst) { - await postgresClient.query('BEGIN'); - await postgresClient.query('DELETE FROM provider_mappings'); - await postgresClient.query('DELETE FROM symbols'); - await postgresClient.query('COMMIT'); - logger.info('Cleared existing symbols and mappings before sync'); + const collection = provider && collections[provider]; + if (!provider || !collection) { + throw new Error('A supported provider (qm, eod, ib) is required'); + } + const { mongodb, postgres } = requireServices(container, 'mongodb', 'postgres'); + const rows = await mongodb.getDatabase().collection(collection).find({}).toArray(); + return PipelineSyncRepository.transaction(postgres, async repository => { + const result: SyncResult = { + processed: rows.length, + created: 0, + updated: 0, + skipped: 0, + errors: 0, + }; + for (const row of rows) { + result[await repository.syncSymbol(provider, row)]++; } - - // Start transaction - await postgresClient.query('BEGIN'); - - let symbols: Record[] = []; - - // Get symbols based on provider - const db = mongoClient.getDatabase(); - switch (provider.toLowerCase()) { - case 'qm': - symbols = await db.collection('qmSymbols').find({}).toArray(); - break; - case 'eod': - symbols = await db.collection('eodSymbols').find({}).toArray(); - break; - case 'ib': - symbols = await db.collection('ibSymbols').find({}).toArray(); - break; - default: - throw new Error(`Unsupported provider: ${provider}`); - } - - logger.info(`Found ${symbols.length} ${provider} symbols to process`); - result.processed = symbols.length; - - for (const symbol of symbols) { - try { - await processSingleSymbol(symbol, provider, result, container); - } catch (error) { - logger.error('Failed to process symbol', { - error, - symbol: symbol.symbol || symbol.code, - provider, - }); - result.errors++; - } - } - - // Update sync status - await updateSyncStatus( - provider, - 'symbols', - result.processed, - requireServices(container, 'postgres').postgres - ); - - await postgresClient.query('COMMIT'); - - logger.info(`${provider} symbols sync completed`, result); + await repository.updateStatus(provider, 'symbols', result.processed); return result; - } catch (error) { - await requireServices(container, 'postgres').postgres.query('ROLLBACK'); - logger.error(`${provider} symbols sync failed`, { error }); - throw error; - } -} - -async function processSingleSymbol( - symbol: Document, - provider: string, - result: SyncResult, - container: IServiceContainer -): Promise { - const symbolCode = symbol.symbol || symbol.code; - const exchangeCode = symbol.exchangeCode || symbol.exchange || symbol.exchange_id; - - if (!symbolCode || !exchangeCode) { - result.skipped++; - return; - } - - // Find active provider exchange mapping - const providerMapping = await findActiveProviderExchangeMapping( - provider, - exchangeCode, - container - ); - - if (!providerMapping) { - result.skipped++; - return; - } - - // Check if symbol exists - const existingSymbol = await findSymbolByCodeAndExchange( - symbolCode, - providerMapping.master_exchange_id, - container - ); - - if (existingSymbol) { - await updateSymbol(existingSymbol.id, symbol, container); - await upsertProviderMapping(existingSymbol.id, provider, symbol, container); - result.updated++; - } else { - const newSymbolId = await createSymbol(symbol, providerMapping.master_exchange_id, container); - await upsertProviderMapping(newSymbolId, provider, symbol, container); - result.created++; - } -} - -async function findActiveProviderExchangeMapping( - provider: string, - providerExchangeCode: string, - container: IServiceContainer -) { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - const query = ` - SELECT pem.*, e.code as master_exchange_code - FROM provider_exchange_mappings pem - JOIN exchanges e ON pem.master_exchange_id = e.id - WHERE pem.provider = $1 AND pem.provider_exchange_code = $2 AND pem.active = true - `; - const result = await postgresClient.query(query, [provider, providerExchangeCode]); - return result.rows[0] || null; -} - -async function findSymbolByCodeAndExchange( - symbol: string, - exchangeId: string, - container: IServiceContainer -) { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - const query = 'SELECT * FROM symbols WHERE symbol = $1 AND exchange_id = $2'; - const result = await postgresClient.query(query, [symbol, exchangeId]); - return result.rows[0] || null; -} - -async function createSymbol( - symbol: Document, - exchangeId: string, - container: IServiceContainer -): Promise { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - const query = ` - INSERT INTO symbols (symbol, exchange_id, company_name, country, currency) - VALUES ($1, $2, $3, $4, $5) - RETURNING id - `; - - const result = await postgresClient.query(query, [ - symbol.symbol || symbol.code, - exchangeId, - symbol.companyName || symbol.name || symbol.company_name, - symbol.countryCode || symbol.country_code || 'US', - symbol.currency || 'USD', - ]); - - return at(result.rows, 0).id; -} - -async function updateSymbol( - symbolId: string, - symbol: Document, - container: IServiceContainer -): Promise { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - const query = ` - UPDATE symbols - SET company_name = COALESCE($2, company_name), - country = COALESCE($3, country), - currency = COALESCE($4, currency), - updated_at = NOW() - WHERE id = $1 - `; - - await postgresClient.query(query, [ - symbolId, - symbol.companyName || symbol.name || symbol.company_name, - symbol.countryCode || symbol.country_code, - symbol.currency, - ]); -} - -async function upsertProviderMapping( - symbolId: string, - provider: string, - symbol: Document, - container: IServiceContainer -): Promise { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - const query = ` - INSERT INTO provider_mappings - (symbol_id, provider, provider_symbol, provider_exchange, last_seen) - VALUES ($1, $2, $3, $4, NOW()) - ON CONFLICT (provider, provider_symbol) - DO UPDATE SET - symbol_id = EXCLUDED.symbol_id, - provider_exchange = EXCLUDED.provider_exchange, - last_seen = NOW() - `; - - await postgresClient.query(query, [ - symbolId, - provider, - symbol.qmSearchCode || symbol.symbol || symbol.code, - symbol.exchangeCode || symbol.exchange || symbol.exchange_id, - ]); -} - -async function updateSyncStatus( - provider: string, - dataType: string, - count: number, - postgresClient: PostgresClient -): Promise { - const query = ` - INSERT INTO sync_status (provider, data_type, last_sync_at, last_sync_count, sync_errors) - VALUES ($1, $2, NOW(), $3, NULL) - ON CONFLICT (provider, data_type) - DO UPDATE SET - last_sync_at = NOW(), - last_sync_count = EXCLUDED.last_sync_count, - sync_errors = NULL, - updated_at = NOW() - `; - - await postgresClient.query(query, [provider, dataType, count]); + }); } diff --git a/apps/stock/data-pipeline/src/index.ts b/apps/stock/data-pipeline/src/index.ts index 4cda4944..138a336a 100644 --- a/apps/stock/data-pipeline/src/index.ts +++ b/apps/stock/data-pipeline/src/index.ts @@ -3,7 +3,7 @@ * Simplified entry point using ServiceApplication framework */ -import { ServiceApplication } from '@stock-bot/di'; +import { createHttpSecurity, httpSecurityOptions, ServiceApplication } from '@stock-bot/di'; import { getLogger } from '@stock-bot/logger'; import { initializeStockConfig } from '@stock-bot/stock-config'; import { createRoutes } from './routes/create-routes'; @@ -13,16 +13,22 @@ import { initializeAllHandlers } from './handlers'; // Initialize configuration with service-specific overrides const config = initializeStockConfig('dataPipeline'); +const security = createHttpSecurity({ ...httpSecurityOptions(), environment: config.environment }); // Log the full configuration const logger = getLogger('data-pipeline'); -logger.info('Service configuration:', config); +logger.info('Service configuration:', { + service: 'data-pipeline', + port: config.service.port, + environment: config.environment, +}); // Create service application const app = new ServiceApplication( config, { serviceName: 'data-pipeline', + hostname: security.hostname, enableHandlers: true, enableScheduledJobs: true, corsConfig: { @@ -42,6 +48,7 @@ const app = new ServiceApplication( }, { // Custom lifecycle hooks + onAppReady: app => security.mount(app), onContainerReady: container => { // Setup service-specific configuration setupServiceContainer(config, container); diff --git a/apps/stock/data-pipeline/src/repositories/PipelineSyncRepository.ts b/apps/stock/data-pipeline/src/repositories/PipelineSyncRepository.ts new file mode 100644 index 00000000..7150640f --- /dev/null +++ b/apps/stock/data-pipeline/src/repositories/PipelineSyncRepository.ts @@ -0,0 +1,180 @@ +import type { Document } from 'mongodb'; +import type { TransactionCallback } from '@stock-bot/postgres'; +import type { PostgresClient } from '@stock-bot/services'; +import { parseReferenceDataResetRequest, type ReferenceDataResetScope } from '@stock-bot/types'; + +type SqlClient = Pick>[0], 'query'>; +export type ResetScope = ReferenceDataResetScope; + +/** Every helper uses the same checked-out transaction connection. */ +export class PipelineSyncRepository { + constructor(private readonly sql: SqlClient) {} + + static async transaction( + postgres: Pick, + work: (repository: PipelineSyncRepository) => Promise + ): Promise { + return postgres.transaction(async client => { + // Serialize sync/reset transactions across service instances. Released on rollback too. + await client.query('SELECT pg_advisory_xact_lock(1937007472, 1)'); + return work(new PipelineSyncRepository(client)); + }); + } + + async syncExchange(input: { + provider: string; + code: string; + name: string; + country?: string | null; + currency?: string | null; + confidence: number; + }): Promise<'created' | 'skipped'> { + const existing = await this.sql.query( + 'SELECT id FROM provider_exchange_mappings WHERE provider = $1 AND provider_exchange_code = $2', + [input.provider, input.code] + ); + if (existing.rows.length) { + return 'skipped'; + } // Preserve manually curated mappings. + const aliases: Record = { + NYE: 'NYSE', + NAS: 'NASDAQ', + TO: 'TSX', + LN: 'LSE', + LON: 'LSE', + }; + const code = aliases[input.code.toUpperCase()] ?? input.code; + const exchange = await this.sql.query<{ id: string }>( + `INSERT INTO exchanges (code, name, country, currency, active) + VALUES ($1, $2, $3, $4, false) ON CONFLICT (code) DO UPDATE SET code = EXCLUDED.code + RETURNING id`, + [code, input.name || code, input.country || 'US', input.currency || 'USD'] + ); + const id = exchange.rows[0]?.id; + if (!id) { + throw new Error('Master exchange could not be resolved'); + } + const inserted = await this.sql.query( + `INSERT INTO provider_exchange_mappings + (provider, provider_exchange_code, provider_exchange_name, master_exchange_id, + country_code, currency, confidence, active, auto_mapped) + VALUES ($1,$2,$3,$4,$5,$6,$7,false,true) + ON CONFLICT (provider, provider_exchange_code) DO NOTHING RETURNING id`, + [ + input.provider, + input.code, + input.name, + id, + input.country ?? null, + input.currency ?? null, + input.confidence, + ] + ); + return inserted.rows.length ? 'created' : 'skipped'; + } + + async syncSymbol(provider: string, symbol: Document): Promise<'created' | 'updated' | 'skipped'> { + const code = symbol.symbol || symbol.code || symbol.Code; + const exchangeCode = + symbol.exchangeCode || symbol.exchange || symbol.exchange_id || symbol.Exchange; + if (!code || !exchangeCode) { + return 'skipped'; + } + const mapping = await this.sql.query<{ master_exchange_id: string }>( + `SELECT master_exchange_id FROM provider_exchange_mappings + WHERE provider = $1 AND provider_exchange_code = $2 AND active = true`, + [provider, exchangeCode] + ); + const exchangeId = mapping.rows[0]?.master_exchange_id; + if (!exchangeId) { + return 'skipped'; + } + const existing = await this.sql.query<{ id: string }>( + 'SELECT id FROM symbols WHERE symbol = $1 AND exchange_id = $2', + [code, exchangeId] + ); + const saved = await this.sql.query<{ id: string }>( + `INSERT INTO symbols (symbol, exchange_id, company_name, country, currency) + VALUES ($1,$2,$3,$4,$5) ON CONFLICT (symbol, exchange_id) DO UPDATE SET + company_name = COALESCE(EXCLUDED.company_name, symbols.company_name), + country = COALESCE(EXCLUDED.country, symbols.country), + currency = COALESCE(EXCLUDED.currency, symbols.currency), updated_at = NOW() RETURNING id`, + [ + code, + exchangeId, + symbol.companyName || symbol.name || symbol.company_name || symbol.Name || null, + symbol.countryCode || symbol.country_code || symbol.Country || null, + symbol.currency || symbol.Currency || null, + ] + ); + const symbolId = saved.rows[0]?.id; + if (!symbolId) { + throw new Error('Symbol could not be resolved'); + } + await this.sql.query( + `INSERT INTO provider_mappings (symbol_id, provider, provider_symbol, provider_exchange, last_seen) + VALUES ($1,$2,$3,$4,NOW()) ON CONFLICT (provider, provider_symbol) DO UPDATE SET + symbol_id = CASE WHEN provider_mappings.verified THEN provider_mappings.symbol_id ELSE EXCLUDED.symbol_id END, + provider_exchange = CASE WHEN provider_mappings.verified THEN provider_mappings.provider_exchange ELSE EXCLUDED.provider_exchange END, + last_seen = NOW()`, + [ + symbolId, + provider, + symbol.qmSearchCode || symbol.eodSearchCode || symbol.symbol || symbol.code || symbol.Code, + exchangeCode, + ] + ); + return existing.rows.length ? 'updated' : 'created'; + } + + async updateStatus(provider: string, kind: string, count: number): Promise { + await this.sql.query( + `INSERT INTO sync_status (provider, data_type, last_sync_at, last_sync_count, sync_errors) + VALUES ($1,$2,NOW(),$3,NULL) ON CONFLICT (provider, data_type) DO UPDATE SET + last_sync_at = NOW(), last_sync_count = EXCLUDED.last_sync_count, sync_errors = NULL, updated_at = NOW()`, + [provider, kind, count] + ); + } + + async reset(scope: ResetScope) { + const counts = { + exchangesCleared: 0, + symbolsCleared: 0, + mappingsCleared: 0, + exchangeMappingsCleared: 0, + }; + const remove = async ( + table: 'provider_mappings' | 'symbols' | 'provider_exchange_mappings' | 'exchanges' + ) => { + const result = await this.sql.query(`DELETE FROM ${table}`); + return result.rowCount ?? 0; + }; + if (scope === 'all' || scope === 'provider_mappings') { + counts.mappingsCleared = await remove('provider_mappings'); + } + if (scope === 'all') { + counts.symbolsCleared = await remove('symbols'); + } + if (scope === 'all' || scope === 'exchanges') { + // FK constraints reject an exchange-only reset if symbols still reference it. + counts.exchangeMappingsCleared = await remove('provider_exchange_mappings'); + counts.exchangesCleared = await remove('exchanges'); + } + await this.sql.query( + 'UPDATE sync_status SET last_sync_at = NULL, last_sync_count = 0, sync_errors = NULL' + ); + return counts; + } +} + +export function rejectDestructiveSync(payload: { clearFirst?: unknown }): void { + if (payload.clearFirst !== undefined && payload.clearFirst !== false) { + throw new Error( + 'Sync is non-destructive; use the explicit, confirmed maintenance reset instead' + ); + } +} + +export function parseResetRequest(payload: Record): ResetScope { + return parseReferenceDataResetRequest(payload).type; +} diff --git a/apps/stock/data-pipeline/src/routes/enhanced-sync.routes.ts b/apps/stock/data-pipeline/src/routes/enhanced-sync.routes.ts index cbecfdbc..a36d2422 100644 --- a/apps/stock/data-pipeline/src/routes/enhanced-sync.routes.ts +++ b/apps/stock/data-pipeline/src/routes/enhanced-sync.routes.ts @@ -1,6 +1,7 @@ import { Hono } from 'hono'; import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; +import { parseReferenceDataResetRequest } from '@stock-bot/types'; const logger = getLogger('enhanced-sync-routes'); @@ -9,6 +10,9 @@ export function createEnhancedSyncRoutes(container: IServiceContainer) { // Enhanced sync endpoints enhancedSync.post('/exchanges/all', async c => { + if (c.req.query('clear') && c.req.query('clear') !== 'false') { + return c.json({ error: 'Sync is non-destructive; use the explicit maintenance reset' }, 400); + } try { const clearFirst = c.req.query('clear') === 'true'; const queueManager = container.queueManager; @@ -118,8 +122,14 @@ export function createEnhancedSyncRoutes(container: IServiceContainer) { }); enhancedSync.post('/clear/postgresql', async c => { + const input: unknown = await c.req.json().catch(() => null); + let payload; + try { + payload = parseReferenceDataResetRequest(input); + } catch (error) { + return c.json({ error: error instanceof Error ? error.message : 'Invalid reset' }, 400); + } try { - const dataType = c.req.query('type') as 'exchanges' | 'provider_mappings' | 'all'; const queueManager = container.queueManager; if (!queueManager) { return c.json({ success: false, error: 'Queue manager not available' }, 503); @@ -130,7 +140,7 @@ export function createEnhancedSyncRoutes(container: IServiceContainer) { const job = await exchangesQueue.add('clear-postgresql-data', { handler: 'exchanges', operation: 'clear-postgresql-data', - payload: { dataType: dataType || 'all' }, + payload, }); return c.json({ diff --git a/apps/stock/engine/src/indicators/stochastic.rs b/apps/stock/engine/src/indicators/stochastic.rs index 23ea3d1c..15a4bdd2 100644 --- a/apps/stock/engine/src/indicators/stochastic.rs +++ b/apps/stock/engine/src/indicators/stochastic.rs @@ -1,297 +1,346 @@ -use super::{Indicator, IncrementalIndicator, IndicatorResult, IndicatorError, PriceData}; -use super::sma::SMA; -use super::common::RollingWindow; - -/// Stochastic Oscillator Indicator -/// -/// %K = 100 × (Close - Lowest Low) / (Highest High - Lowest Low) -/// %D = SMA of %K -pub struct Stochastic { - k_period: usize, - d_period: usize, - smooth_k: usize, - high_window: RollingWindow, - low_window: RollingWindow, - close_window: RollingWindow, - k_sma: SMA, - d_sma: SMA, - k_values: RollingWindow, -} - -impl Stochastic { - pub fn new(k_period: usize, d_period: usize, smooth_k: usize) -> Result { - if k_period == 0 || d_period == 0 { - return Err(IndicatorError::InvalidParameter( - "K and D periods must be greater than 0".to_string() - )); - } - - Ok(Self { - k_period, - d_period, - smooth_k, - high_window: RollingWindow::new(k_period), - low_window: RollingWindow::new(k_period), - close_window: RollingWindow::new(k_period), - k_sma: SMA::new(smooth_k.max(1))?, - d_sma: SMA::new(d_period)?, - k_values: RollingWindow::new(d_period), - }) - } - - /// Standard Fast Stochastic (14, 3) - pub fn fast() -> Result { - Self::new(14, 3, 1) - } - - /// Standard Slow Stochastic (14, 3, 3) - pub fn slow() -> Result { - Self::new(14, 3, 3) - } - - /// Calculate raw %K value - fn calculate_raw_k(high: &[f64], low: &[f64], close: f64) -> Option { - if high.is_empty() || low.is_empty() { - return None; - } - - let highest = high.iter().cloned().fold(f64::NEG_INFINITY, f64::max); - let lowest = low.iter().cloned().fold(f64::INFINITY, f64::min); - - let range = highest - lowest; - if range > 0.0 { - Some(100.0 * (close - lowest) / range) - } else { - Some(50.0) // If no range, return middle value - } - } - - /// Calculate Stochastic for a series of price data - pub fn calculate_series( - high: &[f64], - low: &[f64], - close: &[f64], - k_period: usize, - d_period: usize, - smooth_k: usize, - ) -> Result<(Vec, Vec), IndicatorError> { - if high.len() != low.len() || high.len() != close.len() { - return Err(IndicatorError::InvalidParameter( - "High, low, and close arrays must have the same length".to_string() - )); - } - - if high.len() < k_period { - return Err(IndicatorError::InsufficientData { - required: k_period, - actual: high.len(), - }); - } - - // Calculate raw %K values - let mut raw_k_values = Vec::with_capacity(high.len() - k_period + 1); - for i in k_period - 1..high.len() { - let start = i + 1 - k_period; - if let Some(k) = Self::calculate_raw_k( - &high[start..=i], - &low[start..=i], - close[i] - ) { - raw_k_values.push(k); - } - } - - // Smooth %K if requested - let k_values = if smooth_k > 1 { - SMA::calculate_series(&raw_k_values, smooth_k)? - } else { - raw_k_values - }; - - // Calculate %D (SMA of %K) - let d_values = if k_values.len() >= d_period { - SMA::calculate_series(&k_values, d_period)? - } else { - vec![] - }; - - Ok((k_values, d_values)) - } -} - -impl Indicator for Stochastic { - fn calculate(&mut self, data: &PriceData) -> Result { - if data.high.len() != data.low.len() || data.high.len() != data.close.len() { - return Err(IndicatorError::InvalidParameter( - "Price data arrays must have the same length".to_string() - )); - } - - let (k_values, d_values) = Self::calculate_series( - &data.high, - &data.low, - &data.close, - self.k_period, - self.d_period, - self.smooth_k, - )?; - - Ok(IndicatorResult::Stochastic { - k: k_values, - d: d_values, - }) - } - - fn reset(&mut self) { - self.high_window.clear(); - self.low_window.clear(); - self.close_window.clear(); - self.k_sma.reset(); - self.d_sma.reset(); - self.k_values.clear(); - } - - fn is_ready(&self) -> bool { - self.high_window.is_full() && self.d_sma.is_ready() - } -} - -impl IncrementalIndicator for Stochastic { - fn update(&mut self, value: f64) -> Result, IndicatorError> { - // For incremental updates, we assume value is close price - // In real usage, you'd need to provide high/low/close separately - self.high_window.push(value); - self.low_window.push(value); - self.close_window.push(value); - - if self.high_window.is_full() { - // Calculate raw %K - if let Some(raw_k) = Self::calculate_raw_k( - &self.high_window.as_slice(), - &self.low_window.as_slice(), - value - ) { - // Smooth %K if needed - let k_value = if self.smooth_k > 1 { - self.k_sma.update(raw_k)? - } else { - Some(raw_k) - }; - - if let Some(k) = k_value { - self.k_values.push(k); - - // Calculate %D - if let Some(d) = self.d_sma.update(k)? { - return Ok(Some(d)); - } - } - } - } - - Ok(None) - } - - fn current(&self) -> Option { - self.d_sma.current() - } -} - -/// Structure to hold Stochastic values -pub struct StochasticValues { - pub k: f64, - pub d: f64, -} - -impl Stochastic { - /// Get current %K and %D values - pub fn current_values(&self) -> Option { - if let (Some(&k), Some(d)) = (self.k_values.iter().last(), self.d_sma.current()) { - Some(StochasticValues { k, d }) - } else { - None - } - } - - /// Update with separate high, low, close values - pub fn update_hlc(&mut self, high: f64, low: f64, close: f64) -> Result, IndicatorError> { - self.high_window.push(high); - self.low_window.push(low); - self.close_window.push(close); - - if self.high_window.is_full() { - if let Some(raw_k) = Self::calculate_raw_k( - &self.high_window.as_slice(), - &self.low_window.as_slice(), - close - ) { - let k_value = if self.smooth_k > 1 { - self.k_sma.update(raw_k)? - } else { - Some(raw_k) - }; - - if let Some(k) = k_value { - self.k_values.push(k); - - if let Some(d) = self.d_sma.update(k)? { - return Ok(Some(StochasticValues { k, d })); - } - } - } - } - - Ok(None) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_stochastic_calculation() { - let high = vec![ - 127.01, 127.62, 126.59, 127.35, 128.17, - 128.43, 127.37, 126.42, 126.90, 126.85, - 125.65, 125.72, 127.16, 127.72, 127.69 - ]; - let low = vec![ - 125.36, 126.16, 124.93, 126.09, 126.82, - 126.48, 126.03, 124.83, 126.39, 125.72, - 124.56, 124.57, 125.07, 126.86, 126.63 - ]; - let close = vec![ - 125.36, 126.16, 124.93, 126.09, 126.82, - 126.48, 126.03, 124.83, 126.39, 125.72, - 124.56, 124.57, 125.07, 126.86, 126.63 - ]; - - let (k_values, d_values) = Stochastic::calculate_series(&high, &low, &close, 14, 3, 1).unwrap(); - - assert!(!k_values.is_empty()); - assert!(!d_values.is_empty()); - - // %K should be between 0 and 100 - for k in &k_values { - assert!(*k >= 0.0 && *k <= 100.0); - } - } - - #[test] - fn test_stochastic_extremes() { - // When close is at highest high, %K should be 100 - let high = vec![10.0; 14]; - let low = vec![5.0; 14]; - let mut close = vec![7.5; 14]; - close[13] = 10.0; // Last close at high - - let (k_values, _) = Stochastic::calculate_series(&high, &low, &close, 14, 3, 1).unwrap(); - assert!((k_values[0] - 100.0).abs() < 1e-10); - - // When close is at lowest low, %K should be 0 - close[13] = 5.0; // Last close at low - let (k_values, _) = Stochastic::calculate_series(&high, &low, &close, 14, 3, 1).unwrap(); - assert!(k_values[0].abs() < 1e-10); - } -} \ No newline at end of file +use super::common::RollingWindow; +use super::sma::SMA; +use super::{IncrementalIndicator, Indicator, IndicatorError, IndicatorResult, PriceData}; + +/// Stochastic Oscillator Indicator +/// +/// %K = 100 × (Close - Lowest Low) / (Highest High - Lowest Low) +/// %D = SMA of %K +pub struct Stochastic { + k_period: usize, + d_period: usize, + smooth_k: usize, + high_window: RollingWindow, + low_window: RollingWindow, + close_window: RollingWindow, + k_sma: SMA, + d_sma: SMA, + k_values: RollingWindow, +} + +impl Stochastic { + pub fn new(k_period: usize, d_period: usize, smooth_k: usize) -> Result { + if k_period == 0 || d_period == 0 || smooth_k == 0 { + return Err(IndicatorError::InvalidParameter( + "K, D, and smoothing periods must be greater than 0".to_string(), + )); + } + + Ok(Self { + k_period, + d_period, + smooth_k, + high_window: RollingWindow::new(k_period), + low_window: RollingWindow::new(k_period), + close_window: RollingWindow::new(k_period), + k_sma: SMA::new(smooth_k.max(1))?, + d_sma: SMA::new(d_period)?, + k_values: RollingWindow::new(d_period), + }) + } + + /// Standard Fast Stochastic (14, 3) + pub fn fast() -> Result { + Self::new(14, 3, 1) + } + + /// Standard Slow Stochastic (14, 3, 3) + pub fn slow() -> Result { + Self::new(14, 3, 3) + } + + /// Calculate raw %K value + fn calculate_raw_k(high: &[f64], low: &[f64], close: f64) -> Option { + if high.is_empty() || low.is_empty() { + return None; + } + + let highest = high.iter().cloned().fold(f64::NEG_INFINITY, f64::max); + let lowest = low.iter().cloned().fold(f64::INFINITY, f64::min); + + let range = highest - lowest; + if range > 0.0 { + Some(100.0 * (close - lowest) / range) + } else { + Some(50.0) // If no range, return middle value + } + } + + /// Calculate Stochastic for a series of price data + pub fn calculate_series( + high: &[f64], + low: &[f64], + close: &[f64], + k_period: usize, + d_period: usize, + smooth_k: usize, + ) -> Result<(Vec, Vec), IndicatorError> { + if k_period == 0 || d_period == 0 || smooth_k == 0 { + return Err(IndicatorError::InvalidParameter( + "K, D, and smoothing periods must be greater than 0".to_string(), + )); + } + if high.len() != low.len() || high.len() != close.len() { + return Err(IndicatorError::InvalidParameter( + "High, low, and close arrays must have the same length".to_string(), + )); + } + + if high.len() < k_period { + return Err(IndicatorError::InsufficientData { + required: k_period, + actual: high.len(), + }); + } + + // Calculate raw %K values + let mut raw_k_values = Vec::with_capacity(high.len() - k_period + 1); + for i in k_period - 1..high.len() { + let start = i + 1 - k_period; + if let Some(k) = Self::calculate_raw_k(&high[start..=i], &low[start..=i], close[i]) { + raw_k_values.push(k); + } + } + + // Smooth %K if requested + let k_values = if raw_k_values.len() < smooth_k { + vec![] + } else if smooth_k > 1 { + SMA::calculate_series(&raw_k_values, smooth_k)? + } else { + raw_k_values + }; + + // Calculate %D (SMA of %K) + let d_values = if k_values.len() >= d_period { + SMA::calculate_series(&k_values, d_period)? + } else { + vec![] + }; + + Ok((k_values, d_values)) + } +} + +impl Indicator for Stochastic { + fn calculate(&mut self, data: &PriceData) -> Result { + if data.high.len() != data.low.len() || data.high.len() != data.close.len() { + return Err(IndicatorError::InvalidParameter( + "Price data arrays must have the same length".to_string(), + )); + } + + let (k_values, d_values) = Self::calculate_series( + &data.high, + &data.low, + &data.close, + self.k_period, + self.d_period, + self.smooth_k, + )?; + + Ok(IndicatorResult::Stochastic { + k: k_values, + d: d_values, + }) + } + + fn reset(&mut self) { + self.high_window.clear(); + self.low_window.clear(); + self.close_window.clear(); + self.k_sma.reset(); + self.d_sma.reset(); + self.k_values.clear(); + } + + fn is_ready(&self) -> bool { + self.high_window.is_full() && self.d_sma.is_ready() + } +} + +impl IncrementalIndicator for Stochastic { + fn update(&mut self, value: f64) -> Result, IndicatorError> { + // For incremental updates, we assume value is close price + // In real usage, you'd need to provide high/low/close separately + self.high_window.push(value); + self.low_window.push(value); + self.close_window.push(value); + + if self.high_window.is_full() { + // Calculate raw %K + if let Some(raw_k) = Self::calculate_raw_k( + &self.high_window.as_slice(), + &self.low_window.as_slice(), + value, + ) { + // Smooth %K if needed + let k_value = if self.smooth_k > 1 { + self.k_sma.update(raw_k)? + } else { + Some(raw_k) + }; + + if let Some(k) = k_value { + self.k_values.push(k); + + // Calculate %D + if let Some(d) = self.d_sma.update(k)? { + return Ok(Some(d)); + } + } + } + } + + Ok(None) + } + + fn current(&self) -> Option { + self.d_sma.current() + } +} + +/// Structure to hold Stochastic values +pub struct StochasticValues { + pub k: f64, + pub d: f64, +} + +impl Stochastic { + /// Get current %K and %D values + pub fn current_values(&self) -> Option { + if let (Some(&k), Some(d)) = (self.k_values.iter().last(), self.d_sma.current()) { + Some(StochasticValues { k, d }) + } else { + None + } + } + + /// Update with separate high, low, close values + pub fn update_hlc( + &mut self, + high: f64, + low: f64, + close: f64, + ) -> Result, IndicatorError> { + self.high_window.push(high); + self.low_window.push(low); + self.close_window.push(close); + + if self.high_window.is_full() { + if let Some(raw_k) = Self::calculate_raw_k( + &self.high_window.as_slice(), + &self.low_window.as_slice(), + close, + ) { + let k_value = if self.smooth_k > 1 { + self.k_sma.update(raw_k)? + } else { + Some(raw_k) + }; + + if let Some(k) = k_value { + self.k_values.push(k); + + if let Some(d) = self.d_sma.update(k)? { + return Ok(Some(StochasticValues { k, d })); + } + } + } + } + + Ok(None) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_stochastic_calculation() { + let high = vec![ + 127.01, 127.62, 126.59, 127.35, 128.17, 128.43, 127.37, 126.42, 126.90, 126.85, 125.65, + 125.72, 127.16, 127.72, 127.69, 128.0, + ]; + let low = vec![ + 125.36, 126.16, 124.93, 126.09, 126.82, 126.48, 126.03, 124.83, 126.39, 125.72, 124.56, + 124.57, 125.07, 126.86, 126.63, 126.0, + ]; + let close = vec![ + 125.36, 126.16, 124.93, 126.09, 126.82, 126.48, 126.03, 124.83, 126.39, 125.72, 124.56, + 124.57, 125.07, 126.86, 126.63, 127.0, + ]; + + let (k_values, d_values) = + Stochastic::calculate_series(&high, &low, &close, 14, 3, 1).unwrap(); + + // 14-bar K + 3-value D needs 16 bars, not the old 15-bar fixture. + assert_eq!(k_values.len(), 3); + assert_eq!(d_values.len(), 1); + assert!((d_values[0] - k_values.iter().sum::() / 3.0).abs() < 1e-10); + let (_, warming_d) = + Stochastic::calculate_series(&high[..15], &low[..15], &close[..15], 14, 3, 1).unwrap(); + assert!(warming_d.is_empty()); + + // %K should be between 0 and 100 + for k in &k_values { + assert!(*k >= 0.0 && *k <= 100.0); + } + } + + #[test] + fn test_stochastic_extremes() { + // When close is at highest high, %K should be 100 + let high = vec![10.0; 14]; + let low = vec![5.0; 14]; + let mut close = vec![7.5; 14]; + close[13] = 10.0; // Last close at high + + let (k_values, _) = Stochastic::calculate_series(&high, &low, &close, 14, 3, 1).unwrap(); + assert!((k_values[0] - 100.0).abs() < 1e-10); + + // When close is at lowest low, %K should be 0 + close[13] = 5.0; // Last close at low + let (k_values, _) = Stochastic::calculate_series(&high, &low, &close, 14, 3, 1).unwrap(); + assert!(k_values[0].abs() < 1e-10); + } + + #[test] + fn test_stochastic_invalid_periods_do_not_panic() { + for (k, d, smooth) in [(0, 3, 1), (3, 0, 1), (3, 3, 0)] { + assert!(Stochastic::new(k, d, smooth).is_err()); + assert!( + Stochastic::calculate_series(&[10.0; 5], &[0.0; 5], &[5.0; 5], k, d, smooth) + .is_err() + ); + } + } + + #[test] + fn test_stochastic_golden_values_and_incremental_parity() { + let high = vec![10.0, 11.0, 12.0, 13.0, 14.0, 15.0]; + let low = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0]; + let close = vec![5.0, 6.0, 7.0, 8.0, 9.0, 10.0]; + for smooth in [1, 2] { + let (k, d) = Stochastic::calculate_series(&high, &low, &close, 3, 2, smooth).unwrap(); + for value in k.iter().chain(d.iter()) { + assert!((value - 100.0 * 7.0 / 12.0).abs() < 1e-10); + } + let mut incremental = Stochastic::new(3, 2, smooth).unwrap(); + let mut actual = Vec::new(); + for i in 0..high.len() { + if let Some(value) = incremental.update_hlc(high[i], low[i], close[i]).unwrap() { + actual.push(value.d); + } + } + assert_eq!(actual.len(), d.len()); + for (a, b) in actual.iter().zip(d.iter()) { + assert!((a - b).abs() < 1e-10); + } + } + let (k, d) = + Stochastic::calculate_series(&high[..3], &low[..3], &close[..3], 3, 2, 2).unwrap(); + assert!(k.is_empty() && d.is_empty()); + } +} diff --git a/apps/stock/orchestrator/src/index.ts b/apps/stock/orchestrator/src/index.ts index fd941536..ad422b08 100644 --- a/apps/stock/orchestrator/src/index.ts +++ b/apps/stock/orchestrator/src/index.ts @@ -5,6 +5,7 @@ import { Hono } from 'hono'; import { cors } from 'hono/cors'; +import { createHttpSecurity, httpSecurityOptions } from '@stock-bot/di'; import { getLogger } from '@stock-bot/logger'; import { initializeStockConfig } from '@stock-bot/stock-config'; import { createRoutes } from './routes/create-routes'; @@ -12,6 +13,7 @@ import { createContainer } from './simple-container'; // Initialize configuration with service-specific overrides const config = initializeStockConfig('orchestrator'); +const security = createHttpSecurity({ ...httpSecurityOptions(), environment: config.environment }); const logger = getLogger('orchestrator'); // Get service-specific config @@ -58,6 +60,7 @@ async function main() { credentials: config.services?.webApi?.cors?.credentials ?? true, }) ); + security.mount(app); // Logging middleware app.use('*', async (c, next) => { @@ -75,7 +78,8 @@ async function main() { try { server = Bun.serve({ port: PORT, - hostname: '0.0.0.0', // Explicitly bind to all interfaces + hostname: security.hostname, + maxRequestBodySize: 1_048_576, fetch: async req => { services.logger.debug(`Incoming request: ${req.method} ${req.url}`); try { diff --git a/apps/stock/web-api/src/index.ts b/apps/stock/web-api/src/index.ts index 0d5365ec..312cb70a 100644 --- a/apps/stock/web-api/src/index.ts +++ b/apps/stock/web-api/src/index.ts @@ -18,7 +18,11 @@ if (config.queue) { // Log the full configuration const logger = getLogger('web-api'); -logger.info('Service configuration:', config); +logger.info('Service configuration:', { + service: 'web-api', + port: config.service.port, + environment: config.environment, +}); // Import and start WebSocket-enabled server import('./server-with-websocket').then(({ startServerWithWebSocket }) => { diff --git a/apps/stock/web-api/src/routes/create-routes.ts b/apps/stock/web-api/src/routes/create-routes.ts index b4e0f1a8..78c243bf 100644 --- a/apps/stock/web-api/src/routes/create-routes.ts +++ b/apps/stock/web-api/src/routes/create-routes.ts @@ -5,24 +5,32 @@ import { Hono } from 'hono'; import { cors } from 'hono/cors'; +import { createHttpSecurity, httpSecurityOptions, type HttpSecurity } from '@stock-bot/di'; import type { IServiceContainer } from '@stock-bot/handlers'; +import { createBacktestRoutes } from './backtest.routes'; +import { createBacktestV2Routes } from './backtests-v2.routes'; import { createExchangeRoutes } from './exchange.routes'; import { createHealthRoutes } from './health.routes'; import { createMonitoringRoutes } from './monitoring.routes'; import { createPipelineRoutes } from './pipeline.routes'; -import { createBacktestRoutes } from './backtest.routes'; -import { createBacktestV2Routes } from './backtests-v2.routes'; -export function createRoutes(container: IServiceContainer): Hono { +export function createRoutes( + container: IServiceContainer, + security: HttpSecurity = createHttpSecurity({ ...httpSecurityOptions(), browserSessions: true }) +): Hono { const app = new Hono(); - + // Add CORS middleware - app.use('*', cors({ - origin: ['http://localhost:4200', 'http://localhost:3000', 'http://localhost:3002', 'http://localhost:5173', 'http://localhost:5174'], - allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], - allowHeaders: ['Content-Type', 'Authorization'], - credentials: true, - })); + app.use( + '*', + cors({ + origin: security.allowedOrigins, + allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + allowHeaders: ['Content-Type', 'Authorization'], + credentials: true, + }) + ); + security.mount(app); // Create routes with container const healthRoutes = createHealthRoutes(container); diff --git a/apps/stock/web-api/src/routes/pipeline.routes.ts b/apps/stock/web-api/src/routes/pipeline.routes.ts index d7e862fb..e7677147 100644 --- a/apps/stock/web-api/src/routes/pipeline.routes.ts +++ b/apps/stock/web-api/src/routes/pipeline.routes.ts @@ -6,6 +6,7 @@ import { Hono } from 'hono'; import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; +import { parseReferenceDataResetRequest } from '@stock-bot/types'; import { PipelineService } from '../services/pipeline.service'; const logger = getLogger('pipeline-routes'); @@ -48,6 +49,9 @@ export function createPipelineRoutes(container: IServiceContainer) { }); pipeline.post('/exchanges/all', async c => { + if (c.req.query('clear') && c.req.query('clear') !== 'false') { + return c.json({ error: 'Sync is non-destructive; use the explicit maintenance reset' }, 400); + } try { const clearFirst = c.req.query('clear') === 'true'; const result = await pipelineService.syncAllExchanges(clearFirst); @@ -92,9 +96,15 @@ export function createPipelineRoutes(container: IServiceContainer) { // Clear data endpoint pipeline.post('/clear/postgresql', async c => { + const input: unknown = await c.req.json().catch(() => null); + let reset; try { - const dataType = c.req.query('type') as 'exchanges' | 'provider_mappings' | 'all'; - const result = await pipelineService.clearPostgreSQLData(dataType || 'all'); + reset = parseReferenceDataResetRequest(input); + } catch (error) { + return c.json({ error: error instanceof Error ? error.message : 'Invalid reset' }, 400); + } + try { + const result = await pipelineService.clearPostgreSQLData(reset.type, reset.confirmation); return c.json(result, result.success ? 200 : 503); } catch (error) { logger.error('Error in POST /clear/postgresql', { error }); diff --git a/apps/stock/web-api/src/routes/websocket.routes.ts b/apps/stock/web-api/src/routes/websocket.routes.ts index 65727013..a2094e5d 100644 --- a/apps/stock/web-api/src/routes/websocket.routes.ts +++ b/apps/stock/web-api/src/routes/websocket.routes.ts @@ -1,4 +1,5 @@ import type { Server, ServerWebSocket } from 'bun'; +import { createHttpSecurity, httpSecurityOptions, type HttpSecurity } from '@stock-bot/di'; import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; import { @@ -10,13 +11,20 @@ import { const logger = getLogger('websocket-routes'); -export function createWebSocketRoute(container: IServiceContainer) { +export function createWebSocketRoute( + container: IServiceContainer, + security: HttpSecurity = createHttpSecurity({ ...httpSecurityOptions(), browserSessions: true }) +) { const wsHandler = createWebSocketHandler(container); // Make the handler available globally for other services setWebSocketHandler(wsHandler); return (request: Request, server: Pick) => { + const rejection = security.authorize(request); + if (rejection) { + return rejection; + } const url = new URL(request.url); const runId = url.searchParams.get('runId'); diff --git a/apps/stock/web-api/src/server-with-websocket.ts b/apps/stock/web-api/src/server-with-websocket.ts index b53ffd23..37ea55ba 100644 --- a/apps/stock/web-api/src/server-with-websocket.ts +++ b/apps/stock/web-api/src/server-with-websocket.ts @@ -1,3 +1,4 @@ +import { createHttpSecurity, httpSecurityOptions } from '@stock-bot/di'; import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; import { initializeStockConfig } from '@stock-bot/stock-config'; @@ -7,6 +8,11 @@ import { getWebSocketHandler, type RunSocketData } from './websocket/run-updates // Initialize configuration with service-specific overrides const config = initializeStockConfig('webApi'); +const security = createHttpSecurity({ + ...httpSecurityOptions(), + environment: config.environment, + browserSessions: true, +}); // Override queue settings for web-api (no workers needed) if (config.queue) { @@ -17,7 +23,11 @@ if (config.queue) { // Log the full configuration const logger = getLogger('web-api'); -logger.info('Service configuration:', config); +logger.info('Service configuration:', { + service: 'web-api', + port: config.service.port, + environment: config.environment, +}); // Container factory function async function createContainer(config: import('@stock-bot/config').UnifiedAppConfig) { @@ -56,10 +66,10 @@ export async function startServerWithWebSocket() { container = diContainer.resolve('serviceContainer'); // Create HTTP routes - const routes = createRoutes(container); + const routes = createRoutes(container, security); // Create WebSocket route handler - const wsRoute = createWebSocketRoute(container); + const wsRoute = createWebSocketRoute(container, security); // Start server with WebSocket support const port = config.service.port || 2003; @@ -70,6 +80,8 @@ export async function startServerWithWebSocket() { try { server = Bun.serve({ port, + hostname: security.hostname, + maxRequestBodySize: 1_048_576, // Handle HTTP requests async fetch(req, server) { diff --git a/apps/stock/web-api/src/services/backtest-v2.service.ts b/apps/stock/web-api/src/services/backtest-v2.service.ts index 077593b3..0626be05 100644 --- a/apps/stock/web-api/src/services/backtest-v2.service.ts +++ b/apps/stock/web-api/src/services/backtest-v2.service.ts @@ -1,5 +1,6 @@ import { randomUUID as uuidv4 } from 'node:crypto'; import type { QueryResultRow } from 'pg'; +import { authenticatedServiceFetch } from '@stock-bot/di'; import { at } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; import { requireServices, type IServiceContainer } from '@stock-bot/services'; @@ -64,7 +65,7 @@ export class BacktestServiceV2 { constructor( container: IServiceContainer, - private readonly request: BacktestTransport = fetch + private readonly request: BacktestTransport = authenticatedServiceFetch ) { this.container = requireServices(container, 'postgres'); logger.info('BacktestServiceV2 initialized'); diff --git a/apps/stock/web-api/src/services/pipeline.service.ts b/apps/stock/web-api/src/services/pipeline.service.ts index 38f0eb9b..1bc4a8b6 100644 --- a/apps/stock/web-api/src/services/pipeline.service.ts +++ b/apps/stock/web-api/src/services/pipeline.service.ts @@ -6,6 +6,7 @@ import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; import { getFullQueueName } from '@stock-bot/queue'; +import { parseReferenceDataResetRequest, type ReferenceDataResetScope } from '@stock-bot/types'; const logger = getLogger('pipeline-service'); @@ -119,6 +120,9 @@ export class PipelineService { */ async syncAllExchanges(clearFirst: boolean = false): Promise { try { + if (clearFirst) { + throw new Error('Sync is non-destructive; use the explicit maintenance reset'); + } const queueManager = this.container.queueManager; if (!queueManager) { return { success: false, error: 'Queue manager not available' }; @@ -246,9 +250,11 @@ export class PipelineService { * Clear PostgreSQL data */ async clearPostgreSQLData( - dataType: 'exchanges' | 'provider_mappings' | 'all' = 'all' + dataType: ReferenceDataResetScope, + confirmation: string ): Promise { try { + const payload = parseReferenceDataResetRequest({ type: dataType, confirmation }); const queueManager = this.container.queueManager; if (!queueManager) { return { success: false, error: 'Queue manager not available' }; @@ -258,7 +264,7 @@ export class PipelineService { const job = await exchangesQueue.add('clear-postgresql-data', { handler: 'exchanges', operation: 'clear-postgresql-data', - payload: { dataType }, + payload, }); logger.info('PostgreSQL data clear job queued', { jobId: job.id, dataType }); diff --git a/apps/stock/web-app/src/app/App.tsx b/apps/stock/web-app/src/app/App.tsx index c63f8d65..51f3a9c0 100644 --- a/apps/stock/web-app/src/app/App.tsx +++ b/apps/stock/web-app/src/app/App.tsx @@ -1,48 +1,54 @@ +import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'; import { Layout } from '@/components/layout'; +import { BacktestDetailPageV2, BacktestListPageV2 } from '@/features/backtest'; import { DashboardPage } from '@/features/dashboard'; import { ExchangesPage } from '@/features/exchanges'; import { MonitoringPage } from '@/features/monitoring'; import { PipelinePage } from '@/features/pipeline'; -import { BacktestListPageV2, BacktestDetailPageV2 } from '@/features/backtest'; -import { SymbolsPage, SymbolDetailPage } from '@/features/symbols'; -import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'; +import { SymbolDetailPage, SymbolsPage } from '@/features/symbols'; +import { AuthGate } from './AuthGate'; export function App() { return ( - - - }> - } /> - } /> - - } /> - } /> - - } /> - Portfolio Page - Coming Soon} - /> - Strategies Page - Coming Soon} - /> - Analytics Page - Coming Soon} - /> - - } /> - - } /> - } /> + + + + }> + } /> + } /> + + } /> + } /> + } /> + Portfolio Page - Coming Soon} + /> + Strategies Page - Coming Soon} + /> + Analytics Page - Coming Soon} + /> + + } /> + + } /> + } /> + + + Settings Page - Coming Soon} + /> + } /> + } /> - Settings Page - Coming Soon} /> - } /> - } /> - - - + + + ); } diff --git a/apps/stock/web-app/src/app/AuthGate.tsx b/apps/stock/web-app/src/app/AuthGate.tsx new file mode 100644 index 00000000..23886716 --- /dev/null +++ b/apps/stock/web-app/src/app/AuthGate.tsx @@ -0,0 +1,118 @@ +import { useCallback, useEffect, useState, type FormEvent, type ReactNode } from 'react'; +import { API_BASE_URL } from '@/lib/api'; + +export function AuthGate({ children }: { children: ReactNode }) { + const [role, setRole] = useState(null); + const [checking, setChecking] = useState(true); + const [token, setToken] = useState(''); + const [error, setError] = useState(''); + const [busy, setBusy] = useState(false); + const checkSession = useCallback(async () => { + try { + const response = await fetch(`${API_BASE_URL}/api/auth/session`, { credentials: 'include' }); + const session = await response.json(); + setRole(response.ok && session.authenticated ? session.role : null); + } catch { + setError('Cannot reach the API. Check its URL and service status.'); + } finally { + setChecking(false); + } + }, []); + useEffect(() => { + void checkSession(); + const expired = () => setRole(null); + window.addEventListener('stock-bot-auth-required', expired); + return () => window.removeEventListener('stock-bot-auth-required', expired); + }, [checkSession]); + + const signIn = async (event: FormEvent) => { + event.preventDefault(); + setBusy(true); + setError(''); + try { + const response = await fetch(`${API_BASE_URL}/api/auth/session`, { + method: 'POST', + credentials: 'include', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token }), + }); + if (!response.ok) { + throw new Error( + response.status === 429 + ? 'Too many attempts. Try again in a minute.' + : 'Sign-in failed. Check your access token.' + ); + } + const session = await response.json(); + setRole(session.role); + } catch (failure) { + setError(failure instanceof Error ? failure.message : 'Sign-in failed'); + } finally { + setToken(''); + setBusy(false); + } + }; + const signOut = async () => { + try { + const response = await fetch(`${API_BASE_URL}/api/auth/session`, { + method: 'DELETE', + credentials: 'include', + }); + if (!response.ok) { + throw new Error('Sign-out failed'); + } + setRole(null); + } catch { + setError('Sign-out failed. Please try again.'); + } + }; + if (checking) { + return ( +

+ Checking access… +

+ ); + } + if (role) { + return ( + <> + {children} +
+ {role === 'read' ? 'Read-only access' : 'Administrator access'} + + {error && ( + + {error} + + )} +
+ + ); + } + return ( +
+
void signIn(event)} className="w-full max-w-sm space-y-4"> +

Stock Bot access

+

Enter your administrator or read-only access token. It is not stored in your browser.

+ + setToken(event.target.value)} + className="w-full rounded border p-2 bg-surface" + /> + {error &&

{error}

} + +
+
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts index debfc62f..8a951549 100644 --- a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts +++ b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts @@ -1,8 +1,7 @@ import type { BacktestRunResult } from '@stock-bot/types'; +import { API_BASE_URL, apiFetch as fetch } from '@/lib/api'; import { browserLog } from '@/utils/browserLog'; -const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:2003'; - export interface Backtest { id: string; name: string; diff --git a/apps/stock/web-app/src/features/charts/services/chartDataService.ts b/apps/stock/web-app/src/features/charts/services/chartDataService.ts index 894a80ab..47c861ba 100644 --- a/apps/stock/web-app/src/features/charts/services/chartDataService.ts +++ b/apps/stock/web-app/src/features/charts/services/chartDataService.ts @@ -1,6 +1,7 @@ +import { API_BASE_URL, apiFetch as fetch } from '@/lib/api'; import type { CandlestickData, ChartInterval, MarketData } from '../types'; -const API_BASE = '/api/market-data'; +const API_BASE = `${API_BASE_URL}/api/market-data`; export class ChartDataService { static async getHistoricalData( diff --git a/apps/stock/web-app/src/features/exchanges/services/exchangeApi.ts b/apps/stock/web-app/src/features/exchanges/services/exchangeApi.ts index 3f1f4486..d7fba122 100644 --- a/apps/stock/web-app/src/features/exchanges/services/exchangeApi.ts +++ b/apps/stock/web-app/src/features/exchanges/services/exchangeApi.ts @@ -1,3 +1,4 @@ +import { API_BASE_URL, apiFetch as fetch } from '@/lib/api'; import type { ApiResponse, CreateExchangeRequest, @@ -11,8 +12,6 @@ import type { UpdateProviderMappingRequest, } from '../types/index'; -const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:2003'; - class ExchangeApiService { private async request(endpoint: string, options?: RequestInit): Promise> { const url = `${API_BASE_URL}/api${endpoint}`; diff --git a/apps/stock/web-app/src/features/monitoring/services/monitoringApi.ts b/apps/stock/web-app/src/features/monitoring/services/monitoringApi.ts index df2488e3..51bd6e38 100644 --- a/apps/stock/web-app/src/features/monitoring/services/monitoringApi.ts +++ b/apps/stock/web-app/src/features/monitoring/services/monitoringApi.ts @@ -1,3 +1,4 @@ +import { API_BASE_URL, apiFetch as fetch } from '@/lib/api'; /** * Monitoring API Service */ @@ -12,7 +13,6 @@ import type { SystemOverview, } from '../types'; -const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:2003'; const MONITORING_BASE = `${API_BASE_URL}/api/system/monitoring`; export const monitoringApi = { diff --git a/apps/stock/web-app/src/features/pipeline/PipelinePage.tsx b/apps/stock/web-app/src/features/pipeline/PipelinePage.tsx index 0fbf61d7..412aa3f6 100644 --- a/apps/stock/web-app/src/features/pipeline/PipelinePage.tsx +++ b/apps/stock/web-app/src/features/pipeline/PipelinePage.tsx @@ -96,7 +96,6 @@ export function PipelinePage() { } = usePipeline(); const [selectedProvider, setSelectedProvider] = useState('yahoo'); - const [clearFirst, setClearFirst] = useState(false); const [clearDataType, setClearDataType] = useState<'all' | 'exchanges' | 'provider_mappings'>( 'all' ); @@ -132,7 +131,7 @@ export function PipelinePage() { await syncQMExchanges(); break; case 'sync-all-exchanges': - await syncAllExchanges(clearFirst); + await syncAllExchanges(false); break; case 'sync-qm-provider-mappings': await syncQMProviderMappings(); @@ -141,12 +140,14 @@ export function PipelinePage() { await syncIBExchanges(); break; case 'clear-postgresql': - if ( - confirm( - `Are you sure you want to clear ${clearDataType} data? This action cannot be undone.` - ) - ) { - await clearPostgreSQLData(clearDataType); + { + const expected = `DELETE STOCK REFERENCE DATA:${clearDataType}`; + const confirmation = prompt( + `This permanently deletes ${clearDataType} reference data. Type ${expected} to continue.` + ); + if (confirmation === expected) { + await clearPostgreSQLData(clearDataType, confirmation); + } } break; } @@ -340,20 +341,6 @@ export function PipelinePage() { )} - {op.id === 'sync-all-exchanges' && ( -
- -
- )} -