Repository Public
1"use client";2import Link from "next/link";3import { useMemo, useState } from "react";4import type { Schemas } from "@/api/client";5import { useApiList, useApiQuery } from "@/api/query";6import { NotesPanel } from "@/features/maintenance/NotesPanel";7import { METRIC_FAMILIES, metricLabel, type MetricFamilyId } from "@/features/shared/metrics";8import { useI18n } from "@/i18n";9import { usePeriod } from "@/shell/period";10import { useSession } from "@/shell/session";11import { Badge, Banner, CopyButton, DataStamp, DataTable, EmptyState, ErrorState, FreshnessBadge, KeyValue, LoadMore, Meter, Observed, QueryBoundary, Segmented, SelectField, SkeletonRows, StateDot, Tag, Unmeasured, cx, healthTone, serviceTone, type Column } from "@/ui";12import { TimeSeriesChart } from "@/ui/TimeSeriesChart";13import { groupByMetric, healthCounts, healthStrip, usedPct, type HealthState } from "./logic";1415type Detail = Schemas["NodeDetail"];1617/* ───────────────────────── Metrics ───────────────────────── */1819const LABELED_FAMILIES: readonly MetricFamilyId[] = ["disk", "network"];2021export function MetricsTab({ detail }: { detail: Detail }) {22 const { t } = useI18n();23 const period = usePeriod();24 const [family, setFamily] = useState<MetricFamilyId>("cpu");25 const [label, setLabel] = useState("");26 const def = METRIC_FAMILIES.find((f) => f.id === family) ?? METRIC_FAMILIES[0];27 const q = useApiQuery("/nodes/{id}/metrics", { path: { id: detail.node.id }, query: { metrics: [...def.metrics], from: period.from, to: period.to, resolution: "auto" } }, { placeholderData: (prev) => prev, refetchInterval: period.preset ? 30_000 : false });28 const groups = useMemo(() => groupByMetric(q.data?.series ?? []), [q.data]);29 const labeled = LABELED_FAMILIES.includes(family);30 // labels come from the inventory (mount points, interfaces) and from the series themselves (probe targets)31 const labels = useMemo(() => {32 const set = new Set<string>();33 if (family === "disk") detail.volumes.forEach((v) => set.add(v.mount));34 if (family === "network") detail.interfaces.forEach((i) => set.add(i.name));35 (q.data?.series ?? []).forEach((s) => { if (s.label) set.add(s.label); });36 return [...set].sort();37 }, [family, detail.volumes, detail.interfaces, q.data]);38 const activeLabel = labels.includes(label) ? label : "";3940 return (41 <section className="section" aria-labelledby="node-metrics" data-testid="node-metrics">42 <div className="section-head">43 <h2 id="node-metrics">{t("nodes.metrics.title")}</h2>44 <DataStamp at={q.dataUpdatedAt || undefined} freshness={detail.node.freshness} />45 </div>46 <div className="row-wrap nodes-metrics-bar">47 <Segmented label={t("nodes.metrics.family")} value={family} onChange={(f) => { setFamily(f); setLabel(""); }} options={METRIC_FAMILIES.map((f) => ({ value: f.id, label: t(`metrics.family.${f.id}`) }))} />48 {labeled && labels.length > 0 ? (49 <div className="nodes-metric-picker">50 <SelectField label={t("nodes.metrics.label")} hideLabel value={activeLabel} onChange={setLabel} options={[{ value: "", label: t("nodes.metrics.allLabels") }, ...labels.map((l) => ({ value: l, label: l }))]} data-testid="node-metrics-label" />51 </div>52 ) : null}53 {q.data ? <span className="mcc-hint">{t("nodes.metrics.resolution", { resolution: q.data.resolution })}</span> : null}54 </div>55 {q.isError && !q.data ? <ErrorState error={q.error} onRetry={() => void q.refetch()} /> : (56 <div className="nodes-charts">57 {def.metrics.map((m) => {58 const all = groups.get(m) ?? [];59 const shown = activeLabel ? all.filter((s) => s.label === activeLabel || s.label === "") : all;60 const unit = all[0]?.unit ?? "";61 const a = q.data?.availability[m];62 const hasPoints = shown.some((s) => s.points.length > 0);63 return (64 <div key={m} className="nodes-chart" data-metric={m}>65 <TimeSeriesChart66 title={metricLabel(t, m)}67 unit={unit}68 series={shown.map((s) => ({ id: `${m}:${s.label}`, label: s.label || metricLabel(t, m), points: s.points }))}69 from={period.fromMs}70 to={period.toMs}71 loading={q.isLoading}72 {...(unit === "percent" ? { yMax: 100 } : {})}73 {...(!hasPoints && a && a !== "available" ? { placeholder: <Unmeasured availability={a} reason={detail.latest[m]?.reason} /> } : {})}74 />75 </div>76 );77 })}78 </div>79 )}80 </section>81 );82}8384/* ───────────────────────── Processes ───────────────────────── */8586type Proc = Schemas["Process"];8788export function ProcessesTab({ nodeId }: { nodeId: string }) {89 const { t, fmt } = useI18n();90 const q = useApiQuery("/nodes/{id}/processes", { path: { id: nodeId } }, { refetchInterval: 30_000 });91 const columns: Column<Proc>[] = [92 { id: "name", header: t("nodes.proc.name"), cell: (p) => <span className="mono">{p.name}</span>, sortValue: (p) => p.name },93 { id: "pid", header: "PID", align: "right", cell: (p) => p.pid, sortValue: (p) => p.pid, mono: true, shrink: true },94 { id: "user", header: t("nodes.proc.user"), cell: (p) => p.user ?? <Unmeasured availability="not_observed" />, sortValue: (p) => p.user, hide: "sm" },95 { id: "cpu", header: "CPU", align: "right", cell: (p) => (p.cpu_pct === undefined ? <Unmeasured availability="not_observed" /> : fmt.percent(p.cpu_pct, 1)), sortValue: (p) => p.cpu_pct },96 { id: "mem", header: t("nodes.col.memory"), align: "right", cell: (p) => (p.mem_bytes === undefined ? <Unmeasured availability="not_observed" /> : fmt.bytes(p.mem_bytes)), sortValue: (p) => p.mem_bytes },97 { id: "cmd", header: t("nodes.proc.command"), cell: (p) => (p.command ? <span className="nodes-cmd" title={p.command}>{p.command}</span> : <span className="faint">{t("nodes.proc.noCommand")}</span>), mono: true, hide: "md" },98 ];99 return (100 <section className="section" aria-labelledby="node-procs" data-testid="node-processes">101 <QueryBoundary query={q} skeleton={<SkeletonRows />}>102 {(d) => (103 <>104 <div className="section-head"><h2 id="node-procs">{t("nodes.proc.title")}</h2><DataStamp at={d.observed_at} freshness={d.freshness} label={t("nodes.latest.observed")} /></div>105 {d.availability !== "available" ? <Banner tone={d.availability === "stale" ? "stale" : "offline"}><Unmeasured availability={d.availability} /> {t("nodes.proc.unavailable")}</Banner> : null}106 <p className="mcc-hint">{t("nodes.proc.hint")}</p>107 <DataTable caption={t("nodes.proc.title")} columns={columns} rows={d.items} rowKey={(p) => `${p.pid}:${p.name}`} initialSort={{ id: "cpu", dir: "desc" }} compact empty={<span className="muted">{t("nodes.proc.none")}</span>} />108 </>109 )}110 </QueryBoundary>111 </section>112 );113}114115/* ───────────────────────── Services ───────────────────────── */116117type Service = Schemas["Service"];118119export function ServicesTab({ nodeId }: { nodeId: string }) {120 const { t, fmt } = useI18n();121 const { can } = useSession();122 const list = useApiList("/nodes/{id}/services", { path: { id: nodeId }, query: { limit: 100 } }, { enabled: can("services.read") });123 const columns: Column<Service>[] = [124 { id: "state", header: t("common.state"), cell: (s) => <StateDot tone={serviceTone(s.state)} label={t(`states.service.${s.state}`)} />, sortValue: (s) => s.state, shrink: true },125 { id: "name", header: t("common.name"), cell: (s) => <Link href={`/services/${s.id}`} className="rowlink mono">{s.name}</Link>, sortValue: (s) => s.name },126 { id: "manager", header: t("nodes.svc.manager"), cell: (s) => t(`states.manager.${s.manager}`), sortValue: (s) => s.manager },127 { id: "ports", header: t("nodes.svc.ports"), cell: (s) => (s.ports.length ? s.ports.join(", ") : <span className="faint">{t("nodes.unset")}</span>), mono: true, hide: "sm" },128 { id: "restarts", header: t("nodes.svc.restarts"), align: "right", cell: (s) => (s.restarts === undefined ? <Unmeasured availability="not_observed" /> : fmt.integer(s.restarts)), sortValue: (s) => s.restarts, hide: "sm" },129 { id: "health", header: t("nodes.svc.health"), cell: (s) => (s.health ? <StateDot tone={healthTone(s.health.status)} label={t(`states.health.${s.health.status}`)} subtle /> : <Unmeasured availability="not_observed" />), hide: "md" },130 { id: "fresh", header: t("nodes.filters.freshness"), cell: (s) => <FreshnessBadge freshness={s.freshness} subtle />, hide: "md" },131 ];132 return (133 <section className="section" aria-labelledby="node-svcs" data-testid="node-services">134 <div className="section-head"><h2 id="node-svcs">{t("nodes.svc.title")}</h2><DataStamp at={list.updatedAt || undefined} /></div>135 {!can("services.read") ? <ErrorStateForbidden permission="services.read" /> : list.error && !list.ready ? <ErrorState error={list.error} onRetry={list.refetch} /> : !list.ready ? <SkeletonRows /> : (136 <DataTable caption={t("nodes.svc.title")} columns={columns} rows={list.items} rowKey={(s) => s.id} initialSort={{ id: "name", dir: "asc" }} empty={<span className="muted">{t("nodes.svc.none")}</span>} />137 )}138 <LoadMore hasMore={list.hasMore} loading={list.loadingMore} onMore={list.loadMore} />139 </section>140 );141}142143function ErrorStateForbidden({ permission }: { permission: string }) {144 const { t } = useI18n();145 return <Banner tone="offline" icon="denied"><span data-testid="forbidden">{t("errors.forbidden.bodyPermission", { permission })}</span></Banner>;146}147148/* ───────────────────────── Storage & network ───────────────────────── */149150type Volume = Schemas["Volume"];151type Iface = Schemas["NetworkInterface"];152153export function StorageNetworkTab({ detail }: { detail: Detail }) {154 const { t, fmt } = useI18n();155 const priv = useSession().can("nodes.private.read");156 const volumes: Column<Volume>[] = [157 { id: "mount", header: t("nodes.vol.mount"), cell: (v) => <span className="mono">{v.mount}</span>, sortValue: (v) => v.mount },158 { id: "kind", header: t("nodes.col.kind"), cell: (v) => t(`nodes.vol.kind.${v.kind}`), sortValue: (v) => v.kind, hide: "sm" },159 { id: "fs", header: t("nodes.vol.fs"), cell: (v) => v.fs ?? <Unmeasured availability="not_observed" />, mono: true, hide: "md" },160 { id: "usage", header: t("nodes.vol.usage"), cell: (v) => { const pct = usedPct(v.used_bytes, v.total_bytes); return pct === undefined ? <Unmeasured availability="not_observed" /> : <Meter value={pct} label={t("nodes.vol.usageOf", { mount: v.mount })} text={fmt.percent(pct)} />; }, sortValue: (v) => usedPct(v.used_bytes, v.total_bytes) },161 { id: "used", header: t("nodes.vol.used"), align: "right", cell: (v) => <Observed value={v.used_bytes}>{(x) => fmt.bytes(x)}</Observed>, sortValue: (v) => v.used_bytes, hide: "sm" },162 { id: "total", header: t("nodes.vol.total"), align: "right", cell: (v) => <Observed value={v.total_bytes}>{(x) => fmt.bytes(x)}</Observed>, sortValue: (v) => v.total_bytes },163 { id: "smart", header: "SMART", cell: (v) => (v.smart_status ? <span className="mono">{v.smart_status}</span> : <Unmeasured availability="not_observed" />), hide: "md" },164 { id: "fresh", header: t("nodes.filters.freshness"), cell: (v) => (v.gone_at ? <Badge tone="offline" icon="offline">{t("nodes.vol.gone")}</Badge> : <FreshnessBadge freshness={v.freshness} subtle />), hide: "md" },165 ];166 const rate = (v: number | undefined) => (v === undefined ? <Unmeasured availability="not_observed" /> : fmt.byteRate(v));167 const ifaces: Column<Iface>[] = [168 { id: "name", header: t("common.name"), cell: (i) => <span className="mono">{i.name}</span>, sortValue: (i) => i.name },169 { id: "kind", header: t("nodes.col.kind"), cell: (i) => t(`nodes.net.kind.${i.kind}`), sortValue: (i) => i.kind },170 { id: "up", header: t("nodes.net.link"), cell: (i) => <StateDot tone={i.up ? "ok" : "offline"} label={i.up ? t("nodes.net.up") : t("nodes.net.down")} subtle />, sortValue: (i) => (i.up ? 1 : 0) },171 { id: "speed", header: t("nodes.net.speed"), align: "right", cell: (i) => (i.link_speed_mbps === undefined ? <Unmeasured availability="not_observed" /> : `${fmt.integer(i.link_speed_mbps)} Mb/s`), sortValue: (i) => i.link_speed_mbps, hide: "sm" },172 { id: "addr", header: t("nodes.net.addresses"), cell: (i) => { const a = [...i.ipv4, ...i.ipv6]; return a.length ? <span className="nodes-addrs">{a.map((x) => <span key={x} className="mono">{x}</span>)}</span> : priv ? <span className="faint">{t("nodes.unset")}</span> : <span className="faint">{t("nodes.private.requires")}</span>; }, hide: "md" },173 { id: "mac", header: "MAC", cell: (i) => (i.mac ? i.mac : priv ? <Unmeasured availability="not_observed" /> : <span className="faint">{t("nodes.private.requires")}</span>), mono: true, hide: "md" },174 { id: "rx", header: t("nodes.net.rx"), align: "right", cell: (i) => rate(i.rx_bytes_per_s), sortValue: (i) => i.rx_bytes_per_s },175 { id: "tx", header: t("nodes.net.tx"), align: "right", cell: (i) => rate(i.tx_bytes_per_s), sortValue: (i) => i.tx_bytes_per_s },176 ];177 return (178 <>179 <section className="section" aria-labelledby="node-vols" data-testid="node-volumes">180 <div className="section-head"><h2 id="node-vols">{t("nodes.vol.title")}</h2><DataStamp at={detail.volumes[0]?.observed_at ?? detail.node.observed_at} freshness={detail.node.freshness} label={t("nodes.latest.observed")} /></div>181 <DataTable caption={t("nodes.vol.title")} columns={volumes} rows={detail.volumes} rowKey={(v) => v.id} empty={<span className="muted">{t("nodes.vol.none")}</span>} />182 <p className="mcc-hint">{t("nodes.vol.smartHint")}</p>183 </section>184 <section className="section" aria-labelledby="node-ifs" data-testid="node-interfaces">185 <div className="section-head"><h2 id="node-ifs">{t("nodes.net.title")}</h2><DataStamp at={detail.interfaces[0]?.observed_at ?? detail.node.observed_at} freshness={detail.node.freshness} label={t("nodes.latest.observed")} /></div>186 <DataTable caption={t("nodes.net.title")} columns={ifaces} rows={detail.interfaces} rowKey={(i) => i.name} empty={<span className="muted">{t("nodes.net.none")}</span>} />187 </section>188 </>189 );190}191192/* ───────────────────────── Agent ───────────────────────── */193194export function AgentTab({ detail }: { detail: Detail }) {195 const { t, fmt } = useI18n();196 const a = detail.agent;197 if (!a) {198 return (199 <section className="section" aria-labelledby="node-agent" data-testid="node-agent">200 <h2 id="node-agent">{t("nodes.agent.title")}</h2>201 <EmptyState icon="unknown" title={t("nodes.agent.none")}>{t("nodes.agent.noneBody")}</EmptyState>202 </section>203 );204 }205 return (206 <section className="section" aria-labelledby="node-agent" data-testid="node-agent">207 <div className="section-head"><h2 id="node-agent">{t("nodes.agent.title")}</h2><DataStamp at={a.last_seen_at} freshness={a.freshness} label={t("nodes.agent.lastSeen")} /></div>208 {a.revoked_at ? <Banner tone="critical" role="alert"><strong>{t("nodes.agent.revoked", { time: fmt.dateTime(a.revoked_at) })}</strong> {a.revoked_reason ?? ""}</Banner> : null}209 <KeyValue items={[210 { label: t("nodes.agent.version"), value: <span className="mono">{a.version}</span> },211 { label: t("nodes.agent.os"), value: <span className="mono">{a.os}</span> },212 { label: t("nodes.agent.enrolled"), value: <span className="num">{fmt.dateTime(a.enrolled_at)}</span> },213 { label: t("nodes.agent.capabilities"), value: a.capabilities.length ? <span className="nodes-tags">{a.capabilities.map((c) => <Tag key={c}>{c}</Tag>)}</span> : <span className="faint">{t("nodes.agent.noCapabilities")}</span> },214 { label: t("nodes.agent.overheadCpu"), value: <Observed value={a.overhead?.cpu_pct}>{(v) => <span className="num">{fmt.percent(v, 1)}</span>}</Observed> },215 { label: t("nodes.agent.overheadRss"), value: <Observed value={a.overhead?.rss_bytes}>{(v) => <span className="num">{fmt.bytes(v)}</span>}</Observed> },216 { label: t("nodes.agent.certSerial"), value: <span className="mono">{a.cert_serial}</span> },217 { label: t("nodes.agent.certFingerprint"), value: <span className="row"><code className="nodes-fp">{a.cert_fingerprint_sha256}</code><CopyButton text={a.cert_fingerprint_sha256} /></span> },218 { label: t("nodes.agent.certExpires"), value: <span className="num">{fmt.dateTime(a.cert_not_after)} <span className="muted">({fmt.relative(a.cert_not_after)})</span></span> },219 { label: t("nodes.agent.id"), value: <code>{a.id}</code> },220 ]} />221 </section>222 );223}224225/* ───────────────────────── Health history ───────────────────────── */226227const HEALTH_TONE: Record<HealthState, "ok" | "warning" | "critical" | "maintenance" | "offline"> = { up: "ok", degraded: "warning", down: "critical", maintenance: "maintenance", unknown: "offline" };228const RANGES = ["1h", "24h", "7d", "30d"] as const;229const STATES: HealthState[] = ["up", "degraded", "down", "maintenance", "unknown"];230231export function HealthTab({ nodeId }: { nodeId: string }) {232 const { t, fmt } = useI18n();233 const [range, setRange] = useState<Schemas["TimeRange"]>("24h");234 const [table, setTable] = useState<"strip" | "table">("strip");235 const q = useApiQuery("/nodes/{id}/health-history", { path: { id: nodeId }, query: { range } }, { placeholderData: (prev) => prev });236 type Bucket = Schemas["HealthBucket"];237 const columns: Column<Bucket>[] = [238 { id: "start", header: t("nodes.health.start"), cell: (b) => fmt.dateTime(b.start), sortValue: (b) => b.start, mono: true },239 { id: "end", header: t("nodes.health.end"), cell: (b) => fmt.dateTime(b.end, { zone: false }), mono: true, hide: "sm" },240 { id: "state", header: t("common.state"), cell: (b) => <StateDot tone={HEALTH_TONE[b.state]} label={t(`nodes.health.state.${b.state}`)} />, sortValue: (b) => b.state },241 { id: "alerts", header: t("nodes.health.alerts"), align: "right", cell: (b) => fmt.integer(b.alerts_firing), sortValue: (b) => b.alerts_firing },242 ];243 return (244 <section className="section" aria-labelledby="node-health" data-testid="node-health">245 <div className="section-head">246 <h2 id="node-health">{t("nodes.health.title")}</h2>247 <div className="row-wrap">248 <DataStamp at={q.dataUpdatedAt || undefined} />249 <Segmented label={t("ui.range.label")} value={range} onChange={setRange} options={RANGES.map((r) => ({ value: r, label: t(`ui.range.${r}`), title: t(`ui.range.long.${r}`) }))} />250 <Segmented label={t("nodes.health.view")} value={table} onChange={setTable} options={[{ value: "strip", label: t("nodes.health.strip"), icon: "chart" }, { value: "table", label: t("ui.chart.showTable"), icon: "table" }]} />251 </div>252 </div>253 <QueryBoundary query={q}>254 {(d) => {255 const rects = healthStrip(d.items, 1000, 28);256 const counts = healthCounts(d.items);257 const summary = STATES.filter((s) => counts[s] > 0).map((s) => `${t(`nodes.health.state.${s}`)} : ${counts[s]}`).join(", ");258 return (259 <>260 <div className="row-wrap">261 <div className="mcc-stat"><span className="caps">{t("nodes.health.uptime")}</span><span className="value">{d.uptime_ratio === undefined ? <Unmeasured availability="not_observed" /> : fmt.ratio(d.uptime_ratio, 2)}</span></div>262 <span className="mcc-hint">{t("nodes.health.bucket", { duration: fmt.duration(d.bucket_seconds) })}</span>263 </div>264 {d.items.length === 0 ? <EmptyState compact icon="history" title={t("nodes.health.none")} /> : table === "table" ? (265 <DataTable caption={t("nodes.health.title")} columns={columns} rows={d.items} rowKey={(b) => b.start} initialSort={{ id: "start", dir: "desc" }} compact />266 ) : (267 <>268 <svg className="nodes-health-strip" viewBox="0 0 1000 28" preserveAspectRatio="none" role="img" aria-label={t("nodes.health.stripLabel", { summary })} data-testid="node-health-strip">269 {rects.map((r) => {270 const b = d.items[r.index];271 return (272 <rect key={r.index} x={r.x} y={r.y} width={r.w} height={r.h} className={cx("nodes-health-rect", `tone-${HEALTH_TONE[r.state]}`)}>273 <title>{b ? `${fmt.dateTime(b.start, { zone: false })} — ${t(`nodes.health.state.${r.state}`)}` : ""}</title>274 </rect>275 );276 })}277 </svg>278 <div className="row-between mcc-hint num"><span>{fmt.dateTime(d.items[0]?.start ?? "")}</span><span>{fmt.dateTime(d.items[d.items.length - 1]?.end ?? "")}</span></div>279 </>280 )}281 <ul className="nodes-health-legend" aria-label={t("ui.chart.legend")}>282 {STATES.map((s) => <li key={s}><StateDot tone={HEALTH_TONE[s]} label={t(`nodes.health.state.${s}`)} subtle /><span className="num faint">{counts[s]}</span></li>)}283 </ul>284 <p className="mcc-hint">{t("nodes.health.shapeHint")}</p>285 </>286 );287 }}288 </QueryBoundary>289 </section>290 );291}292293/* ───────────────────────── Maintenance ───────────────────────── */294295export function MaintenanceTab({ detail }: { detail: Detail }) {296 const { t } = useI18n();297 const { can } = useSession();298 const n = detail.node;299 return (300 <>301 <section className="section" aria-labelledby="node-maint" data-testid="node-maintenance">302 <h2 id="node-maint">{t("nodes.maintenance.title")}</h2>303 <KeyValue items={[304 { label: t("nodes.maintenance.mode"), value: <StateDot tone={n.maintenance ? "maintenance" : "neutral"} icon={n.maintenance ? "wrench" : "minus"} label={n.maintenance ? t("nodes.maintenance.on") : t("nodes.maintenance.off")} /> },305 { label: t("nodes.maintenance.reason"), value: n.maintenance_reason ? <span className="pre">{n.maintenance_reason}</span> : <span className="faint">{t("nodes.maintenance.noReason")}</span> },306 { label: t("nodes.maintenance.activeWindow"), value: detail.active_maintenance_window_id ? <Link href={`/maintenance/${detail.active_maintenance_window_id}`}>{t("nodes.maintenance.window")}</Link> : <span className="faint">{t("nodes.maintenance.noWindow")}</span> },307 ]} />308 <p className="mcc-hint">{t("nodes.maintenance.hint")} {can("maintenance.read") ? <Link href={`/maintenance?node_id=${n.id}`}>{t("nodes.maintenance.calendar")}</Link> : null}</p>309 </section>310 <section className="section" aria-labelledby="node-notes" data-testid="node-notes">311 <h2 id="node-notes">{t("nodes.maintenance.notes")}</h2>312 {can("maintenance.read") ? <NotesPanel scope={{ nodeId: n.id }} /> : <ErrorStateForbidden permission="maintenance.read" />}313 </section>314 </>315 );316}317