import { faClock, faCloudDownloadAlt, faCloudUploadAlt, faHdd, faMemory, faMicrochip, faWifi, } from '@fortawesome/free-solid-svg-icons'; import classNames from 'classnames'; import type { ReactNode } from 'react'; import { useEffect, useMemo, useState } from 'react'; import { SocketEvent, SocketRequest } from '@/components/server/events'; import UptimeDuration from '@/components/server/UptimeDuration'; import StatBlock from '@/components/server/console/StatBlock'; import { bytesToString, ip, mbToBytes } from '@/lib/formatters'; import { capitalize } from '@/lib/strings'; import { ServerContext } from '@/state/server'; import useWebsocketEvent from '@/plugins/useWebsocketEvent'; type Stats = Record<'memory' | 'cpu' | 'disk' | 'uptime' | 'rx' | 'tx', number>; function getBackgroundColor(value: number, max: number | null): string | undefined { const delta = !max ? 0 : value / max; if (delta > 0.8) { if (delta > 0.9) { return 'bg-red-500'; } return 'bg-yellow-500'; } return undefined; } function Limit({ limit, children }: { limit: string | null; children: ReactNode }) { return ( <> {children} / {limit || <>∞} ); } function ServerDetailsBlock({ className }: { className?: string }) { const [stats, setStats] = useState({ memory: 0, cpu: 0, disk: 0, uptime: 0, tx: 0, rx: 0 }); const status = ServerContext.useStoreState(state => state.status.value); const connected = ServerContext.useStoreState(state => state.socket.connected); const instance = ServerContext.useStoreState(state => state.socket.instance); const limits = ServerContext.useStoreState(state => state.server.data!.limits); const textLimits = useMemo( () => ({ cpu: limits?.cpu ? `${limits.cpu}%` : null, memory: limits?.memory ? bytesToString(mbToBytes(limits.memory)) : null, disk: limits?.disk ? bytesToString(mbToBytes(limits.disk)) : null, }), [limits], ); const allocation = ServerContext.useStoreState(state => { const match = state.server.data!.allocations.find(allocation => allocation.isDefault); return !match ? 'n/a' : `${match.alias || ip(match.ip)}:${match.port}`; }); useEffect(() => { if (!connected || !instance) { return; } instance.send(SocketRequest.SEND_STATS); }, [instance, connected]); useWebsocketEvent(SocketEvent.STATS, data => { let stats: any = {}; try { stats = JSON.parse(data); } catch (e) { return; } setStats({ memory: stats.memory_bytes, cpu: stats.cpu_absolute, disk: stats.disk_bytes, tx: stats.network.tx_bytes, rx: stats.network.rx_bytes, uptime: stats.uptime || 0, }); }); return (
{allocation} {status === null ? ( 'Offline' ) : stats.uptime > 0 ? ( ) : ( capitalize(status) )} {status === 'offline' ? ( Offline ) : ( {stats.cpu.toFixed(2)}% )} {status === 'offline' ? ( Offline ) : ( {bytesToString(stats.memory)} )} {bytesToString(stats.disk)} {status === 'offline' ? Offline : bytesToString(stats.rx)} {status === 'offline' ? Offline : bytesToString(stats.tx)}
); } export default ServerDetailsBlock;