From 588f6669435a17472925b83063e831debc680e7d Mon Sep 17 00:00:00 2001 From: Boki Date: Tue, 20 Oct 2026 12:39:38 -0400 Subject: [PATCH] first refactor --- .gitignore | 229 ++++++------- .gitlab-ci.yml | 49 +-- README.md | 55 ++++ apps/stock/data-ingestion/package.json | 1 + .../ib/actions/fetch-exchanges.action.ts | 2 +- .../data-ingestion/src/handlers/index.ts | 2 +- .../qm/shared/session-manager-redis.ts | 4 +- .../qm/shared/session-manager-wrapper.ts | 4 +- .../src/handlers/qm/shared/session-manager.ts | 2 +- .../src/routes/market-data.routes.ts | 6 +- .../data-ingestion/src/routes/queue.routes.ts | 2 +- .../BaseOperationProvider.ts | 4 +- .../operation-manager/OperationRegistry.ts | 4 +- .../operation-manager/OperationTracker.ts | 4 +- .../src/shared/operation-manager/types.ts | 4 +- apps/stock/data-ingestion/src/types.ts | 4 +- .../operation-manager.test.ts | 4 +- apps/stock/data-ingestion/tsconfig.json | 3 + apps/stock/data-pipeline/package.json | 1 + .../handlers/exchanges/exchanges.handler.ts | 2 +- .../operations/qm-exchanges.operations.ts | 2 +- .../stock/data-pipeline/src/handlers/index.ts | 2 +- .../src/routes/enhanced-sync.routes.ts | 20 +- .../data-pipeline/src/routes/stats.routes.ts | 12 +- .../data-pipeline/src/routes/sync.routes.ts | 12 +- apps/stock/data-pipeline/tsconfig.json | 3 + apps/stock/engine/index.cjs | 10 + apps/stock/engine/index.d.ts | 9 + apps/stock/engine/index.mjs | 76 +++-- apps/stock/engine/package.json | 14 +- apps/stock/orchestrator/package.json | 88 ++--- apps/stock/orchestrator/tsconfig.json | 68 ++-- apps/stock/package.json | 2 +- apps/stock/web-api/package.json | 2 + .../web-api/src/routes/exchange.routes.ts | 2 +- .../web-api/src/services/exchange.service.ts | 2 +- .../web-api/src/services/pipeline.service.ts | 65 ++-- apps/stock/web-api/src/types.ts | 4 +- apps/stock/web-api/tsconfig.json | 3 + bun.lock | 29 ++ libs/core/config/turbo.json | 4 +- libs/core/di/package.json | 1 + libs/core/di/src/awilix-container.ts | 62 +--- libs/core/di/src/container/builder.ts | 5 +- libs/core/di/src/container/types.ts | 4 +- libs/core/di/src/index.ts | 2 +- libs/core/di/src/service-application.ts | 2 +- libs/core/di/tsconfig.json | 7 +- libs/core/handlers/package.json | 1 + libs/core/handlers/src/base/BaseHandler.ts | 11 +- libs/core/handlers/src/index.ts | 1 + .../handlers/test/base-handler-config.test.ts | 3 +- .../test/base-handler-edge-cases.test.ts | 3 +- .../handlers/test/base-handler-http.test.ts | 3 +- libs/core/handlers/test/base-handler.test.ts | 3 +- libs/core/handlers/test/handlers.test.ts | 4 +- libs/core/handlers/tsconfig.json | 1 + libs/core/logger/src/index.ts | 2 +- libs/core/logger/src/types.ts | 5 + libs/core/queue/src/queue-manager.ts | 11 +- libs/core/queue/src/queue.ts | 22 +- libs/core/queue/tsconfig.json | 1 - libs/core/queue/turbo.json | 4 +- libs/core/services/package.json | 29 ++ libs/core/services/src/index.ts | 44 +++ .../core/services/test/contracts.type-test.ts | 61 ++++ libs/core/services/tsconfig.json | 19 ++ libs/core/types/src/index.ts | 21 -- libs/core/types/src/service-container.ts | 17 - libs/core/types/src/services.ts | 311 ------------------ libs/data/mongodb/src/client.ts | 8 +- libs/services/browser/turbo.json | 4 +- libs/services/proxy/tsconfig.json | 1 + package.json | 18 +- scripts/build-all.sh | 174 ++-------- scripts/build-libs.sh | 95 +----- scripts/check.ts | 42 +++ scripts/test/native-bindings.test.ts | 18 + scripts/test/service-consumers.test.ts | 62 ++++ scripts/test/workspace.test.ts | 101 ++++++ tsconfig.app.json | 4 +- tsconfig.check.json | 32 ++ tsconfig.contracts.json | 4 + turbo.json | 20 +- 84 files changed, 996 insertions(+), 1062 deletions(-) create mode 100644 README.md create mode 100644 apps/stock/engine/index.cjs create mode 100644 apps/stock/engine/index.d.ts create mode 100644 libs/core/services/package.json create mode 100644 libs/core/services/src/index.ts create mode 100644 libs/core/services/test/contracts.type-test.ts create mode 100644 libs/core/services/tsconfig.json delete mode 100644 libs/core/types/src/service-container.ts delete mode 100644 libs/core/types/src/services.ts create mode 100644 scripts/check.ts create mode 100644 scripts/test/native-bindings.test.ts create mode 100644 scripts/test/service-consumers.test.ts create mode 100644 scripts/test/workspace.test.ts create mode 100644 tsconfig.check.json create mode 100644 tsconfig.contracts.json diff --git a/.gitignore b/.gitignore index 2698689a..90f3ea04 100644 --- a/.gitignore +++ b/.gitignore @@ -1,114 +1,115 @@ -# Dependencies -node_modules/ -.pnp -.pnp.js - -# Production builds -dist/ -build/ -.next/ -*.js.map -*.d.ts - - -# Logs -npm-debug.log* -yarn-debug.log* -yarn-error.log* -bun-debug.log* -bun-error.log* -*.log - -# Runtime data -pids -*.pid -*.seed -*.pid.lock -*.tsbuildinfo - -# Coverage directory used by tools like istanbul -coverage/ -*.lcov - -# Dependency directories -.pnpm-store/ - -# Optional npm cache directory -.npm - -# Optional eslint cache -.eslintcache - -# Optional stylelint cache -.stylelintcache - -# Microbundle cache -.rpt2_cache/ -.rts2_cache_cjs/ -.rts2_cache_es/ -.rts2_cache_umd/ - -# Optional REPL history -.node_repl_history - -# Output of 'npm pack' -*.tgz - -# Yarn Integrity file -.yarn-integrity - -# parcel-bundler cache (https://parceljs.org/) -.cache -.parcel-cache - -# Next.js build output -.next - -# Nuxt.js build / generate output -.nuxt - -# Storybook build outputs -.out -.storybook-out - -# Temporary folders -tmp/ -temp/ - -# Editor directories and files -.idea/ -*.swp -*.swo -*~ - -# OS generated files -.DS_Store -.DS_Store? -._* -.Spotlight-V100 -.Trashes -ehthumbs.db -Thumbs.db - -# Trading bot specific -.data/ -.backtest-results/ -.logs/ -.old/ -.mongo/ -.chat/ -*.db -*.sqlite -*.sqlite3 - -# Turbo -.turbo -*.tsbuildinfo - -# AI -.serena/ -.claude/ -docs/configuration-standardization.md - -# Rust -target/ +# Dependencies +node_modules/ +.pnp +.pnp.js + +# Production builds +dist/ +build/ +.next/ +*.js.map +*.d.ts +!apps/stock/engine/index.d.ts + + +# Logs +npm-debug.log* +yarn-debug.log* +yarn-error.log* +bun-debug.log* +bun-error.log* +*.log + +# Runtime data +pids +*.pid +*.seed +*.pid.lock +*.tsbuildinfo + +# Coverage directory used by tools like istanbul +coverage/ +*.lcov + +# Dependency directories +.pnpm-store/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional stylelint cache +.stylelintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next + +# Nuxt.js build / generate output +.nuxt + +# Storybook build outputs +.out +.storybook-out + +# Temporary folders +tmp/ +temp/ + +# Editor directories and files +.idea/ +*.swp +*.swo +*~ + +# OS generated files +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db + +# Trading bot specific +.data/ +.backtest-results/ +.logs/ +.old/ +.mongo/ +.chat/ +*.db +*.sqlite +*.sqlite3 + +# Turbo +.turbo +*.tsbuildinfo + +# AI +.serena/ +.claude/ +docs/configuration-standardization.md + +# Rust +target/ diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index a70399f3..3c3fbb4a 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,19 +1,30 @@ -stages: -- build -- test -- deploy -- review -- dast -- staging -- canary -- production -- incremental rollout 10% -- incremental rollout 25% -- incremental rollout 50% -- incremental rollout 100% -- performance -- cleanup -sast: - stage: test -include: -- template: Auto-DevOps.gitlab-ci.yml +stages: + - build + - test + - deploy + - review + - dast + - staging + - canary + - production + - incremental rollout 10% + - incremental rollout 25% + - incremental rollout 50% + - incremental rollout 100% + - performance + - cleanup +sast: + stage: test +include: + - template: Auto-DevOps.gitlab-ci.yml + +repository-check: + stage: test + image: rust:1.88-bookworm + 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" + - export PATH="/root/.bun/bin:$PATH" + - bun install --frozen-lockfile + script: + - bun run check diff --git a/README.md b/README.md new file mode 100644 index 00000000..86010f7c --- /dev/null +++ b/README.md @@ -0,0 +1,55 @@ +# Stock Bot + +Bun/TypeScript workspaces for market-data collection, processing, APIs, and a React dashboard, +with a Rust native trading engine. `apps/wcag-ada` is an independent project and is not part of +the root workspace checks. + +## Build and verify + +Use Bun 1.2.17, Node.js 18 or newer, and a Rust toolchain with a native linker. CI uses Rust +1.88. Building and the tooling/contract checks do not require running databases or provider +credentials. + +```sh +bun install --frozen-lockfile +bun run build +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 lint:check` | Lint stock applications, libraries, and tools with zero warnings allowed | +| `bun run check` | Run build, type checking, contract tests, tooling tests, and lint; report every failed gate | + +`check` exits nonzero if any gate fails. Existing application type/lint errors are reported; +they are not suppressed or baselined. The larger existing `bun run test` suite is separate: +some tests need databases, Redis, browsers, or native-engine fixes. + +Native builds generate `apps/stock/engine/dist/engine.node` and `dist/index.d.ts`. The public +ESM/CommonJS loaders and declaration facade use those generated artifacts. Rebuild after +changing Rust APIs. TensorFlow is an optional orchestrator peer dependency used by the ML +strategy; install it when using that strategy. + +## Service contracts + +`@stock-bot/types` contains independent domain, job, and handler types. +`@stock-bot/services` composes service capabilities from the public APIs exported by the +owning adapters. It uses type-only imports and does not initialize connections. + +```ts +import type { IServiceContainer, ServiceTypes } from '@stock-bot/services'; +import type { ExecutionContext } from '@stock-bot/types'; +``` + +The DI and handler packages re-export `IServiceContainer` for existing consumers. Queue +managers and individual queues are separate capabilities: obtain queues through +`container.queueManager`, submit with `queue.add`, and await results with `queue.waitForJob`. +Use `getFullQueueName(service, handler)` when addressing another service's queue. diff --git a/apps/stock/data-ingestion/package.json b/apps/stock/data-ingestion/package.json index 9cb6fdd5..6396253b 100644 --- a/apps/stock/data-ingestion/package.json +++ b/apps/stock/data-ingestion/package.json @@ -12,6 +12,7 @@ "clean": "rm -rf dist" }, "dependencies": { + "@stock-bot/services": "workspace:*", "@stock-bot/cache": "*", "@stock-bot/config": "*", "@stock-bot/stock-config": "*", diff --git a/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-exchanges.action.ts b/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-exchanges.action.ts index 36977446..567a0f3b 100644 --- a/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-exchanges.action.ts +++ b/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-exchanges.action.ts @@ -1,4 +1,4 @@ -import type { IServiceContainer } from '@stock-bot/types'; +import type { IServiceContainer } from '@stock-bot/services'; import { IB_CONFIG } from '../shared/config'; import { fetchSession } from './fetch-session.action'; diff --git a/apps/stock/data-ingestion/src/handlers/index.ts b/apps/stock/data-ingestion/src/handlers/index.ts index 357c19d7..06ea86cf 100644 --- a/apps/stock/data-ingestion/src/handlers/index.ts +++ b/apps/stock/data-ingestion/src/handlers/index.ts @@ -4,7 +4,7 @@ */ import { getLogger } from '@stock-bot/logger'; -import type { IServiceContainer } from '@stock-bot/types'; +import type { IServiceContainer } from '@stock-bot/services'; // Import handlers explicitly for bundling (ensures they're included in the build) // These imports trigger the decorator metadata to be set import { CeoHandler } from './ceo/ceo.handler'; diff --git a/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-redis.ts b/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-redis.ts index 5ca1f328..10239ba7 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-redis.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-redis.ts @@ -4,7 +4,7 @@ */ import type { CacheProvider } from '@stock-bot/cache'; -import type { Logger } from '@stock-bot/types'; +import type { Logger } from '@stock-bot/services'; import { QM_SESSION_IDS, SESSION_CONFIG } from './config'; import type { QMSession } from './types'; @@ -379,4 +379,4 @@ export class QMSessionManagerRedis { this.logger?.info('Migration completed'); } -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-wrapper.ts b/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-wrapper.ts index 9418af83..9d0b210b 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-wrapper.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-wrapper.ts @@ -3,7 +3,7 @@ */ import type { CacheProvider } from '@stock-bot/cache'; -import type { Logger } from '@stock-bot/types'; +import type { Logger } from '@stock-bot/services'; import { QMSessionManager } from './session-manager'; import { QMSessionManagerRedis } from './session-manager-redis'; import type { QMSession } from './types'; @@ -125,4 +125,4 @@ export class SessionManagerWrapper { } throw new Error('Migration only available for Redis implementation'); } -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager.ts b/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager.ts index 4e852ebe..424dc81a 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager.ts @@ -3,7 +3,7 @@ */ import type { CacheProvider } from '@stock-bot/cache'; -import type { Logger } from '@stock-bot/types'; +import type { Logger } from '@stock-bot/services'; import { QM_SESSION_IDS, SESSION_CONFIG } from './config'; import type { CachedSession, QMSession } from './types'; diff --git a/apps/stock/data-ingestion/src/routes/market-data.routes.ts b/apps/stock/data-ingestion/src/routes/market-data.routes.ts index 070eb6a3..c0953ac5 100644 --- a/apps/stock/data-ingestion/src/routes/market-data.routes.ts +++ b/apps/stock/data-ingestion/src/routes/market-data.routes.ts @@ -18,7 +18,7 @@ export function createMarketDataRoutes(container: IServiceContainer) { try { // Queue job for live data using Yahoo provider - const queueManager = container.queue; + const queueManager = container.queueManager; if (!queueManager) { return c.json({ status: 'error', message: 'Queue manager not available' }, 503); } @@ -53,7 +53,7 @@ export function createMarketDataRoutes(container: IServiceContainer) { const toDate = to ? new Date(to) : new Date(); // Now // Queue job for historical data using Yahoo provider - const queueManager = container.queue; + const queueManager = container.queueManager; if (!queueManager) { return c.json({ status: 'error', message: 'Queue manager not available' }, 503); } @@ -106,7 +106,7 @@ export function createMarketDataRoutes(container: IServiceContainer) { useBatching, }); - const queueManager = container.queue; + const queueManager = container.queueManager; if (!queueManager) { return c.json({ status: 'error', message: 'Queue manager not available' }, 503); } diff --git a/apps/stock/data-ingestion/src/routes/queue.routes.ts b/apps/stock/data-ingestion/src/routes/queue.routes.ts index ddad40a8..56b246c9 100644 --- a/apps/stock/data-ingestion/src/routes/queue.routes.ts +++ b/apps/stock/data-ingestion/src/routes/queue.routes.ts @@ -10,7 +10,7 @@ export function createQueueRoutes(container: IServiceContainer) { // Queue status endpoint queue.get('/status', async c => { try { - const queueManager = container.queue; + const queueManager = container.queueManager; if (!queueManager) { return c.json({ status: 'error', message: 'Queue manager not available' }, 503); } diff --git a/apps/stock/data-ingestion/src/shared/operation-manager/BaseOperationProvider.ts b/apps/stock/data-ingestion/src/shared/operation-manager/BaseOperationProvider.ts index 4590c1e2..c4cf72ee 100644 --- a/apps/stock/data-ingestion/src/shared/operation-manager/BaseOperationProvider.ts +++ b/apps/stock/data-ingestion/src/shared/operation-manager/BaseOperationProvider.ts @@ -2,7 +2,7 @@ * Base class for operation providers */ -import type { Logger, MongoDBClient } from '@stock-bot/types'; +import type { Logger, MongoDBClient } from '@stock-bot/services'; import type { OperationConfig, OperationUpdate, @@ -170,4 +170,4 @@ export abstract class BaseOperationProvider { })) }); } -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/shared/operation-manager/OperationRegistry.ts b/apps/stock/data-ingestion/src/shared/operation-manager/OperationRegistry.ts index 41372fd3..12dc5dc1 100644 --- a/apps/stock/data-ingestion/src/shared/operation-manager/OperationRegistry.ts +++ b/apps/stock/data-ingestion/src/shared/operation-manager/OperationRegistry.ts @@ -2,7 +2,7 @@ * Central registry for managing operations across multiple providers */ -import type { Logger, MongoDBClient } from '@stock-bot/types'; +import type { Logger, MongoDBClient } from '@stock-bot/services'; import { BaseOperationProvider } from './BaseOperationProvider'; import { OperationTracker } from './OperationTracker'; import type { @@ -330,4 +330,4 @@ export class OperationRegistry { } })); } -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/shared/operation-manager/OperationTracker.ts b/apps/stock/data-ingestion/src/shared/operation-manager/OperationTracker.ts index a8480492..62c8677e 100644 --- a/apps/stock/data-ingestion/src/shared/operation-manager/OperationTracker.ts +++ b/apps/stock/data-ingestion/src/shared/operation-manager/OperationTracker.ts @@ -2,7 +2,7 @@ * General operation tracker that works with any provider */ -import type { Logger, MongoDBClient } from '@stock-bot/types'; +import type { Logger, MongoDBClient } from '@stock-bot/services'; import type { BaseOperationProvider } from './BaseOperationProvider'; import type { BulkOperationUpdate, @@ -781,4 +781,4 @@ export class OperationTracker { getProviderInfo() { return this.provider.getProviderConfig(); } -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/shared/operation-manager/types.ts b/apps/stock/data-ingestion/src/shared/operation-manager/types.ts index f205511c..bf60c408 100644 --- a/apps/stock/data-ingestion/src/shared/operation-manager/types.ts +++ b/apps/stock/data-ingestion/src/shared/operation-manager/types.ts @@ -2,7 +2,7 @@ * Types for the general operation management system */ -import type { Logger, MongoDBClient } from '@stock-bot/types'; +import type { Logger, MongoDBClient } from '@stock-bot/services'; /** * Configuration for a single operation @@ -184,4 +184,4 @@ export interface SymbolWithOperations { export interface OperationComponentOptions { mongodb: MongoDBClient; logger: Logger; -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/types.ts b/apps/stock/data-ingestion/src/types.ts index 4b7b2b6f..7a75ca47 100644 --- a/apps/stock/data-ingestion/src/types.ts +++ b/apps/stock/data-ingestion/src/types.ts @@ -3,7 +3,7 @@ * Defines required services for data ingestion handlers */ -import type { ServiceTypes } from '@stock-bot/types'; +import type { ServiceTypes } from '@stock-bot/services'; /** * Services required by data ingestion handlers @@ -22,4 +22,4 @@ export type DataIngestionServices = ServiceTypes & { postgres: ServiceTypes['postgres']; questdb: ServiceTypes['questdb']; globalCache: ServiceTypes['globalCache']; -}; \ No newline at end of file +}; diff --git a/apps/stock/data-ingestion/test/shared/operation-manager/operation-manager.test.ts b/apps/stock/data-ingestion/test/shared/operation-manager/operation-manager.test.ts index 15d2a577..94946829 100644 --- a/apps/stock/data-ingestion/test/shared/operation-manager/operation-manager.test.ts +++ b/apps/stock/data-ingestion/test/shared/operation-manager/operation-manager.test.ts @@ -3,7 +3,7 @@ */ import { describe, it, expect, beforeEach } from 'bun:test'; -import type { Logger, MongoDBClient } from '@stock-bot/types'; +import type { Logger, MongoDBClient } from '@stock-bot/services'; import { BaseOperationProvider, OperationRegistry, @@ -193,4 +193,4 @@ describe('Operation Management System', () => { expect(stats.totalSymbols).toBe(100); }); }); -}); \ No newline at end of file +}); diff --git a/apps/stock/data-ingestion/tsconfig.json b/apps/stock/data-ingestion/tsconfig.json index 5f0e071c..bb0875e5 100644 --- a/apps/stock/data-ingestion/tsconfig.json +++ b/apps/stock/data-ingestion/tsconfig.json @@ -1,5 +1,8 @@ { "extends": "../../../tsconfig.app.json", + "compilerOptions": { "rootDir": "./src", "outDir": "./dist" }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"], "references": [ { "path": "../../../libs/core/types" }, { "path": "../../../libs/core/config" }, diff --git a/apps/stock/data-pipeline/package.json b/apps/stock/data-pipeline/package.json index 9bc15fca..0041c730 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/services": "workspace:*", "@stock-bot/cache": "*", "@stock-bot/config": "*", "@stock-bot/stock-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 86a5597e..8db8fdc8 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts @@ -1,5 +1,5 @@ import { BaseHandler, Handler, Operation, ScheduledOperation } from '@stock-bot/handlers'; -import type { IServiceContainer } from '@stock-bot/types'; +import type { IServiceContainer } from '@stock-bot/services'; import { clearPostgreSQLData } from './operations/clear-postgresql-data.operations'; import { getSyncStatus } from './operations/enhanced-sync-status.operations'; import { getExchangeStats } from './operations/exchange-stats.operations'; diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/operations/qm-exchanges.operations.ts b/apps/stock/data-pipeline/src/handlers/exchanges/operations/qm-exchanges.operations.ts index 761fdb3b..69892edb 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/operations/qm-exchanges.operations.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/operations/qm-exchanges.operations.ts @@ -1,5 +1,5 @@ import { getLogger } from '@stock-bot/logger'; -import type { IServiceContainer } from '@stock-bot/types'; +import type { IServiceContainer } from '@stock-bot/services'; import type { JobPayload } from '../../../types/job-payloads'; const logger = getLogger('sync-qm-exchanges'); diff --git a/apps/stock/data-pipeline/src/handlers/index.ts b/apps/stock/data-pipeline/src/handlers/index.ts index a41a377a..9fef2055 100644 --- a/apps/stock/data-pipeline/src/handlers/index.ts +++ b/apps/stock/data-pipeline/src/handlers/index.ts @@ -3,7 +3,7 @@ */ import { getLogger } from '@stock-bot/logger'; -import type { IServiceContainer } from '@stock-bot/types'; +import type { IServiceContainer } from '@stock-bot/services'; // Import handlers directly import { ExchangesHandler } from './exchanges/exchanges.handler'; import { SymbolsHandler } from './symbols/symbols.handler'; 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 cc6ff287..cbecfdbc 100644 --- a/apps/stock/data-pipeline/src/routes/enhanced-sync.routes.ts +++ b/apps/stock/data-pipeline/src/routes/enhanced-sync.routes.ts @@ -11,14 +11,14 @@ export function createEnhancedSyncRoutes(container: IServiceContainer) { enhancedSync.post('/exchanges/all', async c => { try { const clearFirst = c.req.query('clear') === 'true'; - const queueManager = container.queue; + const queueManager = container.queueManager; if (!queueManager) { return c.json({ success: false, error: 'Queue manager not available' }, 503); } const exchangesQueue = queueManager.getQueue('exchanges'); - const job = await exchangesQueue.addJob('sync-all-exchanges', { + const job = await exchangesQueue.add('sync-all-exchanges', { handler: 'exchanges', operation: 'sync-all-exchanges', payload: { clearFirst }, @@ -36,14 +36,14 @@ export function createEnhancedSyncRoutes(container: IServiceContainer) { enhancedSync.post('/provider-mappings/qm', async c => { try { - const queueManager = container.queue; + const queueManager = container.queueManager; if (!queueManager) { return c.json({ success: false, error: 'Queue manager not available' }, 503); } const exchangesQueue = queueManager.getQueue('exchanges'); - const job = await exchangesQueue.addJob('sync-qm-provider-mappings', { + const job = await exchangesQueue.add('sync-qm-provider-mappings', { handler: 'exchanges', operation: 'sync-qm-provider-mappings', payload: {}, @@ -65,14 +65,14 @@ export function createEnhancedSyncRoutes(container: IServiceContainer) { enhancedSync.post('/provider-mappings/ib', async c => { try { - const queueManager = container.queue; + const queueManager = container.queueManager; if (!queueManager) { return c.json({ success: false, error: 'Queue manager not available' }, 503); } const exchangesQueue = queueManager.getQueue('exchanges'); - const job = await exchangesQueue.addJob('sync-ib-exchanges', { + const job = await exchangesQueue.add('sync-ib-exchanges', { handler: 'exchanges', operation: 'sync-ib-exchanges', payload: {}, @@ -94,14 +94,14 @@ export function createEnhancedSyncRoutes(container: IServiceContainer) { enhancedSync.get('/status', async c => { try { - const queueManager = container.queue; + const queueManager = container.queueManager; if (!queueManager) { return c.json({ success: false, error: 'Queue manager not available' }, 503); } const symbolsQueue = queueManager.getQueue('symbols'); - const job = await symbolsQueue.addJob('sync-status', { + const job = await symbolsQueue.add('sync-status', { handler: 'symbols', operation: 'sync-status', payload: {}, @@ -120,14 +120,14 @@ export function createEnhancedSyncRoutes(container: IServiceContainer) { enhancedSync.post('/clear/postgresql', async c => { try { const dataType = c.req.query('type') as 'exchanges' | 'provider_mappings' | 'all'; - const queueManager = container.queue; + const queueManager = container.queueManager; if (!queueManager) { return c.json({ success: false, error: 'Queue manager not available' }, 503); } const exchangesQueue = queueManager.getQueue('exchanges'); - const job = await exchangesQueue.addJob('clear-postgresql-data', { + const job = await exchangesQueue.add('clear-postgresql-data', { handler: 'exchanges', operation: 'clear-postgresql-data', payload: { dataType: dataType || 'all' }, diff --git a/apps/stock/data-pipeline/src/routes/stats.routes.ts b/apps/stock/data-pipeline/src/routes/stats.routes.ts index 4340e98d..03c54f20 100644 --- a/apps/stock/data-pipeline/src/routes/stats.routes.ts +++ b/apps/stock/data-pipeline/src/routes/stats.routes.ts @@ -10,21 +10,21 @@ export function createStatsRoutes(container: IServiceContainer) { // Statistics endpoints stats.get('/exchanges', async c => { try { - const queueManager = container.queue; + const queueManager = container.queueManager; if (!queueManager) { return c.json({ error: 'Queue manager not available' }, 503); } const exchangesQueue = queueManager.getQueue('exchanges'); - const job = await exchangesQueue.addJob('get-exchange-stats', { + const job = await exchangesQueue.add('get-exchange-stats', { handler: 'exchanges', operation: 'get-exchange-stats', payload: {}, }); // Wait for job to complete and return result - const result = await job.waitUntilFinished(); + const result = await exchangesQueue.waitForJob(job); return c.json(result); } catch (error) { logger.error('Failed to get exchange stats', { error }); @@ -34,21 +34,21 @@ export function createStatsRoutes(container: IServiceContainer) { stats.get('/provider-mappings', async c => { try { - const queueManager = container.queue; + const queueManager = container.queueManager; if (!queueManager) { return c.json({ error: 'Queue manager not available' }, 503); } const exchangesQueue = queueManager.getQueue('exchanges'); - const job = await exchangesQueue.addJob('get-provider-mapping-stats', { + const job = await exchangesQueue.add('get-provider-mapping-stats', { handler: 'exchanges', operation: 'get-provider-mapping-stats', payload: {}, }); // Wait for job to complete and return result - const result = await job.waitUntilFinished(); + const result = await exchangesQueue.waitForJob(job); return c.json(result); } catch (error) { logger.error('Failed to get provider mapping stats', { error }); diff --git a/apps/stock/data-pipeline/src/routes/sync.routes.ts b/apps/stock/data-pipeline/src/routes/sync.routes.ts index 99ad8395..92e11308 100644 --- a/apps/stock/data-pipeline/src/routes/sync.routes.ts +++ b/apps/stock/data-pipeline/src/routes/sync.routes.ts @@ -10,14 +10,14 @@ export function createSyncRoutes(container: IServiceContainer) { // Manual sync trigger endpoints sync.post('/symbols', async c => { try { - const queueManager = container.queue; + const queueManager = container.queueManager; if (!queueManager) { return c.json({ success: false, error: 'Queue manager not available' }, 503); } const symbolsQueue = queueManager.getQueue('symbols'); - const job = await symbolsQueue.addJob('sync-qm-symbols', { + const job = await symbolsQueue.add('sync-qm-symbols', { handler: 'symbols', operation: 'sync-qm-symbols', payload: {}, @@ -35,14 +35,14 @@ export function createSyncRoutes(container: IServiceContainer) { sync.post('/exchanges', async c => { try { - const queueManager = container.queue; + const queueManager = container.queueManager; if (!queueManager) { return c.json({ success: false, error: 'Queue manager not available' }, 503); } const exchangesQueue = queueManager.getQueue('exchanges'); - const job = await exchangesQueue.addJob('sync-qm-exchanges', { + const job = await exchangesQueue.add('sync-qm-exchanges', { handler: 'exchanges', operation: 'sync-qm-exchanges', payload: {}, @@ -61,14 +61,14 @@ export function createSyncRoutes(container: IServiceContainer) { sync.post('/symbols/:provider', async c => { try { const provider = c.req.param('provider'); - const queueManager = container.queue; + const queueManager = container.queueManager; if (!queueManager) { return c.json({ success: false, error: 'Queue manager not available' }, 503); } const symbolsQueue = queueManager.getQueue('symbols'); - const job = await symbolsQueue.addJob('sync-symbols-from-provider', { + const job = await symbolsQueue.add('sync-symbols-from-provider', { handler: 'symbols', operation: 'sync-symbols-from-provider', payload: { provider }, diff --git a/apps/stock/data-pipeline/tsconfig.json b/apps/stock/data-pipeline/tsconfig.json index 33469657..775d1cb9 100644 --- a/apps/stock/data-pipeline/tsconfig.json +++ b/apps/stock/data-pipeline/tsconfig.json @@ -1,5 +1,8 @@ { "extends": "../../../tsconfig.app.json", + "compilerOptions": { "rootDir": "./src", "outDir": "./dist" }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"], "references": [ { "path": "../../../libs/core/types" }, { "path": "../../../libs/core/config" }, diff --git a/apps/stock/engine/index.cjs b/apps/stock/engine/index.cjs new file mode 100644 index 00000000..2f809ed2 --- /dev/null +++ b/apps/stock/engine/index.cjs @@ -0,0 +1,10 @@ +const { join } = require('node:path'); + +const nativeBinding = require(join(__dirname, 'dist', 'engine.node')); + +module.exports = { + ...nativeBinding, + IncrementalSMA: nativeBinding.IncrementalSma, + IncrementalEMA: nativeBinding.IncrementalEma, + IncrementalRSI: nativeBinding.IncrementalRsi, +}; diff --git a/apps/stock/engine/index.d.ts b/apps/stock/engine/index.d.ts new file mode 100644 index 00000000..963a5065 --- /dev/null +++ b/apps/stock/engine/index.d.ts @@ -0,0 +1,9 @@ +export * from './dist/index'; +export { + IncrementalSma as IncrementalSMA, + IncrementalEma as IncrementalEMA, + IncrementalRsi as IncrementalRSI, +} from './dist/index'; + +declare const nativeBinding: typeof import('./dist/index'); +export default nativeBinding; diff --git a/apps/stock/engine/index.mjs b/apps/stock/engine/index.mjs index 8e6c6d26..97d902d5 100644 --- a/apps/stock/engine/index.mjs +++ b/apps/stock/engine/index.mjs @@ -1,36 +1,40 @@ -// ESM wrapper for the native module -import { createRequire } from 'module'; -import { fileURLToPath } from 'url'; -import { dirname, join } from 'path'; - -const require = createRequire(import.meta.url); -const __filename = fileURLToPath(import.meta.url); -const __dirname = dirname(__filename); - -const nativeBinding = require(join(__dirname, 'index.node')); - -export const { - TradingEngine, - BacktestEngine, - TechnicalIndicators, - IncrementalSMA, - IncrementalEMA, - IncrementalRSI, - RiskAnalyzer, - OrderbookAnalyzer, - MarketData, - MarketUpdate, - Order, - Fill, - Position, - RiskLimits, - RiskMetrics, - ExecutionResult, - OrderBookLevel, - OrderBookSnapshot, - MarketMicrostructure, - PositionUpdate, - RiskCheckResult -} = nativeBinding; - -export default nativeBinding; \ No newline at end of file +// ESM wrapper for the native module +import { createRequire } from 'module'; +import { dirname, join } from 'path'; +import { fileURLToPath } from 'url'; + +const require = createRequire(import.meta.url); +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +const nativeBinding = require(join(__dirname, 'dist', 'engine.node')); + +export const { + TradingEngine, + BacktestEngine, + TechnicalIndicators, + IncrementalSma, + IncrementalEma, + IncrementalRsi, + RiskAnalyzer, + OrderbookAnalyzer, + MarketData, + MarketUpdate, + Order, + Fill, + Position, + RiskLimits, + RiskMetrics, + ExecutionResult, + OrderBookLevel, + OrderBookSnapshot, + MarketMicrostructure, + PositionUpdate, + RiskCheckResult, +} = nativeBinding; + +export const IncrementalSMA = IncrementalSma; +export const IncrementalEMA = IncrementalEma; +export const IncrementalRSI = IncrementalRsi; + +export default nativeBinding; diff --git a/apps/stock/engine/package.json b/apps/stock/engine/package.json index 9b4e57e3..a0aeeb7c 100644 --- a/apps/stock/engine/package.json +++ b/apps/stock/engine/package.json @@ -6,16 +6,16 @@ "types": "index.d.ts", "exports": { ".": { + "types": "./index.d.ts", "import": "./index.mjs", - "require": "./index.js", - "types": "./index.d.ts" + "require": "./index.cjs" } }, "files": [ "index.d.ts", - "index.js", "index.mjs", - "index.node" + "index.cjs", + "dist" ], "napi": { "name": "engine", @@ -30,14 +30,14 @@ } }, "scripts": { - "build": "cargo-cp-artifact -nc index.node -- cargo build --message-format=json-render-diagnostics", + "build": "napi build dist --dts index.d.ts --no-dts-header", "build:debug": "npm run build --", "build:release": "npm run build -- --release", - "build:napi": "napi build --platform --release", + "build:napi": "bun run build --release", "test": "cargo test" }, "devDependencies": { "@napi-rs/cli": "^2.16.3", "cargo-cp-artifact": "^0.1" } -} \ No newline at end of file +} diff --git a/apps/stock/orchestrator/package.json b/apps/stock/orchestrator/package.json index 4414ce39..c0ca19db 100644 --- a/apps/stock/orchestrator/package.json +++ b/apps/stock/orchestrator/package.json @@ -1,40 +1,48 @@ -{ - "name": "@stock-bot/orchestrator", - "version": "0.1.0", - "description": "Trading system orchestrator - coordinates between Rust core, data feeds, and analytics", - "type": "module", - "main": "dist/index.js", - "scripts": { - "dev": "bun --watch src/index.ts", - "build": "bun build src/index.ts --outdir dist --target node", - "start": "bun dist/index.js", - "test": "bun test", - "test:indicators": "bun test tests/indicators.test.ts", - "example:indicators": "bun run examples/indicator-usage.ts", - "test:engine": "bun run examples/test-engine-import.ts", - "build:rust": "cd ../engine && cargo build --release && napi build --platform --release" - }, - "dependencies": { - "@stock-bot/engine": "*", - "@stock-bot/cache": "*", - "@stock-bot/config": "*", - "@stock-bot/di": "*", - "@stock-bot/logger": "*", - "@stock-bot/questdb": "*", - "@stock-bot/queue": "*", - "@stock-bot/shutdown": "*", - "@stock-bot/stock-config": "*", - "@stock-bot/utils": "*", - "hono": "^4.0.0", - "socket.io": "^4.7.2", - "socket.io-client": "^4.7.2", - "zod": "^3.22.0", - "uuid": "^9.0.0", - "axios": "^1.6.0", - "simple-statistics": "^7.8.3" - }, - "devDependencies": { - "@types/node": "^20.0.0", - "typescript": "^5.0.0" - } -} \ No newline at end of file +{ + "name": "@stock-bot/orchestrator", + "version": "0.1.0", + "description": "Trading system orchestrator - coordinates between Rust core, data feeds, and analytics", + "type": "module", + "main": "dist/index.js", + "scripts": { + "dev": "bun --watch src/index.ts", + "build": "bun build src/index.ts --outdir dist --target node --external @stock-bot/engine --external @tensorflow/tfjs-node", + "start": "bun dist/index.js", + "test": "bun test", + "test:indicators": "bun test tests/indicators.test.ts", + "example:indicators": "bun run examples/indicator-usage.ts", + "test:engine": "bun run examples/test-engine-import.ts", + "build:rust": "cd ../engine && cargo build --release && napi build --platform --release" + }, + "dependencies": { + "@stock-bot/engine": "*", + "@stock-bot/cache": "*", + "@stock-bot/config": "*", + "@stock-bot/di": "*", + "@stock-bot/logger": "*", + "@stock-bot/questdb": "*", + "@stock-bot/queue": "*", + "@stock-bot/shutdown": "*", + "@stock-bot/stock-config": "*", + "@stock-bot/utils": "*", + "hono": "^4.0.0", + "socket.io": "^4.7.2", + "socket.io-client": "^4.7.2", + "zod": "^3.22.0", + "uuid": "^9.0.0", + "axios": "^1.6.0", + "simple-statistics": "^7.8.3" + }, + "peerDependencies": { + "@tensorflow/tfjs-node": "^4.0.0" + }, + "peerDependenciesMeta": { + "@tensorflow/tfjs-node": { + "optional": true + } + }, + "devDependencies": { + "@types/node": "^20.0.0", + "typescript": "^5.0.0" + } +} diff --git a/apps/stock/orchestrator/tsconfig.json b/apps/stock/orchestrator/tsconfig.json index 3f4bca26..877b067b 100644 --- a/apps/stock/orchestrator/tsconfig.json +++ b/apps/stock/orchestrator/tsconfig.json @@ -1,34 +1,34 @@ -{ - "compilerOptions": { - "target": "ESNext", - "module": "ESNext", - "lib": ["ESNext"], - "moduleResolution": "bundler", - "moduleDetection": "force", - "allowImportingTsExtensions": true, - "strict": true, - "downlevelIteration": true, - "skipLibCheck": true, - "jsx": "preserve", - "allowSyntheticDefaultImports": true, - "forceConsistentCasingInFileNames": true, - "allowJs": true, - "types": ["bun-types"], - "esModuleInterop": true, - "resolveJsonModule": true, - "noEmit": true, - "composite": true, - "declaration": true, - "declarationMap": true, - "sourceMap": true, - "outDir": "./dist", - "rootDir": "./src", - "paths": { - "@stock-bot/engine": ["../engine/index"], - "@stock-bot/engine/*": ["../engine/*"] - }, - "baseUrl": "." - }, - "include": ["src/**/*"], - "exclude": ["node_modules", "dist"] -} \ No newline at end of file +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "lib": ["ESNext"], + "moduleResolution": "bundler", + "moduleDetection": "force", + "allowImportingTsExtensions": true, + "strict": true, + "downlevelIteration": true, + "skipLibCheck": true, + "jsx": "preserve", + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "allowJs": true, + "types": ["bun-types"], + "esModuleInterop": true, + "resolveJsonModule": true, + "noEmit": true, + "composite": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "outDir": "./dist", + "rootDir": "./src", + "paths": { + "@stock-bot/engine": ["../engine/index"], + "@stock-bot/engine/*": ["../engine/*"] + }, + "baseUrl": "." + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/apps/stock/package.json b/apps/stock/package.json index be8e4962..015f6d88 100644 --- a/apps/stock/package.json +++ b/apps/stock/package.json @@ -69,5 +69,5 @@ "node": ">=18.0.0", "bun": ">=1.1.0" }, - "packageManager": "bun@1.1.12" + "packageManager": "bun@1.2.17" } diff --git a/apps/stock/web-api/package.json b/apps/stock/web-api/package.json index 64a7bbc2..a01aee7b 100644 --- a/apps/stock/web-api/package.json +++ b/apps/stock/web-api/package.json @@ -12,6 +12,8 @@ "clean": "rm -rf dist" }, "dependencies": { + "@stock-bot/queue": "workspace:*", + "@stock-bot/services": "workspace:*", "@stock-bot/config": "*", "@stock-bot/stock-config": "*", "@stock-bot/logger": "*", diff --git a/apps/stock/web-api/src/routes/exchange.routes.ts b/apps/stock/web-api/src/routes/exchange.routes.ts index bf6357de..035ff243 100644 --- a/apps/stock/web-api/src/routes/exchange.routes.ts +++ b/apps/stock/web-api/src/routes/exchange.routes.ts @@ -3,7 +3,7 @@ */ import { Hono } from 'hono'; import { getLogger } from '@stock-bot/logger'; -import type { IServiceContainer } from '@stock-bot/types'; +import type { IServiceContainer } from '@stock-bot/services'; import { createExchangeService } from '../services/exchange.service'; import { createSuccessResponse, handleError } from '../utils/error-handler'; import { diff --git a/apps/stock/web-api/src/services/exchange.service.ts b/apps/stock/web-api/src/services/exchange.service.ts index 528eed4d..f1f570b6 100644 --- a/apps/stock/web-api/src/services/exchange.service.ts +++ b/apps/stock/web-api/src/services/exchange.service.ts @@ -1,5 +1,5 @@ import { getLogger } from '@stock-bot/logger'; -import type { IServiceContainer } from '@stock-bot/types'; +import type { IServiceContainer } from '@stock-bot/services'; import { CreateExchangeRequest, CreateProviderMappingRequest, diff --git a/apps/stock/web-api/src/services/pipeline.service.ts b/apps/stock/web-api/src/services/pipeline.service.ts index 4162e4a3..81036f6f 100644 --- a/apps/stock/web-api/src/services/pipeline.service.ts +++ b/apps/stock/web-api/src/services/pipeline.service.ts @@ -5,6 +5,7 @@ import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; +import { getFullQueueName } from '@stock-bot/queue'; const logger = getLogger('pipeline-service'); @@ -30,13 +31,13 @@ export class PipelineService { */ async syncQMSymbols(): Promise { try { - const queueManager = this.container.queue; + const queueManager = this.container.queueManager; if (!queueManager) { return { success: false, error: 'Queue manager not available' }; } - const symbolsQueue = queueManager.getQueue('symbols'); - const job = await symbolsQueue.addJob('sync-qm-symbols', { + const symbolsQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'symbols')); + const job = await symbolsQueue.add('sync-qm-symbols', { handler: 'symbols', operation: 'sync-qm-symbols', payload: {}, @@ -58,13 +59,13 @@ export class PipelineService { */ async syncQMExchanges(): Promise { try { - const queueManager = this.container.queue; + const queueManager = this.container.queueManager; if (!queueManager) { return { success: false, error: 'Queue manager not available' }; } - const exchangesQueue = queueManager.getQueue('exchanges'); - const job = await exchangesQueue.addJob('sync-qm-exchanges', { + const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges')); + const job = await exchangesQueue.add('sync-qm-exchanges', { handler: 'exchanges', operation: 'sync-qm-exchanges', payload: {}, @@ -86,13 +87,13 @@ export class PipelineService { */ async syncProviderSymbols(provider: string): Promise { try { - const queueManager = this.container.queue; + const queueManager = this.container.queueManager; if (!queueManager) { return { success: false, error: 'Queue manager not available' }; } - const symbolsQueue = queueManager.getQueue('symbols'); - const job = await symbolsQueue.addJob('sync-symbols-from-provider', { + const symbolsQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'symbols')); + const job = await symbolsQueue.add('sync-symbols-from-provider', { handler: 'symbols', operation: 'sync-symbols-from-provider', payload: { provider }, @@ -118,13 +119,13 @@ export class PipelineService { */ async syncAllExchanges(clearFirst: boolean = false): Promise { try { - const queueManager = this.container.queue; + const queueManager = this.container.queueManager; if (!queueManager) { return { success: false, error: 'Queue manager not available' }; } - const exchangesQueue = queueManager.getQueue('exchanges'); - const job = await exchangesQueue.addJob('sync-all-exchanges', { + const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges')); + const job = await exchangesQueue.add('sync-all-exchanges', { handler: 'exchanges', operation: 'sync-all-exchanges', payload: { clearFirst }, @@ -150,13 +151,13 @@ export class PipelineService { */ async syncQMProviderMappings(): Promise { try { - const queueManager = this.container.queue; + const queueManager = this.container.queueManager; if (!queueManager) { return { success: false, error: 'Queue manager not available' }; } - const exchangesQueue = queueManager.getQueue('exchanges'); - const job = await exchangesQueue.addJob('sync-qm-provider-mappings', { + const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges')); + const job = await exchangesQueue.add('sync-qm-provider-mappings', { handler: 'exchanges', operation: 'sync-qm-provider-mappings', payload: {}, @@ -182,13 +183,13 @@ export class PipelineService { */ async syncIBExchanges(): Promise { try { - const queueManager = this.container.queue; + const queueManager = this.container.queueManager; if (!queueManager) { return { success: false, error: 'Queue manager not available' }; } - const exchangesQueue = queueManager.getQueue('exchanges'); - const job = await exchangesQueue.addJob('sync-ib-exchanges', { + const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges')); + const job = await exchangesQueue.add('sync-ib-exchanges', { handler: 'exchanges', operation: 'sync-ib-exchanges', payload: {}, @@ -214,13 +215,13 @@ export class PipelineService { */ async getSyncStatus(): Promise { try { - const queueManager = this.container.queue; + const queueManager = this.container.queueManager; if (!queueManager) { return { success: false, error: 'Queue manager not available' }; } - const symbolsQueue = queueManager.getQueue('symbols'); - const job = await symbolsQueue.addJob('sync-status', { + const symbolsQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'symbols')); + const job = await symbolsQueue.add('sync-status', { handler: 'symbols', operation: 'sync-status', payload: {}, @@ -248,13 +249,13 @@ export class PipelineService { dataType: 'exchanges' | 'provider_mappings' | 'all' = 'all' ): Promise { try { - const queueManager = this.container.queue; + const queueManager = this.container.queueManager; if (!queueManager) { return { success: false, error: 'Queue manager not available' }; } - const exchangesQueue = queueManager.getQueue('exchanges'); - const job = await exchangesQueue.addJob('clear-postgresql-data', { + const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges')); + const job = await exchangesQueue.add('clear-postgresql-data', { handler: 'exchanges', operation: 'clear-postgresql-data', payload: { dataType }, @@ -280,20 +281,20 @@ export class PipelineService { */ async getExchangeStats(): Promise { try { - const queueManager = this.container.queue; + const queueManager = this.container.queueManager; if (!queueManager) { return { success: false, error: 'Queue manager not available' }; } - const exchangesQueue = queueManager.getQueue('exchanges'); - const job = await exchangesQueue.addJob('get-exchange-stats', { + const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges')); + const job = await exchangesQueue.add('get-exchange-stats', { handler: 'exchanges', operation: 'get-exchange-stats', payload: {}, }); // Wait for job to complete and return result - const result = await job.waitUntilFinished(); + const result = await exchangesQueue.waitForJob(job); return { success: true, data: result }; } catch (error) { logger.error('Failed to get exchange stats', { error }); @@ -309,20 +310,20 @@ export class PipelineService { */ async getProviderMappingStats(): Promise { try { - const queueManager = this.container.queue; + const queueManager = this.container.queueManager; if (!queueManager) { return { success: false, error: 'Queue manager not available' }; } - const exchangesQueue = queueManager.getQueue('exchanges'); - const job = await exchangesQueue.addJob('get-provider-mapping-stats', { + const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges')); + const job = await exchangesQueue.add('get-provider-mapping-stats', { handler: 'exchanges', operation: 'get-provider-mapping-stats', payload: {}, }); // Wait for job to complete and return result - const result = await job.waitUntilFinished(); + const result = await exchangesQueue.waitForJob(job); return { success: true, data: result }; } catch (error) { logger.error('Failed to get provider mapping stats', { error }); diff --git a/apps/stock/web-api/src/types.ts b/apps/stock/web-api/src/types.ts index 4a28ae91..83d5e66f 100644 --- a/apps/stock/web-api/src/types.ts +++ b/apps/stock/web-api/src/types.ts @@ -3,7 +3,7 @@ * Defines required services for web API handlers */ -import type { ServiceTypes } from '@stock-bot/types'; +import type { ServiceTypes } from '@stock-bot/services'; /** * Services required by web API handlers @@ -22,4 +22,4 @@ export type WebApiServices = ServiceTypes & { proxy: ServiceTypes['proxy']; questdb: ServiceTypes['questdb']; globalCache: ServiceTypes['globalCache']; -}; \ No newline at end of file +}; diff --git a/apps/stock/web-api/tsconfig.json b/apps/stock/web-api/tsconfig.json index 33469657..775d1cb9 100644 --- a/apps/stock/web-api/tsconfig.json +++ b/apps/stock/web-api/tsconfig.json @@ -1,5 +1,8 @@ { "extends": "../../../tsconfig.app.json", + "compilerOptions": { "rootDir": "./src", "outDir": "./dist" }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"], "references": [ { "path": "../../../libs/core/types" }, { "path": "../../../libs/core/config" }, diff --git a/bun.lock b/bun.lock index b7c6d5ad..e829db09 100644 --- a/bun.lock +++ b/bun.lock @@ -76,6 +76,7 @@ "@stock-bot/proxy": "*", "@stock-bot/questdb": "*", "@stock-bot/queue": "*", + "@stock-bot/services": "workspace:*", "@stock-bot/shutdown": "*", "@stock-bot/stock-config": "*", "@stock-bot/utils": "*", @@ -100,6 +101,7 @@ "@stock-bot/postgres": "*", "@stock-bot/questdb": "*", "@stock-bot/queue": "*", + "@stock-bot/services": "workspace:*", "@stock-bot/shutdown": "*", "@stock-bot/stock-config": "*", "hono": "^4.0.0", @@ -142,6 +144,12 @@ "@types/node": "^20.0.0", "typescript": "^5.0.0", }, + "peerDependencies": { + "@tensorflow/tfjs-node": "^4.0.0", + }, + "optionalPeers": [ + "@tensorflow/tfjs-node", + ], }, "apps/stock/web-api": { "name": "@stock-bot/web-api", @@ -153,6 +161,8 @@ "@stock-bot/logger": "*", "@stock-bot/mongodb": "*", "@stock-bot/postgres": "*", + "@stock-bot/queue": "workspace:*", + "@stock-bot/services": "workspace:*", "@stock-bot/shutdown": "*", "@stock-bot/stock-config": "*", "hono": "^4.0.0", @@ -242,6 +252,7 @@ "@stock-bot/proxy": "workspace:*", "@stock-bot/questdb": "workspace:*", "@stock-bot/queue": "workspace:*", + "@stock-bot/services": "workspace:*", "@stock-bot/shutdown": "workspace:*", "@stock-bot/types": "workspace:*", "awilix": "^12.0.5", @@ -286,6 +297,7 @@ "@stock-bot/config": "workspace:*", "@stock-bot/handler-registry": "workspace:*", "@stock-bot/logger": "workspace:*", + "@stock-bot/services": "workspace:*", "@stock-bot/types": "workspace:*", "@stock-bot/utils": "workspace:*", "mongodb": "^6.12.0", @@ -329,6 +341,21 @@ "typescript": "^5.3.0", }, }, + "libs/core/services": { + "name": "@stock-bot/services", + "version": "1.0.0", + "dependencies": { + "@stock-bot/browser": "workspace:*", + "@stock-bot/cache": "workspace:*", + "@stock-bot/logger": "workspace:*", + "@stock-bot/mongodb": "workspace:*", + "@stock-bot/postgres": "workspace:*", + "@stock-bot/proxy": "workspace:*", + "@stock-bot/questdb": "workspace:*", + "@stock-bot/queue": "workspace:*", + "playwright": "^1.40.0", + }, + }, "libs/core/shutdown": { "name": "@stock-bot/shutdown", "version": "1.0.0", @@ -928,6 +955,8 @@ "@stock-bot/queue": ["@stock-bot/queue@workspace:libs/core/queue"], + "@stock-bot/services": ["@stock-bot/services@workspace:libs/core/services"], + "@stock-bot/shutdown": ["@stock-bot/shutdown@workspace:libs/core/shutdown"], "@stock-bot/stock-app": ["@stock-bot/stock-app@workspace:apps/stock"], diff --git a/libs/core/config/turbo.json b/libs/core/config/turbo.json index 6d18e623..1a1d2ee5 100644 --- a/libs/core/config/turbo.json +++ b/libs/core/config/turbo.json @@ -2,8 +2,8 @@ "extends": ["//"], "tasks": { "build": { - "dependsOn": [], - "outputs": ["dist/**"], + "dependsOn": ["^build"], + "outputs": ["dist/**", "*.tsbuildinfo"], "inputs": [ "src/**", "package.json", diff --git a/libs/core/di/package.json b/libs/core/di/package.json index 293bdad2..58f19380 100644 --- a/libs/core/di/package.json +++ b/libs/core/di/package.json @@ -9,6 +9,7 @@ "test": "bun test" }, "dependencies": { + "@stock-bot/services": "workspace:*", "@stock-bot/config": "workspace:*", "@stock-bot/logger": "workspace:*", "@stock-bot/types": "workspace:*", diff --git a/libs/core/di/src/awilix-container.ts b/libs/core/di/src/awilix-container.ts index 1c779d36..7e3a0c8b 100644 --- a/libs/core/di/src/awilix-container.ts +++ b/libs/core/di/src/awilix-container.ts @@ -1,59 +1,7 @@ -/** - * Awilix DI Container Setup - * Creates a decoupled, reusable dependency injection container - */ +import type { AwilixContainer } from 'awilix'; +import type { ServiceDefinitions } from './container/types'; -import { type AwilixContainer } from 'awilix'; -import type { Browser } from '@stock-bot/browser'; -import type { CacheProvider } from '@stock-bot/cache'; -import type { Logger } from '@stock-bot/logger'; -import type { MongoDBClient } from '@stock-bot/mongodb'; -import type { PostgreSQLClient } from '@stock-bot/postgres'; -import type { ProxyManager } from '@stock-bot/proxy'; -import type { QuestDBClient } from '@stock-bot/questdb'; -import type { QueueManager } from '@stock-bot/queue'; -import type { IServiceContainer } from '@stock-bot/types'; -import type { AppConfig } from './config/schemas'; - -// Re-export for backward compatibility -export type { AppConfig }; - -/** - * Service type definitions for type-safe resolution - */ -export interface ServiceDefinitions { - // Configuration - config: AppConfig; - logger: Logger; - - // Core services - cache: CacheProvider | null; - proxyManager: ProxyManager | null; - browser: Browser; - queueManager: QueueManager | null; - - // Database clients - mongoClient: MongoDBClient | null; - postgresClient: PostgreSQLClient | null; - questdbClient: QuestDBClient | null; - - // Aggregate service container - serviceContainer: IServiceContainer; -} - -// Export typed container +// Compatibility exports use the same composition contract as the active builder. +export type { AppConfig } from './config/schemas'; +export type { ServiceCradle, ServiceDefinitions, ServiceContainerOptions } from './container/types'; export type ServiceContainer = AwilixContainer; -export type ServiceCradle = ServiceDefinitions; - -/** - * Service-specific options for container creation - */ -export interface ServiceContainerOptions { - enableQuestDB?: boolean; - enableMongoDB?: boolean; - enablePostgres?: boolean; - enableCache?: boolean; - enableQueue?: boolean; - enableBrowser?: boolean; - enableProxy?: boolean; -} diff --git a/libs/core/di/src/container/builder.ts b/libs/core/di/src/container/builder.ts index ee7914bf..87b9b0f5 100644 --- a/libs/core/di/src/container/builder.ts +++ b/libs/core/di/src/container/builder.ts @@ -2,6 +2,7 @@ import { asClass, asFunction, createContainer, InjectionMode, type AwilixContain import type { BaseAppConfig as StockBotAppConfig, UnifiedAppConfig } from '@stock-bot/config'; import { toUnifiedConfig } from '@stock-bot/config'; import { HandlerRegistry } from '@stock-bot/handler-registry'; +import type { IServiceContainer } from '@stock-bot/services'; import { appConfigSchema, type AppConfig } from '../config/schemas'; import { registerApplicationServices, @@ -163,7 +164,7 @@ export class ServiceContainerBuilder { // Register service container aggregate container.register({ - serviceContainer: asFunction( + serviceContainer: asFunction( ({ config: _config, logger, @@ -175,7 +176,7 @@ export class ServiceContainerBuilder { mongoClient, postgresClient, questdbClient, - }) => ({ + }: ServiceDefinitions) => ({ logger, cache, globalCache, diff --git a/libs/core/di/src/container/types.ts b/libs/core/di/src/container/types.ts index 7f5bf33a..a16b8760 100644 --- a/libs/core/di/src/container/types.ts +++ b/libs/core/di/src/container/types.ts @@ -7,7 +7,7 @@ import type { PostgreSQLClient } from '@stock-bot/postgres'; import type { ProxyManager } from '@stock-bot/proxy'; import type { QuestDBClient } from '@stock-bot/questdb'; import type { QueueManager } from '@stock-bot/queue'; -import type { IServiceContainer } from '@stock-bot/types'; +import type { IServiceContainer } from '@stock-bot/services'; import type { AppConfig } from '../config/schemas'; import type { HandlerScanner } from '../scanner'; @@ -24,7 +24,7 @@ export interface ServiceDefinitions { cache: CacheProvider | null; globalCache: CacheProvider | null; proxyManager: ProxyManager | null; - browser: Browser; + browser: Browser | null; queueManager: QueueManager | null; // Database clients diff --git a/libs/core/di/src/index.ts b/libs/core/di/src/index.ts index 9bc147d3..30de3048 100644 --- a/libs/core/di/src/index.ts +++ b/libs/core/di/src/index.ts @@ -5,7 +5,7 @@ export { OperationContext } from './operation-context'; export { calculatePoolSize, getServicePoolSize, getHandlerPoolSize } from './pool-size-calculator'; export { ServiceLifecycleManager } from './utils/lifecycle'; export { HandlerScanner } from './scanner/handler-scanner'; -export type { IServiceContainer } from '@stock-bot/types'; +export type { IServiceContainer } from '@stock-bot/services'; // Export schemas export { diff --git a/libs/core/di/src/service-application.ts b/libs/core/di/src/service-application.ts index f0df482b..373afc2f 100644 --- a/libs/core/di/src/service-application.ts +++ b/libs/core/di/src/service-application.ts @@ -8,7 +8,7 @@ import { toUnifiedConfig } from '@stock-bot/config'; import type { HandlerRegistry } from '@stock-bot/handler-registry'; import { getLogger, setLoggerConfig, shutdownLoggers, type Logger } from '@stock-bot/logger'; import { Shutdown, SHUTDOWN_DEFAULTS } from '@stock-bot/shutdown'; -import type { IServiceContainer } from '@stock-bot/types'; +import type { IServiceContainer } from '@stock-bot/services'; import type { AwilixContainer } from 'awilix'; import { Hono } from 'hono'; import { cors } from 'hono/cors'; diff --git a/libs/core/di/tsconfig.json b/libs/core/di/tsconfig.json index cd2db067..2c18f1ec 100644 --- a/libs/core/di/tsconfig.json +++ b/libs/core/di/tsconfig.json @@ -10,5 +10,10 @@ }, "include": ["src/**/*.ts"], "exclude": ["node_modules", "dist", "test"], - "references": [{ "path": "../config" }, { "path": "../logger" }, { "path": "../queue" }] + "references": [ + { "path": "../services" }, + { "path": "../config" }, + { "path": "../logger" }, + { "path": "../queue" } + ] } diff --git a/libs/core/handlers/package.json b/libs/core/handlers/package.json index 3a299045..894ffa24 100644 --- a/libs/core/handlers/package.json +++ b/libs/core/handlers/package.json @@ -10,6 +10,7 @@ "test": "bun test" }, "dependencies": { + "@stock-bot/services": "workspace:*", "@stock-bot/cache": "workspace:*", "@stock-bot/config": "workspace:*", "@stock-bot/handler-registry": "workspace:*", diff --git a/libs/core/handlers/src/base/BaseHandler.ts b/libs/core/handlers/src/base/BaseHandler.ts index c63d7d84..a9248f20 100644 --- a/libs/core/handlers/src/base/BaseHandler.ts +++ b/libs/core/handlers/src/base/BaseHandler.ts @@ -5,12 +5,11 @@ import type { HandlerConfigWithSchedule, HandlerMetadata, IHandler, - IServiceContainer, JobHandler, - ServiceTypes, } from '@stock-bot/types'; +import type { IServiceContainer, ServiceTypes } from '@stock-bot/services'; import { fetch } from '@stock-bot/utils'; -import type { Collection } from 'mongodb'; +import type { Collection, Document } from 'mongodb'; // Handler registry is now injected, not imported import { createJobHandler } from '../utils/create-job-handler'; @@ -63,7 +62,7 @@ export abstract class BaseHandler constructor.__handlerName || handlerName || this.constructor.name.toLowerCase(); // Flatten all services onto the handler instance - this.logger = getLogger(this.constructor.name) as TServices['logger']; + this.logger = (services.logger ?? getLogger(this.constructor.name)) as TServices['logger']; this.cache = services.cache as TServices['cache']; this.globalCache = services.globalCache as TServices['globalCache']; this.queueManager = services.queueManager as TServices['queueManager']; @@ -160,11 +159,11 @@ export abstract class BaseHandler /** * Get a MongoDB collection with type safety */ - protected collection(name: string): Collection { + protected collection(name: string): Collection { if (!this.mongodb) { throw new Error('MongoDB service is not available'); } - return this.mongodb.collection(name); + return this.mongodb.collection(name); } /** diff --git a/libs/core/handlers/src/index.ts b/libs/core/handlers/src/index.ts index 7ce2373a..6c4d9d05 100644 --- a/libs/core/handlers/src/index.ts +++ b/libs/core/handlers/src/index.ts @@ -14,6 +14,7 @@ export type { RateLimitOptions } from './decorators/rate-limit'; export { createJobHandler } from './utils/create-job-handler'; +export type { IServiceContainer, ServiceTypes } from '@stock-bot/services'; // Re-export commonly used types from @stock-bot/types for convenience export type { diff --git a/libs/core/handlers/test/base-handler-config.test.ts b/libs/core/handlers/test/base-handler-config.test.ts index df091c1b..c78cf5d1 100644 --- a/libs/core/handlers/test/base-handler-config.test.ts +++ b/libs/core/handlers/test/base-handler-config.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, mock } from 'bun:test'; -import type { ExecutionContext, IServiceContainer } from '@stock-bot/types'; +import type { ExecutionContext } from '@stock-bot/types'; +import type { IServiceContainer } from '@stock-bot/services'; import { BaseHandler } from '../src/base/BaseHandler'; // Test handler with metadata diff --git a/libs/core/handlers/test/base-handler-edge-cases.test.ts b/libs/core/handlers/test/base-handler-edge-cases.test.ts index 8c088183..6453a4da 100644 --- a/libs/core/handlers/test/base-handler-edge-cases.test.ts +++ b/libs/core/handlers/test/base-handler-edge-cases.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, mock } from 'bun:test'; -import type { ExecutionContext, IServiceContainer } from '@stock-bot/types'; +import type { ExecutionContext } from '@stock-bot/types'; +import type { IServiceContainer } from '@stock-bot/services'; import { BaseHandler, ScheduledHandler } from '../src/base/BaseHandler'; // Test handler implementation diff --git a/libs/core/handlers/test/base-handler-http.test.ts b/libs/core/handlers/test/base-handler-http.test.ts index d886f4e0..ffdf6026 100644 --- a/libs/core/handlers/test/base-handler-http.test.ts +++ b/libs/core/handlers/test/base-handler-http.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; -import type { ExecutionContext, IServiceContainer } from '@stock-bot/types'; +import type { ExecutionContext } from '@stock-bot/types'; +import type { IServiceContainer } from '@stock-bot/services'; import * as utils from '@stock-bot/utils'; import { BaseHandler } from '../src/base/BaseHandler'; diff --git a/libs/core/handlers/test/base-handler.test.ts b/libs/core/handlers/test/base-handler.test.ts index 2fec650e..87b1c914 100644 --- a/libs/core/handlers/test/base-handler.test.ts +++ b/libs/core/handlers/test/base-handler.test.ts @@ -6,7 +6,8 @@ import type { CacheProvider } from '@stock-bot/cache'; import type { Logger } from '@stock-bot/logger'; import type { SimpleProxyManager } from '@stock-bot/proxy'; import type { Queue, QueueManager } from '@stock-bot/queue'; -import type { ExecutionContext, IServiceContainer, ServiceTypes } from '@stock-bot/types'; +import type { ExecutionContext } from '@stock-bot/types'; +import type { IServiceContainer, ServiceTypes } from '@stock-bot/services'; import { BaseHandler, ScheduledHandler } from '../src/base/BaseHandler'; import { Handler, Operation } from '../src/decorators/decorators'; diff --git a/libs/core/handlers/test/handlers.test.ts b/libs/core/handlers/test/handlers.test.ts index e7011f2a..130c55c1 100644 --- a/libs/core/handlers/test/handlers.test.ts +++ b/libs/core/handlers/test/handlers.test.ts @@ -2,7 +2,8 @@ import { beforeEach, describe, expect, it, mock, type Mock } from 'bun:test'; import type { CacheProvider } from '@stock-bot/cache'; import type { Logger } from '@stock-bot/logger'; import type { Queue, QueueManager } from '@stock-bot/queue'; -import type { ExecutionContext, IServiceContainer, ServiceTypes } from '@stock-bot/types'; +import type { ExecutionContext } from '@stock-bot/types'; +import type { IServiceContainer, ServiceTypes } from '@stock-bot/services'; import { BaseHandler } from '../src/base/BaseHandler'; import { Handler, @@ -75,6 +76,7 @@ describe('BaseHandler', () => { const handler = new BaseHandler(mockServices, 'test-handler'); expect(handler).toBeDefined(); expect(handler.logger).toBeDefined(); + expect(handler.logger).toBe(mockServices.logger); }); it('should execute operations', async () => { diff --git a/libs/core/handlers/tsconfig.json b/libs/core/handlers/tsconfig.json index 6007caa4..a2c07439 100644 --- a/libs/core/handlers/tsconfig.json +++ b/libs/core/handlers/tsconfig.json @@ -7,6 +7,7 @@ }, "include": ["src/**/*"], "references": [ + { "path": "../services" }, { "path": "../config" }, { "path": "../logger" }, { "path": "../cache" }, diff --git a/libs/core/logger/src/index.ts b/libs/core/logger/src/index.ts index 81d9113d..56b421e5 100644 --- a/libs/core/logger/src/index.ts +++ b/libs/core/logger/src/index.ts @@ -8,4 +8,4 @@ export { Logger, getLogger, shutdownLoggers, setLoggerConfig } from './logger'; // Type definitions -export type { LogLevel, LogContext, LogMetadata, LoggerConfig } from './types'; +export type { LogLevel, LogContext, LogMetadata, LoggerConfig, LoggerLike } from './types'; diff --git a/libs/core/logger/src/types.ts b/libs/core/logger/src/types.ts index 557f9ae9..f0c91222 100644 --- a/libs/core/logger/src/types.ts +++ b/libs/core/logger/src/types.ts @@ -1,10 +1,15 @@ /** * Simplified type definitions for the logger library */ +import type { Logger } from './logger'; // Standard log levels (simplified to pino defaults) export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'; +/** Logging capability accepted by adapters, including console-compatible loggers. */ +export type LoggerLike = Pick> & + Partial>; + // Context that persists across log calls export interface LogContext { [key: string]: any; diff --git a/libs/core/queue/src/queue-manager.ts b/libs/core/queue/src/queue-manager.ts index 4eacbbe9..dcb00c5c 100644 --- a/libs/core/queue/src/queue-manager.ts +++ b/libs/core/queue/src/queue-manager.ts @@ -3,6 +3,7 @@ import type { CacheProvider } from '@stock-bot/cache'; import { createCache } from '@stock-bot/cache'; import type { HandlerRegistry } from '@stock-bot/handler-registry'; import { getLogger } from '@stock-bot/logger'; +import type { LoggerLike as Logger } from '@stock-bot/logger'; import Redis from 'ioredis'; import { Queue, type QueueWorkerConfig } from './queue'; import { QueueRateLimiter } from './rate-limiter'; @@ -19,16 +20,6 @@ import type { } from './types'; import { getRedisConnection } from './utils'; -// Logger interface for type safety -interface Logger { - info(message: string, meta?: Record): void; - error(message: string, meta?: Record): void; - warn(message: string, meta?: Record): void; - debug(message: string, meta?: Record): void; - trace(message: string, meta?: Record): void; - child?(name: string, context?: Record): Logger; -} - /** * QueueManager provides unified queue and cache management with service discovery * Handles both local and cross-service queue operations diff --git a/libs/core/queue/src/queue.ts b/libs/core/queue/src/queue.ts index b079beb0..e2a35f9f 100644 --- a/libs/core/queue/src/queue.ts +++ b/libs/core/queue/src/queue.ts @@ -1,19 +1,10 @@ import { Queue as BullQueue, QueueEvents, Worker, type Job } from 'bullmq'; +import type { LoggerLike as Logger } from '@stock-bot/logger'; // Handler registry will be injected import type { HandlerRegistry } from '@stock-bot/handler-registry'; import type { ExtendedJobOptions, JobData, JobOptions, QueueStats, RedisConfig } from './types'; import { getRedisConnection } from './utils'; -// Logger interface for type safety -interface Logger { - info(message: string, meta?: Record): void; - error(message: string, meta?: Record): void; - warn(message: string, meta?: Record): void; - debug(message: string, meta?: Record): void; - trace(message: string, meta?: Record): void; - child?(name: string, context?: Record): Logger; -} - export interface QueueWorkerConfig { workers?: number; concurrency?: number; @@ -205,6 +196,17 @@ export class Queue { return await this.bullQueue.getJob(jobId); } + /** Wait for a result using a QueueEvents connection owned by this queue. */ + async waitForJob(job: Job, timeout = 30000): Promise { + if (!this.queueEvents) { + this.queueEvents = new QueueEvents(this.queueName, { + connection: getRedisConnection(this.redisConfig), + }); + } + await this.queueEvents.waitUntilReady(); + return job.waitUntilFinished(this.queueEvents, timeout); + } + /** * Get jobs by state */ diff --git a/libs/core/queue/tsconfig.json b/libs/core/queue/tsconfig.json index 64b10ca1..d9e93a7a 100644 --- a/libs/core/queue/tsconfig.json +++ b/libs/core/queue/tsconfig.json @@ -9,7 +9,6 @@ "references": [ { "path": "../cache" }, { "path": "../handler-registry" }, - { "path": "../handlers" }, { "path": "../logger" }, { "path": "../types" } ] diff --git a/libs/core/queue/turbo.json b/libs/core/queue/turbo.json index 49d5a876..1a1d2ee5 100644 --- a/libs/core/queue/turbo.json +++ b/libs/core/queue/turbo.json @@ -2,8 +2,8 @@ "extends": ["//"], "tasks": { "build": { - "dependsOn": ["@stock-bot/cache#build", "@stock-bot/logger#build", "@stock-bot/types#build"], - "outputs": ["dist/**"], + "dependsOn": ["^build"], + "outputs": ["dist/**", "*.tsbuildinfo"], "inputs": [ "src/**", "package.json", diff --git a/libs/core/services/package.json b/libs/core/services/package.json new file mode 100644 index 00000000..e6ba70a8 --- /dev/null +++ b/libs/core/services/package.json @@ -0,0 +1,29 @@ +{ + "name": "@stock-bot/services", + "version": "1.0.0", + "private": true, + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "scripts": { + "build": "tsc", + "clean": "rm -rf dist" + }, + "dependencies": { + "@stock-bot/browser": "workspace:*", + "@stock-bot/cache": "workspace:*", + "@stock-bot/logger": "workspace:*", + "@stock-bot/mongodb": "workspace:*", + "@stock-bot/postgres": "workspace:*", + "@stock-bot/proxy": "workspace:*", + "@stock-bot/questdb": "workspace:*", + "@stock-bot/queue": "workspace:*", + "playwright": "^1.40.0" + } +} diff --git a/libs/core/services/src/index.ts b/libs/core/services/src/index.ts new file mode 100644 index 00000000..953fd227 --- /dev/null +++ b/libs/core/services/src/index.ts @@ -0,0 +1,44 @@ +import type { Browser as BrowserImplementation } from '@stock-bot/browser'; +import type { CacheProvider } from '@stock-bot/cache'; +import type { Logger as LoggerImplementation } from '@stock-bot/logger'; +import type { MongoDBClient as MongoDBImplementation } from '@stock-bot/mongodb'; +import type { PostgreSQLClient as PostgresImplementation } from '@stock-bot/postgres'; +import type { ProxyManager as ProxyImplementation } from '@stock-bot/proxy'; +import type { QuestDBClient as QuestDBImplementation } from '@stock-bot/questdb'; +import type { + Queue as QueueImplementation, + QueueManager as QueueManagerImplementation, +} from '@stock-bot/queue'; + +/** Public capabilities, derived from the owning adapter instead of copied signatures. */ +type Public = Pick; + +export type Logger = Public; +export type Queue = Public; +export type QueueManager = Public; +export type MongoDBClient = Public; +export type PostgresClient = Public; +export type QuestDBClient = Public; +export type Browser = Public; +export type ProxyManager = Public; +export type { CacheProvider, CacheStats } from '@stock-bot/cache'; +export type { BrowserContext, Page } from 'playwright'; +export type { ProxyInfo, ProxyStats } from '@stock-bot/proxy'; + +/** Disabled adapters are null; omitted capabilities are undefined. */ +export interface ServiceTypes { + logger: Logger; + cache?: CacheProvider | null; + globalCache?: CacheProvider | null; + queueManager?: QueueManager | null; + queue?: Queue | null; + proxy?: ProxyManager | null; + browser?: Browser | null; + mongodb?: MongoDBClient | null; + postgres?: PostgresClient | null; + questdb?: QuestDBClient | null; +} + +export interface IServiceContainer extends ServiceTypes { + readonly custom?: Record; +} diff --git a/libs/core/services/test/contracts.type-test.ts b/libs/core/services/test/contracts.type-test.ts new file mode 100644 index 00000000..19588da5 --- /dev/null +++ b/libs/core/services/test/contracts.type-test.ts @@ -0,0 +1,61 @@ +import type { Browser as BrowserImplementation } from '@stock-bot/browser'; +import type { MongoDBClient as MongoDBImplementation } from '@stock-bot/mongodb'; +import type { PostgreSQLClient as PostgresImplementation } from '@stock-bot/postgres'; +import type { ProxyManager as ProxyImplementation } from '@stock-bot/proxy'; +import type { QuestDBClient as QuestDBImplementation } from '@stock-bot/questdb'; +import type { + Queue as QueueImplementation, + QueueManager as QueueManagerImplementation, +} from '@stock-bot/queue'; +import type { + Browser, + IServiceContainer, + MongoDBClient, + PostgresClient, + ProxyManager, + QuestDBClient, + Queue, + QueueManager, +} from '../src'; + +// Implementations must remain assignable to the capabilities injected into consumers. +declare const implementations: { + browser: BrowserImplementation; + mongodb: MongoDBImplementation; + postgres: PostgresImplementation; + proxy: ProxyImplementation; + questdb: QuestDBImplementation; + queue: QueueImplementation; + queueManager: QueueManagerImplementation; +}; +implementations satisfies { + browser: Browser; + mongodb: MongoDBClient; + postgres: PostgresClient; + proxy: ProxyManager; + questdb: QuestDBClient; + queue: Queue; + queueManager: QueueManager; +}; + +declare const services: IServiceContainer; +services.queueManager?.getQueue('symbols').add('sync', { + handler: 'symbols', + operation: 'sync', + payload: {}, +}); +services.postgres?.connected; +services.mongodb?.collection<{ symbol: string }>('symbols').findOne({ symbol: 'AAPL' }); +services.browser?.createPageWithProxy('https://example.com'); + +// These obsolete APIs must not silently return through a copied service interface. +// @ts-expect-error An individual queue is not a queue manager. +services.queue?.getQueue('symbols'); +// @ts-expect-error The queue adapter exposes add(), not addJob(). +services.queue?.addJob('sync', {}); +// @ts-expect-error PostgreSQL exposes connected as a property. +services.postgres?.isConnected(); +// @ts-expect-error The browser capability is the managed adapter, not a Playwright Browser. +services.browser?.newPage(); +// @ts-expect-error A typed collection retains its document fields. +services.mongodb?.collection<{ symbol: string }>('symbols').findOne({ symbol: 123 }); diff --git a/libs/core/services/tsconfig.json b/libs/core/services/tsconfig.json new file mode 100644 index 00000000..36acf155 --- /dev/null +++ b/libs/core/services/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "rootDir": "./src", + "outDir": "./dist", + "composite": true + }, + "include": ["src/**/*.ts"], + "references": [ + { "path": "../../services/browser" }, + { "path": "../cache" }, + { "path": "../logger" }, + { "path": "../../data/mongodb" }, + { "path": "../../data/postgres" }, + { "path": "../../services/proxy" }, + { "path": "../../data/questdb" }, + { "path": "../queue" } + ] +} diff --git a/libs/core/types/src/index.ts b/libs/core/types/src/index.ts index af50f215..0cd7e5bf 100644 --- a/libs/core/types/src/index.ts +++ b/libs/core/types/src/index.ts @@ -61,27 +61,6 @@ export type { TypedJobHandler, } from './handlers'; -// Export service container interface -export type { IServiceContainer } from './service-container'; - -// Export service types -export type { - ServiceTypes, - Logger, - CacheProvider, - QueueManager, - Queue, - MongoDBClient, - PostgresClient, - QuestDBClient, - Browser, - BrowserContext, - Page, - ProxyManager, - ProxyInfo, - ProxyStats, -} from './services'; - // Export decorator types export type { ScheduleConfig, diff --git a/libs/core/types/src/service-container.ts b/libs/core/types/src/service-container.ts deleted file mode 100644 index de23db30..00000000 --- a/libs/core/types/src/service-container.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * Service Container Interface - * Pure interface definition with full type safety - * Used by both DI and Handlers packages - */ - -import type { ServiceTypes } from './services'; - -/** - * Universal service container interface - * Provides access to all common services in a type-safe manner - * Designed to work across different service contexts - */ -export interface IServiceContainer extends ServiceTypes { - // Optional extensions for future use - readonly custom?: Record; -} diff --git a/libs/core/types/src/services.ts b/libs/core/types/src/services.ts deleted file mode 100644 index 1009a2ec..00000000 --- a/libs/core/types/src/services.ts +++ /dev/null @@ -1,311 +0,0 @@ -/** - * Service Type Definitions - * Provides full type safety for all injected services - */ - -// Import actual service types from their packages -// These are type-only imports, so no runtime dependencies - -// Logger types -export interface Logger { - info(message: string, meta?: Record): void; - error(message: string, meta?: Record): void; - warn(message: string, meta?: Record): void; - debug(message: string, meta?: Record): void; - trace(message: string, meta?: Record): void; - fatal(message: string, meta?: Record): void; - child?(name: string, context?: Record): Logger; -} - -// Cache types - matches the actual CacheProvider interface from @stock-bot/cache -export interface CacheProvider { - get(key: string): Promise; - set( - key: string, - value: T, - options?: - | number - | { - ttl?: number; - preserveTTL?: boolean; - onlyIfExists?: boolean; - onlyIfNotExists?: boolean; - getOldValue?: boolean; - } - ): Promise; - del(key: string): Promise; - exists(key: string): Promise; - clear(): Promise; - keys(pattern: string): Promise; - getStats(): CacheStats; - health(): Promise; - waitForReady(timeout?: number): Promise; - isReady(): boolean; -} - -export interface CacheStats { - hits: number; - misses: number; - errors: number; - hitRate: number; - total: number; - uptime: number; -} - -// Queue Manager types -export interface QueueManager { - getQueue(queueName: string, options?: any): Queue; - createQueue(queueName: string, options?: any): Queue; - getOrCreateQueue(queueName: string, options?: any): Queue; - queueExists(queueName: string): boolean; - deleteQueue(queueName: string): Promise; - getQueueStats(queueName?: string): Promise; - getBatchCache(queueName: string): CacheProvider | null; - getRateLimiter(): any; - checkRateLimit(key: string, rule?: string): Promise<{ allowed: boolean; retryAfter?: number }>; - shutdown(): Promise; -} - -export interface Queue { - add(name: string, data: any, opts?: any): Promise; - addBulk(jobs: Array<{ name: string; data: any; opts?: any }>): Promise; - process(concurrency: number, processor: any): Promise; - process(name: string, concurrency: number, processor: any): Promise; - process(processor: any): Promise; - on(event: string, listener: (...args: any[]) => void): void; - pause(): Promise; - resume(): Promise; - close(): Promise; - clean(grace: number, limit?: number, type?: string): Promise; - getJobs(types: string[], start?: number, end?: number, asc?: boolean): Promise; - getJobCounts(...types: string[]): Promise>; - name: string; -} - -// MongoDB types -export interface MongoDBClient { - connect(): Promise; - disconnect(): Promise; - isConnected(): boolean; - getDb(dbName?: string): any; // MongoDB Db type - collection(name: string, dbName?: string): any; // MongoDB Collection - createCollection(name: string, options?: any, dbName?: string): Promise; - dropCollection(name: string, dbName?: string): Promise; - listCollections(dbName?: string): Promise>; - find(collection: string, filter?: any, options?: any, dbName?: string): Promise; - findOne( - collection: string, - filter: any, - options?: any, - dbName?: string - ): Promise; - insertOne(collection: string, document: T, options?: any, dbName?: string): Promise; - insertMany( - collection: string, - documents: T[], - options?: any, - dbName?: string - ): Promise; - updateOne( - collection: string, - filter: any, - update: any, - options?: any, - dbName?: string - ): Promise; - updateMany( - collection: string, - filter: any, - update: any, - options?: any, - dbName?: string - ): Promise; - deleteOne(collection: string, filter: any, options?: any, dbName?: string): Promise; - deleteMany(collection: string, filter: any, options?: any, dbName?: string): Promise; - countDocuments(collection: string, filter?: any, options?: any, dbName?: string): Promise; - aggregate( - collection: string, - pipeline: any[], - options?: any, - dbName?: string - ): Promise; - createIndex(collection: string, indexSpec: any, options?: any, dbName?: string): Promise; - dropIndex(collection: string, indexName: string, options?: any, dbName?: string): Promise; - listIndexes(collection: string, dbName?: string): Promise; - batchUpsert( - collection: string, - documents: T[], - uniqueKeys: string | string[], - options?: any, - dbName?: string - ): Promise; - batchUpsertStock( - collection: string, - documents: T[], - uniqueKeys: string | string[], - options?: any - ): Promise; - batchUpsertTrading( - collection: string, - documents: T[], - uniqueKeys: string | string[], - options?: any - ): Promise; - batchUpsertAnalytics( - collection: string, - documents: T[], - uniqueKeys: string | string[], - options?: any - ): Promise; -} - -// PostgreSQL types -export interface PostgresClient { - query(text: string, params?: any[]): Promise<{ rows: T[]; rowCount: number }>; - queryOne(text: string, params?: any[]): Promise; - execute(text: string, params?: any[]): Promise<{ rowCount: number }>; - transaction(callback: (client: any) => Promise): Promise; - insert(table: string, data: Record, returning?: string | string[]): Promise; - update( - table: string, - data: Record, - where: Record, - returning?: string | string[] - ): Promise; - delete(table: string, where: Record, returning?: string | string[]): Promise; - upsert( - table: string, - data: Record, - conflictColumns: string | string[], - returning?: string | string[] - ): Promise; - batchInsert( - table: string, - data: Record[], - returning?: string | string[] - ): Promise; - batchUpsert( - table: string, - data: Record[], - conflictColumns: string | string[], - returning?: string | string[] - ): Promise; - exists(table: string, where: Record): Promise; - count(table: string, where?: Record): Promise; - getClient(): Promise; - releaseClient(client: any): void; - end(): Promise; - isConnected(): boolean; -} - -// QuestDB types -export interface QuestDBClient { - connect(): Promise; - disconnect(): Promise; - isConnected(): boolean; - query(sql: string): Promise; - insert(table: string, data: Record | Record[]): Promise; - insertBatch(table: string, data: Record[]): Promise; - createTable(tableDef: any): Promise; - dropTable(tableName: string): Promise; - tableExists(tableName: string): Promise; - getTableSchema(tableName: string): Promise; - flush(): Promise; - insertWithTimestamp( - table: string, - data: Record, - timestamp?: Date | number - ): Promise; - batchInsertWithTimestamp( - table: string, - data: Array & { timestamp?: Date | number }> - ): Promise; -} - -// Browser types (Playwright) -export interface Browser { - newPage(): Promise; - newContext(options?: any): Promise; - close(): Promise; - isConnected(): boolean; - version(): string; -} - -export interface BrowserContext { - newPage(): Promise; - close(): Promise; - pages(): Page[]; - setDefaultTimeout(timeout: number): void; - setDefaultNavigationTimeout(timeout: number): void; - addCookies(cookies: any[]): Promise; - clearCookies(): Promise; -} - -export interface Page { - goto(url: string, options?: any): Promise; - waitForSelector(selector: string, options?: any): Promise; - click(selector: string, options?: any): Promise; - fill(selector: string, value: string, options?: any): Promise; - evaluate(pageFunction: any, arg?: any): Promise; - evaluateHandle(pageFunction: any, arg?: any): Promise; - screenshot(options?: any): Promise; - pdf(options?: any): Promise; - content(): Promise; - title(): Promise; - url(): string; - close(): Promise; - waitForTimeout(timeout: number): Promise; - waitForLoadState(state?: string, options?: any): Promise; - locator(selector: string): any; - $$(selector: string): Promise; - textContent(selector: string): Promise; -} - -// Proxy Manager types -export interface ProxyManager { - getProxy(): string | null; - getProxyInfo(): ProxyInfo | null; - getProxies(count: number, key?: string): Promise; - releaseProxy(proxy: ProxyInfo | string): Promise; - markProxyFailed(proxy: ProxyInfo | string, reason?: string): Promise; - getStats(): ProxyStats; - resetProxy(proxy: ProxyInfo | string): Promise; - blacklistProxy(proxy: ProxyInfo | string, duration?: number): Promise; - isBlacklisted(proxy: ProxyInfo | string): Promise; - refreshProxies(): Promise; -} - -// ProxyInfo should be imported from @stock-bot/proxy package -// to avoid duplication. Using minimal definition here for type compatibility -export interface ProxyInfo { - host: string; - port: number; - protocol: 'http' | 'https'; - username?: string; - password?: string; - [key: string]: any; // Allow additional properties from proxy package -} - -export interface ProxyStats { - total: number; - available: number; - inUse: number; - failed: number; - blacklisted: number; -} - -/** - * Complete service types for dependency injection - */ -export interface ServiceTypes { - logger: Logger; - cache?: CacheProvider; - globalCache?: CacheProvider; - queueManager?: QueueManager; - queue?: Queue; // Individual queue instance - proxy?: ProxyManager; - browser?: Browser; - mongodb?: MongoDBClient; - postgres?: PostgresClient; - questdb?: QuestDBClient; -} diff --git a/libs/data/mongodb/src/client.ts b/libs/data/mongodb/src/client.ts index 40eeafa0..88fa2233 100644 --- a/libs/data/mongodb/src/client.ts +++ b/libs/data/mongodb/src/client.ts @@ -1,5 +1,5 @@ import type { Logger } from '@stock-bot/logger'; -import type { OptionalUnlessRequiredId } from 'mongodb'; +import type { Document, OptionalUnlessRequiredId } from 'mongodb'; import { Collection, Db, MongoClient } from 'mongodb'; import type { ConnectionEvents, @@ -328,7 +328,7 @@ export class MongoDBClient { /** * Get a typed collection */ - getCollection(name: string, database?: string): Collection { + getCollection(name: string, database?: string): Collection { const db = this.getDatabase(database); return db.collection(name); } @@ -337,8 +337,8 @@ export class MongoDBClient { * Get a collection (interface compatibility method) * This method provides compatibility with the IMongoDBClient interface */ - collection(name: string, database?: string): Collection { - return this.getCollection(name, database); + collection(name: string, database?: string): Collection { + return this.getCollection(name, database); } /** diff --git a/libs/services/browser/turbo.json b/libs/services/browser/turbo.json index 76e50436..1a1d2ee5 100644 --- a/libs/services/browser/turbo.json +++ b/libs/services/browser/turbo.json @@ -2,8 +2,8 @@ "extends": ["//"], "tasks": { "build": { - "dependsOn": ["@stock-bot/logger#build"], - "outputs": ["dist/**"], + "dependsOn": ["^build"], + "outputs": ["dist/**", "*.tsbuildinfo"], "inputs": [ "src/**", "package.json", diff --git a/libs/services/proxy/tsconfig.json b/libs/services/proxy/tsconfig.json index 0c67432d..c3177f85 100644 --- a/libs/services/proxy/tsconfig.json +++ b/libs/services/proxy/tsconfig.json @@ -2,6 +2,7 @@ "extends": "../../../tsconfig.json", "compilerOptions": { "outDir": "./dist", + "composite": true, "rootDir": "./src", "declaration": true, "declarationMap": true, diff --git a/package.json b/package.json index d4184563..d6f6c2e3 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,11 @@ "build:all:clean": "./scripts/build-all.sh --clean", "build:all:verbose": "./scripts/build-all.sh --verbose", "build:libs": "./scripts/build-libs.sh", - "test": "turbo run test", + "typecheck": "tsc --project tsconfig.check.json --noEmit", + "check": "bun run scripts/check.ts", + "test:tooling": "bun test scripts/test/", + "test:contracts": "tsc --project tsconfig.contracts.json --noEmit", + "test": "turbo run test --filter=!@stock-bot/stock-app", "test:watch": "bun test --watch", "test:coverage": "bun test --coverage", "coverage": "bun run tools/coverage-cli/src/index.ts --reporters html markdown", @@ -19,11 +23,11 @@ "test:unit": "bun test test/unit", "test:integration": "bun test test/integration", "test:e2e": "bun test test/e2e", - "test:libs": "turbo run test --filter='./libs/*'", + "test:libs": "turbo run test --filter='./libs/**'", "test:apps": "turbo run test --filter=./apps/*/*", - "lint": "eslint apps libs --ext .ts,.tsx", - "lint:fix": "eslint apps libs --ext .ts,.tsx --fix", - "lint:check": "eslint apps libs --ext .ts,.tsx --max-warnings 0", + "lint": "eslint apps/stock libs tools --ext .ts,.tsx", + "lint:fix": "eslint apps/stock libs tools --ext .ts,.tsx --fix", + "lint:check": "eslint apps/stock libs tools --ext .ts,.tsx --max-warnings 0", "lint:apps": "eslint apps --ext .ts,.tsx", "lint:libs": "eslint libs --ext .ts,.tsx", "format": "./scripts/format.sh", @@ -102,10 +106,10 @@ "typescript": "^5.8.3", "yup": "^1.6.1" }, - "packageManager": "bun@1.1.12", + "packageManager": "bun@1.2.17", "engines": { "node": ">=18.0.0", - "bun": ">=1.1.0" + "bun": ">=1.2.17" }, "dependencies": { "@types/pg": "^8.15.4", diff --git a/scripts/build-all.sh b/scripts/build-all.sh index 1c420da2..374c3a28 100755 --- a/scripts/build-all.sh +++ b/scripts/build-all.sh @@ -1,158 +1,24 @@ -#!/bin/bash +#!/usr/bin/env bash +set -euo pipefail -# Build All Script for Stock Bot -# Builds libraries first, then apps with Turbo, then dashboard with Angular CLI +cd "$(dirname "${BASH_SOURCE[0]}")/.." -set -e - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -CYAN='\033[0;36m' -GRAY='\033[0;37m' -NC='\033[0m' # No Color - -# Default options -CLEAN=false -VERBOSE=false - -# Parse command line arguments -while [[ $# -gt 0 ]]; do - case $1 in - --clean|-c) - CLEAN=true - shift - ;; - --verbose|-v) - VERBOSE=true - shift - ;; - --help|-h) - echo "Usage: $0 [--clean] [--verbose]" - echo " --clean, -c Clean previous builds before building" - echo " --verbose, -v Show verbose output" - echo " --help, -h Show this help message" - exit 0 - ;; - *) - echo "Unknown option: $1" - echo "Use --help for usage information" - exit 1 - ;; - esac +args=() +for option in "$@"; do + case "$option" in + --clean|-c) args+=(--force) ;; + --verbose|-v) args+=(--output-logs=full) ;; + --dry|--dry=json|--dry-run|--dry-run=json) args+=("$option") ;; + --help|-h) + echo "Usage: $0 [--clean] [--verbose]" + echo " --clean Force every workspace build, ignoring cached results" + echo " --verbose Print complete workspace build logs" + exit 0 + ;; + *) echo "Unknown option: $option" >&2; exit 1 ;; + esac done -echo -e "${CYAN}๐Ÿš€ Starting complete build process...${NC}" - -# Store original location -ORIGINAL_DIR=$(pwd) - -# Find git root directory -GIT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null) -if [ $? -ne 0 ]; then - echo -e "${RED}Error: Not in a git repository. Please run this script from within the stock-bot git repository.${NC}" - exit 1 -fi - -cd "$GIT_ROOT" - -cleanup() { - cd "$ORIGINAL_DIR" -} - -# Set up cleanup on exit -trap cleanup EXIT - -# Step 1: Clean if requested -if [ "$CLEAN" = true ]; then - echo -e "${YELLOW}๐Ÿงน Cleaning previous builds...${NC}" - ./scripts/clean.sh --dist - if [ $? -ne 0 ]; then - echo -e "${RED}โŒ Clean failed${NC}" - exit 1 - fi -fi - -# Step 2: Build libraries first -echo -e "${GREEN}๐Ÿ“š Building libraries...${NC}" -./scripts/build-libs.sh -if [ $? -ne 0 ]; then - echo -e "${RED}โŒ Library build failed${NC}" - exit 1 -fi - -# Step 3: Build apps with Turbo (excluding dashboard) -echo -e "${GREEN}๐Ÿ—๏ธ Building applications with Turbo...${NC}" - -# Get list of apps excluding dashboard -if [ -d "apps" ]; then - app_dirs=$(find apps -maxdepth 1 -type d -name "*" ! -name "dashboard" ! -name "apps" | sort) - - if [ -n "$app_dirs" ]; then - # Build each app individually to avoid filter syntax issues - for app_dir in $app_dirs; do - app_name=$(basename "$app_dir") - app_path="./apps/$app_name" - echo -e "${CYAN} Building $app_name...${NC}" - - turbo_cmd="turbo run build --filter=$app_path" - - if [ "$VERBOSE" = true ]; then - echo -e "${GRAY} Running: $turbo_cmd${NC}" - fi - - eval $turbo_cmd - if [ $? -ne 0 ]; then - echo -e "${RED}โŒ Failed to build app: $app_name${NC}" - exit 1 - fi - done - - app_names=$(echo "$app_dirs" | xargs -n1 basename | tr '\n' ', ' | sed 's/,$//') - echo -e "${GREEN}โœ… Apps built successfully: $app_names${NC}" - else - echo -e "${YELLOW}โ„น๏ธ No non-dashboard apps found to build with Turbo${NC}" - fi -fi - -# Step 4: Build dashboard with Angular CLI -dashboard_path="apps/dashboard" -if [ -d "$dashboard_path" ]; then - echo -e "${GREEN}๐ŸŽจ Building Angular dashboard...${NC}" - - cd "$dashboard_path" - - # Check if ng is available - if ! command -v ng &> /dev/null; then - echo -e "${RED}โŒ Angular CLI not found. Installing...${NC}" - npm install -g @angular/cli - if [ $? -ne 0 ]; then - echo -e "${RED}โŒ Failed to install Angular CLI${NC}" - exit 1 - fi - fi - - # Build dashboard - ng build --configuration production - if [ $? -ne 0 ]; then - echo -e "${RED}โŒ Dashboard build failed${NC}" - exit 1 - fi - - echo -e "${GREEN}โœ… Dashboard built successfully${NC}" - cd "$ORIGINAL_DIR" -else - echo -e "${YELLOW}โš ๏ธ Dashboard not found at $dashboard_path${NC}" -fi - -echo -e "${GREEN}๐ŸŽ‰ Complete build finished successfully!${NC}" -echo "" -echo -e "${CYAN}Build Summary:${NC}" -echo -e "${GREEN} โœ… Libraries built${NC}" -if [ -n "$app_dirs" ]; then - echo -e "${GREEN} โœ… Apps built: $app_names${NC}" -fi -if [ -d "apps/dashboard" ]; then - echo -e "${GREEN} โœ… Dashboard built${NC}" -fi +# The stock-app package contains convenience commands, not buildable source. +# Select all leaf workspaces so nested stock services are actually built. +exec bun run turbo run build --filter='!@stock-bot/stock-app' "${args[@]}" diff --git a/scripts/build-libs.sh b/scripts/build-libs.sh index d7df8aef..8ba2cc17 100755 --- a/scripts/build-libs.sh +++ b/scripts/build-libs.sh @@ -1,92 +1,7 @@ -#!/bin/bash +#!/usr/bin/env bash +set -euo pipefail -# Build and install the new libraries +cd "$(dirname "${BASH_SOURCE[0]}")/.." -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -CYAN='\033[0;36m' -NC='\033[0m' # No Color - -echo -e "${CYAN}Building and installing new libraries...${NC}" - -# Store original location -ORIGINAL_DIR=$(pwd) - -# Find git root directory -GIT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null) -if [ $? -ne 0 ]; then - echo -e "${RED}Error: Not in a git repository. Please run this script from within the stock-bot git repository.${NC}" - exit 1 -fi - -cd "$GIT_ROOT" - -cleanup() { - cd "$ORIGINAL_DIR" -} - -# Set up cleanup on exit -trap cleanup EXIT - -# Build order is important due to dependencies -libs=( - # Core Libraries - minimal dependencies - "core/types" # Base types - no dependencies - "core/logger" # Logging utilities - depends on types - "core/config" # Configuration - depends on types and logger - - # Utils - needed by many libraries - "utils" # Utilities - minimal dependencies - - # Data access libraries - "data/mongodb" # MongoDB client - depends on core libs - "data/postgres" # PostgreSQL client - depends on core libs - "data/questdb" # QuestDB client - depends on core libs - - # Core infrastructure services - "core/shutdown" # Shutdown - no dependencies - "core/cache" # Cache - depends on core libs - "core/event-bus" # Event bus - depends on core libs - "core/handler-registry" # Handler registry - depends on core libs - "core/handlers" # Handlers - depends on core libs, handler-registry, and utils - "core/queue" # Queue - depends on core libs, cache, handlers, and handler-registry - - # Application services - "services/browser" # Browser - depends on core libs - "services/proxy" # Proxy manager - depends on core libs and cache - - # DI - dependency injection library - "core/di" # Dependency injection - depends on data, service libs, and handlers -) - -# Build each library in order -for lib in "${libs[@]}"; do - lib_path="$GIT_ROOT/libs/$lib" - - echo -e "${GREEN}Building $lib...${NC}" - cd "$lib_path" - - # Clean previous build artifacts - rm -rf dist tsconfig.tsbuildinfo - - # Use tsc with build mode to respect project references - # npx tsc -b - bun run build - - if [ $? -ne 0 ]; then - echo -e "${RED}Failed to build $lib. Exiting.${NC}" - exit 1 - fi - - # Verify build was successful - if [ -d "dist" ]; then - echo -e "${GREEN}โœ“ Built successfully${NC}" - else - echo -e "${RED}โœ— Build did not create dist directory${NC}" - exit 1 - fi -done - -echo -e "${GREEN}All libraries built successfully!${NC}" -cd "$GIT_ROOT" +# Turbo derives ordering from package dependencies, including contract packages. +exec bun run turbo run build --filter='./libs/**' "$@" diff --git a/scripts/check.ts b/scripts/check.ts new file mode 100644 index 00000000..cba18659 --- /dev/null +++ b/scripts/check.ts @@ -0,0 +1,42 @@ +/** Run every repository gate and report failures without hiding later checks. */ +import { fileURLToPath } from 'node:url'; + +export const checks = [ + 'build', + 'typecheck', + 'test:contracts', + 'test:tooling', + 'lint:check', +] as const; + +async function runTask(check: string): Promise { + process.stdout.write(`\nRunning ${check}\n`); + const child = Bun.spawn([process.execPath, 'run', check], { + cwd: fileURLToPath(new URL('..', import.meta.url)), + stdin: 'inherit', + stdout: 'inherit', + stderr: 'inherit', + }); + return child.exited; +} + +export async function runChecks( + tasks: readonly string[] = checks, + run: (task: string) => Promise = runTask +): Promise { + const failed: string[] = []; + for (const task of tasks) { + if ((await run(task)) !== 0) failed.push(task); + } + return failed; +} + +if (import.meta.main) { + const failed = await runChecks(); + if (failed.length > 0) { + process.stderr.write(`\nFailed checks: ${failed.join(', ')}\n`); + process.exitCode = 1; + } else { + process.stdout.write('\nAll repository checks passed.\n'); + } +} diff --git a/scripts/test/native-bindings.test.ts b/scripts/test/native-bindings.test.ts new file mode 100644 index 00000000..a6d05786 --- /dev/null +++ b/scripts/test/native-bindings.test.ts @@ -0,0 +1,18 @@ +import { createRequire } from 'node:module'; +import { describe, expect, it } from 'bun:test'; +import { IncrementalSMA, TechnicalIndicators } from '@stock-bot/engine'; + +describe('generated native bindings', () => { + it('ESM loads the generated artifact and exposes the documented constructor aliases', () => { + const sma = new IncrementalSMA(2); + sma.update(10); + expect(sma.update(12)).toBe(11); + expect(new TechnicalIndicators().calculateSma([1, 2, 3], 2)).toEqual([1.5, 2.5]); + }); + + it('CommonJS exposes the same native constructors', () => { + const binding = createRequire(import.meta.url)('@stock-bot/engine'); + expect(binding.TechnicalIndicators).toBe(TechnicalIndicators); + expect(binding.IncrementalSMA).toBe(IncrementalSMA); + }); +}); diff --git a/scripts/test/service-consumers.test.ts b/scripts/test/service-consumers.test.ts new file mode 100644 index 00000000..9c6ba873 --- /dev/null +++ b/scripts/test/service-consumers.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it, mock } from 'bun:test'; +import { getLogger } from '@stock-bot/logger'; +import type { IServiceContainer, QueueManager } from '@stock-bot/services'; +import { createQueueRoutes } from '../../apps/stock/data-ingestion/src/routes/queue.routes'; +import { PipelineService } from '../../apps/stock/web-api/src/services/pipeline.service'; + +function fixture() { + const job = { id: 'job-1' }; + const queue = { + add: mock(async () => job), + waitForJob: mock(async () => ({ exchanges: 12 })), + }; + const manager = { + getQueue: mock(() => queue), + getGlobalStats: mock(async () => ({ totalJobs: 3 })), + }; + const container: IServiceContainer = { + logger: getLogger('service-consumer-test'), + queueManager: manager as unknown as QueueManager, + }; + return { container, manager, queue, job }; +} + +describe('service consumers', () => { + it('the web API submits work to the pipeline queue through the real adapter API', async () => { + const { container, manager, queue } = fixture(); + const result = await new PipelineService(container).syncQMSymbols(); + expect(result.success).toBe(true); + expect(result.jobId).toBe('job-1'); + expect(manager.getQueue).toHaveBeenCalledWith('{data-pipeline_symbols}'); + expect(queue.add).toHaveBeenCalledWith('sync-qm-symbols', { + handler: 'symbols', + operation: 'sync-qm-symbols', + payload: {}, + }); + }); + + it('statistics wait for completion through the queue-owned events connection', async () => { + const { container, manager, queue, job } = fixture(); + const result = await new PipelineService(container).getExchangeStats(); + expect(result).toEqual({ success: true, data: { exchanges: 12 } }); + expect(manager.getQueue).toHaveBeenCalledWith('{data-pipeline_exchanges}'); + expect(queue.waitForJob).toHaveBeenCalledWith(job); + }); + + it('queue monitoring uses queueManager without requiring an individual queue', async () => { + const { container, manager } = fixture(); + const response = await createQueueRoutes(container).request('http://localhost/status'); + expect(response.status).toBe(200); + expect(manager.getGlobalStats).toHaveBeenCalledTimes(1); + expect(await response.json()).toMatchObject({ status: 'success', data: { totalJobs: 3 } }); + }); + + it('a missing queue manager produces an explicit unavailable result', async () => { + const { container } = fixture(); + container.queueManager = null; + expect(await new PipelineService(container).syncQMSymbols()).toEqual({ + success: false, + error: 'Queue manager not available', + }); + }); +}); diff --git a/scripts/test/workspace.test.ts b/scripts/test/workspace.test.ts new file mode 100644 index 00000000..e5f741b5 --- /dev/null +++ b/scripts/test/workspace.test.ts @@ -0,0 +1,101 @@ +import { existsSync, readFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'bun:test'; +import ts from 'typescript'; +import { runChecks } from '../check'; + +const root = fileURLToPath(new URL('../../', import.meta.url)); +const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')); +const packageFiles = [ + ...new Set( + manifest.workspaces.flatMap((pattern: string) => + Array.from(new Bun.Glob(`${pattern}/package.json`).scanSync({ cwd: root })) + ) + ), +]; + +function config(path: string) { + const result = ts.getParsedCommandLineOfConfigFile( + path, + {}, + { + ...ts.sys, + onUnRecoverableConfigFileDiagnostic(diagnostic) { + throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')); + }, + } + ); + if (!result) throw new Error(`Cannot read ${path}`); + return result; +} + +describe('workspace verification', () => { + it('the real root build selects every buildable workspace and excludes the command aggregate', () => { + const result = Bun.spawnSync([process.execPath, 'run', 'build', '--dry=json'], { + cwd: root, + env: { ...process.env, TURBO_TELEMETRY_DISABLED: '1' }, + }); + expect(result.exitCode).toBe(0); + const plan = JSON.parse(new TextDecoder().decode(result.stdout)); + const planned = new Set(plan.tasks.map((task: { taskId: string }) => task.taskId)); + for (const file of packageFiles) { + const pkg = JSON.parse(readFileSync(join(root, file), 'utf8')); + if (pkg.scripts?.build && pkg.name !== '@stock-bot/stock-app') { + expect(planned.has(`${pkg.name}#build`)).toBe(true); + } + } + expect(planned.has('@stock-bot/stock-app#build')).toBe(false); + }); + + it('each TypeScript workspace has source inputs covered by the root type check', () => { + const checked = new Set( + config(join(root, 'tsconfig.check.json')).fileNames.map(file => resolve(file)) + ); + for (const file of packageFiles) { + const directory = join(root, dirname(file)); + const project = join(directory, 'tsconfig.json'); + if (!existsSync(join(directory, 'src')) || !existsSync(project)) continue; + const parsed = config(project); + expect(parsed.errors).toHaveLength(0); + expect(parsed.fileNames.length).toBeGreaterThan(0); + for (const source of parsed.fileNames.filter(path => /\.tsx?$/.test(path))) { + expect(checked.has(resolve(source))).toBe(true); + } + } + }); + + it('the package dependency graph remains acyclic', () => { + const packages = new Map(); + for (const file of packageFiles) { + const pkg = JSON.parse(readFileSync(join(root, file), 'utf8')); + packages.set(pkg.name, Object.keys(pkg.dependencies ?? {})); + } + function visit(name: string, stack: string[]) { + if (stack.includes(name)) + throw new Error(`Dependency cycle: ${[...stack, name].join(' -> ')}`); + for (const dependency of packages.get(name) ?? []) { + if (packages.has(dependency)) visit(dependency, [...stack, name]); + } + } + for (const name of packages.keys()) visit(name, []); + }); + + it('the foundational types package has no adapter dependencies', () => { + const pkg = JSON.parse(readFileSync(join(root, 'libs/core/types/package.json'), 'utf8')); + expect(Object.keys(pkg.dependencies ?? {})).toHaveLength(0); + const source = readFileSync(join(root, 'libs/core/types/src/index.ts'), 'utf8'); + expect(source).not.toContain('./services'); + expect(source).not.toContain('./service-container'); + }); + + it('a failed gate does not prevent later gates from running', async () => { + const visited: string[] = []; + const failed = await runChecks(['build', 'typecheck', 'tests'], async task => { + visited.push(task); + return task === 'build' ? 1 : 0; + }); + expect(visited).toEqual(['build', 'typecheck', 'tests']); + expect(failed).toEqual(['build']); + }); +}); diff --git a/tsconfig.app.json b/tsconfig.app.json index 774bfcb3..8ffdb4be 100644 --- a/tsconfig.app.json +++ b/tsconfig.app.json @@ -11,7 +11,5 @@ "emitDecoratorMetadata": true, // Suppress decorator-related type checking issues due to Bun's hybrid implementation "skipLibCheck": true - }, - "include": ["src/**/*"], - "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"] + } } diff --git a/tsconfig.check.json b/tsconfig.check.json new file mode 100644 index 00000000..ed028ade --- /dev/null +++ b/tsconfig.check.json @@ -0,0 +1,32 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": true, + "composite": false, + "incremental": false, + "declaration": false, + "declarationMap": false, + "allowImportingTsExtensions": true, + "paths": { + "@/*": ["apps/stock/web-app/src/*"], + "@stock-bot/stock-config": ["apps/stock/config/src/index.ts"], + "@stock-bot/engine": ["apps/stock/engine/index.d.ts"], + "@stock-bot/*": [ + "libs/core/*/src/index.ts", + "libs/data/*/src/index.ts", + "libs/services/*/src/index.ts", + "libs/*/src/index.ts", + "apps/stock/*/src/index.ts", + "tools/*/src/index.ts" + ] + } + }, + "include": [ + "libs/**/src/**/*.ts", + "apps/stock/**/src/**/*.ts", + "apps/stock/**/src/**/*.tsx", + "tools/**/src/**/*.ts", + "libs/core/services/test/contracts.type-test.ts" + ], + "exclude": ["node_modules", "**/dist/**", "**/*.test.ts", "**/*.spec.ts"] +} diff --git a/tsconfig.contracts.json b/tsconfig.contracts.json new file mode 100644 index 00000000..e7dc4cea --- /dev/null +++ b/tsconfig.contracts.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.check.json", + "include": ["libs/core/services/test/contracts.type-test.ts"] +} diff --git a/turbo.json b/turbo.json index 68e9ec89..ec0ba630 100644 --- a/turbo.json +++ b/turbo.json @@ -1,27 +1,13 @@ { "$schema": "https://turbo.build/schema.json", "ui": "tui", - "globalDependencies": ["**/.env.*local"], + "globalDependencies": ["**/.env.*local", "tsconfig.json", "tsconfig.app.json", "tsconfig.lib.json", "Cargo.toml", "Cargo.lock"], "tasks": { "build": { "dependsOn": ["^build"], - "outputs": ["dist/**"], + "outputs": ["dist/**", "*.tsbuildinfo"], "inputs": [ - "src/**", - "package.json", - "tsconfig.json", - "!**/*.test.ts", - "!**/*.spec.ts", - "!**/test/**", - "!**/tests/**", - "!**/__tests__/**" - ] - }, - "build:libs": { - "dependsOn": [], - "outputs": ["dist/**"], - "inputs": [ - "src/**", + "$TURBO_DEFAULT$", "package.json", "tsconfig.json", "!**/*.test.ts",