SPB Git

Repository Public

CompareScreen.tsx 8.9 KB 163 lines tsx

1"use client";2import Link from "next/link";3import { useQueries } from "@tanstack/react-query";4import { useSearchParams } from "next/navigation";5import { Suspense, useMemo, useState, type ReactNode } from "react";6import { apiGet, type Schemas } from "@/api/client";7import { ApiError } from "@/api/errors";8import { queryKey, useApiQuery } from "@/api/query";9import { metricLabel } from "@/features/shared/metrics";10import { useI18n } from "@/i18n";11import { Page, RequirePermission } from "@/shell/AppShell";12import { usePeriod } from "@/shell/period";13import { DataStamp, EmptyState, ErrorState, LinkButton, SelectField, Skeleton, Unmeasured } from "@/ui";14import { TimeSeriesChart } from "@/ui/TimeSeriesChart";15import { COMPARE_MAX, COMPARE_MIN, formatPerfLevels, parseCompareIds } from "./logic";16import { LastContact, NodeState } from "./parts";1718type Detail = Schemas["NodeDetail"];1920export function CompareScreen() {21  return (22    <RequirePermission permission="nodes.read">23      <Suspense fallback={null}>24        <CompareInner />25      </Suspense>26    </RequirePermission>27  );28}2930function CompareInner() {31  const { t, fmt } = useI18n();32  const params = useSearchParams();33  const ids = useMemo(() => parseCompareIds(params.get("ids")), [params]);34  const details = useQueries({35    queries: ids.map((id) => ({36      queryKey: queryKey("/nodes/{id}", { path: { id } }),37      queryFn: ({ signal }: { signal: AbortSignal }) => apiGet("/nodes/{id}", { path: { id }, signal }),38      retry: false,39    })),40  });4142  const back = <LinkButton href="/nodes" icon="chevron-left">{t("nodes.compare.back")}</LinkButton>;43  if (ids.length < COMPARE_MIN) {44    return (45      <Page title={t("nodes.compare.title")} actions={back}>46        <div data-testid="screen-nodes-compare">47          <EmptyState icon="chart" title={t("nodes.compare.needTwo")} actions={<LinkButton href="/nodes" variant="primary">{t("nodes.compare.pick")}</LinkButton>}>{t("nodes.compare.hint", { min: COMPARE_MIN, max: COMPARE_MAX })}</EmptyState>48        </div>49      </Page>50    );51  }5253  const aliasOf = (id: string, i: number) => details[i]?.data?.node.alias ?? id.slice(0, 8);54  const row = (label: string, cell: (d: Detail) => ReactNode) => (55    <tr key={label}>56      <th scope="row">{label}</th>57      {ids.map((id, i) => {58        const q = details[i];59        return <td key={id}>{q?.data ? cell(q.data) : q?.isError ? <span className="faint">{t("nodes.compare.unavailable")}</span> : <Skeleton width="60" />}</td>;60      })}61    </tr>62  );63  const opt = <T,>(v: T | undefined, f: (v: T) => ReactNode) => (v === undefined ? <Unmeasured availability="not_observed" /> : f(v));64  const firstError = details.find((d) => d.isError)?.error;65  const allFailed = details.length > 0 && details.every((d) => d.isError);66  const updated = Math.max(0, ...details.map((d) => d.dataUpdatedAt));6768  return (69    <Page title={t("nodes.compare.title")} sub={t("nodes.compare.sub", { count: ids.length })} actions={<><DataStamp at={updated || undefined} />{back}</>}>70      <div data-testid="screen-nodes-compare" className="stack-lg">71        <section className="section" aria-labelledby="cmp-specs">72          <h2 id="cmp-specs">{t("nodes.compare.specs")}</h2>73          {allFailed ? <ErrorState error={firstError instanceof ApiError ? firstError : null} onRetry={() => details.forEach((d) => void d.refetch())} /> : (74            <div className="mcc-table-wrap">75              <table className="mcc-table nodes-compare-table" data-testid="compare-specs">76                <caption className="sr-only">{t("nodes.compare.specs")}</caption>77                <thead>78                  <tr>79                    <th scope="col">{t("nodes.compare.property")}</th>80                    {ids.map((id, i) => <th key={id} scope="col"><Link href={`/nodes/${id}`} className="mono">{aliasOf(id, i)}</Link></th>)}81                  </tr>82                </thead>83                <tbody>84                  {row(t("common.state"), (d) => <NodeState node={d.node} subtle />)}85                  {row(t("nodes.col.lastContact"), (d) => <LastContact at={d.node.last_seen_at} />)}86                  {row(t("nodes.hw.model"), (d) => opt(d.node.model, (v) => v))}87                  {row(t("nodes.hw.chip"), (d) => opt(d.node.chip, (v) => v))}88                  {row(t("nodes.hw.cpuCores"), (d) => opt(d.node.cpu_cores, (v) => <span className="num">{fmt.integer(v)}</span>))}89                  {row(t("nodes.hw.perfLevels"), (d) => (d.cpu_levels.length ? formatPerfLevels(d.cpu_levels) : <Unmeasured availability="not_observed" />))}90                  {row(t("nodes.hw.gpuCores"), (d) => opt(d.node.gpu_cores, (v) => <span className="num">{fmt.integer(v)}</span>))}91                  {row(t("nodes.hw.memory"), (d) => opt(d.node.mem_bytes, (v) => <span className="num">{fmt.bytes(v)}</span>))}92                  {row(t("nodes.hw.storage"), (d) => opt(d.node.storage_bytes, (v) => <span className="num">{fmt.bytes(v)}</span>))}93                  {row(t("nodes.hw.os"), (d) => (d.node.os_name || d.node.os_version ? [d.node.os_name, d.node.os_version].filter(Boolean).join(" ") : <Unmeasured availability="not_observed" />))}94                  {row(t("nodes.col.agent"), (d) => (d.node.agent_version ? <span className="mono">{d.node.agent_version}</span> : <span className="faint">{t("nodes.noAgent")}</span>))}95                  {row(t("nodes.col.site"), (d) => d.node.site || <span className="faint">{t("nodes.unset")}</span>)}96                  {row(t("nodes.col.role"), (d) => d.node.role || <span className="faint">{t("nodes.unset")}</span>)}97                </tbody>98              </table>99            </div>100          )}101        </section>102        <CompareCharts ids={ids} aliasOf={(id) => aliasOf(id, ids.indexOf(id))} />103      </div>104    </Page>105  );106}107108const DEFAULT_METRICS = ["cpu.usage", "mem.used", "load.1"];109110function CompareCharts({ ids, aliasOf }: { ids: string[]; aliasOf: (id: string) => string }) {111  const { t } = useI18n();112  const catalog = useApiQuery("/metrics/catalog", undefined, { staleTime: 10 * 60_000 });113  const [metric, setMetric] = useState("cpu.usage");114  const names = catalog.data ? catalog.data.items.map((m) => m.name) : DEFAULT_METRICS;115  const options = (names.includes(metric) ? names : [metric, ...names]).map((n) => ({ value: n, label: metricLabel(t, n) }));116  const entry = catalog.data?.items.find((m) => m.name === metric);117  return (118    <section className="section" aria-labelledby="cmp-charts">119      <div className="section-head">120        <h2 id="cmp-charts">{t("nodes.compare.charts")}</h2>121        <div className="nodes-metric-picker"><SelectField label={t("nodes.compare.metric")} value={metric} onChange={setMetric} options={options} data-testid="compare-metric" /></div>122      </div>123      {catalog.isError && !catalog.error.notImplemented ? <ErrorState error={catalog.error} compact onRetry={() => void catalog.refetch()} /> : null}124      {entry ? <p className="mcc-hint">{entry.description} <span className="faint">({entry.source})</span></p> : null}125      <CompareChart ids={ids} metric={metric} aliasOf={aliasOf} />126    </section>127  );128}129130function CompareChart({ ids, metric, aliasOf }: { ids: string[]; metric: string; aliasOf: (id: string) => string }) {131  const { t } = useI18n();132  const period = usePeriod();133  const q = useApiQuery("/metrics/compare", { query: { metric, node_ids: ids, from: period.from, to: period.to } }, { placeholderData: (prev) => prev });134  const title = metricLabel(t, metric);135  if (q.isError && !q.data) return <ErrorState error={q.error} onRetry={() => void q.refetch()} />;136  const data = q.data;137  const series = (data?.series ?? []).map((s) => {138    const alias = s.node_alias ?? (s.node_id ? aliasOf(s.node_id) : "");139    return { id: `${s.node_id ?? ""}:${s.label}`, label: s.label && s.label !== alias ? (alias ? `${alias} · ${s.label}` : s.label) : alias || s.label, points: s.points };140  });141  // nodes without any point: say why (availability reported by the server), never a silent empty line142  const withData = new Set((data?.series ?? []).filter((s) => s.points.length > 0).map((s) => s.node_id));143  const missing = data ? ids.filter((id) => !withData.has(id)) : [];144  return (145    <div className="stack" data-testid="compare-chart">146      <TimeSeriesChart title={title} unit={data?.unit ?? ""} series={series} from={period.fromMs} to={period.toMs} size="tall" loading={q.isLoading} {...(data?.unit === "percent" ? { yMax: 100 } : {})} actions={<DataStamp at={q.dataUpdatedAt || undefined} />} />147      {missing.length > 0 ? (148        <ul className="nodes-missing" aria-label={t("nodes.compare.missing")}>149          {missing.map((id) => {150            const a = data?.availability[id] ?? data?.availability[aliasOf(id)];151            return (152              <li key={id} data-testid="compare-missing">153                <span className="mono">{aliasOf(id)}</span>154                <Unmeasured availability={!a || a === "available" ? "not_observed" : a} reason={t("nodes.compare.noData")} />155              </li>156            );157          })}158        </ul>159      ) : null}160    </div>161  );162}163
Files main
Menu

Theme