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

@ -3,13 +3,14 @@
*/
import React, { useState } from 'react';
import { ReadinessCard } from './components/ReadinessCard';
import {
CacheStatsCard,
DatabaseStatsGrid,
ProxyStatsCard,
QueueStatsTable,
ServiceStatusGrid,
SystemHealthCard
SystemHealthCard,
} from './components';
import {
useCacheStats,
@ -18,23 +19,51 @@ import {
useQueueStats,
useServiceStatus,
useSystemHealth,
useSystemOverview
useSystemOverview,
} from './hooks';
export function MonitoringPage() {
const [refreshInterval, setRefreshInterval] = useState(5000); // 5 seconds default
const [useOverview, setUseOverview] = useState(false); // Toggle between individual calls and overview
// Individual API calls
const { data: health, loading: healthLoading, error: healthError } = useSystemHealth(useOverview ? 0 : refreshInterval);
const { data: cache, loading: cacheLoading, error: cacheError } = useCacheStats(useOverview ? 0 : refreshInterval);
const { data: queues, loading: queuesLoading, error: queuesError } = useQueueStats(useOverview ? 0 : refreshInterval);
const { data: databases, loading: dbLoading, error: dbError } = useDatabaseStats(useOverview ? 0 : refreshInterval);
const { data: services, loading: servicesLoading, error: servicesError } = useServiceStatus(useOverview ? 0 : refreshInterval);
const { data: proxies, loading: proxiesLoading, error: proxiesError } = useProxyStats(useOverview ? 0 : refreshInterval);
const {
data: health,
loading: healthLoading,
error: healthError,
} = useSystemHealth(useOverview ? 0 : refreshInterval);
const {
data: cache,
loading: cacheLoading,
error: cacheError,
} = useCacheStats(useOverview ? 0 : refreshInterval);
const {
data: queues,
loading: queuesLoading,
error: queuesError,
} = useQueueStats(useOverview ? 0 : refreshInterval);
const {
data: databases,
loading: dbLoading,
error: dbError,
} = useDatabaseStats(useOverview ? 0 : refreshInterval);
const {
data: services,
loading: servicesLoading,
error: servicesError,
} = useServiceStatus(useOverview ? 0 : refreshInterval);
const {
data: proxies,
loading: proxiesLoading,
error: proxiesError,
} = useProxyStats(useOverview ? 0 : refreshInterval);
// Combined overview call
const { data: overview, loading: overviewLoading, error: overviewError } = useSystemOverview(useOverview ? refreshInterval : 0);
const {
data: overview,
loading: overviewLoading,
error: overviewError,
} = useSystemOverview(useOverview ? refreshInterval : 0);
const handleRefreshIntervalChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
setRefreshInterval(Number(e.target.value));
@ -52,12 +81,19 @@ export function MonitoringPage() {
const displayQueues = useOverview && overview ? overview.health.services.queues : queues;
const displayDatabases = useOverview && overview ? overview.health.services.databases : databases;
const isLoading = useOverview
? overviewLoading
: (healthLoading || cacheLoading || queuesLoading || dbLoading || servicesLoading || proxiesLoading);
const isLoading = useOverview
? overviewLoading
: healthLoading ||
cacheLoading ||
queuesLoading ||
dbLoading ||
servicesLoading ||
proxiesLoading;
const errors = useOverview
? (overviewError ? [overviewError] : [])
const errors = useOverview
? overviewError
? [overviewError]
: []
: [healthError, cacheError, queuesError, dbError, servicesError, proxiesError].filter(Boolean);
if (isLoading) {
@ -73,44 +109,41 @@ export function MonitoringPage() {
return (
<div className="flex flex-col h-full space-y-4">
<ReadinessCard />
<div className="flex items-center justify-between flex-shrink-0">
<div>
<h1 className="text-lg font-bold text-text-primary mb-2">System Monitoring</h1>
</div>
<div className="flex items-center space-x-4">
<div className="flex items-center space-x-2">
<label className="text-sm text-text-secondary">
Data source:
</label>
<button
onClick={handleDataSourceToggle}
className={`px-3 py-1 rounded text-sm font-medium transition-colors ${
useOverview
? 'bg-primary-600 text-white'
: 'bg-surface-tertiary text-text-primary'
}`}
>
{useOverview ? 'Overview API' : 'Individual APIs'}
</button>
</div>
<div className="flex items-center space-x-2">
<label htmlFor="refresh-interval" className="text-sm text-text-secondary">
Refresh interval:
</label>
<select
id="refresh-interval"
value={refreshInterval}
onChange={handleRefreshIntervalChange}
className="text-sm bg-surface-secondary border border-border text-text-primary rounded px-2 py-1"
>
<option value={0}>Manual</option>
<option value={5000}>5 seconds</option>
<option value={10000}>10 seconds</option>
<option value={30000}>30 seconds</option>
<option value={60000}>1 minute</option>
</select>
</div>
<div className="flex items-center space-x-4">
<div className="flex items-center space-x-2">
<label className="text-sm text-text-secondary">Data source:</label>
<button
onClick={handleDataSourceToggle}
className={`px-3 py-1 rounded text-sm font-medium transition-colors ${
useOverview ? 'bg-primary-600 text-white' : 'bg-surface-tertiary text-text-primary'
}`}
>
{useOverview ? 'Overview API' : 'Individual APIs'}
</button>
</div>
<div className="flex items-center space-x-2">
<label htmlFor="refresh-interval" className="text-sm text-text-secondary">
Refresh interval:
</label>
<select
id="refresh-interval"
value={refreshInterval}
onChange={handleRefreshIntervalChange}
className="text-sm bg-surface-secondary border border-border text-text-primary rounded px-2 py-1"
>
<option value={0}>Manual</option>
<option value={5000}>5 seconds</option>
<option value={10000}>10 seconds</option>
<option value={30000}>30 seconds</option>
<option value={60000}>1 minute</option>
</select>
</div>
</div>
</div>
{errors.length > 0 && (
@ -129,16 +162,20 @@ export function MonitoringPage() {
<h3 className="font-semibold text-primary-400 mb-2">System Environment</h3>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
<div>
<span className="text-primary-400">Node:</span> <span className="text-text-primary">{overview.environment.nodeVersion}</span>
<span className="text-primary-400">Node:</span>{' '}
<span className="text-text-primary">{overview.environment.nodeVersion}</span>
</div>
<div>
<span className="text-primary-400">Platform:</span> <span className="text-text-primary">{overview.environment.platform}</span>
<span className="text-primary-400">Platform:</span>{' '}
<span className="text-text-primary">{overview.environment.platform}</span>
</div>
<div>
<span className="text-primary-400">Architecture:</span> <span className="text-text-primary">{overview.environment.architecture}</span>
<span className="text-primary-400">Architecture:</span>{' '}
<span className="text-text-primary">{overview.environment.architecture}</span>
</div>
<div>
<span className="text-primary-400">Hostname:</span> <span className="text-text-primary">{overview.environment.hostname}</span>
<span className="text-primary-400">Hostname:</span>{' '}
<span className="text-text-primary">{overview.environment.hostname}</span>
</div>
</div>
</div>
@ -186,4 +223,4 @@ export function MonitoringPage() {
</div>
</div>
);
}
}

View file

@ -2,19 +2,20 @@
* Cache Statistics Card Component
*/
import { Card, CardContent, CardHeader } from '@/components/ui/Card';
import type { CacheStats } from '../types';
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { ConnectionStatus } from './StatusBadge';
import { formatBytes, formatNumber, formatPercentage } from '../utils/formatters';
import { ConnectionStatus } from './StatusBadge';
interface CacheStatsCardProps {
stats: CacheStats;
}
export function CacheStatsCard({ stats }: CacheStatsCardProps) {
const hitRate = stats.stats && (stats.stats.hits + stats.stats.misses) > 0
? (stats.stats.hits / (stats.stats.hits + stats.stats.misses) * 100)
: 0;
const hitRate =
stats.stats && stats.stats.hits + stats.stats.misses > 0
? (stats.stats.hits / (stats.stats.hits + stats.stats.misses)) * 100
: null;
return (
<Card className="p-4">
@ -32,11 +33,15 @@ export function CacheStatsCard({ stats }: CacheStatsCardProps) {
<div className="grid grid-cols-2 gap-3">
<div>
<div className="text-sm text-text-secondary">Memory Used</div>
<div className="text-lg font-semibold text-text-primary">{formatBytes(stats.memoryUsage.used)}</div>
<div className="text-lg font-semibold text-text-primary">
{formatBytes(stats.memoryUsage.used)}
</div>
</div>
<div>
<div className="text-sm text-text-secondary">Peak Memory</div>
<div className="text-lg font-semibold text-text-primary">{formatBytes(stats.memoryUsage.peak)}</div>
<div className="text-lg font-semibold text-text-primary">
{formatBytes(stats.memoryUsage.peak)}
</div>
</div>
</div>
)}
@ -46,29 +51,41 @@ export function CacheStatsCard({ stats }: CacheStatsCardProps) {
<div className="grid grid-cols-2 gap-3">
<div>
<div className="text-sm text-text-secondary">Hit Rate</div>
<div className="text-lg font-semibold text-text-primary">{formatPercentage(hitRate)}</div>
<div className="text-lg font-semibold text-text-primary">
{formatPercentage(hitRate)}
</div>
</div>
<div>
<div className="text-sm text-text-secondary">Total Keys</div>
<div className="text-lg font-semibold text-text-primary">{formatNumber(stats.stats.keys)}</div>
<div className="text-lg font-semibold text-text-primary">
{formatNumber(stats.stats.keys)}
</div>
</div>
</div>
<div className="grid grid-cols-2 gap-3 text-sm">
<div>
<span className="text-text-secondary">Hits:</span> <span className="text-text-primary">{formatNumber(stats.stats.hits)}</span>
<span className="text-text-secondary">Hits:</span>{' '}
<span className="text-text-primary">{formatNumber(stats.stats.hits)}</span>
</div>
<div>
<span className="text-text-secondary">Misses:</span> <span className="text-text-primary">{formatNumber(stats.stats.misses)}</span>
<span className="text-text-secondary">Misses:</span>{' '}
<span className="text-text-primary">{formatNumber(stats.stats.misses)}</span>
</div>
{stats.stats.evictedKeys !== undefined && (
<div>
<span className="text-text-secondary">Evicted:</span> <span className="text-text-primary">{formatNumber(stats.stats.evictedKeys)}</span>
<span className="text-text-secondary">Evicted:</span>{' '}
<span className="text-text-primary">
{formatNumber(stats.stats.evictedKeys)}
</span>
</div>
)}
{stats.stats.expiredKeys !== undefined && (
<div>
<span className="text-text-secondary">Expired:</span> <span className="text-text-primary">{formatNumber(stats.stats.expiredKeys)}</span>
<span className="text-text-secondary">Expired:</span>{' '}
<span className="text-text-primary">
{formatNumber(stats.stats.expiredKeys)}
</span>
</div>
)}
</div>
@ -82,11 +99,9 @@ export function CacheStatsCard({ stats }: CacheStatsCardProps) {
)}
</div>
) : (
<div className="text-center py-8 text-text-secondary">
Cache service is not available
</div>
<div className="text-center py-8 text-text-secondary">Cache service is not available</div>
)}
</CardContent>
</Card>
);
}
}

View file

@ -2,28 +2,22 @@
* Queue Statistics Table Component
*/
import type { QueueStats } from '../types';
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { formatNumber } from '../utils/formatters';
import { Card, CardContent, CardHeader } from '@/components/ui/Card';
import { cn } from '@/lib/utils';
import type { QueueStats } from '../types';
import { formatNumber } from '../utils/formatters';
interface QueueStatsTableProps {
queues: QueueStats[];
}
export function QueueStatsTable({ queues }: QueueStatsTableProps) {
const totalJobs = (queue: QueueStats) => {
const { jobs } = queue;
return jobs.waiting + jobs.active + jobs.completed + jobs.failed + jobs.delayed + jobs.paused +
(jobs.prioritized || 0) + (jobs['waiting-children'] || 0);
};
return (
<Card className="p-4">
<CardHeader className="p-0 pb-3">
<h3 className="text-base font-semibold text-text-primary">Queue Statistics</h3>
</CardHeader>
<CardContent className="p-0">
{queues.length > 0 ? (
<div className="overflow-x-auto">
@ -35,61 +29,94 @@ export function QueueStatsTable({ queues }: QueueStatsTableProps) {
<th className="text-center py-2 px-3 text-text-secondary font-medium">Status</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Waiting</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Active</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Completed</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">
Completed
</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Failed</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Delayed</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Prioritized</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">
Prioritized
</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Children</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Workers</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Total</th>
</tr>
</thead>
<tbody>
{queues.map((queue) => (
<tr key={queue.name} className="border-b border-border hover:bg-surface-tertiary/50 transition-colors">
{queues.map(queue => (
<tr
key={queue.name}
className="border-b border-border hover:bg-surface-tertiary/50 transition-colors"
>
<td className="py-2 px-3 font-medium text-text-primary">{queue.service}</td>
<td className="py-2 px-3 font-medium text-text-primary">{queue.queue}</td>
<td className="py-2 px-3 text-center">
<span className={cn(
'inline-block w-2 h-2 rounded-full',
queue.connected ? 'bg-success' : 'bg-danger'
)} />
</td>
<td className="py-2 px-3 text-right text-text-primary">{formatNumber(queue.jobs.waiting)}</td>
<td className="py-2 px-3 text-right">
{queue.jobs.active > 0 ? (
<span className="text-primary-400 font-medium">{formatNumber(queue.jobs.active)}</span>
) : (
<span className="text-text-primary">{queue.jobs.active}</span>
)}
</td>
<td className="py-2 px-3 text-right text-text-primary">{formatNumber(queue.jobs.completed)}</td>
<td className="py-2 px-3 text-right">
{queue.jobs.failed > 0 ? (
<span className="text-danger font-medium">{formatNumber(queue.jobs.failed)}</span>
) : (
<span className="text-text-primary">{queue.jobs.failed}</span>
)}
</td>
<td className="py-2 px-3 text-right text-text-primary">{formatNumber(queue.jobs.delayed)}</td>
<td className="py-2 px-3 text-right">
{queue.jobs.prioritized && queue.jobs.prioritized > 0 ? (
<span className="text-primary-300 font-medium">{formatNumber(queue.jobs.prioritized)}</span>
) : (
<span className="text-text-primary">0</span>
)}
</td>
<td className="py-2 px-3 text-right">
{queue.jobs['waiting-children'] && queue.jobs['waiting-children'] > 0 ? (
<span className="text-warning font-medium">{formatNumber(queue.jobs['waiting-children'])}</span>
) : (
<span className="text-text-primary">0</span>
)}
<span
className={cn(
'inline-block w-2 h-2 rounded-full',
queue.connected ? 'bg-success' : 'bg-danger'
)}
/>
</td>
{!queue.jobs ? (
<td colSpan={8} className="py-2 px-3 text-right">
Unknown — queue unavailable
</td>
) : (
<>
<td className="py-2 px-3 text-right text-text-primary">
{formatNumber(queue.jobs.waiting)}
</td>
<td className="py-2 px-3 text-right">
{queue.jobs.active > 0 ? (
<span className="text-primary-400 font-medium">
{formatNumber(queue.jobs.active)}
</span>
) : (
<span className="text-text-primary">{queue.jobs.active}</span>
)}
</td>
<td className="py-2 px-3 text-right text-text-primary">
{formatNumber(queue.jobs.completed)}
</td>
<td className="py-2 px-3 text-right">
{queue.jobs.failed > 0 ? (
<span className="text-danger font-medium">
{formatNumber(queue.jobs.failed)}
</span>
) : (
<span className="text-text-primary">{queue.jobs.failed}</span>
)}
</td>
<td className="py-2 px-3 text-right text-text-primary">
{formatNumber(queue.jobs.delayed)}
</td>
<td className="py-2 px-3 text-right">
{queue.jobs.prioritized && queue.jobs.prioritized > 0 ? (
<span className="text-primary-300 font-medium">
{formatNumber(queue.jobs.prioritized)}
</span>
) : (
<span className="text-text-primary">
{formatNumber(queue.jobs.prioritized)}
</span>
)}
</td>
<td className="py-2 px-3 text-right">
{queue.jobs['waiting-children'] && queue.jobs['waiting-children'] > 0 ? (
<span className="text-warning font-medium">
{formatNumber(queue.jobs['waiting-children'])}
</span>
) : (
<span className="text-text-primary">
{formatNumber(queue.jobs['waiting-children'])}
</span>
)}
</td>
</>
)}
<td className="py-2 px-3 text-right text-text-primary">
{queue.workers ? `${queue.workers.count}/${queue.workers.concurrency}` : '-'}
{queue.workers ? formatNumber(queue.workers.count) : 'Unknown'}
</td>
<td className="py-2 px-3 text-right font-medium text-text-primary">{formatNumber(totalJobs(queue))}</td>
</tr>
))}
</tbody>
@ -103,4 +130,4 @@ export function QueueStatsTable({ queues }: QueueStatsTableProps) {
</CardContent>
</Card>
);
}
}

View file

@ -0,0 +1,122 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { MonitoringReadiness } from '@stock-bot/stock-config/diagnostics';
import { Card, CardContent, CardHeader } from '@/components/ui/Card';
import { monitoringApi } from '../services/monitoringApi';
/** Explicit refresh: never turn an older successful snapshot into current readiness. */
export function ReadinessCard() {
const [data, setData] = useState<MonitoringReadiness | null>(null);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(true);
const active = useRef<AbortController | null>(null);
const refresh = useCallback(async () => {
active.current?.abort();
const request = new AbortController();
active.current = request;
setLoading(true);
setError(false);
setData(null);
try {
const snapshot = await monitoringApi.getReadiness(request.signal);
if (active.current === request && !request.signal.aborted) {
setData(snapshot);
}
} catch {
if (active.current === request && !request.signal.aborted) {
setError(true);
}
} finally {
if (active.current === request && !request.signal.aborted) {
setLoading(false);
}
}
}, []);
useEffect(() => {
void refresh();
return () => {
active.current?.abort();
active.current = null;
};
}, [refresh]);
const paper = data?.orchestrator?.paper;
return (
<Card className="p-4">
<CardHeader>
<h2>Research and paper diagnostics</h2>
</CardHeader>
<CardContent>
<p>
This is a point-in-time snapshot. A responding HTTP service does not prove native
execution readiness.
</p>
<button type="button" onClick={() => void refresh()} disabled={loading}>
{loading ? 'Checking readiness…' : 'Refresh readiness'}
</button>
{error && (
<p role="alert">Readiness diagnostics unavailable. Retry to obtain a new snapshot.</p>
)}
{data && (
<>
<p>Observed: {data.observedAt}</p>
<p>
Research: {data.research.status}. PostgreSQL: {data.postgres}. Workers:{' '}
{data.queue.workers ?? 'Unknown'}.
</p>
<ul>
{data.research.reasons.map(reason => (
<li key={reason}>{reason}</li>
))}
</ul>
<p>
Native build: {data.orchestrator?.build?.engineBinarySha256 ?? 'Unknown'}. Native
execution: unverified until run start.
</p>
<p>
Paper:{' '}
{paper
? paper.ready
? 'Ready for operator review'
: 'Not ready'
: 'Unknown or not configured'}
.
</p>
{paper && (
<>
<p>
Feed connected: {String(paper.connected)}. Last received:{' '}
{paper.lastReceivedAt === null
? 'Unknown'
: new Date(paper.lastReceivedAt).toISOString()}
.
</p>
<p>
Active: {String(paper.active)}. Operator halted: {String(paper.operatorHalted)}.
Historical recovery required: {String(paper.requiresHistoricalRecovery)}.
</p>
<ul>
{paper.reasons.map(reason => (
<li key={reason}>{reason}</li>
))}
</ul>
</>
)}
<p>Live trading: disabled.</p>
{data.orchestrator?.research?.slots.map((slot, index) => (
<p key={index}>
Slot {index + 1}: {slot.phase}. Run {slot.runId ?? 'none'}; attempt{' '}
{slot.attemptId ?? 'none'}; strategy version {slot.strategyVersionId ?? 'none'}.
</p>
))}
{data.leases?.map(lease => (
<p key={lease.runId}>
SQL attempt {lease.attemptId ?? 'unknown'} for run {lease.runId}:{' '}
{lease.expired ? 'expired; recovery required' : 'lease current'}.
</p>
))}
</>
)}
<a href="/paper">Open deployment-specific paper readiness and recovery</a>
</CardContent>
</Card>
);
}

View file

@ -1,56 +1,60 @@
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { ServiceStatusIndicator, HealthStatus } from './StatusBadge';
import { formatUptime } from '../utils/formatters';
import type { ServiceStatus } from '../types';
interface ServiceCardProps {
service: ServiceStatus;
}
export function ServiceCard({ service }: ServiceCardProps) {
return (
<Card className="p-3">
<CardHeader className="p-0 pb-2">
<div className="flex items-center justify-between">
<h3 className="font-semibold text-sm capitalize text-text-primary">
{service.name.replace(/-/g, ' ')}
</h3>
<ServiceStatusIndicator status={service.status} />
</div>
</CardHeader>
<CardContent className="p-0 space-y-1.5 text-xs">
<div className="flex justify-between">
<span className="text-text-secondary">Status:</span>
<span className="font-medium capitalize text-text-primary">{service.status}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary">Port:</span>
<span className="font-medium text-text-primary">{service.port || 'N/A'}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary">Version:</span>
<span className="font-medium text-text-primary">{service.version}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary">Uptime:</span>
<span className="font-medium text-text-primary">{formatUptime(service.uptime)}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-text-secondary">Health:</span>
<HealthStatus healthy={service.healthy} />
</div>
{service.error && (
<div className="mt-2 text-xs text-danger bg-danger/10 p-2 rounded">
Error: {service.error}
</div>
)}
</CardContent>
</Card>
);
}
import { Card, CardContent, CardHeader } from '@/components/ui/Card';
import type { ServiceStatus } from '../types';
import { formatUptime } from '../utils/formatters';
import { HealthStatus, ServiceStatusIndicator } from './StatusBadge';
interface ServiceCardProps {
service: ServiceStatus;
}
export function ServiceCard({ service }: ServiceCardProps) {
return (
<Card className="p-3">
<CardHeader className="p-0 pb-2">
<div className="flex items-center justify-between">
<h3 className="font-semibold text-sm capitalize text-text-primary">
{service.name.replace(/-/g, ' ')}
</h3>
<ServiceStatusIndicator status={service.status} />
</div>
</CardHeader>
<CardContent className="p-0 space-y-1.5 text-xs">
<div className="flex justify-between">
<span className="text-text-secondary">Status:</span>
<span className="font-medium capitalize text-text-primary">{service.status}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary">Port:</span>
<span className="font-medium text-text-primary">{service.port || 'N/A'}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary">Version:</span>
<span className="font-medium text-text-primary">{service.version}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary">Uptime:</span>
<span className="font-medium text-text-primary">{formatUptime(service.uptime)}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-text-secondary">Health:</span>
{service.healthy === null ? (
<span>Unknown (liveness only)</span>
) : (
<HealthStatus healthy={service.healthy} />
)}
</div>
{service.error && (
<div className="mt-2 text-xs text-danger bg-danger/10 p-2 rounded">
Error: {service.error}
</div>
)}
</CardContent>
</Card>
);
}

View file

@ -1,3 +1,7 @@
import {
monitoringReadinessSchema,
type MonitoringReadiness,
} from '@stock-bot/stock-config/diagnostics';
import { API_BASE_URL, apiFetch as fetch } from '@/lib/api';
/**
* Monitoring API Service
@ -16,15 +20,38 @@ import type {
const MONITORING_BASE = `${API_BASE_URL}/api/system/monitoring`;
export const monitoringApi = {
async getReadiness(signal?: AbortSignal): Promise<MonitoringReadiness> {
const response = await fetch(`${MONITORING_BASE}/readiness`, { signal });
if (!response.ok) {
throw new Error('Readiness diagnostics unavailable');
}
return monitoringReadinessSchema.parse(await response.json());
},
/**
* Get overall system health
*/
async getSystemHealth(): Promise<SystemHealth> {
const response = await fetch(MONITORING_BASE);
if (!response.ok) {
throw new Error(`Failed to fetch system health: ${response.statusText}`);
const body = await response.json();
if (
!response.ok &&
!(
[500, 503].includes(response.status) &&
['degraded', 'unhealthy'].includes(body?.status) &&
typeof body?.timestamp === 'string' &&
typeof body?.uptime === 'number' &&
typeof body?.memory?.used === 'number' &&
typeof body?.memory?.total === 'number' &&
typeof body?.memory?.percentage === 'number' &&
body?.services?.cache &&
Array.isArray(body?.services?.queues) &&
Array.isArray(body?.services?.databases) &&
Array.isArray(body?.errors)
)
) {
throw new Error('System health unavailable');
}
return response.json();
return body;
},
/**

View file

@ -14,7 +14,7 @@ export interface CacheStats {
stats?: {
hits: number;
misses: number;
keys: number;
keys: number | null;
evictedKeys?: number;
expiredKeys?: number;
};
@ -26,19 +26,20 @@ export interface QueueStats {
service: string;
queue: string;
connected: boolean;
paused?: boolean;
jobs: {
waiting: number;
active: number;
completed: number;
failed: number;
delayed: number;
paused: number;
paused: number | null;
prioritized?: number;
'waiting-children'?: number;
};
} | null;
workers?: {
count: number;
concurrency: number;
concurrency?: number;
};
throughput?: {
processed: number;
@ -98,9 +99,9 @@ export interface ServiceStatus {
version: string;
status: 'running' | 'stopped' | 'error';
port?: number;
uptime: number;
uptime: number | null;
lastCheck: string;
healthy: boolean;
healthy: boolean | null;
error?: string;
}

View file

@ -2,7 +2,10 @@
* Common formatting utilities for monitoring components
*/
export function formatUptime(ms: number): string {
export function formatUptime(ms: number | null): string {
if (ms === null) {
return 'Unknown';
}
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
@ -39,10 +42,13 @@ export function formatBytes(bytes: number): string {
return bytes + ' B';
}
export function formatNumber(num: number): string {
return num.toLocaleString();
export function formatNumber(num: number | null | undefined): string {
return num === null || num === undefined ? 'Unknown' : num.toLocaleString();
}
export function formatPercentage(value: number, decimals: number = 1): string {
export function formatPercentage(value: number | null, decimals: number = 1): string {
if (value === null) {
return 'Unknown';
}
return `${value.toFixed(decimals)}%`;
}