Repository Public
1"use client";2import { useRouter } from "next/navigation";3import { Suspense, useMemo } from "react";4import type { Schemas } from "@/api/client";5import { useApiList, useApiQuery } from "@/api/query";6import { When, useUrlState } from "@/features/services/url";7import { NodeLink, useNodeOptions } from "@/features/shared/nodes";8import { useI18n } from "@/i18n";9import { Page, RequirePermission } from "@/shell/AppShell";10import { usePeriod } from "@/shell/period";11import { useSession } from "@/shell/session";12import { Banner, Combobox, DataStamp, DataTable, EmptyState, ErrorState, ForbiddenState, FreshnessBadge, LoadMore, Observed, QueryBoundary, Skeleton, SkeletonRows, StateDot, Tag, Unmeasured, cx, freshnessTone, type Column, type Tone } from "@/ui";13import { TimeSeriesChart, type ChartSeries } from "@/ui/TimeSeriesChart";14import { layoutTopology } from "./topology";1516type Topology = Schemas["NetworkTopology"];17type TLink = Schemas["TopologyLink"];18type Iface = Schemas["NetworkInterface"];1920const linkTone = (s: TLink["state"]): Tone => (s === "up" ? "ok" : s === "down" ? "critical" : "stale");2122function Latency({ link }: { link: TLink }) {23 const { fmt } = useI18n();24 if (link.latency_availability === "available" && link.latency_ms !== undefined) return <span className="num">{fmt.ms(link.latency_ms)}</span>;25 return <Unmeasured availability={link.latency_availability === "available" ? "not_observed" : link.latency_availability} />;26}27function Loss({ link }: { link: TLink }) {28 const { fmt } = useI18n();29 if (link.loss_availability === "available" && link.loss_pct !== undefined) return <span className="num">{fmt.percent(link.loss_pct, link.loss_pct > 0 && link.loss_pct < 10 ? 1 : 0)}</span>;30 return <Unmeasured availability={link.loss_availability === "available" ? "not_observed" : link.loss_availability} />;31}3233function TopologyMap({ topology }: { topology: Topology }) {34 const { t, fmt } = useI18n();35 const router = useRouter();36 const layout = useMemo(() => layoutTopology(topology.nodes, topology.links), [topology]);37 const up = topology.links.filter((l) => l.state === "up").length;38 const down = topology.links.filter((l) => l.state === "down").length;39 const summary = t("network.topo.summary", { nodes: topology.nodes.filter((n) => n.kind === "node").length, infra: topology.nodes.filter((n) => n.kind !== "node").length, links: topology.links.length, up, down, unknown: topology.links.length - up - down });40 return (41 <figure className="net-map" data-testid="network-topology">42 <svg viewBox={`0 0 ${layout.width} ${layout.height}`} role="group" aria-label={t("network.topo.aria")} aria-describedby="net-topo-summary" className="net-svg">43 <g aria-hidden="true">44 {layout.links.map((p) => (45 <g key={p.link.id} className={cx("net-link", `kind-${p.link.kind}`, `state-${p.link.state}`)}>46 <line x1={p.x1} y1={p.y1} x2={p.x2} y2={p.y2} />47 <text x={p.lx} y={p.ly - 4} textAnchor={p.anchor} className="net-link-label">48 {p.link.latency_availability === "available" && p.link.latency_ms !== undefined ? fmt.ms(p.link.latency_ms) : t("network.topo.notObservedShort")}49 {p.link.loss_availability === "available" && p.link.loss_pct !== undefined && p.link.loss_pct > 0 ? ` · ${fmt.percent(p.link.loss_pct)}` : ""}50 {p.link.state === "down" ? ` · ${t("network.state.down")}` : ""}51 </text>52 </g>53 ))}54 </g>55 {layout.nodes.map((n) => {56 const label = n.kind === "node" ? n.label : `${n.label} (${t(`network.vertex.${n.kind}`)})`;57 const state = n.freshness ? t(`states.freshness.${n.freshness}`) : n.kind === "node" ? t("states.availability.not_observed") : "";58 const body = (59 <>60 {n.kind === "node" ? <circle cx={n.x} cy={n.y} r="6" className="net-dot" /> : <rect x={n.x - 54} y={n.y - 17} width="108" height="34" rx="6" className="net-hub" />}61 {n.kind === "node" && n.freshness !== "fresh" ? <path d={`M${n.x - 3} ${n.y - 3}l6 6M${n.x + 3} ${n.y - 3}l-6 6`} className="net-cross" /> : null}62 <text x={n.kind === "node" ? (n.side === "left" ? n.x - 14 : n.x + 14) : n.x} y={n.y + 4} textAnchor={n.kind === "node" ? (n.side === "left" ? "end" : "start") : "middle"} className={n.kind === "node" ? "net-label mono" : "net-label hub"}>{n.label}</text>63 </>64 );65 const cls = cx("net-vertex", `tone-${n.freshness ? freshnessTone(n.freshness) : "neutral"}`);66 return n.nodeId ? (67 <a key={n.id} href={`/nodes/${n.nodeId}`} className={cls} aria-label={`${label} — ${state}`} onClick={(e) => { if (e.metaKey || e.ctrlKey || e.shiftKey) return; e.preventDefault(); router.push(`/nodes/${n.nodeId}`); }}>{body}</a>68 ) : (69 <g key={n.id} className={cls} role="img" aria-label={state ? `${label} — ${state}` : label}>{body}</g>70 );71 })}72 </svg>73 <figcaption>74 <p id="net-topo-summary" className="muted" data-testid="network-topology-summary">{summary}</p>75 <ul className="net-legend" aria-label={t("network.topo.legend")}>76 <li><svg viewBox="0 0 28 8" aria-hidden="true" className="net-link kind-lan state-up"><line x1="0" y1="4" x2="28" y2="4" /></svg>{t("network.kind.lan")}</li>77 <li><svg viewBox="0 0 28 8" aria-hidden="true" className="net-link kind-wireguard state-up"><line x1="0" y1="4" x2="28" y2="4" /></svg>{t("network.kind.wireguard")}</li>78 <li><svg viewBox="0 0 28 8" aria-hidden="true" className="net-link kind-lan state-down"><line x1="0" y1="4" x2="28" y2="4" /></svg>{t("network.state.down")}</li>79 <li><svg viewBox="0 0 28 8" aria-hidden="true" className="net-link kind-lan state-unknown"><line x1="0" y1="4" x2="28" y2="4" /></svg>{t("network.state.unknown")}</li>80 </ul>81 </figcaption>82 </figure>83 );84}8586function LinksTable({ topology }: { topology: Topology }) {87 const { t } = useI18n();88 const vertex = useMemo(() => new Map(topology.nodes.map((n) => [n.id, n])), [topology]);89 const name = (id: string) => vertex.get(id)?.label ?? id;90 const columns: Column<TLink>[] = [91 { id: "source", header: t("network.col.source"), sortValue: (l) => name(l.source), cell: (l) => { const v = vertex.get(l.source); return v?.node_id ? <NodeLink id={v.node_id} alias={v.label} /> : <span className="mono">{name(l.source)}</span>; } },92 { id: "target", header: t("network.col.target"), sortValue: (l) => name(l.target), cell: (l) => { const v = vertex.get(l.target); return v?.node_id ? <NodeLink id={v.node_id} alias={v.label} /> : <span>{name(l.target)}</span>; } },93 { id: "kind", header: t("network.col.kind"), sortValue: (l) => l.kind, cell: (l) => <Tag>{t(`network.kind.${l.kind}`)}</Tag> },94 { id: "iface", header: t("network.col.interface"), mono: true, cell: (l) => <Observed value={l.interface}>{(v) => v}</Observed>, hide: "md" },95 { id: "state", header: t("common.state"), sortValue: (l) => l.state, cell: (l) => <StateDot tone={linkTone(l.state)} label={t(`network.state.${l.state}`)} /> },96 { id: "latency", header: t("network.col.latency"), align: "right", sortValue: (l) => l.latency_ms, cell: (l) => <Latency link={l} /> },97 { id: "loss", header: t("network.col.loss"), align: "right", sortValue: (l) => l.loss_pct, cell: (l) => <Loss link={l} />, hide: "sm" },98 { id: "observed", header: t("network.col.observed"), sortValue: (l) => l.observed_at, cell: (l) => (l.observed_at ? <When at={l.observed_at} /> : <Unmeasured availability="not_observed" />), hide: "md" },99 { id: "fresh", header: t("network.col.freshness"), sortValue: (l) => l.freshness, cell: (l) => <FreshnessBadge freshness={l.freshness} subtle />, hide: "sm" },100 ];101 return <DataTable caption={t("network.links.title")} columns={columns} rows={topology.links} rowKey={(l) => l.id} initialSort={{ id: "source", dir: "asc" }} compact empty={<span className="muted">{t("network.links.empty")}</span>} />;102}103104function TopologySection() {105 const { t } = useI18n();106 const q = useApiQuery("/network/topology", undefined, { refetchInterval: 60_000 });107 return (108 <section className="section" aria-labelledby="net-topo-h">109 <div className="section-head"><h2 id="net-topo-h">{t("network.topo.title")}</h2><DataStamp at={q.data?.generated_at} label={t("network.topo.generated")} /></div>110 <QueryBoundary query={q} skeleton={<Skeleton height="xl" label={t("common.loading")} />}>111 {(topology) => topology.nodes.length === 0 ? (112 <EmptyState icon="network" title={t("network.topo.emptyTitle")}>{t("network.topo.emptyBody")}</EmptyState>113 ) : (114 <>115 <TopologyMap topology={topology} />116 <h3>{t("network.links.title")}</h3>117 <p className="mcc-hint">{t("network.links.hint")}</p>118 <LinksTable topology={topology} />119 </>120 )}121 </QueryBoundary>122 </section>123 );124}125126function ThroughputSection() {127 const { t } = useI18n();128 const period = usePeriod();129 const range = period.preset ?? "24h";130 const rx = useApiQuery("/cluster/trends", { query: { metric: "net.rx", range, group_by: "cluster" } }, { refetchInterval: 60_000 });131 const tx = useApiQuery("/cluster/trends", { query: { metric: "net.tx", range, group_by: "cluster" } }, { refetchInterval: 60_000 });132 const series: ChartSeries[] = [133 ...(rx.data?.series.map((s, i) => ({ id: `rx-${i}`, label: t("network.throughput.rx"), points: s.points })) ?? []),134 ...(tx.data?.series.map((s, i) => ({ id: `tx-${i}`, label: t("network.throughput.tx"), points: s.points })) ?? []),135 ];136 const error = rx.error ?? tx.error;137 const coverage = rx.data?.series[0]?.coverage;138 return (139 <section className="section" aria-labelledby="net-thr-h" data-testid="network-throughput">140 <div className="section-head"><h2 id="net-thr-h">{t("network.throughput.title")}</h2><DataStamp at={rx.data?.generated_at} /></div>141 {period.preset === null ? <Banner tone="info">{t("network.throughput.presetOnly")}</Banner> : null}142 {error && series.length === 0 ? <ErrorState error={error} onRetry={() => { void rx.refetch(); void tx.refetch(); }} compact /> : (143 <>144 <TimeSeriesChart title={t("network.throughput.chart", { range: t(`ui.range.long.${range}`) })} unit={rx.data?.unit ?? tx.data?.unit ?? "bytes_per_s"} series={series} loading={rx.isLoading || tx.isLoading} />145 <p className="mcc-hint">{t("network.throughput.note")}{coverage !== undefined ? ` ${t("network.throughput.coverage", { count: coverage })}` : ""}</p>146 </>147 )}148 </section>149 );150}151152function InterfacesSection() {153 const { t, fmt } = useI18n();154 const { can } = useSession();155 const url = useUrlState();156 const nodes = useNodeOptions();157 const allowed = can("nodes.read");158 const list = useApiList("/network/interfaces", { query: { limit: 200, ...(url.get("node") ? { node_id: url.get("node") } : {}) } }, { enabled: allowed, refetchInterval: 60_000 });159 const columns: Column<Iface>[] = [160 { id: "node", header: t("common.node"), sortValue: (i) => i.node_alias, cell: (i) => <NodeLink id={i.node_id} alias={i.node_alias} /> },161 { id: "name", header: t("network.col.interface"), sortValue: (i) => i.name, mono: true, cell: (i) => i.name },162 { id: "kind", header: t("network.col.kind"), sortValue: (i) => i.kind, cell: (i) => <Tag>{t(`network.ifkind.${i.kind}`)}</Tag>, hide: "sm" },163 { id: "up", header: t("common.state"), sortValue: (i) => (i.up ? 1 : 0), cell: (i) => <StateDot tone={i.up ? "ok" : "offline"} label={i.up ? t("network.state.up") : t("network.state.down")} /> },164 { id: "speed", header: t("network.col.speed"), align: "right", sortValue: (i) => i.link_speed_mbps, cell: (i) => <Observed value={i.link_speed_mbps}>{(v) => t("network.mbps", { value: fmt.integer(v) })}</Observed>, hide: "md" },165 { id: "addr", header: t("network.col.addresses"), mono: true, cell: (i) => { const a = [...i.ipv4, ...i.ipv6]; return a.length > 0 ? <span className="net-addrs">{a.join(", ")}</span> : <span className="faint" title={t("network.addressesHint")}>{t("network.addressesNone")}</span>; }, hide: "md" },166 { id: "rx", header: t("network.col.rx"), align: "right", sortValue: (i) => i.rx_bytes_per_s, cell: (i) => <Observed value={i.rx_bytes_per_s}>{(v) => fmt.byteRate(v)}</Observed> },167 { id: "tx", header: t("network.col.tx"), align: "right", sortValue: (i) => i.tx_bytes_per_s, cell: (i) => <Observed value={i.tx_bytes_per_s}>{(v) => fmt.byteRate(v)}</Observed> },168 { id: "err", header: t("network.col.errors"), align: "right", sortValue: (i) => (i.rx_errors_per_s ?? 0) + (i.tx_errors_per_s ?? 0), cell: (i) => (i.rx_errors_per_s === undefined && i.tx_errors_per_s === undefined ? <Unmeasured availability="not_observed" /> : t("network.errorsValue", { rx: i.rx_errors_per_s === undefined ? "?" : fmt.number(i.rx_errors_per_s, 2), tx: i.tx_errors_per_s === undefined ? "?" : fmt.number(i.tx_errors_per_s, 2) })), hide: "md" },169 { id: "fresh", header: t("network.col.freshness"), sortValue: (i) => i.freshness, cell: (i) => <FreshnessBadge freshness={i.freshness} subtle />, hide: "sm" },170 ];171 return (172 <section className="section" aria-labelledby="net-if-h" data-testid="network-interfaces">173 <div className="section-head">174 <h2 id="net-if-h">{t("network.interfaces.title")}</h2>175 <DataStamp at={list.ready ? list.updatedAt : undefined} />176 </div>177 {!allowed ? <ForbiddenState permission="nodes.read" /> : (178 <>179 <div className="toolbar"><div className="svc-node-filter"><Combobox label={t("common.node")} options={nodes.options} value={url.get("node") || null} onChange={(v) => url.set({ node: v })} placeholder={t("common.all")} /></div></div>180 {list.error && !list.ready ? <ErrorState error={list.error} onRetry={list.refetch} compact /> : !list.ready ? <SkeletonRows rows={5} /> : (181 <>182 <DataTable caption={t("network.interfaces.title")} columns={columns} rows={list.items} rowKey={(i) => `${i.node_id}:${i.name}`} initialSort={{ id: "node", dir: "asc" }} compact183 empty={<EmptyState compact icon="network" title={t("network.interfaces.emptyTitle")}>{t("network.interfaces.emptyBody")}</EmptyState>} />184 <LoadMore hasMore={list.hasMore} loading={list.loadingMore} onMore={list.loadMore} />185 </>186 )}187 </>188 )}189 </section>190 );191}192193export function NetworkScreen() {194 const { t } = useI18n();195 return (196 <RequirePermission permission="cluster.read">197 <Page title={t("network.title")} sub={t("network.sub")}>198 <div data-testid="screen-network" className="stack-lg">199 <TopologySection />200 <ThroughputSection />201 <Suspense fallback={null}><InterfacesSection /></Suspense>202 </div>203 </Page>204 </RequirePermission>205 );206}207