fix(monitoring): report observed research and paper readiness (O02)

This commit is contained in:
Boki 2026-10-28 12:58:38 -04:00
parent 70d173a908
commit 8c858b9d5c
23 changed files with 1340 additions and 319 deletions

View file

@ -7,6 +7,11 @@ 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 {
monitoringReadinessSchema,
orchestratorDiagnosticSchema,
type MonitoringReadiness,
} from '@stock-bot/stock-config/diagnostics';
import type {
CacheStats,
DatabaseStats,
@ -22,7 +27,135 @@ export class MonitoringService {
private readonly logger = getLogger('monitoring-service');
private startTime = Date.now();
constructor(private readonly container: IServiceContainer) {}
constructor(
private readonly container: IServiceContainer,
private readonly options: {
origin?: string;
request?: (url: URL, init: RequestInit) => Promise<Response>;
} = {}
) {}
/** Explicit prerequisites and unknown execution capability; never a readiness shortcut. */
async getReadiness(request: Request): Promise<MonitoringReadiness> {
const reasons: string[] = [];
const [leases, queue, orchestrator] = await Promise.all([
(async () => {
try {
if (!this.container.postgres) {
return null;
}
const result = await this.container.postgres.query<{
run_id: string;
attempt_id: string | null;
expired: boolean;
}>(
"SELECT id AS run_id, attempt_id, (lease_expires_at IS NULL OR lease_expires_at <= NOW()) AS expired FROM runs WHERE status IN ('running','paused') ORDER BY id"
);
return result.rows.map(row => ({
runId: row.run_id,
attemptId: row.attempt_id,
expired: row.expired,
}));
} catch {
return null;
}
})(),
(async () => {
try {
if (!this.container.queueManager) {
throw new Error('Unavailable');
}
const snapshot = await this.container.queueManager
.getQueue(getFullQueueName('orchestrator', 'orchestrator'), { workers: 0 })
.getStats();
return { connected: true, workers: snapshot.workers ?? null, paused: snapshot.paused };
} catch {
return { connected: false, workers: null, paused: null };
}
})(),
(async () => {
try {
if (!this.options.origin) {
return null;
}
const origin = new URL(this.options.origin);
if (
!['http:', 'https:'].includes(origin.protocol) ||
origin.username ||
origin.password ||
origin.pathname !== '/' ||
origin.search ||
origin.hash
) {
return null;
}
const headers = new Headers();
for (const name of ['authorization', 'cookie', 'origin']) {
const value = request.headers.get(name);
if (value) {
headers.set(name, value);
}
}
const response = await (this.options.request ?? fetch)(
new URL('/api/diagnostics', origin),
{ headers, redirect: 'error', signal: AbortSignal.timeout(5000) }
);
if (!response.ok) {
return null;
}
return orchestratorDiagnosticSchema.parse(await response.json());
} catch {
return null;
}
})(),
]);
if (leases === null) {
reasons.push('Research PostgreSQL unavailable');
}
if (!queue.connected) {
reasons.push('Research queue unavailable');
}
if (queue.workers === null) {
reasons.push('Research worker count unknown');
} else if (queue.workers === 0) {
reasons.push('No research queue workers');
}
if (queue.paused) {
reasons.push('Research queue paused');
}
if (!orchestrator) {
reasons.push(
this.options.origin
? 'Orchestrator diagnostics unavailable'
: 'Configure ORCHESTRATOR_URL to inspect orchestrator readiness'
);
} else {
if (!orchestrator.research) {
reasons.push('Research runtime unavailable');
} else if (!orchestrator.research.accepting) {
reasons.push('Research runtime shutting down');
}
if (!orchestrator.build) {
reasons.push('Canonical build artifacts unavailable');
}
}
if (leases?.some(lease => lease.expired)) {
reasons.push('Expired research attempts require durable recovery');
}
const unavailable = reasons.length > 0;
reasons.push(
'Native execution is verified at run start; this snapshot does not launch a worker'
);
return monitoringReadinessSchema.parse({
observedAt: new Date().toISOString(),
postgres: leases === null ? 'unavailable' : 'connected',
queue,
leases,
orchestrator,
research: { status: unavailable ? 'unavailable' : 'unknown', reasons },
live: 'disabled',
});
}
/**
* Get cache/Dragonfly statistics
@ -56,9 +189,7 @@ export class MonitoringService {
stats: {
hits: cacheStats.hits,
misses: cacheStats.misses,
keys: 0, // We can't get total keys without direct Redis access
evictedKeys: 0,
expiredKeys: 0,
keys: null, // Not measured by the public cache capability.
},
};
} catch (error) {
@ -85,26 +216,28 @@ export class MonitoringService {
webshare: 'data-ingestion',
exchanges: 'data-pipeline',
symbols: 'data-pipeline',
orchestrator: 'orchestrator',
};
return Promise.all(
Object.entries(owners).map(async ([name, service]) => {
try {
const queue = manager.getQueue(getFullQueueName(service, name));
const queue = manager.getQueue(getFullQueueName(service, name), { workers: 0 });
const snapshot = await queue.getStats();
return {
name,
service,
queue: name,
connected: true,
paused: snapshot.paused,
jobs: {
waiting: snapshot.waiting,
active: snapshot.active,
completed: snapshot.completed,
failed: snapshot.failed,
delayed: snapshot.delayed,
paused: snapshot.paused ? 1 : 0,
paused: null, // Queue pause status does not measure paused-job count.
},
workers: { count: snapshot.workers ?? queue.getWorkerCount(), concurrency: 1 },
workers: snapshot.workers === undefined ? undefined : { count: snapshot.workers },
};
} catch (error) {
this.logger.warn('Unable to inspect queue', { name, service, error });
@ -113,7 +246,7 @@ export class MonitoringService {
service,
queue: name,
connected: false,
jobs: { waiting: 0, active: 0, completed: 0, failed: 0, delayed: 0, paused: 0 },
jobs: null,
};
}
})
@ -199,7 +332,8 @@ export class MonitoringService {
const startTime = Date.now();
// QuestDB health check
const response = await fetch(
`http://${process.env.QUESTDB_HOST || 'localhost'}:9000/exec?query=SELECT%201`
`http://${process.env.QUESTDB_HOST || 'localhost'}:9000/exec?query=SELECT%201`,
{ signal: AbortSignal.timeout(5000), redirect: 'error' }
);
const latency = Date.now() - startTime;
@ -249,6 +383,18 @@ export class MonitoringService {
errors.push(`${disconnectedQueues.length} queue(s) are disconnected`);
}
if (!databaseStats.some(db => db.type === 'postgres')) {
errors.push('Research PostgreSQL is not configured');
}
if (
!queueStats.some(
queue =>
queue.service === 'orchestrator' && queue.connected && (queue.workers?.count ?? 0) > 0
)
) {
errors.push('Research queue worker unavailable');
}
const disconnectedDbs = databaseStats.filter(db => !db.connected);
if (disconnectedDbs.length > 0) {
errors.push(`${disconnectedDbs.length} database(s) are disconnected`);
@ -288,58 +434,27 @@ export class MonitoringService {
return {
requestsPerSecond: {
timestamp: now,
value: 0,
value: null,
unit: 'req/s',
},
averageResponseTime: {
timestamp: now,
value: 0,
value: null,
unit: 'ms',
},
errorRate: {
timestamp: now,
value: 0,
value: null,
unit: '%',
},
activeConnections: {
timestamp: now,
value: 0,
value: null,
unit: 'connections',
},
};
}
/**
* Parse value from Redis INFO output
*/
private parseInfoValue(info: string, key: string): number {
const match = info.match(new RegExp(`${key}:(\\d+)`));
return match?.[1] ? parseInt(match[1], 10) : 0;
}
/**
* Parse Redis INFO into structured object
*/
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) {
const lines = section.split('\r\n');
const sectionName = lines[0]?.replace('# ', '') || 'general';
result[sectionName] = {};
for (let i = 1; i < lines.length; i++) {
const [key, value] = (lines[i] ?? '').split(':');
if (key && value) {
result[sectionName][key] = value;
}
}
}
return result;
}
/**
* Get service status for all microservices
*/
@ -359,12 +474,12 @@ export class MonitoringService {
if (service.name === 'web-api') {
services.push({
name: 'web-api',
version: '1.0.0',
version: 'unknown',
status: 'running',
port: process.env.PORT ? parseInt(process.env.PORT) : 2003,
uptime: Date.now() - this.startTime,
lastCheck: new Date().toISOString(),
healthy: true,
healthy: null,
});
continue;
}
@ -379,12 +494,15 @@ export class MonitoringService {
const data = await response.json();
services.push({
name: service.name,
version: data.version || '1.0.0',
version: typeof data.version === 'string' ? data.version : 'unknown',
status: 'running',
port: service.port,
uptime: data.uptime || 0,
uptime:
typeof data.uptime === 'number' && Number.isFinite(data.uptime) && data.uptime >= 0
? data.uptime
: null,
lastCheck: new Date().toISOString(),
healthy: true,
healthy: null,
});
} else {
services.push({
@ -392,22 +510,22 @@ export class MonitoringService {
version: 'unknown',
status: 'error',
port: service.port,
uptime: 0,
uptime: null,
lastCheck: new Date().toISOString(),
healthy: false,
error: `HTTP ${response.status}`,
});
}
} catch (error) {
} catch {
services.push({
name: service.name,
version: 'unknown',
status: 'stopped',
port: service.port,
uptime: 0,
uptime: null,
lastCheck: new Date().toISOString(),
healthy: false,
error: error instanceof Error ? error.message : 'Connection failed',
error: 'Service health request unavailable',
});
}
}