first refactor
This commit is contained in:
parent
1f5dac28c7
commit
588f666943
84 changed files with 996 additions and 1062 deletions
229
.gitignore
vendored
229
.gitignore
vendored
|
|
@ -1,114 +1,115 @@
|
||||||
# Dependencies
|
# Dependencies
|
||||||
node_modules/
|
node_modules/
|
||||||
.pnp
|
.pnp
|
||||||
.pnp.js
|
.pnp.js
|
||||||
|
|
||||||
# Production builds
|
# Production builds
|
||||||
dist/
|
dist/
|
||||||
build/
|
build/
|
||||||
.next/
|
.next/
|
||||||
*.js.map
|
*.js.map
|
||||||
*.d.ts
|
*.d.ts
|
||||||
|
!apps/stock/engine/index.d.ts
|
||||||
|
|
||||||
# Logs
|
|
||||||
npm-debug.log*
|
# Logs
|
||||||
yarn-debug.log*
|
npm-debug.log*
|
||||||
yarn-error.log*
|
yarn-debug.log*
|
||||||
bun-debug.log*
|
yarn-error.log*
|
||||||
bun-error.log*
|
bun-debug.log*
|
||||||
*.log
|
bun-error.log*
|
||||||
|
*.log
|
||||||
# Runtime data
|
|
||||||
pids
|
# Runtime data
|
||||||
*.pid
|
pids
|
||||||
*.seed
|
*.pid
|
||||||
*.pid.lock
|
*.seed
|
||||||
*.tsbuildinfo
|
*.pid.lock
|
||||||
|
*.tsbuildinfo
|
||||||
# Coverage directory used by tools like istanbul
|
|
||||||
coverage/
|
# Coverage directory used by tools like istanbul
|
||||||
*.lcov
|
coverage/
|
||||||
|
*.lcov
|
||||||
# Dependency directories
|
|
||||||
.pnpm-store/
|
# Dependency directories
|
||||||
|
.pnpm-store/
|
||||||
# Optional npm cache directory
|
|
||||||
.npm
|
# Optional npm cache directory
|
||||||
|
.npm
|
||||||
# Optional eslint cache
|
|
||||||
.eslintcache
|
# Optional eslint cache
|
||||||
|
.eslintcache
|
||||||
# Optional stylelint cache
|
|
||||||
.stylelintcache
|
# Optional stylelint cache
|
||||||
|
.stylelintcache
|
||||||
# Microbundle cache
|
|
||||||
.rpt2_cache/
|
# Microbundle cache
|
||||||
.rts2_cache_cjs/
|
.rpt2_cache/
|
||||||
.rts2_cache_es/
|
.rts2_cache_cjs/
|
||||||
.rts2_cache_umd/
|
.rts2_cache_es/
|
||||||
|
.rts2_cache_umd/
|
||||||
# Optional REPL history
|
|
||||||
.node_repl_history
|
# Optional REPL history
|
||||||
|
.node_repl_history
|
||||||
# Output of 'npm pack'
|
|
||||||
*.tgz
|
# Output of 'npm pack'
|
||||||
|
*.tgz
|
||||||
# Yarn Integrity file
|
|
||||||
.yarn-integrity
|
# Yarn Integrity file
|
||||||
|
.yarn-integrity
|
||||||
# parcel-bundler cache (https://parceljs.org/)
|
|
||||||
.cache
|
# parcel-bundler cache (https://parceljs.org/)
|
||||||
.parcel-cache
|
.cache
|
||||||
|
.parcel-cache
|
||||||
# Next.js build output
|
|
||||||
.next
|
# Next.js build output
|
||||||
|
.next
|
||||||
# Nuxt.js build / generate output
|
|
||||||
.nuxt
|
# Nuxt.js build / generate output
|
||||||
|
.nuxt
|
||||||
# Storybook build outputs
|
|
||||||
.out
|
# Storybook build outputs
|
||||||
.storybook-out
|
.out
|
||||||
|
.storybook-out
|
||||||
# Temporary folders
|
|
||||||
tmp/
|
# Temporary folders
|
||||||
temp/
|
tmp/
|
||||||
|
temp/
|
||||||
# Editor directories and files
|
|
||||||
.idea/
|
# Editor directories and files
|
||||||
*.swp
|
.idea/
|
||||||
*.swo
|
*.swp
|
||||||
*~
|
*.swo
|
||||||
|
*~
|
||||||
# OS generated files
|
|
||||||
.DS_Store
|
# OS generated files
|
||||||
.DS_Store?
|
.DS_Store
|
||||||
._*
|
.DS_Store?
|
||||||
.Spotlight-V100
|
._*
|
||||||
.Trashes
|
.Spotlight-V100
|
||||||
ehthumbs.db
|
.Trashes
|
||||||
Thumbs.db
|
ehthumbs.db
|
||||||
|
Thumbs.db
|
||||||
# Trading bot specific
|
|
||||||
.data/
|
# Trading bot specific
|
||||||
.backtest-results/
|
.data/
|
||||||
.logs/
|
.backtest-results/
|
||||||
.old/
|
.logs/
|
||||||
.mongo/
|
.old/
|
||||||
.chat/
|
.mongo/
|
||||||
*.db
|
.chat/
|
||||||
*.sqlite
|
*.db
|
||||||
*.sqlite3
|
*.sqlite
|
||||||
|
*.sqlite3
|
||||||
# Turbo
|
|
||||||
.turbo
|
# Turbo
|
||||||
*.tsbuildinfo
|
.turbo
|
||||||
|
*.tsbuildinfo
|
||||||
# AI
|
|
||||||
.serena/
|
# AI
|
||||||
.claude/
|
.serena/
|
||||||
docs/configuration-standardization.md
|
.claude/
|
||||||
|
docs/configuration-standardization.md
|
||||||
# Rust
|
|
||||||
target/
|
# Rust
|
||||||
|
target/
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,30 @@
|
||||||
stages:
|
stages:
|
||||||
- build
|
- build
|
||||||
- test
|
- test
|
||||||
- deploy
|
- deploy
|
||||||
- review
|
- review
|
||||||
- dast
|
- dast
|
||||||
- staging
|
- staging
|
||||||
- canary
|
- canary
|
||||||
- production
|
- production
|
||||||
- incremental rollout 10%
|
- incremental rollout 10%
|
||||||
- incremental rollout 25%
|
- incremental rollout 25%
|
||||||
- incremental rollout 50%
|
- incremental rollout 50%
|
||||||
- incremental rollout 100%
|
- incremental rollout 100%
|
||||||
- performance
|
- performance
|
||||||
- cleanup
|
- cleanup
|
||||||
sast:
|
sast:
|
||||||
stage: test
|
stage: test
|
||||||
include:
|
include:
|
||||||
- template: Auto-DevOps.gitlab-ci.yml
|
- 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
55
README.md
Normal 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.
|
||||||
|
|
@ -12,6 +12,7 @@
|
||||||
"clean": "rm -rf dist"
|
"clean": "rm -rf dist"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@stock-bot/services": "workspace:*",
|
||||||
"@stock-bot/cache": "*",
|
"@stock-bot/cache": "*",
|
||||||
"@stock-bot/config": "*",
|
"@stock-bot/config": "*",
|
||||||
"@stock-bot/stock-config": "*",
|
"@stock-bot/stock-config": "*",
|
||||||
|
|
|
||||||
|
|
@ -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 { IB_CONFIG } from '../shared/config';
|
||||||
import { fetchSession } from './fetch-session.action';
|
import { fetchSession } from './fetch-session.action';
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { getLogger } from '@stock-bot/logger';
|
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)
|
// Import handlers explicitly for bundling (ensures they're included in the build)
|
||||||
// These imports trigger the decorator metadata to be set
|
// These imports trigger the decorator metadata to be set
|
||||||
import { CeoHandler } from './ceo/ceo.handler';
|
import { CeoHandler } from './ceo/ceo.handler';
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import type { CacheProvider } from '@stock-bot/cache';
|
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 { QM_SESSION_IDS, SESSION_CONFIG } from './config';
|
||||||
import type { QMSession } from './types';
|
import type { QMSession } from './types';
|
||||||
|
|
||||||
|
|
@ -379,4 +379,4 @@ export class QMSessionManagerRedis {
|
||||||
|
|
||||||
this.logger?.info('Migration completed');
|
this.logger?.info('Migration completed');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import type { CacheProvider } from '@stock-bot/cache';
|
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 { QMSessionManager } from './session-manager';
|
||||||
import { QMSessionManagerRedis } from './session-manager-redis';
|
import { QMSessionManagerRedis } from './session-manager-redis';
|
||||||
import type { QMSession } from './types';
|
import type { QMSession } from './types';
|
||||||
|
|
@ -125,4 +125,4 @@ export class SessionManagerWrapper {
|
||||||
}
|
}
|
||||||
throw new Error('Migration only available for Redis implementation');
|
throw new Error('Migration only available for Redis implementation');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import type { CacheProvider } from '@stock-bot/cache';
|
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 { QM_SESSION_IDS, SESSION_CONFIG } from './config';
|
||||||
import type { CachedSession, QMSession } from './types';
|
import type { CachedSession, QMSession } from './types';
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -18,7 +18,7 @@ export function createMarketDataRoutes(container: IServiceContainer) {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Queue job for live data using Yahoo provider
|
// Queue job for live data using Yahoo provider
|
||||||
const queueManager = container.queue;
|
const queueManager = container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return c.json({ status: 'error', message: 'Queue manager not available' }, 503);
|
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
|
const toDate = to ? new Date(to) : new Date(); // Now
|
||||||
|
|
||||||
// Queue job for historical data using Yahoo provider
|
// Queue job for historical data using Yahoo provider
|
||||||
const queueManager = container.queue;
|
const queueManager = container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return c.json({ status: 'error', message: 'Queue manager not available' }, 503);
|
return c.json({ status: 'error', message: 'Queue manager not available' }, 503);
|
||||||
}
|
}
|
||||||
|
|
@ -106,7 +106,7 @@ export function createMarketDataRoutes(container: IServiceContainer) {
|
||||||
useBatching,
|
useBatching,
|
||||||
});
|
});
|
||||||
|
|
||||||
const queueManager = container.queue;
|
const queueManager = container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return c.json({ status: 'error', message: 'Queue manager not available' }, 503);
|
return c.json({ status: 'error', message: 'Queue manager not available' }, 503);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ export function createQueueRoutes(container: IServiceContainer) {
|
||||||
// Queue status endpoint
|
// Queue status endpoint
|
||||||
queue.get('/status', async c => {
|
queue.get('/status', async c => {
|
||||||
try {
|
try {
|
||||||
const queueManager = container.queue;
|
const queueManager = container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return c.json({ status: 'error', message: 'Queue manager not available' }, 503);
|
return c.json({ status: 'error', message: 'Queue manager not available' }, 503);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
* Base class for operation providers
|
* Base class for operation providers
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import type { Logger, MongoDBClient } from '@stock-bot/types';
|
import type { Logger, MongoDBClient } from '@stock-bot/services';
|
||||||
import type {
|
import type {
|
||||||
OperationConfig,
|
OperationConfig,
|
||||||
OperationUpdate,
|
OperationUpdate,
|
||||||
|
|
@ -170,4 +170,4 @@ export abstract class BaseOperationProvider {
|
||||||
}))
|
}))
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
* Central registry for managing operations across multiple providers
|
* 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 { BaseOperationProvider } from './BaseOperationProvider';
|
||||||
import { OperationTracker } from './OperationTracker';
|
import { OperationTracker } from './OperationTracker';
|
||||||
import type {
|
import type {
|
||||||
|
|
@ -330,4 +330,4 @@ export class OperationRegistry {
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
* General operation tracker that works with any provider
|
* 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 { BaseOperationProvider } from './BaseOperationProvider';
|
||||||
import type {
|
import type {
|
||||||
BulkOperationUpdate,
|
BulkOperationUpdate,
|
||||||
|
|
@ -781,4 +781,4 @@ export class OperationTracker {
|
||||||
getProviderInfo() {
|
getProviderInfo() {
|
||||||
return this.provider.getProviderConfig();
|
return this.provider.getProviderConfig();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
* Types for the general operation management system
|
* 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
|
* Configuration for a single operation
|
||||||
|
|
@ -184,4 +184,4 @@ export interface SymbolWithOperations {
|
||||||
export interface OperationComponentOptions {
|
export interface OperationComponentOptions {
|
||||||
mongodb: MongoDBClient;
|
mongodb: MongoDBClient;
|
||||||
logger: Logger;
|
logger: Logger;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
* Defines required services for data ingestion handlers
|
* 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
|
* Services required by data ingestion handlers
|
||||||
|
|
@ -22,4 +22,4 @@ export type DataIngestionServices = ServiceTypes & {
|
||||||
postgres: ServiceTypes['postgres'];
|
postgres: ServiceTypes['postgres'];
|
||||||
questdb: ServiceTypes['questdb'];
|
questdb: ServiceTypes['questdb'];
|
||||||
globalCache: ServiceTypes['globalCache'];
|
globalCache: ServiceTypes['globalCache'];
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { describe, it, expect, beforeEach } from 'bun:test';
|
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 {
|
import {
|
||||||
BaseOperationProvider,
|
BaseOperationProvider,
|
||||||
OperationRegistry,
|
OperationRegistry,
|
||||||
|
|
@ -193,4 +193,4 @@ describe('Operation Management System', () => {
|
||||||
expect(stats.totalSymbols).toBe(100);
|
expect(stats.totalSymbols).toBe(100);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,8 @@
|
||||||
{
|
{
|
||||||
"extends": "../../../tsconfig.app.json",
|
"extends": "../../../tsconfig.app.json",
|
||||||
|
"compilerOptions": { "rootDir": "./src", "outDir": "./dist" },
|
||||||
|
"include": ["src/**/*"],
|
||||||
|
"exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"],
|
||||||
"references": [
|
"references": [
|
||||||
{ "path": "../../../libs/core/types" },
|
{ "path": "../../../libs/core/types" },
|
||||||
{ "path": "../../../libs/core/config" },
|
{ "path": "../../../libs/core/config" },
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@
|
||||||
"clean": "rm -rf dist"
|
"clean": "rm -rf dist"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@stock-bot/services": "workspace:*",
|
||||||
"@stock-bot/cache": "*",
|
"@stock-bot/cache": "*",
|
||||||
"@stock-bot/config": "*",
|
"@stock-bot/config": "*",
|
||||||
"@stock-bot/stock-config": "*",
|
"@stock-bot/stock-config": "*",
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { BaseHandler, Handler, Operation, ScheduledOperation } from '@stock-bot/handlers';
|
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 { clearPostgreSQLData } from './operations/clear-postgresql-data.operations';
|
||||||
import { getSyncStatus } from './operations/enhanced-sync-status.operations';
|
import { getSyncStatus } from './operations/enhanced-sync-status.operations';
|
||||||
import { getExchangeStats } from './operations/exchange-stats.operations';
|
import { getExchangeStats } from './operations/exchange-stats.operations';
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { getLogger } from '@stock-bot/logger';
|
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';
|
import type { JobPayload } from '../../../types/job-payloads';
|
||||||
|
|
||||||
const logger = getLogger('sync-qm-exchanges');
|
const logger = getLogger('sync-qm-exchanges');
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { getLogger } from '@stock-bot/logger';
|
import { getLogger } from '@stock-bot/logger';
|
||||||
import type { IServiceContainer } from '@stock-bot/types';
|
import type { IServiceContainer } from '@stock-bot/services';
|
||||||
// Import handlers directly
|
// Import handlers directly
|
||||||
import { ExchangesHandler } from './exchanges/exchanges.handler';
|
import { ExchangesHandler } from './exchanges/exchanges.handler';
|
||||||
import { SymbolsHandler } from './symbols/symbols.handler';
|
import { SymbolsHandler } from './symbols/symbols.handler';
|
||||||
|
|
|
||||||
|
|
@ -11,14 +11,14 @@ export function createEnhancedSyncRoutes(container: IServiceContainer) {
|
||||||
enhancedSync.post('/exchanges/all', async c => {
|
enhancedSync.post('/exchanges/all', async c => {
|
||||||
try {
|
try {
|
||||||
const clearFirst = c.req.query('clear') === 'true';
|
const clearFirst = c.req.query('clear') === 'true';
|
||||||
const queueManager = container.queue;
|
const queueManager = container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return c.json({ success: false, error: 'Queue manager not available' }, 503);
|
return c.json({ success: false, error: 'Queue manager not available' }, 503);
|
||||||
}
|
}
|
||||||
|
|
||||||
const exchangesQueue = queueManager.getQueue('exchanges');
|
const exchangesQueue = queueManager.getQueue('exchanges');
|
||||||
|
|
||||||
const job = await exchangesQueue.addJob('sync-all-exchanges', {
|
const job = await exchangesQueue.add('sync-all-exchanges', {
|
||||||
handler: 'exchanges',
|
handler: 'exchanges',
|
||||||
operation: 'sync-all-exchanges',
|
operation: 'sync-all-exchanges',
|
||||||
payload: { clearFirst },
|
payload: { clearFirst },
|
||||||
|
|
@ -36,14 +36,14 @@ export function createEnhancedSyncRoutes(container: IServiceContainer) {
|
||||||
|
|
||||||
enhancedSync.post('/provider-mappings/qm', async c => {
|
enhancedSync.post('/provider-mappings/qm', async c => {
|
||||||
try {
|
try {
|
||||||
const queueManager = container.queue;
|
const queueManager = container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return c.json({ success: false, error: 'Queue manager not available' }, 503);
|
return c.json({ success: false, error: 'Queue manager not available' }, 503);
|
||||||
}
|
}
|
||||||
|
|
||||||
const exchangesQueue = queueManager.getQueue('exchanges');
|
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',
|
handler: 'exchanges',
|
||||||
operation: 'sync-qm-provider-mappings',
|
operation: 'sync-qm-provider-mappings',
|
||||||
payload: {},
|
payload: {},
|
||||||
|
|
@ -65,14 +65,14 @@ export function createEnhancedSyncRoutes(container: IServiceContainer) {
|
||||||
|
|
||||||
enhancedSync.post('/provider-mappings/ib', async c => {
|
enhancedSync.post('/provider-mappings/ib', async c => {
|
||||||
try {
|
try {
|
||||||
const queueManager = container.queue;
|
const queueManager = container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return c.json({ success: false, error: 'Queue manager not available' }, 503);
|
return c.json({ success: false, error: 'Queue manager not available' }, 503);
|
||||||
}
|
}
|
||||||
|
|
||||||
const exchangesQueue = queueManager.getQueue('exchanges');
|
const exchangesQueue = queueManager.getQueue('exchanges');
|
||||||
|
|
||||||
const job = await exchangesQueue.addJob('sync-ib-exchanges', {
|
const job = await exchangesQueue.add('sync-ib-exchanges', {
|
||||||
handler: 'exchanges',
|
handler: 'exchanges',
|
||||||
operation: 'sync-ib-exchanges',
|
operation: 'sync-ib-exchanges',
|
||||||
payload: {},
|
payload: {},
|
||||||
|
|
@ -94,14 +94,14 @@ export function createEnhancedSyncRoutes(container: IServiceContainer) {
|
||||||
|
|
||||||
enhancedSync.get('/status', async c => {
|
enhancedSync.get('/status', async c => {
|
||||||
try {
|
try {
|
||||||
const queueManager = container.queue;
|
const queueManager = container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return c.json({ success: false, error: 'Queue manager not available' }, 503);
|
return c.json({ success: false, error: 'Queue manager not available' }, 503);
|
||||||
}
|
}
|
||||||
|
|
||||||
const symbolsQueue = queueManager.getQueue('symbols');
|
const symbolsQueue = queueManager.getQueue('symbols');
|
||||||
|
|
||||||
const job = await symbolsQueue.addJob('sync-status', {
|
const job = await symbolsQueue.add('sync-status', {
|
||||||
handler: 'symbols',
|
handler: 'symbols',
|
||||||
operation: 'sync-status',
|
operation: 'sync-status',
|
||||||
payload: {},
|
payload: {},
|
||||||
|
|
@ -120,14 +120,14 @@ export function createEnhancedSyncRoutes(container: IServiceContainer) {
|
||||||
enhancedSync.post('/clear/postgresql', async c => {
|
enhancedSync.post('/clear/postgresql', async c => {
|
||||||
try {
|
try {
|
||||||
const dataType = c.req.query('type') as 'exchanges' | 'provider_mappings' | 'all';
|
const dataType = c.req.query('type') as 'exchanges' | 'provider_mappings' | 'all';
|
||||||
const queueManager = container.queue;
|
const queueManager = container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return c.json({ success: false, error: 'Queue manager not available' }, 503);
|
return c.json({ success: false, error: 'Queue manager not available' }, 503);
|
||||||
}
|
}
|
||||||
|
|
||||||
const exchangesQueue = queueManager.getQueue('exchanges');
|
const exchangesQueue = queueManager.getQueue('exchanges');
|
||||||
|
|
||||||
const job = await exchangesQueue.addJob('clear-postgresql-data', {
|
const job = await exchangesQueue.add('clear-postgresql-data', {
|
||||||
handler: 'exchanges',
|
handler: 'exchanges',
|
||||||
operation: 'clear-postgresql-data',
|
operation: 'clear-postgresql-data',
|
||||||
payload: { dataType: dataType || 'all' },
|
payload: { dataType: dataType || 'all' },
|
||||||
|
|
|
||||||
|
|
@ -10,21 +10,21 @@ export function createStatsRoutes(container: IServiceContainer) {
|
||||||
// Statistics endpoints
|
// Statistics endpoints
|
||||||
stats.get('/exchanges', async c => {
|
stats.get('/exchanges', async c => {
|
||||||
try {
|
try {
|
||||||
const queueManager = container.queue;
|
const queueManager = container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return c.json({ error: 'Queue manager not available' }, 503);
|
return c.json({ error: 'Queue manager not available' }, 503);
|
||||||
}
|
}
|
||||||
|
|
||||||
const exchangesQueue = queueManager.getQueue('exchanges');
|
const exchangesQueue = queueManager.getQueue('exchanges');
|
||||||
|
|
||||||
const job = await exchangesQueue.addJob('get-exchange-stats', {
|
const job = await exchangesQueue.add('get-exchange-stats', {
|
||||||
handler: 'exchanges',
|
handler: 'exchanges',
|
||||||
operation: 'get-exchange-stats',
|
operation: 'get-exchange-stats',
|
||||||
payload: {},
|
payload: {},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Wait for job to complete and return result
|
// Wait for job to complete and return result
|
||||||
const result = await job.waitUntilFinished();
|
const result = await exchangesQueue.waitForJob(job);
|
||||||
return c.json(result);
|
return c.json(result);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to get exchange stats', { error });
|
logger.error('Failed to get exchange stats', { error });
|
||||||
|
|
@ -34,21 +34,21 @@ export function createStatsRoutes(container: IServiceContainer) {
|
||||||
|
|
||||||
stats.get('/provider-mappings', async c => {
|
stats.get('/provider-mappings', async c => {
|
||||||
try {
|
try {
|
||||||
const queueManager = container.queue;
|
const queueManager = container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return c.json({ error: 'Queue manager not available' }, 503);
|
return c.json({ error: 'Queue manager not available' }, 503);
|
||||||
}
|
}
|
||||||
|
|
||||||
const exchangesQueue = queueManager.getQueue('exchanges');
|
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',
|
handler: 'exchanges',
|
||||||
operation: 'get-provider-mapping-stats',
|
operation: 'get-provider-mapping-stats',
|
||||||
payload: {},
|
payload: {},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Wait for job to complete and return result
|
// Wait for job to complete and return result
|
||||||
const result = await job.waitUntilFinished();
|
const result = await exchangesQueue.waitForJob(job);
|
||||||
return c.json(result);
|
return c.json(result);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to get provider mapping stats', { error });
|
logger.error('Failed to get provider mapping stats', { error });
|
||||||
|
|
|
||||||
|
|
@ -10,14 +10,14 @@ export function createSyncRoutes(container: IServiceContainer) {
|
||||||
// Manual sync trigger endpoints
|
// Manual sync trigger endpoints
|
||||||
sync.post('/symbols', async c => {
|
sync.post('/symbols', async c => {
|
||||||
try {
|
try {
|
||||||
const queueManager = container.queue;
|
const queueManager = container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return c.json({ success: false, error: 'Queue manager not available' }, 503);
|
return c.json({ success: false, error: 'Queue manager not available' }, 503);
|
||||||
}
|
}
|
||||||
|
|
||||||
const symbolsQueue = queueManager.getQueue('symbols');
|
const symbolsQueue = queueManager.getQueue('symbols');
|
||||||
|
|
||||||
const job = await symbolsQueue.addJob('sync-qm-symbols', {
|
const job = await symbolsQueue.add('sync-qm-symbols', {
|
||||||
handler: 'symbols',
|
handler: 'symbols',
|
||||||
operation: 'sync-qm-symbols',
|
operation: 'sync-qm-symbols',
|
||||||
payload: {},
|
payload: {},
|
||||||
|
|
@ -35,14 +35,14 @@ export function createSyncRoutes(container: IServiceContainer) {
|
||||||
|
|
||||||
sync.post('/exchanges', async c => {
|
sync.post('/exchanges', async c => {
|
||||||
try {
|
try {
|
||||||
const queueManager = container.queue;
|
const queueManager = container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return c.json({ success: false, error: 'Queue manager not available' }, 503);
|
return c.json({ success: false, error: 'Queue manager not available' }, 503);
|
||||||
}
|
}
|
||||||
|
|
||||||
const exchangesQueue = queueManager.getQueue('exchanges');
|
const exchangesQueue = queueManager.getQueue('exchanges');
|
||||||
|
|
||||||
const job = await exchangesQueue.addJob('sync-qm-exchanges', {
|
const job = await exchangesQueue.add('sync-qm-exchanges', {
|
||||||
handler: 'exchanges',
|
handler: 'exchanges',
|
||||||
operation: 'sync-qm-exchanges',
|
operation: 'sync-qm-exchanges',
|
||||||
payload: {},
|
payload: {},
|
||||||
|
|
@ -61,14 +61,14 @@ export function createSyncRoutes(container: IServiceContainer) {
|
||||||
sync.post('/symbols/:provider', async c => {
|
sync.post('/symbols/:provider', async c => {
|
||||||
try {
|
try {
|
||||||
const provider = c.req.param('provider');
|
const provider = c.req.param('provider');
|
||||||
const queueManager = container.queue;
|
const queueManager = container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return c.json({ success: false, error: 'Queue manager not available' }, 503);
|
return c.json({ success: false, error: 'Queue manager not available' }, 503);
|
||||||
}
|
}
|
||||||
|
|
||||||
const symbolsQueue = queueManager.getQueue('symbols');
|
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',
|
handler: 'symbols',
|
||||||
operation: 'sync-symbols-from-provider',
|
operation: 'sync-symbols-from-provider',
|
||||||
payload: { provider },
|
payload: { provider },
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,8 @@
|
||||||
{
|
{
|
||||||
"extends": "../../../tsconfig.app.json",
|
"extends": "../../../tsconfig.app.json",
|
||||||
|
"compilerOptions": { "rootDir": "./src", "outDir": "./dist" },
|
||||||
|
"include": ["src/**/*"],
|
||||||
|
"exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"],
|
||||||
"references": [
|
"references": [
|
||||||
{ "path": "../../../libs/core/types" },
|
{ "path": "../../../libs/core/types" },
|
||||||
{ "path": "../../../libs/core/config" },
|
{ "path": "../../../libs/core/config" },
|
||||||
|
|
|
||||||
10
apps/stock/engine/index.cjs
Normal file
10
apps/stock/engine/index.cjs
Normal 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
9
apps/stock/engine/index.d.ts
vendored
Normal 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;
|
||||||
|
|
@ -1,36 +1,40 @@
|
||||||
// ESM wrapper for the native module
|
// ESM wrapper for the native module
|
||||||
import { createRequire } from 'module';
|
import { createRequire } from 'module';
|
||||||
import { fileURLToPath } from 'url';
|
import { dirname, join } from 'path';
|
||||||
import { dirname, join } from 'path';
|
import { fileURLToPath } from 'url';
|
||||||
|
|
||||||
const require = createRequire(import.meta.url);
|
const require = createRequire(import.meta.url);
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
const __dirname = dirname(__filename);
|
const __dirname = dirname(__filename);
|
||||||
|
|
||||||
const nativeBinding = require(join(__dirname, 'index.node'));
|
const nativeBinding = require(join(__dirname, 'dist', 'engine.node'));
|
||||||
|
|
||||||
export const {
|
export const {
|
||||||
TradingEngine,
|
TradingEngine,
|
||||||
BacktestEngine,
|
BacktestEngine,
|
||||||
TechnicalIndicators,
|
TechnicalIndicators,
|
||||||
IncrementalSMA,
|
IncrementalSma,
|
||||||
IncrementalEMA,
|
IncrementalEma,
|
||||||
IncrementalRSI,
|
IncrementalRsi,
|
||||||
RiskAnalyzer,
|
RiskAnalyzer,
|
||||||
OrderbookAnalyzer,
|
OrderbookAnalyzer,
|
||||||
MarketData,
|
MarketData,
|
||||||
MarketUpdate,
|
MarketUpdate,
|
||||||
Order,
|
Order,
|
||||||
Fill,
|
Fill,
|
||||||
Position,
|
Position,
|
||||||
RiskLimits,
|
RiskLimits,
|
||||||
RiskMetrics,
|
RiskMetrics,
|
||||||
ExecutionResult,
|
ExecutionResult,
|
||||||
OrderBookLevel,
|
OrderBookLevel,
|
||||||
OrderBookSnapshot,
|
OrderBookSnapshot,
|
||||||
MarketMicrostructure,
|
MarketMicrostructure,
|
||||||
PositionUpdate,
|
PositionUpdate,
|
||||||
RiskCheckResult
|
RiskCheckResult,
|
||||||
} = nativeBinding;
|
} = nativeBinding;
|
||||||
|
|
||||||
export default nativeBinding;
|
export const IncrementalSMA = IncrementalSma;
|
||||||
|
export const IncrementalEMA = IncrementalEma;
|
||||||
|
export const IncrementalRSI = IncrementalRsi;
|
||||||
|
|
||||||
|
export default nativeBinding;
|
||||||
|
|
|
||||||
|
|
@ -6,16 +6,16 @@
|
||||||
"types": "index.d.ts",
|
"types": "index.d.ts",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": {
|
".": {
|
||||||
|
"types": "./index.d.ts",
|
||||||
"import": "./index.mjs",
|
"import": "./index.mjs",
|
||||||
"require": "./index.js",
|
"require": "./index.cjs"
|
||||||
"types": "./index.d.ts"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"index.d.ts",
|
"index.d.ts",
|
||||||
"index.js",
|
|
||||||
"index.mjs",
|
"index.mjs",
|
||||||
"index.node"
|
"index.cjs",
|
||||||
|
"dist"
|
||||||
],
|
],
|
||||||
"napi": {
|
"napi": {
|
||||||
"name": "engine",
|
"name": "engine",
|
||||||
|
|
@ -30,14 +30,14 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"scripts": {
|
"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:debug": "npm run build --",
|
||||||
"build:release": "npm run build -- --release",
|
"build:release": "npm run build -- --release",
|
||||||
"build:napi": "napi build --platform --release",
|
"build:napi": "bun run build --release",
|
||||||
"test": "cargo test"
|
"test": "cargo test"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@napi-rs/cli": "^2.16.3",
|
"@napi-rs/cli": "^2.16.3",
|
||||||
"cargo-cp-artifact": "^0.1"
|
"cargo-cp-artifact": "^0.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,40 +1,48 @@
|
||||||
{
|
{
|
||||||
"name": "@stock-bot/orchestrator",
|
"name": "@stock-bot/orchestrator",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"description": "Trading system orchestrator - coordinates between Rust core, data feeds, and analytics",
|
"description": "Trading system orchestrator - coordinates between Rust core, data feeds, and analytics",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "bun --watch src/index.ts",
|
"dev": "bun --watch src/index.ts",
|
||||||
"build": "bun build src/index.ts --outdir dist --target node",
|
"build": "bun build src/index.ts --outdir dist --target node --external @stock-bot/engine --external @tensorflow/tfjs-node",
|
||||||
"start": "bun dist/index.js",
|
"start": "bun dist/index.js",
|
||||||
"test": "bun test",
|
"test": "bun test",
|
||||||
"test:indicators": "bun test tests/indicators.test.ts",
|
"test:indicators": "bun test tests/indicators.test.ts",
|
||||||
"example:indicators": "bun run examples/indicator-usage.ts",
|
"example:indicators": "bun run examples/indicator-usage.ts",
|
||||||
"test:engine": "bun run examples/test-engine-import.ts",
|
"test:engine": "bun run examples/test-engine-import.ts",
|
||||||
"build:rust": "cd ../engine && cargo build --release && napi build --platform --release"
|
"build:rust": "cd ../engine && cargo build --release && napi build --platform --release"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@stock-bot/engine": "*",
|
"@stock-bot/engine": "*",
|
||||||
"@stock-bot/cache": "*",
|
"@stock-bot/cache": "*",
|
||||||
"@stock-bot/config": "*",
|
"@stock-bot/config": "*",
|
||||||
"@stock-bot/di": "*",
|
"@stock-bot/di": "*",
|
||||||
"@stock-bot/logger": "*",
|
"@stock-bot/logger": "*",
|
||||||
"@stock-bot/questdb": "*",
|
"@stock-bot/questdb": "*",
|
||||||
"@stock-bot/queue": "*",
|
"@stock-bot/queue": "*",
|
||||||
"@stock-bot/shutdown": "*",
|
"@stock-bot/shutdown": "*",
|
||||||
"@stock-bot/stock-config": "*",
|
"@stock-bot/stock-config": "*",
|
||||||
"@stock-bot/utils": "*",
|
"@stock-bot/utils": "*",
|
||||||
"hono": "^4.0.0",
|
"hono": "^4.0.0",
|
||||||
"socket.io": "^4.7.2",
|
"socket.io": "^4.7.2",
|
||||||
"socket.io-client": "^4.7.2",
|
"socket.io-client": "^4.7.2",
|
||||||
"zod": "^3.22.0",
|
"zod": "^3.22.0",
|
||||||
"uuid": "^9.0.0",
|
"uuid": "^9.0.0",
|
||||||
"axios": "^1.6.0",
|
"axios": "^1.6.0",
|
||||||
"simple-statistics": "^7.8.3"
|
"simple-statistics": "^7.8.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"peerDependencies": {
|
||||||
"@types/node": "^20.0.0",
|
"@tensorflow/tfjs-node": "^4.0.0"
|
||||||
"typescript": "^5.0.0"
|
},
|
||||||
}
|
"peerDependenciesMeta": {
|
||||||
}
|
"@tensorflow/tfjs-node": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^20.0.0",
|
||||||
|
"typescript": "^5.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,34 +1,34 @@
|
||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"target": "ESNext",
|
"target": "ESNext",
|
||||||
"module": "ESNext",
|
"module": "ESNext",
|
||||||
"lib": ["ESNext"],
|
"lib": ["ESNext"],
|
||||||
"moduleResolution": "bundler",
|
"moduleResolution": "bundler",
|
||||||
"moduleDetection": "force",
|
"moduleDetection": "force",
|
||||||
"allowImportingTsExtensions": true,
|
"allowImportingTsExtensions": true,
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"downlevelIteration": true,
|
"downlevelIteration": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"jsx": "preserve",
|
"jsx": "preserve",
|
||||||
"allowSyntheticDefaultImports": true,
|
"allowSyntheticDefaultImports": true,
|
||||||
"forceConsistentCasingInFileNames": true,
|
"forceConsistentCasingInFileNames": true,
|
||||||
"allowJs": true,
|
"allowJs": true,
|
||||||
"types": ["bun-types"],
|
"types": ["bun-types"],
|
||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"resolveJsonModule": true,
|
"resolveJsonModule": true,
|
||||||
"noEmit": true,
|
"noEmit": true,
|
||||||
"composite": true,
|
"composite": true,
|
||||||
"declaration": true,
|
"declaration": true,
|
||||||
"declarationMap": true,
|
"declarationMap": true,
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"outDir": "./dist",
|
"outDir": "./dist",
|
||||||
"rootDir": "./src",
|
"rootDir": "./src",
|
||||||
"paths": {
|
"paths": {
|
||||||
"@stock-bot/engine": ["../engine/index"],
|
"@stock-bot/engine": ["../engine/index"],
|
||||||
"@stock-bot/engine/*": ["../engine/*"]
|
"@stock-bot/engine/*": ["../engine/*"]
|
||||||
},
|
},
|
||||||
"baseUrl": "."
|
"baseUrl": "."
|
||||||
},
|
},
|
||||||
"include": ["src/**/*"],
|
"include": ["src/**/*"],
|
||||||
"exclude": ["node_modules", "dist"]
|
"exclude": ["node_modules", "dist"]
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -69,5 +69,5 @@
|
||||||
"node": ">=18.0.0",
|
"node": ">=18.0.0",
|
||||||
"bun": ">=1.1.0"
|
"bun": ">=1.1.0"
|
||||||
},
|
},
|
||||||
"packageManager": "bun@1.1.12"
|
"packageManager": "bun@1.2.17"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,8 @@
|
||||||
"clean": "rm -rf dist"
|
"clean": "rm -rf dist"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@stock-bot/queue": "workspace:*",
|
||||||
|
"@stock-bot/services": "workspace:*",
|
||||||
"@stock-bot/config": "*",
|
"@stock-bot/config": "*",
|
||||||
"@stock-bot/stock-config": "*",
|
"@stock-bot/stock-config": "*",
|
||||||
"@stock-bot/logger": "*",
|
"@stock-bot/logger": "*",
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
*/
|
*/
|
||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
import { getLogger } from '@stock-bot/logger';
|
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 { createExchangeService } from '../services/exchange.service';
|
||||||
import { createSuccessResponse, handleError } from '../utils/error-handler';
|
import { createSuccessResponse, handleError } from '../utils/error-handler';
|
||||||
import {
|
import {
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { getLogger } from '@stock-bot/logger';
|
import { getLogger } from '@stock-bot/logger';
|
||||||
import type { IServiceContainer } from '@stock-bot/types';
|
import type { IServiceContainer } from '@stock-bot/services';
|
||||||
import {
|
import {
|
||||||
CreateExchangeRequest,
|
CreateExchangeRequest,
|
||||||
CreateProviderMappingRequest,
|
CreateProviderMappingRequest,
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@
|
||||||
|
|
||||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||||
import { getLogger } from '@stock-bot/logger';
|
import { getLogger } from '@stock-bot/logger';
|
||||||
|
import { getFullQueueName } from '@stock-bot/queue';
|
||||||
|
|
||||||
const logger = getLogger('pipeline-service');
|
const logger = getLogger('pipeline-service');
|
||||||
|
|
||||||
|
|
@ -30,13 +31,13 @@ export class PipelineService {
|
||||||
*/
|
*/
|
||||||
async syncQMSymbols(): Promise<PipelineJobResult> {
|
async syncQMSymbols(): Promise<PipelineJobResult> {
|
||||||
try {
|
try {
|
||||||
const queueManager = this.container.queue;
|
const queueManager = this.container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return { success: false, error: 'Queue manager not available' };
|
return { success: false, error: 'Queue manager not available' };
|
||||||
}
|
}
|
||||||
|
|
||||||
const symbolsQueue = queueManager.getQueue('symbols');
|
const symbolsQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'symbols'));
|
||||||
const job = await symbolsQueue.addJob('sync-qm-symbols', {
|
const job = await symbolsQueue.add('sync-qm-symbols', {
|
||||||
handler: 'symbols',
|
handler: 'symbols',
|
||||||
operation: 'sync-qm-symbols',
|
operation: 'sync-qm-symbols',
|
||||||
payload: {},
|
payload: {},
|
||||||
|
|
@ -58,13 +59,13 @@ export class PipelineService {
|
||||||
*/
|
*/
|
||||||
async syncQMExchanges(): Promise<PipelineJobResult> {
|
async syncQMExchanges(): Promise<PipelineJobResult> {
|
||||||
try {
|
try {
|
||||||
const queueManager = this.container.queue;
|
const queueManager = this.container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return { success: false, error: 'Queue manager not available' };
|
return { success: false, error: 'Queue manager not available' };
|
||||||
}
|
}
|
||||||
|
|
||||||
const exchangesQueue = queueManager.getQueue('exchanges');
|
const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges'));
|
||||||
const job = await exchangesQueue.addJob('sync-qm-exchanges', {
|
const job = await exchangesQueue.add('sync-qm-exchanges', {
|
||||||
handler: 'exchanges',
|
handler: 'exchanges',
|
||||||
operation: 'sync-qm-exchanges',
|
operation: 'sync-qm-exchanges',
|
||||||
payload: {},
|
payload: {},
|
||||||
|
|
@ -86,13 +87,13 @@ export class PipelineService {
|
||||||
*/
|
*/
|
||||||
async syncProviderSymbols(provider: string): Promise<PipelineJobResult> {
|
async syncProviderSymbols(provider: string): Promise<PipelineJobResult> {
|
||||||
try {
|
try {
|
||||||
const queueManager = this.container.queue;
|
const queueManager = this.container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return { success: false, error: 'Queue manager not available' };
|
return { success: false, error: 'Queue manager not available' };
|
||||||
}
|
}
|
||||||
|
|
||||||
const symbolsQueue = queueManager.getQueue('symbols');
|
const symbolsQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'symbols'));
|
||||||
const job = await symbolsQueue.addJob('sync-symbols-from-provider', {
|
const job = await symbolsQueue.add('sync-symbols-from-provider', {
|
||||||
handler: 'symbols',
|
handler: 'symbols',
|
||||||
operation: 'sync-symbols-from-provider',
|
operation: 'sync-symbols-from-provider',
|
||||||
payload: { provider },
|
payload: { provider },
|
||||||
|
|
@ -118,13 +119,13 @@ export class PipelineService {
|
||||||
*/
|
*/
|
||||||
async syncAllExchanges(clearFirst: boolean = false): Promise<PipelineJobResult> {
|
async syncAllExchanges(clearFirst: boolean = false): Promise<PipelineJobResult> {
|
||||||
try {
|
try {
|
||||||
const queueManager = this.container.queue;
|
const queueManager = this.container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return { success: false, error: 'Queue manager not available' };
|
return { success: false, error: 'Queue manager not available' };
|
||||||
}
|
}
|
||||||
|
|
||||||
const exchangesQueue = queueManager.getQueue('exchanges');
|
const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges'));
|
||||||
const job = await exchangesQueue.addJob('sync-all-exchanges', {
|
const job = await exchangesQueue.add('sync-all-exchanges', {
|
||||||
handler: 'exchanges',
|
handler: 'exchanges',
|
||||||
operation: 'sync-all-exchanges',
|
operation: 'sync-all-exchanges',
|
||||||
payload: { clearFirst },
|
payload: { clearFirst },
|
||||||
|
|
@ -150,13 +151,13 @@ export class PipelineService {
|
||||||
*/
|
*/
|
||||||
async syncQMProviderMappings(): Promise<PipelineJobResult> {
|
async syncQMProviderMappings(): Promise<PipelineJobResult> {
|
||||||
try {
|
try {
|
||||||
const queueManager = this.container.queue;
|
const queueManager = this.container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return { success: false, error: 'Queue manager not available' };
|
return { success: false, error: 'Queue manager not available' };
|
||||||
}
|
}
|
||||||
|
|
||||||
const exchangesQueue = queueManager.getQueue('exchanges');
|
const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges'));
|
||||||
const job = await exchangesQueue.addJob('sync-qm-provider-mappings', {
|
const job = await exchangesQueue.add('sync-qm-provider-mappings', {
|
||||||
handler: 'exchanges',
|
handler: 'exchanges',
|
||||||
operation: 'sync-qm-provider-mappings',
|
operation: 'sync-qm-provider-mappings',
|
||||||
payload: {},
|
payload: {},
|
||||||
|
|
@ -182,13 +183,13 @@ export class PipelineService {
|
||||||
*/
|
*/
|
||||||
async syncIBExchanges(): Promise<PipelineJobResult> {
|
async syncIBExchanges(): Promise<PipelineJobResult> {
|
||||||
try {
|
try {
|
||||||
const queueManager = this.container.queue;
|
const queueManager = this.container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return { success: false, error: 'Queue manager not available' };
|
return { success: false, error: 'Queue manager not available' };
|
||||||
}
|
}
|
||||||
|
|
||||||
const exchangesQueue = queueManager.getQueue('exchanges');
|
const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges'));
|
||||||
const job = await exchangesQueue.addJob('sync-ib-exchanges', {
|
const job = await exchangesQueue.add('sync-ib-exchanges', {
|
||||||
handler: 'exchanges',
|
handler: 'exchanges',
|
||||||
operation: 'sync-ib-exchanges',
|
operation: 'sync-ib-exchanges',
|
||||||
payload: {},
|
payload: {},
|
||||||
|
|
@ -214,13 +215,13 @@ export class PipelineService {
|
||||||
*/
|
*/
|
||||||
async getSyncStatus(): Promise<PipelineJobResult> {
|
async getSyncStatus(): Promise<PipelineJobResult> {
|
||||||
try {
|
try {
|
||||||
const queueManager = this.container.queue;
|
const queueManager = this.container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return { success: false, error: 'Queue manager not available' };
|
return { success: false, error: 'Queue manager not available' };
|
||||||
}
|
}
|
||||||
|
|
||||||
const symbolsQueue = queueManager.getQueue('symbols');
|
const symbolsQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'symbols'));
|
||||||
const job = await symbolsQueue.addJob('sync-status', {
|
const job = await symbolsQueue.add('sync-status', {
|
||||||
handler: 'symbols',
|
handler: 'symbols',
|
||||||
operation: 'sync-status',
|
operation: 'sync-status',
|
||||||
payload: {},
|
payload: {},
|
||||||
|
|
@ -248,13 +249,13 @@ export class PipelineService {
|
||||||
dataType: 'exchanges' | 'provider_mappings' | 'all' = 'all'
|
dataType: 'exchanges' | 'provider_mappings' | 'all' = 'all'
|
||||||
): Promise<PipelineJobResult> {
|
): Promise<PipelineJobResult> {
|
||||||
try {
|
try {
|
||||||
const queueManager = this.container.queue;
|
const queueManager = this.container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return { success: false, error: 'Queue manager not available' };
|
return { success: false, error: 'Queue manager not available' };
|
||||||
}
|
}
|
||||||
|
|
||||||
const exchangesQueue = queueManager.getQueue('exchanges');
|
const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges'));
|
||||||
const job = await exchangesQueue.addJob('clear-postgresql-data', {
|
const job = await exchangesQueue.add('clear-postgresql-data', {
|
||||||
handler: 'exchanges',
|
handler: 'exchanges',
|
||||||
operation: 'clear-postgresql-data',
|
operation: 'clear-postgresql-data',
|
||||||
payload: { dataType },
|
payload: { dataType },
|
||||||
|
|
@ -280,20 +281,20 @@ export class PipelineService {
|
||||||
*/
|
*/
|
||||||
async getExchangeStats(): Promise<PipelineStatsResult> {
|
async getExchangeStats(): Promise<PipelineStatsResult> {
|
||||||
try {
|
try {
|
||||||
const queueManager = this.container.queue;
|
const queueManager = this.container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return { success: false, error: 'Queue manager not available' };
|
return { success: false, error: 'Queue manager not available' };
|
||||||
}
|
}
|
||||||
|
|
||||||
const exchangesQueue = queueManager.getQueue('exchanges');
|
const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges'));
|
||||||
const job = await exchangesQueue.addJob('get-exchange-stats', {
|
const job = await exchangesQueue.add('get-exchange-stats', {
|
||||||
handler: 'exchanges',
|
handler: 'exchanges',
|
||||||
operation: 'get-exchange-stats',
|
operation: 'get-exchange-stats',
|
||||||
payload: {},
|
payload: {},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Wait for job to complete and return result
|
// Wait for job to complete and return result
|
||||||
const result = await job.waitUntilFinished();
|
const result = await exchangesQueue.waitForJob(job);
|
||||||
return { success: true, data: result };
|
return { success: true, data: result };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to get exchange stats', { error });
|
logger.error('Failed to get exchange stats', { error });
|
||||||
|
|
@ -309,20 +310,20 @@ export class PipelineService {
|
||||||
*/
|
*/
|
||||||
async getProviderMappingStats(): Promise<PipelineStatsResult> {
|
async getProviderMappingStats(): Promise<PipelineStatsResult> {
|
||||||
try {
|
try {
|
||||||
const queueManager = this.container.queue;
|
const queueManager = this.container.queueManager;
|
||||||
if (!queueManager) {
|
if (!queueManager) {
|
||||||
return { success: false, error: 'Queue manager not available' };
|
return { success: false, error: 'Queue manager not available' };
|
||||||
}
|
}
|
||||||
|
|
||||||
const exchangesQueue = queueManager.getQueue('exchanges');
|
const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges'));
|
||||||
const job = await exchangesQueue.addJob('get-provider-mapping-stats', {
|
const job = await exchangesQueue.add('get-provider-mapping-stats', {
|
||||||
handler: 'exchanges',
|
handler: 'exchanges',
|
||||||
operation: 'get-provider-mapping-stats',
|
operation: 'get-provider-mapping-stats',
|
||||||
payload: {},
|
payload: {},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Wait for job to complete and return result
|
// Wait for job to complete and return result
|
||||||
const result = await job.waitUntilFinished();
|
const result = await exchangesQueue.waitForJob(job);
|
||||||
return { success: true, data: result };
|
return { success: true, data: result };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to get provider mapping stats', { error });
|
logger.error('Failed to get provider mapping stats', { error });
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
* Defines required services for web API handlers
|
* 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
|
* Services required by web API handlers
|
||||||
|
|
@ -22,4 +22,4 @@ export type WebApiServices = ServiceTypes & {
|
||||||
proxy: ServiceTypes['proxy'];
|
proxy: ServiceTypes['proxy'];
|
||||||
questdb: ServiceTypes['questdb'];
|
questdb: ServiceTypes['questdb'];
|
||||||
globalCache: ServiceTypes['globalCache'];
|
globalCache: ServiceTypes['globalCache'];
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,8 @@
|
||||||
{
|
{
|
||||||
"extends": "../../../tsconfig.app.json",
|
"extends": "../../../tsconfig.app.json",
|
||||||
|
"compilerOptions": { "rootDir": "./src", "outDir": "./dist" },
|
||||||
|
"include": ["src/**/*"],
|
||||||
|
"exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"],
|
||||||
"references": [
|
"references": [
|
||||||
{ "path": "../../../libs/core/types" },
|
{ "path": "../../../libs/core/types" },
|
||||||
{ "path": "../../../libs/core/config" },
|
{ "path": "../../../libs/core/config" },
|
||||||
|
|
|
||||||
29
bun.lock
29
bun.lock
|
|
@ -76,6 +76,7 @@
|
||||||
"@stock-bot/proxy": "*",
|
"@stock-bot/proxy": "*",
|
||||||
"@stock-bot/questdb": "*",
|
"@stock-bot/questdb": "*",
|
||||||
"@stock-bot/queue": "*",
|
"@stock-bot/queue": "*",
|
||||||
|
"@stock-bot/services": "workspace:*",
|
||||||
"@stock-bot/shutdown": "*",
|
"@stock-bot/shutdown": "*",
|
||||||
"@stock-bot/stock-config": "*",
|
"@stock-bot/stock-config": "*",
|
||||||
"@stock-bot/utils": "*",
|
"@stock-bot/utils": "*",
|
||||||
|
|
@ -100,6 +101,7 @@
|
||||||
"@stock-bot/postgres": "*",
|
"@stock-bot/postgres": "*",
|
||||||
"@stock-bot/questdb": "*",
|
"@stock-bot/questdb": "*",
|
||||||
"@stock-bot/queue": "*",
|
"@stock-bot/queue": "*",
|
||||||
|
"@stock-bot/services": "workspace:*",
|
||||||
"@stock-bot/shutdown": "*",
|
"@stock-bot/shutdown": "*",
|
||||||
"@stock-bot/stock-config": "*",
|
"@stock-bot/stock-config": "*",
|
||||||
"hono": "^4.0.0",
|
"hono": "^4.0.0",
|
||||||
|
|
@ -142,6 +144,12 @@
|
||||||
"@types/node": "^20.0.0",
|
"@types/node": "^20.0.0",
|
||||||
"typescript": "^5.0.0",
|
"typescript": "^5.0.0",
|
||||||
},
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@tensorflow/tfjs-node": "^4.0.0",
|
||||||
|
},
|
||||||
|
"optionalPeers": [
|
||||||
|
"@tensorflow/tfjs-node",
|
||||||
|
],
|
||||||
},
|
},
|
||||||
"apps/stock/web-api": {
|
"apps/stock/web-api": {
|
||||||
"name": "@stock-bot/web-api",
|
"name": "@stock-bot/web-api",
|
||||||
|
|
@ -153,6 +161,8 @@
|
||||||
"@stock-bot/logger": "*",
|
"@stock-bot/logger": "*",
|
||||||
"@stock-bot/mongodb": "*",
|
"@stock-bot/mongodb": "*",
|
||||||
"@stock-bot/postgres": "*",
|
"@stock-bot/postgres": "*",
|
||||||
|
"@stock-bot/queue": "workspace:*",
|
||||||
|
"@stock-bot/services": "workspace:*",
|
||||||
"@stock-bot/shutdown": "*",
|
"@stock-bot/shutdown": "*",
|
||||||
"@stock-bot/stock-config": "*",
|
"@stock-bot/stock-config": "*",
|
||||||
"hono": "^4.0.0",
|
"hono": "^4.0.0",
|
||||||
|
|
@ -242,6 +252,7 @@
|
||||||
"@stock-bot/proxy": "workspace:*",
|
"@stock-bot/proxy": "workspace:*",
|
||||||
"@stock-bot/questdb": "workspace:*",
|
"@stock-bot/questdb": "workspace:*",
|
||||||
"@stock-bot/queue": "workspace:*",
|
"@stock-bot/queue": "workspace:*",
|
||||||
|
"@stock-bot/services": "workspace:*",
|
||||||
"@stock-bot/shutdown": "workspace:*",
|
"@stock-bot/shutdown": "workspace:*",
|
||||||
"@stock-bot/types": "workspace:*",
|
"@stock-bot/types": "workspace:*",
|
||||||
"awilix": "^12.0.5",
|
"awilix": "^12.0.5",
|
||||||
|
|
@ -286,6 +297,7 @@
|
||||||
"@stock-bot/config": "workspace:*",
|
"@stock-bot/config": "workspace:*",
|
||||||
"@stock-bot/handler-registry": "workspace:*",
|
"@stock-bot/handler-registry": "workspace:*",
|
||||||
"@stock-bot/logger": "workspace:*",
|
"@stock-bot/logger": "workspace:*",
|
||||||
|
"@stock-bot/services": "workspace:*",
|
||||||
"@stock-bot/types": "workspace:*",
|
"@stock-bot/types": "workspace:*",
|
||||||
"@stock-bot/utils": "workspace:*",
|
"@stock-bot/utils": "workspace:*",
|
||||||
"mongodb": "^6.12.0",
|
"mongodb": "^6.12.0",
|
||||||
|
|
@ -329,6 +341,21 @@
|
||||||
"typescript": "^5.3.0",
|
"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": {
|
"libs/core/shutdown": {
|
||||||
"name": "@stock-bot/shutdown",
|
"name": "@stock-bot/shutdown",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
|
|
@ -928,6 +955,8 @@
|
||||||
|
|
||||||
"@stock-bot/queue": ["@stock-bot/queue@workspace:libs/core/queue"],
|
"@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/shutdown": ["@stock-bot/shutdown@workspace:libs/core/shutdown"],
|
||||||
|
|
||||||
"@stock-bot/stock-app": ["@stock-bot/stock-app@workspace:apps/stock"],
|
"@stock-bot/stock-app": ["@stock-bot/stock-app@workspace:apps/stock"],
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,8 @@
|
||||||
"extends": ["//"],
|
"extends": ["//"],
|
||||||
"tasks": {
|
"tasks": {
|
||||||
"build": {
|
"build": {
|
||||||
"dependsOn": [],
|
"dependsOn": ["^build"],
|
||||||
"outputs": ["dist/**"],
|
"outputs": ["dist/**", "*.tsbuildinfo"],
|
||||||
"inputs": [
|
"inputs": [
|
||||||
"src/**",
|
"src/**",
|
||||||
"package.json",
|
"package.json",
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@
|
||||||
"test": "bun test"
|
"test": "bun test"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@stock-bot/services": "workspace:*",
|
||||||
"@stock-bot/config": "workspace:*",
|
"@stock-bot/config": "workspace:*",
|
||||||
"@stock-bot/logger": "workspace:*",
|
"@stock-bot/logger": "workspace:*",
|
||||||
"@stock-bot/types": "workspace:*",
|
"@stock-bot/types": "workspace:*",
|
||||||
|
|
|
||||||
|
|
@ -1,59 +1,7 @@
|
||||||
/**
|
import type { AwilixContainer } from 'awilix';
|
||||||
* Awilix DI Container Setup
|
import type { ServiceDefinitions } from './container/types';
|
||||||
* Creates a decoupled, reusable dependency injection container
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { type AwilixContainer } from 'awilix';
|
// Compatibility exports use the same composition contract as the active builder.
|
||||||
import type { Browser } from '@stock-bot/browser';
|
export type { AppConfig } from './config/schemas';
|
||||||
import type { CacheProvider } from '@stock-bot/cache';
|
export type { ServiceCradle, ServiceDefinitions, ServiceContainerOptions } from './container/types';
|
||||||
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
|
|
||||||
export type ServiceContainer = AwilixContainer<ServiceDefinitions>;
|
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;
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ import { asClass, asFunction, createContainer, InjectionMode, type AwilixContain
|
||||||
import type { BaseAppConfig as StockBotAppConfig, UnifiedAppConfig } from '@stock-bot/config';
|
import type { BaseAppConfig as StockBotAppConfig, UnifiedAppConfig } from '@stock-bot/config';
|
||||||
import { toUnifiedConfig } from '@stock-bot/config';
|
import { toUnifiedConfig } from '@stock-bot/config';
|
||||||
import { HandlerRegistry } from '@stock-bot/handler-registry';
|
import { HandlerRegistry } from '@stock-bot/handler-registry';
|
||||||
|
import type { IServiceContainer } from '@stock-bot/services';
|
||||||
import { appConfigSchema, type AppConfig } from '../config/schemas';
|
import { appConfigSchema, type AppConfig } from '../config/schemas';
|
||||||
import {
|
import {
|
||||||
registerApplicationServices,
|
registerApplicationServices,
|
||||||
|
|
@ -163,7 +164,7 @@ export class ServiceContainerBuilder {
|
||||||
|
|
||||||
// Register service container aggregate
|
// Register service container aggregate
|
||||||
container.register({
|
container.register({
|
||||||
serviceContainer: asFunction(
|
serviceContainer: asFunction<IServiceContainer>(
|
||||||
({
|
({
|
||||||
config: _config,
|
config: _config,
|
||||||
logger,
|
logger,
|
||||||
|
|
@ -175,7 +176,7 @@ export class ServiceContainerBuilder {
|
||||||
mongoClient,
|
mongoClient,
|
||||||
postgresClient,
|
postgresClient,
|
||||||
questdbClient,
|
questdbClient,
|
||||||
}) => ({
|
}: ServiceDefinitions) => ({
|
||||||
logger,
|
logger,
|
||||||
cache,
|
cache,
|
||||||
globalCache,
|
globalCache,
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ import type { PostgreSQLClient } from '@stock-bot/postgres';
|
||||||
import type { ProxyManager } from '@stock-bot/proxy';
|
import type { ProxyManager } from '@stock-bot/proxy';
|
||||||
import type { QuestDBClient } from '@stock-bot/questdb';
|
import type { QuestDBClient } from '@stock-bot/questdb';
|
||||||
import type { QueueManager } from '@stock-bot/queue';
|
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 { AppConfig } from '../config/schemas';
|
||||||
import type { HandlerScanner } from '../scanner';
|
import type { HandlerScanner } from '../scanner';
|
||||||
|
|
||||||
|
|
@ -24,7 +24,7 @@ export interface ServiceDefinitions {
|
||||||
cache: CacheProvider | null;
|
cache: CacheProvider | null;
|
||||||
globalCache: CacheProvider | null;
|
globalCache: CacheProvider | null;
|
||||||
proxyManager: ProxyManager | null;
|
proxyManager: ProxyManager | null;
|
||||||
browser: Browser;
|
browser: Browser | null;
|
||||||
queueManager: QueueManager | null;
|
queueManager: QueueManager | null;
|
||||||
|
|
||||||
// Database clients
|
// Database clients
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ export { OperationContext } from './operation-context';
|
||||||
export { calculatePoolSize, getServicePoolSize, getHandlerPoolSize } from './pool-size-calculator';
|
export { calculatePoolSize, getServicePoolSize, getHandlerPoolSize } from './pool-size-calculator';
|
||||||
export { ServiceLifecycleManager } from './utils/lifecycle';
|
export { ServiceLifecycleManager } from './utils/lifecycle';
|
||||||
export { HandlerScanner } from './scanner/handler-scanner';
|
export { HandlerScanner } from './scanner/handler-scanner';
|
||||||
export type { IServiceContainer } from '@stock-bot/types';
|
export type { IServiceContainer } from '@stock-bot/services';
|
||||||
|
|
||||||
// Export schemas
|
// Export schemas
|
||||||
export {
|
export {
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ import { toUnifiedConfig } from '@stock-bot/config';
|
||||||
import type { HandlerRegistry } from '@stock-bot/handler-registry';
|
import type { HandlerRegistry } from '@stock-bot/handler-registry';
|
||||||
import { getLogger, setLoggerConfig, shutdownLoggers, type Logger } from '@stock-bot/logger';
|
import { getLogger, setLoggerConfig, shutdownLoggers, type Logger } from '@stock-bot/logger';
|
||||||
import { Shutdown, SHUTDOWN_DEFAULTS } from '@stock-bot/shutdown';
|
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 type { AwilixContainer } from 'awilix';
|
||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
import { cors } from 'hono/cors';
|
import { cors } from 'hono/cors';
|
||||||
|
|
|
||||||
|
|
@ -10,5 +10,10 @@
|
||||||
},
|
},
|
||||||
"include": ["src/**/*.ts"],
|
"include": ["src/**/*.ts"],
|
||||||
"exclude": ["node_modules", "dist", "test"],
|
"exclude": ["node_modules", "dist", "test"],
|
||||||
"references": [{ "path": "../config" }, { "path": "../logger" }, { "path": "../queue" }]
|
"references": [
|
||||||
|
{ "path": "../services" },
|
||||||
|
{ "path": "../config" },
|
||||||
|
{ "path": "../logger" },
|
||||||
|
{ "path": "../queue" }
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@
|
||||||
"test": "bun test"
|
"test": "bun test"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@stock-bot/services": "workspace:*",
|
||||||
"@stock-bot/cache": "workspace:*",
|
"@stock-bot/cache": "workspace:*",
|
||||||
"@stock-bot/config": "workspace:*",
|
"@stock-bot/config": "workspace:*",
|
||||||
"@stock-bot/handler-registry": "workspace:*",
|
"@stock-bot/handler-registry": "workspace:*",
|
||||||
|
|
|
||||||
|
|
@ -5,12 +5,11 @@ import type {
|
||||||
HandlerConfigWithSchedule,
|
HandlerConfigWithSchedule,
|
||||||
HandlerMetadata,
|
HandlerMetadata,
|
||||||
IHandler,
|
IHandler,
|
||||||
IServiceContainer,
|
|
||||||
JobHandler,
|
JobHandler,
|
||||||
ServiceTypes,
|
|
||||||
} from '@stock-bot/types';
|
} from '@stock-bot/types';
|
||||||
|
import type { IServiceContainer, ServiceTypes } from '@stock-bot/services';
|
||||||
import { fetch } from '@stock-bot/utils';
|
import { fetch } from '@stock-bot/utils';
|
||||||
import type { Collection } from 'mongodb';
|
import type { Collection, Document } from 'mongodb';
|
||||||
// Handler registry is now injected, not imported
|
// Handler registry is now injected, not imported
|
||||||
import { createJobHandler } from '../utils/create-job-handler';
|
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();
|
constructor.__handlerName || handlerName || this.constructor.name.toLowerCase();
|
||||||
|
|
||||||
// Flatten all services onto the handler instance
|
// 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.cache = services.cache as TServices['cache'];
|
||||||
this.globalCache = services.globalCache as TServices['globalCache'];
|
this.globalCache = services.globalCache as TServices['globalCache'];
|
||||||
this.queueManager = services.queueManager as TServices['queueManager'];
|
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
|
* 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) {
|
if (!this.mongodb) {
|
||||||
throw new Error('MongoDB service is not available');
|
throw new Error('MongoDB service is not available');
|
||||||
}
|
}
|
||||||
return this.mongodb.collection(name);
|
return this.mongodb.collection<T>(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,7 @@ export type {
|
||||||
RateLimitOptions
|
RateLimitOptions
|
||||||
} from './decorators/rate-limit';
|
} from './decorators/rate-limit';
|
||||||
export { createJobHandler } from './utils/create-job-handler';
|
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
|
// Re-export commonly used types from @stock-bot/types for convenience
|
||||||
export type {
|
export type {
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
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';
|
import { BaseHandler } from '../src/base/BaseHandler';
|
||||||
|
|
||||||
// Test handler with metadata
|
// Test handler with metadata
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
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';
|
import { BaseHandler, ScheduledHandler } from '../src/base/BaseHandler';
|
||||||
|
|
||||||
// Test handler implementation
|
// Test handler implementation
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
|
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 * as utils from '@stock-bot/utils';
|
||||||
import { BaseHandler } from '../src/base/BaseHandler';
|
import { BaseHandler } from '../src/base/BaseHandler';
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,8 @@ import type { CacheProvider } from '@stock-bot/cache';
|
||||||
import type { Logger } from '@stock-bot/logger';
|
import type { Logger } from '@stock-bot/logger';
|
||||||
import type { SimpleProxyManager } from '@stock-bot/proxy';
|
import type { SimpleProxyManager } from '@stock-bot/proxy';
|
||||||
import type { Queue, QueueManager } from '@stock-bot/queue';
|
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 { BaseHandler, ScheduledHandler } from '../src/base/BaseHandler';
|
||||||
import { Handler, Operation } from '../src/decorators/decorators';
|
import { Handler, Operation } from '../src/decorators/decorators';
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,8 @@ import { beforeEach, describe, expect, it, mock, type Mock } from 'bun:test';
|
||||||
import type { CacheProvider } from '@stock-bot/cache';
|
import type { CacheProvider } from '@stock-bot/cache';
|
||||||
import type { Logger } from '@stock-bot/logger';
|
import type { Logger } from '@stock-bot/logger';
|
||||||
import type { Queue, QueueManager } from '@stock-bot/queue';
|
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 { BaseHandler } from '../src/base/BaseHandler';
|
||||||
import {
|
import {
|
||||||
Handler,
|
Handler,
|
||||||
|
|
@ -75,6 +76,7 @@ describe('BaseHandler', () => {
|
||||||
const handler = new BaseHandler(mockServices, 'test-handler');
|
const handler = new BaseHandler(mockServices, 'test-handler');
|
||||||
expect(handler).toBeDefined();
|
expect(handler).toBeDefined();
|
||||||
expect(handler.logger).toBeDefined();
|
expect(handler.logger).toBeDefined();
|
||||||
|
expect(handler.logger).toBe(mockServices.logger);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should execute operations', async () => {
|
it('should execute operations', async () => {
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@
|
||||||
},
|
},
|
||||||
"include": ["src/**/*"],
|
"include": ["src/**/*"],
|
||||||
"references": [
|
"references": [
|
||||||
|
{ "path": "../services" },
|
||||||
{ "path": "../config" },
|
{ "path": "../config" },
|
||||||
{ "path": "../logger" },
|
{ "path": "../logger" },
|
||||||
{ "path": "../cache" },
|
{ "path": "../cache" },
|
||||||
|
|
|
||||||
|
|
@ -8,4 +8,4 @@
|
||||||
export { Logger, getLogger, shutdownLoggers, setLoggerConfig } from './logger';
|
export { Logger, getLogger, shutdownLoggers, setLoggerConfig } from './logger';
|
||||||
|
|
||||||
// Type definitions
|
// Type definitions
|
||||||
export type { LogLevel, LogContext, LogMetadata, LoggerConfig } from './types';
|
export type { LogLevel, LogContext, LogMetadata, LoggerConfig, LoggerLike } from './types';
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,15 @@
|
||||||
/**
|
/**
|
||||||
* Simplified type definitions for the logger library
|
* Simplified type definitions for the logger library
|
||||||
*/
|
*/
|
||||||
|
import type { Logger } from './logger';
|
||||||
|
|
||||||
// Standard log levels (simplified to pino defaults)
|
// Standard log levels (simplified to pino defaults)
|
||||||
export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
|
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
|
// Context that persists across log calls
|
||||||
export interface LogContext {
|
export interface LogContext {
|
||||||
[key: string]: any;
|
[key: string]: any;
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ import type { CacheProvider } from '@stock-bot/cache';
|
||||||
import { createCache } from '@stock-bot/cache';
|
import { createCache } from '@stock-bot/cache';
|
||||||
import type { HandlerRegistry } from '@stock-bot/handler-registry';
|
import type { HandlerRegistry } from '@stock-bot/handler-registry';
|
||||||
import { getLogger } from '@stock-bot/logger';
|
import { getLogger } from '@stock-bot/logger';
|
||||||
|
import type { LoggerLike as Logger } from '@stock-bot/logger';
|
||||||
import Redis from 'ioredis';
|
import Redis from 'ioredis';
|
||||||
import { Queue, type QueueWorkerConfig } from './queue';
|
import { Queue, type QueueWorkerConfig } from './queue';
|
||||||
import { QueueRateLimiter } from './rate-limiter';
|
import { QueueRateLimiter } from './rate-limiter';
|
||||||
|
|
@ -19,16 +20,6 @@ import type {
|
||||||
} from './types';
|
} from './types';
|
||||||
import { getRedisConnection } from './utils';
|
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
|
* QueueManager provides unified queue and cache management with service discovery
|
||||||
* Handles both local and cross-service queue operations
|
* Handles both local and cross-service queue operations
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,10 @@
|
||||||
import { Queue as BullQueue, QueueEvents, Worker, type Job } from 'bullmq';
|
import { Queue as BullQueue, QueueEvents, Worker, type Job } from 'bullmq';
|
||||||
|
import type { LoggerLike as Logger } from '@stock-bot/logger';
|
||||||
// Handler registry will be injected
|
// Handler registry will be injected
|
||||||
import type { HandlerRegistry } from '@stock-bot/handler-registry';
|
import type { HandlerRegistry } from '@stock-bot/handler-registry';
|
||||||
import type { ExtendedJobOptions, JobData, JobOptions, QueueStats, RedisConfig } from './types';
|
import type { ExtendedJobOptions, JobData, JobOptions, QueueStats, RedisConfig } from './types';
|
||||||
import { getRedisConnection } from './utils';
|
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 {
|
export interface QueueWorkerConfig {
|
||||||
workers?: number;
|
workers?: number;
|
||||||
concurrency?: number;
|
concurrency?: number;
|
||||||
|
|
@ -205,6 +196,17 @@ export class Queue {
|
||||||
return await this.bullQueue.getJob(jobId);
|
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
|
* Get jobs by state
|
||||||
*/
|
*/
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,6 @@
|
||||||
"references": [
|
"references": [
|
||||||
{ "path": "../cache" },
|
{ "path": "../cache" },
|
||||||
{ "path": "../handler-registry" },
|
{ "path": "../handler-registry" },
|
||||||
{ "path": "../handlers" },
|
|
||||||
{ "path": "../logger" },
|
{ "path": "../logger" },
|
||||||
{ "path": "../types" }
|
{ "path": "../types" }
|
||||||
]
|
]
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,8 @@
|
||||||
"extends": ["//"],
|
"extends": ["//"],
|
||||||
"tasks": {
|
"tasks": {
|
||||||
"build": {
|
"build": {
|
||||||
"dependsOn": ["@stock-bot/cache#build", "@stock-bot/logger#build", "@stock-bot/types#build"],
|
"dependsOn": ["^build"],
|
||||||
"outputs": ["dist/**"],
|
"outputs": ["dist/**", "*.tsbuildinfo"],
|
||||||
"inputs": [
|
"inputs": [
|
||||||
"src/**",
|
"src/**",
|
||||||
"package.json",
|
"package.json",
|
||||||
|
|
|
||||||
29
libs/core/services/package.json
Normal file
29
libs/core/services/package.json
Normal 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"
|
||||||
|
}
|
||||||
|
}
|
||||||
44
libs/core/services/src/index.ts
Normal file
44
libs/core/services/src/index.ts
Normal 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>;
|
||||||
|
}
|
||||||
61
libs/core/services/test/contracts.type-test.ts
Normal file
61
libs/core/services/test/contracts.type-test.ts
Normal 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 });
|
||||||
19
libs/core/services/tsconfig.json
Normal file
19
libs/core/services/tsconfig.json
Normal 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" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -61,27 +61,6 @@ export type {
|
||||||
TypedJobHandler,
|
TypedJobHandler,
|
||||||
} from './handlers';
|
} 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 decorator types
|
||||||
export type {
|
export type {
|
||||||
ScheduleConfig,
|
ScheduleConfig,
|
||||||
|
|
|
||||||
|
|
@ -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>;
|
|
||||||
}
|
|
||||||
|
|
@ -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;
|
|
||||||
}
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import type { Logger } from '@stock-bot/logger';
|
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 { Collection, Db, MongoClient } from 'mongodb';
|
||||||
import type {
|
import type {
|
||||||
ConnectionEvents,
|
ConnectionEvents,
|
||||||
|
|
@ -328,7 +328,7 @@ export class MongoDBClient {
|
||||||
/**
|
/**
|
||||||
* Get a typed collection
|
* 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);
|
const db = this.getDatabase(database);
|
||||||
return db.collection<T>(name);
|
return db.collection<T>(name);
|
||||||
}
|
}
|
||||||
|
|
@ -337,8 +337,8 @@ export class MongoDBClient {
|
||||||
* Get a collection (interface compatibility method)
|
* Get a collection (interface compatibility method)
|
||||||
* This method provides compatibility with the IMongoDBClient interface
|
* This method provides compatibility with the IMongoDBClient interface
|
||||||
*/
|
*/
|
||||||
collection(name: string, database?: string): Collection<DocumentBase> {
|
collection<T extends Document = Document>(name: string, database?: string): Collection<T> {
|
||||||
return this.getCollection(name, database);
|
return this.getCollection<T>(name, database);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,8 @@
|
||||||
"extends": ["//"],
|
"extends": ["//"],
|
||||||
"tasks": {
|
"tasks": {
|
||||||
"build": {
|
"build": {
|
||||||
"dependsOn": ["@stock-bot/logger#build"],
|
"dependsOn": ["^build"],
|
||||||
"outputs": ["dist/**"],
|
"outputs": ["dist/**", "*.tsbuildinfo"],
|
||||||
"inputs": [
|
"inputs": [
|
||||||
"src/**",
|
"src/**",
|
||||||
"package.json",
|
"package.json",
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
"extends": "../../../tsconfig.json",
|
"extends": "../../../tsconfig.json",
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"outDir": "./dist",
|
"outDir": "./dist",
|
||||||
|
"composite": true,
|
||||||
"rootDir": "./src",
|
"rootDir": "./src",
|
||||||
"declaration": true,
|
"declaration": true,
|
||||||
"declarationMap": true,
|
"declarationMap": true,
|
||||||
|
|
|
||||||
18
package.json
18
package.json
|
|
@ -10,7 +10,11 @@
|
||||||
"build:all:clean": "./scripts/build-all.sh --clean",
|
"build:all:clean": "./scripts/build-all.sh --clean",
|
||||||
"build:all:verbose": "./scripts/build-all.sh --verbose",
|
"build:all:verbose": "./scripts/build-all.sh --verbose",
|
||||||
"build:libs": "./scripts/build-libs.sh",
|
"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:watch": "bun test --watch",
|
||||||
"test:coverage": "bun test --coverage",
|
"test:coverage": "bun test --coverage",
|
||||||
"coverage": "bun run tools/coverage-cli/src/index.ts --reporters html markdown",
|
"coverage": "bun run tools/coverage-cli/src/index.ts --reporters html markdown",
|
||||||
|
|
@ -19,11 +23,11 @@
|
||||||
"test:unit": "bun test test/unit",
|
"test:unit": "bun test test/unit",
|
||||||
"test:integration": "bun test test/integration",
|
"test:integration": "bun test test/integration",
|
||||||
"test:e2e": "bun test test/e2e",
|
"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/*/*",
|
"test:apps": "turbo run test --filter=./apps/*/*",
|
||||||
"lint": "eslint apps libs --ext .ts,.tsx",
|
"lint": "eslint apps/stock libs tools --ext .ts,.tsx",
|
||||||
"lint:fix": "eslint apps libs --ext .ts,.tsx --fix",
|
"lint:fix": "eslint apps/stock libs tools --ext .ts,.tsx --fix",
|
||||||
"lint:check": "eslint apps libs --ext .ts,.tsx --max-warnings 0",
|
"lint:check": "eslint apps/stock libs tools --ext .ts,.tsx --max-warnings 0",
|
||||||
"lint:apps": "eslint apps --ext .ts,.tsx",
|
"lint:apps": "eslint apps --ext .ts,.tsx",
|
||||||
"lint:libs": "eslint libs --ext .ts,.tsx",
|
"lint:libs": "eslint libs --ext .ts,.tsx",
|
||||||
"format": "./scripts/format.sh",
|
"format": "./scripts/format.sh",
|
||||||
|
|
@ -102,10 +106,10 @@
|
||||||
"typescript": "^5.8.3",
|
"typescript": "^5.8.3",
|
||||||
"yup": "^1.6.1"
|
"yup": "^1.6.1"
|
||||||
},
|
},
|
||||||
"packageManager": "bun@1.1.12",
|
"packageManager": "bun@1.2.17",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18.0.0",
|
"node": ">=18.0.0",
|
||||||
"bun": ">=1.1.0"
|
"bun": ">=1.2.17"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@types/pg": "^8.15.4",
|
"@types/pg": "^8.15.4",
|
||||||
|
|
|
||||||
|
|
@ -1,158 +1,24 @@
|
||||||
#!/bin/bash
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
# Build All Script for Stock Bot
|
cd "$(dirname "${BASH_SOURCE[0]}")/.."
|
||||||
# Builds libraries first, then apps with Turbo, then dashboard with Angular CLI
|
|
||||||
|
|
||||||
set -e
|
args=()
|
||||||
|
for option in "$@"; do
|
||||||
# Colors for output
|
case "$option" in
|
||||||
RED='\033[0;31m'
|
--clean|-c) args+=(--force) ;;
|
||||||
GREEN='\033[0;32m'
|
--verbose|-v) args+=(--output-logs=full) ;;
|
||||||
YELLOW='\033[1;33m'
|
--dry|--dry=json|--dry-run|--dry-run=json) args+=("$option") ;;
|
||||||
CYAN='\033[0;36m'
|
--help|-h)
|
||||||
GRAY='\033[0;37m'
|
echo "Usage: $0 [--clean] [--verbose]"
|
||||||
NC='\033[0m' # No Color
|
echo " --clean Force every workspace build, ignoring cached results"
|
||||||
|
echo " --verbose Print complete workspace build logs"
|
||||||
# Default options
|
exit 0
|
||||||
CLEAN=false
|
;;
|
||||||
VERBOSE=false
|
*) echo "Unknown option: $option" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
# 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
|
|
||||||
done
|
done
|
||||||
|
|
||||||
echo -e "${CYAN}🚀 Starting complete build process...${NC}"
|
# The stock-app package contains convenience commands, not buildable source.
|
||||||
|
# Select all leaf workspaces so nested stock services are actually built.
|
||||||
# Store original location
|
exec bun run turbo run build --filter='!@stock-bot/stock-app' "${args[@]}"
|
||||||
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
|
|
||||||
|
|
|
||||||
|
|
@ -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
|
# Turbo derives ordering from package dependencies, including contract packages.
|
||||||
RED='\033[0;31m'
|
exec bun run turbo run build --filter='./libs/**' "$@"
|
||||||
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"
|
|
||||||
|
|
|
||||||
42
scripts/check.ts
Normal file
42
scripts/check.ts
Normal 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');
|
||||||
|
}
|
||||||
|
}
|
||||||
18
scripts/test/native-bindings.test.ts
Normal file
18
scripts/test/native-bindings.test.ts
Normal 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);
|
||||||
|
});
|
||||||
|
});
|
||||||
62
scripts/test/service-consumers.test.ts
Normal file
62
scripts/test/service-consumers.test.ts
Normal 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',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
101
scripts/test/workspace.test.ts
Normal file
101
scripts/test/workspace.test.ts
Normal 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']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -11,7 +11,5 @@
|
||||||
"emitDecoratorMetadata": true,
|
"emitDecoratorMetadata": true,
|
||||||
// Suppress decorator-related type checking issues due to Bun's hybrid implementation
|
// Suppress decorator-related type checking issues due to Bun's hybrid implementation
|
||||||
"skipLibCheck": true
|
"skipLibCheck": true
|
||||||
},
|
}
|
||||||
"include": ["src/**/*"],
|
|
||||||
"exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"]
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
32
tsconfig.check.json
Normal file
32
tsconfig.check.json
Normal 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
4
tsconfig.contracts.json
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
{
|
||||||
|
"extends": "./tsconfig.check.json",
|
||||||
|
"include": ["libs/core/services/test/contracts.type-test.ts"]
|
||||||
|
}
|
||||||
20
turbo.json
20
turbo.json
|
|
@ -1,27 +1,13 @@
|
||||||
{
|
{
|
||||||
"$schema": "https://turbo.build/schema.json",
|
"$schema": "https://turbo.build/schema.json",
|
||||||
"ui": "tui",
|
"ui": "tui",
|
||||||
"globalDependencies": ["**/.env.*local"],
|
"globalDependencies": ["**/.env.*local", "tsconfig.json", "tsconfig.app.json", "tsconfig.lib.json", "Cargo.toml", "Cargo.lock"],
|
||||||
"tasks": {
|
"tasks": {
|
||||||
"build": {
|
"build": {
|
||||||
"dependsOn": ["^build"],
|
"dependsOn": ["^build"],
|
||||||
"outputs": ["dist/**"],
|
"outputs": ["dist/**", "*.tsbuildinfo"],
|
||||||
"inputs": [
|
"inputs": [
|
||||||
"src/**",
|
"$TURBO_DEFAULT$",
|
||||||
"package.json",
|
|
||||||
"tsconfig.json",
|
|
||||||
"!**/*.test.ts",
|
|
||||||
"!**/*.spec.ts",
|
|
||||||
"!**/test/**",
|
|
||||||
"!**/tests/**",
|
|
||||||
"!**/__tests__/**"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"build:libs": {
|
|
||||||
"dependsOn": [],
|
|
||||||
"outputs": ["dist/**"],
|
|
||||||
"inputs": [
|
|
||||||
"src/**",
|
|
||||||
"package.json",
|
"package.json",
|
||||||
"tsconfig.json",
|
"tsconfig.json",
|
||||||
"!**/*.test.ts",
|
"!**/*.test.ts",
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue