'use client'; import React, { useState, useEffect, useRef, useCallback } from 'react'; import { OperationsInfrastructureData, ServiceStatusValue, ComponentHealthStatus, OperationsRole, } from './types'; import { normalizeInfrastructureResponse } from '../../lib/ops-data'; import { OperationsActions } from './operations-actions'; interface OperationsInfrastructureProps { role: OperationsRole; } export function OperationsInfrastructure({ role }: OperationsInfrastructureProps) { const [data, setData] = useState(null); const [isRefreshing, setIsRefreshing] = useState(false); const [lastFetchedAt, setLastFetchedAt] = useState(null); const [fetchError, setFetchError] = useState(null); const [copiedSha, setCopiedSha] = useState(false); const isFetchingRef = useRef(false); const pollTimerRef = useRef(null); const fetchData = useCallback(async () => { if (isFetchingRef.current) return; isFetchingRef.current = true; setIsRefreshing(true); try { const resp = await fetch('/api/ops/infrastructure', { method: 'GET', headers: { accept: 'application/json' }, cache: 'no-store', }); if (resp.ok) { const raw = await resp.json(); const normalized = normalizeInfrastructureResponse(raw); setData(normalized); setLastFetchedAt(new Date().toLocaleTimeString()); setFetchError(null); } else if (resp.status === 401 || resp.status === 403) { setFetchError('Authorization failed. Access restricted.'); } else { const raw = await resp.json().catch(() => null); setData(normalizeInfrastructureResponse(raw)); setFetchError('Metrics collector degraded or partially unavailable.'); } } catch { setFetchError('Network error reaching infrastructure endpoint.'); } finally { isFetchingRef.current = false; setIsRefreshing(false); } }, []); // Initial fetch and 30-second visibility-gated polling loop useEffect(() => { void fetchData(); const handleVisibilityChange = () => { if (document.visibilityState === 'visible') { void fetchData(); } }; document.addEventListener('visibilitychange', handleVisibilityChange); pollTimerRef.current = setInterval(() => { if (document.visibilityState === 'visible') { void fetchData(); } }, 30000); return () => { document.removeEventListener('visibilitychange', handleVisibilityChange); if (pollTimerRef.current) { clearInterval(pollTimerRef.current); } }; }, [fetchData]); const handleCopySha = (sha: string) => { if (!sha) return; navigator.clipboard.writeText(sha).then(() => { setCopiedSha(true); setTimeout(() => setCopiedSha(false), 2000); }); }; const formatBytes = (bytes: number | null): string => { if (bytes === null || bytes === undefined) return 'N/A'; if (bytes >= 1e12) return `${(bytes / 1e12).toFixed(2)} TB`; if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(2)} GB`; if (bytes >= 1e6) return `${(bytes / 1e6).toFixed(1)} MB`; return `${(bytes / 1e3).toFixed(1)} KB`; }; const getServiceStatusBadge = (status: ServiceStatusValue) => { switch (status) { case 'active': return { label: 'Active (Running)', icon: 'check_circle', classes: 'bg-emerald-950/60 text-emerald-400 border-emerald-800/60', }; case 'inactive': return { label: 'Inactive (Stopped)', icon: 'pause_circle', classes: 'bg-amber-950/60 text-amber-400 border-amber-800/60', }; case 'failed': return { label: 'Failed', icon: 'cancel', classes: 'bg-rose-950/60 text-rose-400 border-rose-800/60', }; case 'unknown': default: return { label: 'Unknown / Unreachable', icon: 'help', classes: 'bg-slate-900/60 text-slate-400 border-slate-700/60', }; } }; const getComponentHealthBadge = (status: ComponentHealthStatus) => { switch (status) { case 'available': return { label: 'Available', icon: 'check_circle', classes: 'bg-emerald-950/60 text-emerald-400 border-emerald-800/60', }; case 'degraded': return { label: 'Degraded', icon: 'warning', classes: 'bg-amber-950/60 text-amber-400 border-amber-800/60', }; case 'unavailable': return { label: 'Unavailable', icon: 'cancel', classes: 'bg-rose-950/60 text-rose-400 border-rose-800/60', }; case 'unknown': default: return { label: 'Unknown', icon: 'help', classes: 'bg-slate-900/60 text-slate-400 border-slate-700/60', }; } }; const resources = data?.resources; const services = data?.services ?? []; const network = data?.network; const deployment = data?.deployment; return (
{/* Header & Controls */}
dns

Infrastructure & Runtime

Phase 2 Operations

Host system resources, systemd core services, network totals, and deployment runtime health.

{/* Polling indicator */}
Auto 30s
{/* Last refreshed */} {lastFetchedAt && ( Updated: {lastFetchedAt} )} {/* Manual Refresh Button */}
{/* Optional Warning Banner */} {fetchError && (
warning {fetchError}
)} {/* SECTION 1: System Resources */}

Server Resources

Target Host: Ubuntu VPS
{/* CPU Usage */}
CPU Usage memory
{resources?.cpu_percent !== null && resources?.cpu_percent !== undefined ? `${resources.cpu_percent}%` : 'Unavailable'}

Load: {resources?.load_avg ? resources.load_avg.join(', ') : 'N/A'}

{/* Progress Bar */}
{/* Memory (RAM) */}
Memory (RAM) developer_board
{resources?.memory ? `${formatBytes(resources.memory.used)} / ${formatBytes(resources.memory.total)}` : 'Unavailable'}

{resources?.memory ? `${resources.memory.percent}% used (${formatBytes(resources.memory.available)} free)` : 'N/A'}

{/* Progress Bar */}
= 90 ? 'bg-rose-500' : (resources?.memory?.percent ?? 0) >= 80 ? 'bg-amber-500' : 'bg-primary-container' }`} style={{ width: `${Math.min(100, Math.max(0, resources?.memory?.percent ?? 0))}%` }} />
{/* Swap Memory */}
Swap Space swap_horiz
{resources?.swap ? `${formatBytes(resources.swap.used)} / ${formatBytes(resources.swap.total)}` : 'Unavailable'}

{resources?.swap ? `${resources.swap.percent}% utilized` : 'N/A'}

{/* Progress Bar */}
{/* Disk Storage (/) */}
Root Disk (/) {resources?.disk?.critical ? ( CRITICAL ) : resources?.disk?.warning ? ( WARNING ) : null}
hard_drive
{resources?.disk ? `${formatBytes(resources.disk.used)} / ${formatBytes(resources.disk.total)}` : 'Unavailable'}

{resources?.disk ? `${resources.disk.percent}% used (${formatBytes(resources.disk.available)} free)` : 'N/A'}

{/* Progress Bar */}
{/* Server Uptime */}
Server Uptime schedule
{resources?.uptime_formatted || 'Unavailable'}

{resources?.uptime_seconds ? `${resources.uptime_seconds.toLocaleString()}s total uptime` : 'N/A'}

System running continuously
{/* SECTION 2: Core Systemd Services */}

Core Services (systemd)

Strict Allowlist: 4 Services
{services.map((svc) => { const badge = getServiceStatusBadge(svc.status); return (

{svc.display_name}

{svc.name}.service

{svc.description}

Service Status
{badge.icon} {badge.label}
); })}
{/* SECTION 3 & 4: Network Cumulative Totals & Deployment Health */}
{/* Network Cumulative Totals */}
network_check

Network Cumulative Totals

Aggregated across non-loopback interfaces since host boot

Not a rate
download Total Received
{formatBytes(network?.bytes_received ?? null)}

{network?.bytes_received ? `${network.bytes_received.toLocaleString()} bytes` : 'N/A'}

upload Total Transmitted
{formatBytes(network?.bytes_transmitted ?? null)}

{network?.bytes_transmitted ? `${network.bytes_transmitted.toLocaleString()} bytes` : 'N/A'}

info Cumulative Total Since Boot across physical network interfaces. Instantaneous bandwidth rates are not tracked.
{/* Deployment Health Foundations */}
deployed_code

Deployment Health Foundations

Active code revision and subsystem runtime readiness

Foundation
{/* Active Git Revision */}
Active Git Revision
{deployment?.short_revision || 'Unavailable'} {deployment?.git_revision && ( )}
{deployment?.revision_status ?? 'unavailable'}
{/* Health indicators */}
Website Ingress
{(() => { const badge = getComponentHealthBadge(deployment?.website_health ?? 'unknown'); return (
{badge.icon} {badge.label}
); })()}
API Readiness
{(() => { const badge = getComponentHealthBadge(deployment?.api_health ?? 'unknown'); return (
{badge.icon} {badge.label}
); })()}
{/* Deployment History Status */}
Deployment History: Audited in Phase 2
{/* Operations Actions & Deployment Controls */}
); }