first refactor

This commit is contained in:
Boki 2026-10-20 12:39:38 -04:00
parent 1f5dac28c7
commit 588f666943
84 changed files with 996 additions and 1062 deletions

229
.gitignore vendored
View file

@ -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/

View file

@ -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

55
README.md Normal file
View file

@ -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.

View file

@ -12,6 +12,7 @@
"clean": "rm -rf dist"
},
"dependencies": {
"@stock-bot/services": "workspace:*",
"@stock-bot/cache": "*",
"@stock-bot/config": "*",
"@stock-bot/stock-config": "*",

View file

@ -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';

View file

@ -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';

View file

@ -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');
}
}
}

View file

@ -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');
}
}
}

View file

@ -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';

View file

@ -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);
}

View file

@ -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);
}

View file

@ -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 {
}))
});
}
}
}

View file

@ -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 {
}
}));
}
}
}

View file

@ -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();
}
}
}

View file

@ -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;
}
}

View file

@ -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'];
};
};

View file

@ -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);
});
});
});
});

View file

@ -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" },

View file

@ -12,6 +12,7 @@
"clean": "rm -rf dist"
},
"dependencies": {
"@stock-bot/services": "workspace:*",
"@stock-bot/cache": "*",
"@stock-bot/config": "*",
"@stock-bot/stock-config": "*",

View file

@ -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';

View file

@ -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');

View file

@ -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';

View file

@ -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' },

View file

@ -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 });

View file

@ -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 },

View file

@ -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" },

View file

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

9
apps/stock/engine/index.d.ts vendored Normal file
View file

@ -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;

View file

@ -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;
// 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;

View file

@ -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"
}
}
}

View file

@ -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"
}
}
{
"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"
}
}

View file

@ -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"]
}
{
"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"]
}

View file

@ -69,5 +69,5 @@
"node": ">=18.0.0",
"bun": ">=1.1.0"
},
"packageManager": "bun@1.1.12"
"packageManager": "bun@1.2.17"
}

View file

@ -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": "*",

View file

@ -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 {

View file

@ -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,

View file

@ -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<PipelineJobResult> {
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<PipelineJobResult> {
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<PipelineJobResult> {
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<PipelineJobResult> {
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<PipelineJobResult> {
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<PipelineJobResult> {
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<PipelineJobResult> {
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<PipelineJobResult> {
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<PipelineStatsResult> {
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<PipelineStatsResult> {
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 });

View file

@ -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'];
};
};

View file

@ -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" },

View file

@ -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"],

View file

@ -2,8 +2,8 @@
"extends": ["//"],
"tasks": {
"build": {
"dependsOn": [],
"outputs": ["dist/**"],
"dependsOn": ["^build"],
"outputs": ["dist/**", "*.tsbuildinfo"],
"inputs": [
"src/**",
"package.json",

View file

@ -9,6 +9,7 @@
"test": "bun test"
},
"dependencies": {
"@stock-bot/services": "workspace:*",
"@stock-bot/config": "workspace:*",
"@stock-bot/logger": "workspace:*",
"@stock-bot/types": "workspace:*",

View file

@ -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<ServiceDefinitions>;
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;
}

View file

@ -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<IServiceContainer>(
({
config: _config,
logger,
@ -175,7 +176,7 @@ export class ServiceContainerBuilder {
mongoClient,
postgresClient,
questdbClient,
}) => ({
}: ServiceDefinitions) => ({
logger,
cache,
globalCache,

View file

@ -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

View file

@ -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 {

View file

@ -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';

View file

@ -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" }
]
}

View file

@ -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:*",

View file

@ -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<TServices extends ServiceTypes = ServiceTypes>
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<TServices extends ServiceTypes = ServiceTypes>
/**
* Get a MongoDB collection with type safety
*/
protected collection<T extends {} = any>(name: string): Collection<T> {
protected collection<T extends Document = Document>(name: string): Collection<T> {
if (!this.mongodb) {
throw new Error('MongoDB service is not available');
}
return this.mongodb.collection(name);
return this.mongodb.collection<T>(name);
}
/**

View file

@ -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 {

View file

@ -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

View file

@ -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

View file

@ -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';

View file

@ -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';

View file

@ -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 () => {

View file

@ -7,6 +7,7 @@
},
"include": ["src/**/*"],
"references": [
{ "path": "../services" },
{ "path": "../config" },
{ "path": "../logger" },
{ "path": "../cache" },

View file

@ -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';

View file

@ -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<Logger, Exclude<LogLevel, 'fatal'>> &
Partial<Pick<Logger, 'child' | 'fatal'>>;
// Context that persists across log calls
export interface LogContext {
[key: string]: any;

View file

@ -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<string, unknown>): void;
error(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
debug(message: string, meta?: Record<string, unknown>): void;
trace(message: string, meta?: Record<string, unknown>): void;
child?(name: string, context?: Record<string, unknown>): Logger;
}
/**
* QueueManager provides unified queue and cache management with service discovery
* Handles both local and cross-service queue operations

View file

@ -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<string, unknown>): void;
error(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
debug(message: string, meta?: Record<string, unknown>): void;
trace(message: string, meta?: Record<string, unknown>): void;
child?(name: string, context?: Record<string, unknown>): 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<T>(job: Job<unknown, T>, timeout = 30000): Promise<T> {
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
*/

View file

@ -9,7 +9,6 @@
"references": [
{ "path": "../cache" },
{ "path": "../handler-registry" },
{ "path": "../handlers" },
{ "path": "../logger" },
{ "path": "../types" }
]

View file

@ -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",

View file

@ -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"
}
}

View file

@ -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<T> = Pick<T, keyof T>;
export type Logger = Public<LoggerImplementation>;
export type Queue = Public<QueueImplementation>;
export type QueueManager = Public<QueueManagerImplementation>;
export type MongoDBClient = Public<MongoDBImplementation>;
export type PostgresClient = Public<PostgresImplementation>;
export type QuestDBClient = Public<QuestDBImplementation>;
export type Browser = Public<BrowserImplementation>;
export type ProxyManager = Public<ProxyImplementation>;
export type { CacheProvider, CacheStats } from '@stock-bot/cache';
export type { BrowserContext, Page } from 'playwright';
export type { ProxyInfo, ProxyStats } from '@stock-bot/proxy';
/** Disabled adapters are null; omitted capabilities are undefined. */
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<string, any>;
}

View file

@ -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 });

View file

@ -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" }
]
}

View file

@ -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,

View file

@ -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<string, any>;
}

View file

@ -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<string, unknown>): void;
error(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
debug(message: string, meta?: Record<string, unknown>): void;
trace(message: string, meta?: Record<string, unknown>): void;
fatal(message: string, meta?: Record<string, unknown>): void;
child?(name: string, context?: Record<string, unknown>): Logger;
}
// Cache types - matches the actual CacheProvider interface from @stock-bot/cache
export interface CacheProvider {
get<T>(key: string): Promise<T | null>;
set<T>(
key: string,
value: T,
options?:
| number
| {
ttl?: number;
preserveTTL?: boolean;
onlyIfExists?: boolean;
onlyIfNotExists?: boolean;
getOldValue?: boolean;
}
): Promise<T | null>;
del(key: string): Promise<void>;
exists(key: string): Promise<boolean>;
clear(): Promise<void>;
keys(pattern: string): Promise<string[]>;
getStats(): CacheStats;
health(): Promise<boolean>;
waitForReady(timeout?: number): Promise<void>;
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<void>;
getQueueStats(queueName?: string): Promise<any>;
getBatchCache(queueName: string): CacheProvider | null;
getRateLimiter(): any;
checkRateLimit(key: string, rule?: string): Promise<{ allowed: boolean; retryAfter?: number }>;
shutdown(): Promise<void>;
}
export interface Queue {
add(name: string, data: any, opts?: any): Promise<any>;
addBulk(jobs: Array<{ name: string; data: any; opts?: any }>): Promise<any[]>;
process(concurrency: number, processor: any): Promise<void>;
process(name: string, concurrency: number, processor: any): Promise<void>;
process(processor: any): Promise<void>;
on(event: string, listener: (...args: any[]) => void): void;
pause(): Promise<void>;
resume(): Promise<void>;
close(): Promise<void>;
clean(grace: number, limit?: number, type?: string): Promise<string[]>;
getJobs(types: string[], start?: number, end?: number, asc?: boolean): Promise<any[]>;
getJobCounts(...types: string[]): Promise<Record<string, number>>;
name: string;
}
// MongoDB types
export interface MongoDBClient {
connect(): Promise<void>;
disconnect(): Promise<void>;
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<void>;
dropCollection(name: string, dbName?: string): Promise<boolean>;
listCollections(dbName?: string): Promise<Array<{ name: string; type: string }>>;
find<T = any>(collection: string, filter?: any, options?: any, dbName?: string): Promise<T[]>;
findOne<T = any>(
collection: string,
filter: any,
options?: any,
dbName?: string
): Promise<T | null>;
insertOne<T = any>(collection: string, document: T, options?: any, dbName?: string): Promise<any>;
insertMany<T = any>(
collection: string,
documents: T[],
options?: any,
dbName?: string
): Promise<any>;
updateOne(
collection: string,
filter: any,
update: any,
options?: any,
dbName?: string
): Promise<any>;
updateMany(
collection: string,
filter: any,
update: any,
options?: any,
dbName?: string
): Promise<any>;
deleteOne(collection: string, filter: any, options?: any, dbName?: string): Promise<any>;
deleteMany(collection: string, filter: any, options?: any, dbName?: string): Promise<any>;
countDocuments(collection: string, filter?: any, options?: any, dbName?: string): Promise<number>;
aggregate<T = any>(
collection: string,
pipeline: any[],
options?: any,
dbName?: string
): Promise<T[]>;
createIndex(collection: string, indexSpec: any, options?: any, dbName?: string): Promise<string>;
dropIndex(collection: string, indexName: string, options?: any, dbName?: string): Promise<void>;
listIndexes(collection: string, dbName?: string): Promise<any[]>;
batchUpsert<T = any>(
collection: string,
documents: T[],
uniqueKeys: string | string[],
options?: any,
dbName?: string
): Promise<any>;
batchUpsertStock<T = any>(
collection: string,
documents: T[],
uniqueKeys: string | string[],
options?: any
): Promise<any>;
batchUpsertTrading<T = any>(
collection: string,
documents: T[],
uniqueKeys: string | string[],
options?: any
): Promise<any>;
batchUpsertAnalytics<T = any>(
collection: string,
documents: T[],
uniqueKeys: string | string[],
options?: any
): Promise<any>;
}
// PostgreSQL types
export interface PostgresClient {
query<T = any>(text: string, params?: any[]): Promise<{ rows: T[]; rowCount: number }>;
queryOne<T = any>(text: string, params?: any[]): Promise<T | null>;
execute(text: string, params?: any[]): Promise<{ rowCount: number }>;
transaction<T>(callback: (client: any) => Promise<T>): Promise<T>;
insert(table: string, data: Record<string, any>, returning?: string | string[]): Promise<any>;
update(
table: string,
data: Record<string, any>,
where: Record<string, any>,
returning?: string | string[]
): Promise<any>;
delete(table: string, where: Record<string, any>, returning?: string | string[]): Promise<any>;
upsert(
table: string,
data: Record<string, any>,
conflictColumns: string | string[],
returning?: string | string[]
): Promise<any>;
batchInsert(
table: string,
data: Record<string, any>[],
returning?: string | string[]
): Promise<any[]>;
batchUpsert(
table: string,
data: Record<string, any>[],
conflictColumns: string | string[],
returning?: string | string[]
): Promise<any[]>;
exists(table: string, where: Record<string, any>): Promise<boolean>;
count(table: string, where?: Record<string, any>): Promise<number>;
getClient(): Promise<any>;
releaseClient(client: any): void;
end(): Promise<void>;
isConnected(): boolean;
}
// QuestDB types
export interface QuestDBClient {
connect(): Promise<void>;
disconnect(): Promise<void>;
isConnected(): boolean;
query<T = any>(sql: string): Promise<T[]>;
insert(table: string, data: Record<string, any> | Record<string, any>[]): Promise<void>;
insertBatch(table: string, data: Record<string, any>[]): Promise<void>;
createTable(tableDef: any): Promise<void>;
dropTable(tableName: string): Promise<void>;
tableExists(tableName: string): Promise<boolean>;
getTableSchema(tableName: string): Promise<any>;
flush(): Promise<void>;
insertWithTimestamp(
table: string,
data: Record<string, any>,
timestamp?: Date | number
): Promise<void>;
batchInsertWithTimestamp(
table: string,
data: Array<Record<string, any> & { timestamp?: Date | number }>
): Promise<void>;
}
// Browser types (Playwright)
export interface Browser {
newPage(): Promise<Page>;
newContext(options?: any): Promise<BrowserContext>;
close(): Promise<void>;
isConnected(): boolean;
version(): string;
}
export interface BrowserContext {
newPage(): Promise<Page>;
close(): Promise<void>;
pages(): Page[];
setDefaultTimeout(timeout: number): void;
setDefaultNavigationTimeout(timeout: number): void;
addCookies(cookies: any[]): Promise<void>;
clearCookies(): Promise<void>;
}
export interface Page {
goto(url: string, options?: any): Promise<any>;
waitForSelector(selector: string, options?: any): Promise<any>;
click(selector: string, options?: any): Promise<void>;
fill(selector: string, value: string, options?: any): Promise<void>;
evaluate<T = any>(pageFunction: any, arg?: any): Promise<T>;
evaluateHandle<T = any>(pageFunction: any, arg?: any): Promise<T>;
screenshot(options?: any): Promise<Buffer>;
pdf(options?: any): Promise<Buffer>;
content(): Promise<string>;
title(): Promise<string>;
url(): string;
close(): Promise<void>;
waitForTimeout(timeout: number): Promise<void>;
waitForLoadState(state?: string, options?: any): Promise<void>;
locator(selector: string): any;
$$(selector: string): Promise<any[]>;
textContent(selector: string): Promise<string | null>;
}
// Proxy Manager types
export interface ProxyManager {
getProxy(): string | null;
getProxyInfo(): ProxyInfo | null;
getProxies(count: number, key?: string): Promise<ProxyInfo[]>;
releaseProxy(proxy: ProxyInfo | string): Promise<void>;
markProxyFailed(proxy: ProxyInfo | string, reason?: string): Promise<void>;
getStats(): ProxyStats;
resetProxy(proxy: ProxyInfo | string): Promise<void>;
blacklistProxy(proxy: ProxyInfo | string, duration?: number): Promise<void>;
isBlacklisted(proxy: ProxyInfo | string): Promise<boolean>;
refreshProxies(): Promise<void>;
}
// 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;
}

View file

@ -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<T extends DocumentBase>(name: string, database?: string): Collection<T> {
getCollection<T extends Document = Document>(name: string, database?: string): Collection<T> {
const db = this.getDatabase(database);
return db.collection<T>(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<DocumentBase> {
return this.getCollection(name, database);
collection<T extends Document = Document>(name: string, database?: string): Collection<T> {
return this.getCollection<T>(name, database);
}
/**

View file

@ -2,8 +2,8 @@
"extends": ["//"],
"tasks": {
"build": {
"dependsOn": ["@stock-bot/logger#build"],
"outputs": ["dist/**"],
"dependsOn": ["^build"],
"outputs": ["dist/**", "*.tsbuildinfo"],
"inputs": [
"src/**",
"package.json",

View file

@ -2,6 +2,7 @@
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"composite": true,
"rootDir": "./src",
"declaration": true,
"declarationMap": true,

View file

@ -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",

View file

@ -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[@]}"

View file

@ -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/**' "$@"

42
scripts/check.ts Normal file
View file

@ -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<number> {
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<number> = runTask
): Promise<string[]> {
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');
}
}

View file

@ -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);
});
});

View file

@ -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',
});
});
});

View file

@ -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<string>(
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<string, string[]>();
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']);
});
});

View file

@ -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"]
}
}

32
tsconfig.check.json Normal file
View file

@ -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"]
}

4
tsconfig.contracts.json Normal file
View file

@ -0,0 +1,4 @@
{
"extends": "./tsconfig.check.json",
"include": ["libs/core/services/test/contracts.type-test.ts"]
}

View file

@ -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",