commit 2 refactor

This commit is contained in:
Boki 2026-10-20 14:35:45 -04:00
parent 588f666943
commit 32e43c9243
310 changed files with 33318 additions and 31189 deletions

File diff suppressed because it is too large Load diff

View file

@ -1,294 +1,301 @@
import { v4 as uuidv4 } from 'uuid';
import { getLogger } from '@stock-bot/logger';
import type { IServiceContainer } from '@stock-bot/handlers';
const logger = getLogger('backtest-service');
// Use environment variable or default
const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004';
export interface BacktestRequest {
strategy: string;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
config?: Record<string, any>;
}
export interface BacktestJob {
id: string;
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
strategy: string;
symbols: string[];
startDate: Date;
endDate: Date;
initialCapital: number;
config: Record<string, any>;
createdAt: Date;
updatedAt: Date;
error?: string;
}
export class BacktestService {
private container: IServiceContainer;
constructor(container: IServiceContainer) {
this.container = container;
logger.info('BacktestService initialized', {
hasPostgres: !!container.postgres,
containerKeys: Object.keys(container)
});
}
async createBacktest(request: BacktestRequest): Promise<BacktestJob> {
const backtestId = uuidv4();
// Insert into PostgreSQL
const result = await this.container.postgres.query(
`INSERT INTO backtests
(id, name, strategy, symbols, start_date, end_date, initial_capital, config, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending')
RETURNING *`,
[
backtestId,
request.config?.name || `Backtest ${new Date().toISOString()}`,
request.strategy,
JSON.stringify(request.symbols),
request.startDate,
request.endDate,
request.initialCapital,
JSON.stringify(request.config || {})
]
);
const backtest: BacktestJob = {
id: result.rows[0].id,
status: result.rows[0].status,
strategy: result.rows[0].strategy,
symbols: result.rows[0].symbols,
startDate: result.rows[0].start_date,
endDate: result.rows[0].end_date,
initialCapital: parseFloat(result.rows[0].initial_capital),
config: result.rows[0].config,
createdAt: result.rows[0].created_at,
updatedAt: result.rows[0].updated_at,
};
// Call orchestrator to run backtest
try {
const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/run`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
mode: 'backtest',
startDate: new Date(request.startDate).toISOString(),
endDate: new Date(request.endDate).toISOString(),
symbols: request.symbols,
strategy: request.strategy,
initialCapital: request.initialCapital,
dataFrequency: '1d', // Default to daily
commission: request.config?.commission,
slippage: request.config?.slippage,
speed: 'max', // Default speed
fillModel: {
slippage: 'realistic',
marketImpact: true,
partialFills: true
}
}),
});
if (!response.ok) {
throw new Error(`Orchestrator returned ${response.status}`);
}
const result = await response.json();
// Store result directly without transformation
if (result.status === 'completed') {
// Update backtest status
await this.container.postgres.query(
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
['completed', backtestId]
);
// Store results in backtest_results table
await this.saveBacktestResults(backtestId, result);
logger.info('Backtest completed', {
backtestId,
trades: result.metrics?.totalTrades,
return: result.metrics?.totalReturn
});
} else {
// Update status to running if not completed
await this.container.postgres.query(
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
['running', backtestId]
);
}
logger.info('Backtest started in orchestrator', { backtestId, result });
} catch (error) {
logger.error('Failed to start backtest in orchestrator', { backtestId, error });
await this.container.postgres.query(
'UPDATE backtests SET status = $1, error = $2, updated_at = NOW() WHERE id = $3',
['failed', error.message, backtestId]
);
backtest.status = 'failed';
backtest.error = error.message;
}
return backtest;
}
async getBacktest(id: string): Promise<BacktestJob | null> {
const result = await this.container.postgres.query(
'SELECT * FROM backtests WHERE id = $1',
[id]
);
if (result.rows.length === 0) {
return null;
}
const row = result.rows[0];
return {
id: row.id,
status: row.status,
strategy: row.strategy,
symbols: row.symbols,
startDate: row.start_date,
endDate: row.end_date,
initialCapital: parseFloat(row.initial_capital),
config: row.config,
createdAt: row.created_at,
updatedAt: row.updated_at,
error: row.error,
};
}
async getBacktestResults(id: string): Promise<any> {
const result = await this.container.postgres.query(
`SELECT
br.*,
b.strategy,
b.symbols,
b.start_date,
b.end_date,
b.initial_capital,
b.config as backtest_config
FROM backtest_results br
JOIN backtests b ON b.id = br.backtest_id
WHERE br.backtest_id = $1`,
[id]
);
if (result.rows.length === 0) {
return null;
}
const row = result.rows[0];
// Reconstruct the result format expected by frontend
return {
backtestId: row.backtest_id,
status: 'completed',
completedAt: row.completed_at.toISOString(),
config: {
name: row.backtest_config?.name || 'Backtest',
strategy: row.strategy,
symbols: row.symbols,
startDate: row.start_date.toISOString(),
endDate: row.end_date.toISOString(),
initialCapital: parseFloat(row.initial_capital),
commission: row.backtest_config?.commission ?? 0.001,
slippage: row.backtest_config?.slippage ?? 0.0001,
dataFrequency: row.backtest_config?.dataFrequency || '1d',
},
metrics: row.metrics,
equity: row.equity_curve,
ohlcData: row.ohlc_data,
trades: row.trades,
positions: row.positions,
analytics: row.analytics,
executionTime: row.execution_time,
};
}
async listBacktests(params: { limit: number; offset: number }): Promise<BacktestJob[]> {
const result = await this.container.postgres.query(
`SELECT * FROM backtests
ORDER BY created_at DESC
LIMIT $1 OFFSET $2`,
[params.limit, params.offset]
);
return result.rows.map(row => ({
id: row.id,
status: row.status,
strategy: row.strategy,
symbols: row.symbols,
startDate: row.start_date,
endDate: row.end_date,
initialCapital: parseFloat(row.initial_capital),
config: row.config,
createdAt: row.created_at,
updatedAt: row.updated_at,
error: row.error,
}));
}
async updateBacktestStatus(id: string, status: BacktestJob['status'], error?: string): Promise<void> {
if (error) {
await this.container.postgres.query(
'UPDATE backtests SET status = $1, error = $2, updated_at = NOW() WHERE id = $3',
[status, error, id]
);
} else {
await this.container.postgres.query(
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
[status, id]
);
}
}
async cancelBacktest(id: string): Promise<void> {
await this.updateBacktestStatus(id, 'cancelled');
// Call orchestrator to stop backtest
try {
await fetch(`${ORCHESTRATOR_URL}/api/backtest/stop`, {
method: 'POST',
});
} catch (error) {
logger.error('Failed to stop backtest in orchestrator', { backtestId: id, error });
}
}
private async saveBacktestResults(backtestId: string, result: any): Promise<void> {
try {
await this.container.postgres.query(
`INSERT INTO backtest_results
(backtest_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
[
backtestId,
result.completedAt || new Date(),
JSON.stringify(result.metrics || {}),
JSON.stringify(result.equity || result.equityCurve || []),
JSON.stringify(result.ohlcData || {}),
JSON.stringify(result.trades || []),
JSON.stringify(result.positions || result.finalPositions || {}),
JSON.stringify(result.analytics || {}),
result.executionTime || 0
]
);
} catch (error) {
logger.error('Failed to save backtest results', { backtestId, error });
throw error;
}
}
}
import { randomUUID as uuidv4 } from 'node:crypto';
import { at } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
const logger = getLogger('backtest-service');
// Use environment variable or default
const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004';
export interface BacktestRequest {
strategy: string;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
config?: Record<string, unknown>;
}
export interface BacktestJob {
id: string;
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
strategy: string;
symbols: string[];
startDate: Date;
endDate: Date;
initialCapital: number;
config: Record<string, unknown>;
createdAt: Date;
updatedAt: Date;
error?: string;
}
export class BacktestService {
private container: IServiceContainer & { postgres: NonNullable<IServiceContainer['postgres']> };
constructor(container: IServiceContainer) {
this.container = requireServices(container, 'postgres');
logger.info('BacktestService initialized', {
hasPostgres: !!container.postgres,
containerKeys: Object.keys(container),
});
}
async createBacktest(request: BacktestRequest): Promise<BacktestJob> {
const backtestId = uuidv4();
// Insert into PostgreSQL
const result = await this.container.postgres.query(
`INSERT INTO backtests
(id, name, strategy, symbols, start_date, end_date, initial_capital, config, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending')
RETURNING *`,
[
backtestId,
request.config?.name || `Backtest ${new Date().toISOString()}`,
request.strategy,
JSON.stringify(request.symbols),
request.startDate,
request.endDate,
request.initialCapital,
JSON.stringify(request.config || {}),
]
);
const backtest: BacktestJob = {
id: at(result.rows, 0).id,
status: at(result.rows, 0).status,
strategy: at(result.rows, 0).strategy,
symbols: at(result.rows, 0).symbols,
startDate: at(result.rows, 0).start_date,
endDate: at(result.rows, 0).end_date,
initialCapital: parseFloat(at(result.rows, 0).initial_capital),
config: at(result.rows, 0).config,
createdAt: at(result.rows, 0).created_at,
updatedAt: at(result.rows, 0).updated_at,
};
// Call orchestrator to run backtest
try {
const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/run`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
mode: 'backtest',
startDate: new Date(request.startDate).toISOString(),
endDate: new Date(request.endDate).toISOString(),
symbols: request.symbols,
strategy: request.strategy,
initialCapital: request.initialCapital,
dataFrequency: '1d', // Default to daily
commission: request.config?.commission,
slippage: request.config?.slippage,
speed: 'max', // Default speed
fillModel: {
slippage: 'realistic',
marketImpact: true,
partialFills: true,
},
}),
});
if (!response.ok) {
throw new Error(`Orchestrator returned ${response.status}`);
}
const result = await response.json();
// Store result directly without transformation
if (result.status === 'completed') {
// Update backtest status
await this.container.postgres.query(
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
['completed', backtestId]
);
// Store results in backtest_results table
await this.saveBacktestResults(backtestId, result);
logger.info('Backtest completed', {
backtestId,
trades: result.metrics?.totalTrades,
return: result.metrics?.totalReturn,
});
} else {
// Update status to running if not completed
await this.container.postgres.query(
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
['running', backtestId]
);
}
logger.info('Backtest started in orchestrator', { backtestId, result });
} catch (error) {
logger.error('Failed to start backtest in orchestrator', { backtestId, error });
await this.container.postgres.query(
'UPDATE backtests SET status = $1, error = $2, updated_at = NOW() WHERE id = $3',
['failed', error instanceof Error ? error.message : String(error), backtestId]
);
backtest.status = 'failed';
backtest.error = error instanceof Error ? error.message : String(error);
}
return backtest;
}
async getBacktest(id: string): Promise<BacktestJob | null> {
const result = await this.container.postgres.query('SELECT * FROM backtests WHERE id = $1', [
id,
]);
if (result.rows.length === 0) {
return null;
}
const row = at(result.rows, 0);
return {
id: row.id,
status: row.status,
strategy: row.strategy,
symbols: row.symbols,
startDate: row.start_date,
endDate: row.end_date,
initialCapital: parseFloat(row.initial_capital),
config: row.config,
createdAt: row.created_at,
updatedAt: row.updated_at,
error: row.error,
};
}
async getBacktestResults(id: string) {
const result = await this.container.postgres.query(
`SELECT
br.*,
b.strategy,
b.symbols,
b.start_date,
b.end_date,
b.initial_capital,
b.config as backtest_config
FROM backtest_results br
JOIN backtests b ON b.id = br.backtest_id
WHERE br.backtest_id = $1`,
[id]
);
if (result.rows.length === 0) {
return null;
}
const row = at(result.rows, 0);
// Reconstruct the result format expected by frontend
return {
backtestId: row.backtest_id,
status: 'completed',
completedAt: row.completed_at.toISOString(),
config: {
name: row.backtest_config?.name || 'Backtest',
strategy: row.strategy,
symbols: row.symbols,
startDate: row.start_date.toISOString(),
endDate: row.end_date.toISOString(),
initialCapital: parseFloat(row.initial_capital),
commission: row.backtest_config?.commission ?? 0.001,
slippage: row.backtest_config?.slippage ?? 0.0001,
dataFrequency: row.backtest_config?.dataFrequency || '1d',
},
metrics: row.metrics,
equity: row.equity_curve,
ohlcData: row.ohlc_data,
trades: row.trades,
positions: row.positions,
analytics: row.analytics,
executionTime: row.execution_time,
};
}
async listBacktests(params: { limit: number; offset: number }): Promise<BacktestJob[]> {
const result = await this.container.postgres.query(
`SELECT * FROM backtests
ORDER BY created_at DESC
LIMIT $1 OFFSET $2`,
[params.limit, params.offset]
);
return result.rows.map(row => ({
id: row.id,
status: row.status,
strategy: row.strategy,
symbols: row.symbols,
startDate: row.start_date,
endDate: row.end_date,
initialCapital: parseFloat(row.initial_capital),
config: row.config,
createdAt: row.created_at,
updatedAt: row.updated_at,
error: row.error,
}));
}
async updateBacktestStatus(
id: string,
status: BacktestJob['status'],
error?: string
): Promise<void> {
if (error) {
await this.container.postgres.query(
'UPDATE backtests SET status = $1, error = $2, updated_at = NOW() WHERE id = $3',
[status, error, id]
);
} else {
await this.container.postgres.query(
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
[status, id]
);
}
}
async cancelBacktest(id: string): Promise<void> {
await this.updateBacktestStatus(id, 'cancelled');
// Call orchestrator to stop backtest
try {
await fetch(`${ORCHESTRATOR_URL}/api/backtest/stop`, {
method: 'POST',
});
} catch (error) {
logger.error('Failed to stop backtest in orchestrator', { backtestId: id, error });
}
}
private async saveBacktestResults(
backtestId: string,
result: Record<string, unknown>
): Promise<void> {
try {
await this.container.postgres.query(
`INSERT INTO backtest_results
(backtest_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
[
backtestId,
result.completedAt || new Date(),
JSON.stringify(result.metrics || {}),
JSON.stringify(result.equity || result.equityCurve || []),
JSON.stringify(result.ohlcData || {}),
JSON.stringify(result.trades || []),
JSON.stringify(result.positions || result.finalPositions || {}),
JSON.stringify(result.analytics || {}),
result.executionTime || 0,
]
);
} catch (error) {
logger.error('Failed to save backtest results', { backtestId, error });
throw error;
}
}
}

View file

@ -1,15 +1,16 @@
import { at } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import type { IServiceContainer } from '@stock-bot/services';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import {
CreateExchangeRequest,
CreateProviderMappingRequest,
Exchange,
ExchangeStats,
ExchangeWithMappings,
ProviderExchange,
ProviderMapping,
UpdateExchangeRequest,
UpdateProviderMappingRequest,
type CreateExchangeRequest,
type CreateProviderMappingRequest,
type Exchange,
type ExchangeStats,
type ExchangeWithMappings,
type ProviderExchange,
type ProviderMapping,
type UpdateExchangeRequest,
type UpdateProviderMappingRequest,
} from '../types/exchange.types';
const logger = getLogger('exchange-service');
@ -18,11 +19,11 @@ export class ExchangeService {
constructor(private container: IServiceContainer) {}
private get postgresClient() {
return this.container.postgres;
return requireServices(this.container, 'postgres').postgres;
}
private get mongoClient() {
return this.container.mongodb;
return requireServices(this.container, 'mongodb').mongodb;
}
// Exchanges
@ -49,7 +50,7 @@ export class ExchangeService {
ORDER BY e.code
`;
const exchangesResult = await this.postgresClient.query(exchangesQuery);
const exchangesResult = await this.postgresClient.query<ExchangeWithMappings>(exchangesQuery);
// Get all provider mappings
const mappingsQuery = `
@ -62,7 +63,7 @@ export class ExchangeService {
WHERE e.visible = true
ORDER BY pem.master_exchange_id, pem.provider, pem.provider_exchange_code
`;
const mappingsResult = await this.postgresClient.query(mappingsQuery);
const mappingsResult = await this.postgresClient.query<ProviderMapping>(mappingsQuery);
// Group mappings by exchange ID
const mappingsByExchange = mappingsResult.rows.reduce(
@ -88,7 +89,7 @@ export class ExchangeService {
id: string
): Promise<{ exchange: Exchange; provider_mappings: ProviderMapping[] } | null> {
const exchangeQuery = 'SELECT * FROM exchanges WHERE id = $1 AND visible = true';
const exchangeResult = await this.postgresClient.query(exchangeQuery, [id]);
const exchangeResult = await this.postgresClient.query<Exchange>(exchangeQuery, [id]);
if (exchangeResult.rows.length === 0) {
return null;
@ -104,10 +105,10 @@ export class ExchangeService {
WHERE pem.master_exchange_id = $1
ORDER BY pem.provider, pem.provider_exchange_code
`;
const mappingsResult = await this.postgresClient.query(mappingsQuery, [id]);
const mappingsResult = await this.postgresClient.query<ProviderMapping>(mappingsQuery, [id]);
return {
exchange: exchangeResult.rows[0],
exchange: at(exchangeResult.rows, 0),
provider_mappings: mappingsResult.rows,
};
}
@ -119,7 +120,7 @@ export class ExchangeService {
RETURNING *
`;
const result = await this.postgresClient.query(query, [
const result = await this.postgresClient.query<Exchange>(query, [
data.code,
data.name,
data.country,
@ -128,12 +129,12 @@ export class ExchangeService {
]);
logger.info('Exchange created', {
exchangeId: result.rows[0].id,
exchangeId: at(result.rows, 0).id,
code: data.code,
name: data.name,
});
return result.rows[0];
return at(result.rows, 0);
}
async updateExchange(id: string, updates: UpdateExchangeRequest): Promise<Exchange | null> {
@ -156,7 +157,7 @@ export class ExchangeService {
RETURNING *
`;
const result = await this.postgresClient.query(query, values);
const result = await this.postgresClient.query<Exchange>(query, values);
if (result.rows.length === 0) {
return null;
@ -169,7 +170,7 @@ export class ExchangeService {
logger.info('Exchange updated', { exchangeId: id, updates });
return result.rows[0];
return result.rows[0] ?? null;
}
// Provider Mappings
@ -186,7 +187,7 @@ export class ExchangeService {
ORDER BY pem.provider, pem.provider_exchange_code
`;
const result = await this.postgresClient.query(query);
const result = await this.postgresClient.query<ProviderMapping>(query);
return result.rows;
}
@ -203,7 +204,7 @@ export class ExchangeService {
ORDER BY pem.provider_exchange_code
`;
const result = await this.postgresClient.query(query, [provider]);
const result = await this.postgresClient.query<ProviderMapping>(query, [provider]);
return result.rows;
}
@ -216,7 +217,7 @@ export class ExchangeService {
RETURNING *
`;
const result = await this.postgresClient.query(query, [
const result = await this.postgresClient.query<ProviderMapping>(query, [
data.provider,
data.provider_exchange_code,
data.provider_exchange_name,
@ -234,7 +235,7 @@ export class ExchangeService {
master_exchange_id: data.master_exchange_id,
});
return result.rows[0];
return at(result.rows, 0);
}
async updateProviderMapping(
@ -261,7 +262,7 @@ export class ExchangeService {
RETURNING *
`;
const result = await this.postgresClient.query(query, values);
const result = await this.postgresClient.query<ProviderMapping>(query, values);
if (result.rows.length === 0) {
return null;
@ -269,7 +270,7 @@ export class ExchangeService {
logger.info('Provider mapping updated', { mappingId: id, updates });
return result.rows[0];
return result.rows[0] ?? null;
}
async deleteProviderMappingsByExchangeId(exchangeId: string): Promise<number> {
@ -309,8 +310,8 @@ export class ExchangeService {
(SELECT COUNT(DISTINCT provider) FROM provider_exchange_mappings pem JOIN exchanges e ON pem.master_exchange_id = e.id WHERE e.visible = true) as providers
`;
const result = await this.postgresClient.query(query);
return result.rows[0];
const result = await this.postgresClient.query<ExchangeStats>(query);
return at(result.rows, 0);
}
async getUnmappedProviderExchanges(provider: string): Promise<ProviderExchange[]> {

View file

@ -6,6 +6,7 @@
import * as os from 'os';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import { getFullQueueName } from '@stock-bot/queue';
import type {
CacheStats,
DatabaseStats,
@ -73,269 +74,53 @@ export class MonitoringService {
* Get queue statistics
*/
async getQueueStats(): Promise<QueueStats[]> {
const stats: QueueStats[] = [];
try {
if (!this.container.queueManager) {
this.logger.warn('No queue manager available');
return stats;
}
// Get all queue names from the QueueManager
const queueManager = this.container.queueManager as any;
this.logger.debug('Queue manager type:', {
type: queueManager.constructor.name,
hasGetAllQueues: typeof queueManager.getAllQueues === 'function',
hasQueues: !!queueManager.queues,
hasGetQueue: typeof queueManager.getQueue === 'function',
});
// Always use the known queue names since web-api doesn't create worker queues
const handlerMapping = {
qm: 'data-ingestion',
ib: 'data-ingestion',
ceo: 'data-ingestion',
webshare: 'data-ingestion',
exchanges: 'data-pipeline',
symbols: 'data-pipeline',
};
// Worker configuration per queue (from service configs)
const workerConfig: Record<string, { count: number; concurrency: number }> = {
qm: { count: 1, concurrency: 2 },
ib: { count: 1, concurrency: 1 },
ceo: { count: 1, concurrency: 2 },
webshare: { count: 1, concurrency: 1 },
exchanges: { count: 1, concurrency: 1 },
symbols: { count: 1, concurrency: 2 },
};
const queueNames = Object.keys(handlerMapping);
this.logger.debug('Using known queue names', { count: queueNames.length, names: queueNames });
// Create BullMQ queues directly with the correct format
for (const handlerName of queueNames) {
try {
// Import BullMQ directly to create queue instances
const { Queue: BullMQQueue } = await import('bullmq');
const connection = {
host: 'localhost',
port: 6379,
db: 0, // All queues now in DB 0
};
// Get the service that owns this handler
const serviceName = handlerMapping[handlerName as keyof typeof handlerMapping];
// Create BullMQ queue with the new naming format {service_handler}
const fullQueueName = `{${serviceName}_${handlerName}}`;
const bullQueue = new BullMQQueue(fullQueueName, { connection });
// Get stats directly from BullMQ
const queueStats = await this.getQueueStatsForBullQueue(bullQueue, handlerName);
// Get actual worker count from BullMQ
const actualWorkerCount = await this.getActiveWorkerCountFromBullMQ(bullQueue);
const configuredWorkers = workerConfig[handlerName] || { count: 0, concurrency: 1 };
stats.push({
name: handlerName,
service: serviceName,
queue: handlerName,
connected: true,
jobs: queueStats,
workers: {
count: actualWorkerCount,
concurrency: configuredWorkers.concurrency,
},
});
// Close the queue connection after getting stats
await bullQueue.close();
} catch (error) {
this.logger.warn(`Failed to get stats for queue ${handlerName}`, { error });
stats.push({
name: handlerName,
service: serviceName,
queue: handlerName,
connected: false,
jobs: {
waiting: 0,
active: 0,
completed: 0,
failed: 0,
delayed: 0,
paused: 0,
},
});
}
}
} catch (error) {
this.logger.error('Failed to get queue stats', { error });
const manager = this.container.queueManager;
if (!manager) {
return [];
}
return stats;
}
/**
* Get stats for a BullMQ queue directly
*/
private async getQueueStatsForBullQueue(bullQueue: any, queueName: string) {
try {
// BullMQ provides getJobCounts which returns all counts at once
const counts = await bullQueue.getJobCounts();
return {
waiting: counts.waiting || 0,
active: counts.active || 0,
completed: counts.completed || 0,
failed: counts.failed || 0,
delayed: counts.delayed || 0,
paused: counts.paused || 0,
prioritized: counts.prioritized || 0,
'waiting-children': counts['waiting-children'] || 0,
};
} catch (error) {
this.logger.error(`Failed to get stats for BullMQ queue ${queueName}`, { error });
// Fallback to individual methods
try {
const [waiting, active, completed, failed, delayed, paused] = await Promise.all([
bullQueue.getWaitingCount(),
bullQueue.getActiveCount(),
bullQueue.getCompletedCount(),
bullQueue.getFailedCount(),
bullQueue.getDelayedCount(),
bullQueue.getPausedCount ? bullQueue.getPausedCount() : 0,
]);
return {
waiting,
active,
completed,
failed,
delayed,
paused,
};
} catch (fallbackError) {
this.logger.error(`Fallback also failed for queue ${queueName}`, { fallbackError });
return this.getQueueStatsForQueue(bullQueue, queueName);
}
}
}
/**
* Get stats for a specific queue
*/
private async getQueueStatsForQueue(queue: any, _queueName: string) {
// Check if it has the getStats method
if (queue.getStats && typeof queue.getStats === 'function') {
const stats = await queue.getStats();
return {
waiting: stats.waiting || 0,
active: stats.active || 0,
completed: stats.completed || 0,
failed: stats.failed || 0,
delayed: stats.delayed || 0,
paused: stats.paused || 0,
};
}
// Try individual count methods
const [waiting, active, completed, failed, delayed] = await Promise.all([
this.safeGetCount(queue, 'getWaitingCount', 'getWaiting'),
this.safeGetCount(queue, 'getActiveCount', 'getActive'),
this.safeGetCount(queue, 'getCompletedCount', 'getCompleted'),
this.safeGetCount(queue, 'getFailedCount', 'getFailed'),
this.safeGetCount(queue, 'getDelayedCount', 'getDelayed'),
]);
const paused = await this.safeGetPausedStatus(queue);
return {
waiting,
active,
completed,
failed,
delayed,
paused,
const owners = {
qm: 'data-ingestion',
ib: 'data-ingestion',
ceo: 'data-ingestion',
webshare: 'data-ingestion',
exchanges: 'data-pipeline',
symbols: 'data-pipeline',
};
}
/**
* Safely get count from queue
*/
private async safeGetCount(queue: any, ...methodNames: string[]): Promise<number> {
for (const methodName of methodNames) {
if (queue[methodName] && typeof queue[methodName] === 'function') {
return Promise.all(
Object.entries(owners).map(async ([name, service]) => {
try {
const result = await queue[methodName]();
return Array.isArray(result) ? result.length : result || 0;
} catch (_e) {
// Continue to next method
const queue = manager.getQueue(getFullQueueName(service, name));
const snapshot = await queue.getStats();
return {
name,
service,
queue: name,
connected: true,
jobs: {
waiting: snapshot.waiting,
active: snapshot.active,
completed: snapshot.completed,
failed: snapshot.failed,
delayed: snapshot.delayed,
paused: snapshot.paused ? 1 : 0,
},
workers: { count: snapshot.workers ?? queue.getWorkerCount(), concurrency: 1 },
};
} catch (error) {
this.logger.warn('Unable to inspect queue', { name, service, error });
return {
name,
service,
queue: name,
connected: false,
jobs: { waiting: 0, active: 0, completed: 0, failed: 0, delayed: 0, paused: 0 },
};
}
}
}
return 0;
})
);
}
/**
* Get paused status
*/
private async safeGetPausedStatus(queue: any): Promise<number> {
try {
if (queue.isPaused && typeof queue.isPaused === 'function') {
const isPaused = await queue.isPaused();
return isPaused ? 1 : 0;
}
if (queue.getPausedCount && typeof queue.getPausedCount === 'function') {
return await queue.getPausedCount();
}
} catch (_e) {
// Ignore
}
return 0;
}
/**
* Get worker info for a queue
*/
private getWorkerInfo(queue: any, queueManager: any, _queueName: string) {
try {
// Check queue itself for worker info
if (queue.workers && Array.isArray(queue.workers)) {
return {
count: queue.workers.length,
concurrency: queue.workers[0]?.concurrency || 1,
};
}
// Check queue manager for worker config
if (queueManager.config?.defaultQueueOptions) {
const options = queueManager.config.defaultQueueOptions;
return {
count: options.workers || 1,
concurrency: options.concurrency || 1,
};
}
// Check for getWorkerCount method
if (queue.getWorkerCount && typeof queue.getWorkerCount === 'function') {
const count = queue.getWorkerCount();
return {
count,
concurrency: 1,
};
}
} catch (_e) {
// Ignore
}
return undefined;
}
/**
* Get database statistics
*/
/** Database health uses the public adapter capabilities. */
async getDatabaseStats(): Promise<DatabaseStats[]> {
const stats: DatabaseStats[] = [];
@ -347,12 +132,13 @@ export class MonitoringService {
const latency = Date.now() - startTime;
// Get pool stats
const pool = (this.container.postgres as any).pool;
const pool = this.container.postgres.connectionPool;
const poolStats = pool
? {
size: pool.totalCount || 0,
active: pool.idleCount || 0,
idle: pool.waitingCount || 0,
active: pool.totalCount - pool.idleCount,
idle: pool.idleCount,
waiting: pool.waitingCount,
max: pool.options?.max || 0,
}
: undefined;
@ -378,7 +164,7 @@ export class MonitoringService {
if (this.container.mongodb) {
try {
const startTime = Date.now();
const mongoClient = this.container.mongodb as any; // This is MongoDBClient
const mongoClient = this.container.mongodb; // This is MongoDBClient
const db = mongoClient.getDatabase();
await db.admin().ping();
const latency = Date.now() - startTime;
@ -528,14 +314,14 @@ export class MonitoringService {
*/
private parseInfoValue(info: string, key: string): number {
const match = info.match(new RegExp(`${key}:(\\d+)`));
return match ? parseInt(match[1], 10) : 0;
return match?.[1] ? parseInt(match[1], 10) : 0;
}
/**
* Parse Redis INFO into structured object
*/
private parseRedisInfo(info: string): Record<string, any> {
const result: Record<string, any> = {};
private parseRedisInfo(info: string): Record<string, Record<string, string>> {
const result: Record<string, Record<string, string>> = {};
const sections = info.split('\r\n\r\n');
for (const section of sections) {
@ -544,7 +330,7 @@ export class MonitoringService {
result[sectionName] = {};
for (let i = 1; i < lines.length; i++) {
const [key, value] = lines[i].split(':');
const [key, value] = (lines[i] ?? '').split(':');
if (key && value) {
result[sectionName][key] = value;
}
@ -656,7 +442,7 @@ export class MonitoringService {
this.logger.debug('Attempting to fetch proxy data from cache');
const [cachedProxies, lastUpdateStr] = await Promise.all([
cacheProvider.getRaw<any[]>('cache:proxy:active'),
cacheProvider.getRaw<{ isWorking?: boolean }[]>('cache:proxy:active'),
cacheProvider.getRaw<string>('cache:proxy:last-update'),
]);
@ -668,8 +454,8 @@ export class MonitoringService {
});
if (cachedProxies && Array.isArray(cachedProxies)) {
const workingCount = cachedProxies.filter((p: any) => p.isWorking !== false).length;
const failedCount = cachedProxies.filter((p: any) => p.isWorking === false).length;
const workingCount = cachedProxies.filter(p => p.isWorking !== false).length;
const failedCount = cachedProxies.filter(p => p.isWorking === false).length;
return {
enabled: true,
@ -811,23 +597,4 @@ export class MonitoringService {
/**
* Get active worker count using BullMQ's built-in tracking
*/
private async getActiveWorkerCountFromBullMQ(bullQueue: any): Promise<number> {
try {
// Use BullMQ's built-in getWorkers method
if (bullQueue.getWorkers && typeof bullQueue.getWorkers === 'function') {
const workers = await bullQueue.getWorkers();
return workers.length;
}
// Fallback to getWorkersCount if available
if (bullQueue.getWorkersCount && typeof bullQueue.getWorkersCount === 'function') {
return await bullQueue.getWorkersCount();
}
return 0;
} catch (error) {
this.logger.debug('Failed to get active worker count from BullMQ', { error });
return 0;
}
}
}

View file

@ -14,12 +14,12 @@ export interface PipelineJobResult {
jobId?: string;
message?: string;
error?: string;
data?: any;
data?: unknown;
}
export interface PipelineStatsResult {
success: boolean;
data?: any;
data?: Record<string, unknown>;
error?: string;
}
@ -294,7 +294,7 @@ export class PipelineService {
});
// Wait for job to complete and return result
const result = await exchangesQueue.waitForJob(job);
const result = await exchangesQueue.waitForJob<Record<string, unknown>>(job);
return { success: true, data: result };
} catch (error) {
logger.error('Failed to get exchange stats', { error });
@ -323,7 +323,7 @@ export class PipelineService {
});
// Wait for job to complete and return result
const result = await exchangesQueue.waitForJob(job);
const result = await exchangesQueue.waitForJob<Record<string, unknown>>(job);
return { success: true, data: result };
} catch (error) {
logger.error('Failed to get provider mapping stats', { error });