SPB Git

Repository Public

StorageScreen.tsx 18.0 KB 249 lines tsx

1"use client";2import { useQueryClient } from "@tanstack/react-query";3import { Suspense, useMemo, useState } from "react";4import { apiDelete, apiPost, type ApiQuery, type Schemas } from "@/api/client";5import { ApiError } from "@/api/errors";6import { invalidatePaths, useApiList, useApiQuery } from "@/api/query";7import { When, useUrlState } from "@/features/services/url";8import { NodeLink, useNodeOptions } from "@/features/shared/nodes";9import { useI18n } from "@/i18n";10import { Page, RequirePermission } from "@/shell/AppShell";11import { useSession } from "@/shell/session";12import { Badge, Banner, Button, Combobox, ConfirmDialog, DataStamp, DataTable, Dialog, EmptyState, ErrorState, ForbiddenState, FreshnessBadge, IconButton, LoadMore, Meter, Observed, QueryBoundary, SelectField, SkeletonRows, StateDot, Tag, TextAreaField, TextField, Unmeasured, useErrorMessage, useToast, type Column, type Tone } from "@/ui";13import { groupByNode, isIpAddress, usedPct } from "./group";1415type Volume = Schemas["Volume"];16type Nas = Schemas["NasTarget"];17type Backup = Schemas["Backup"];18const KINDS = ["internal", "external", "network"] as const;19const THRESHOLDS = ["50", "80", "90"] as const;20const PROTOCOLS = ["smb", "nfs", "afp"] as const;2122function Usage({ used, total, label }: { used: number | undefined; total: number | undefined; label: string }) {23  const { t, fmt } = useI18n();24  const pct = usedPct({ used_bytes: used, total_bytes: total });25  if (pct === undefined || used === undefined || total === undefined) {26    return total !== undefined ? <span className="row gap-2"><Unmeasured availability="not_observed" reason={t("storage.usageUnknown")} /><span className="faint num">{t("storage.totalOnly", { total: fmt.bytes(total) })}</span></span> : <Unmeasured availability="not_observed" reason={t("storage.usageUnknown")} />;27  }28  return <div className="sto-usage"><Meter value={pct} label={label} text={`${fmt.percent(pct)} · ${t("storage.usedOf", { used: fmt.bytes(used), total: fmt.bytes(total) })}`} /></div>;29}3031function Smart({ status }: { status: string | undefined }) {32  const { t } = useI18n();33  if (status === undefined) return <Unmeasured availability="not_observed" reason={t("storage.smartNone")} />;34  const s = status.toLowerCase();35  const tone: Tone = s === "verified" || s === "passed" || s === "ok" ? "ok" : s.includes("fail") ? "critical" : "stale";36  return <StateDot tone={tone} label={status} />;37}3839function VolumesSection() {40  const { t, fmt } = useI18n();41  const url = useUrlState();42  const nodes = useNodeOptions();43  const kind = KINDS.find((k) => k === url.get("kind"));44  const min = THRESHOLDS.find((x) => x === url.get("min"));45  const query: ApiQuery<"/storage/volumes"> = { limit: 200, ...(kind ? { kind } : {}), ...(url.get("node") ? { node_id: url.get("node") } : {}), ...(min ? { min_used_pct: Number(min) } : {}) };46  const list = useApiList("/storage/volumes", { query }, { refetchInterval: 120_000 });47  const groups = useMemo(() => groupByNode(list.items), [list.items]);48  const filtered = !!kind || !!min || url.get("node") !== "";49  const columns: Column<Volume>[] = [50    { id: "mount", header: t("storage.col.mount"), sortValue: (v) => v.mount, mono: true, cell: (v) => v.mount },51    { id: "kind", header: t("storage.col.kind"), sortValue: (v) => v.kind, cell: (v) => <Tag>{t(`storage.kind.${v.kind}`)}</Tag>, hide: "sm" },52    { id: "usage", header: t("storage.col.usage"), sortValue: (v) => usedPct(v), cell: (v) => <Usage used={v.used_bytes} total={v.total_bytes} label={t("storage.usageOf", { mount: v.mount })} /> },53    { id: "device", header: t("storage.col.device"), mono: true, cell: (v) => <Observed value={v.device}>{(d) => d}</Observed>, hide: "md" },54    { id: "fs", header: t("storage.col.fs"), mono: true, cell: (v) => <Observed value={v.fs}>{(d) => d}</Observed>, hide: "md" },55    { id: "smart", header: t("storage.col.smart"), cell: (v) => <Smart status={v.smart_status} />, hide: "sm" },56    { id: "fresh", header: t("storage.col.freshness"), sortValue: (v) => v.freshness, cell: (v) => (v.gone_at ? <StateDot tone="offline" label={t("storage.goneSince", { time: fmt.dateTime(v.gone_at, { zone: false }) })} /> : <FreshnessBadge freshness={v.freshness} subtle />) },57    { id: "seen", header: t("storage.col.lastSeen"), sortValue: (v) => v.last_seen_at, cell: (v) => <When at={v.last_seen_at} />, hide: "md" },58  ];59  return (60    <section className="section" aria-labelledby="sto-vol-h" data-testid="storage-volumes">61      <div className="section-head"><h2 id="sto-vol-h">{t("storage.volumes.title")}</h2><DataStamp at={list.ready ? list.updatedAt : undefined} /></div>62      <div className="toolbar" role="search" aria-label={t("storage.volumes.filters")}>63        <SelectField label={t("storage.col.kind")} value={kind ?? ""} onChange={(v) => url.set({ kind: v })} options={[{ value: "", label: t("common.all") }, ...KINDS.map((k) => ({ value: k, label: t(`storage.kind.${k}`) }))]} />64        <SelectField label={t("storage.volumes.minUsed")} value={min ?? ""} onChange={(v) => url.set({ min: v })} options={[{ value: "", label: t("common.all") }, ...THRESHOLDS.map((x) => ({ value: x, label: t("storage.volumes.atLeast", { pct: x }) }))]} />65        <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>66        {filtered ? <Button variant="ghost" icon="close" onClick={() => url.clear(["kind", "min", "node"])}>{t("common.reset")}</Button> : null}67      </div>68      {list.error && !list.ready ? <ErrorState error={list.error} onRetry={list.refetch} /> : !list.ready ? <SkeletonRows rows={6} /> : groups.length === 0 ? (69        <EmptyState icon="storage" title={filtered ? t("storage.volumes.emptyFilteredTitle") : t("storage.volumes.emptyTitle")}>{filtered ? t("storage.volumes.emptyFilteredBody") : t("storage.volumes.emptyBody")}</EmptyState>70      ) : (71        <>72          {list.error ? <ErrorState error={list.error} onRetry={list.refetch} compact /> : null}73          <div className="stack-lg">74            {groups.map((g) => (75              <article key={g.nodeId} className="stack-sm sto-node" aria-labelledby={`sto-n-${g.nodeId}`} data-testid="storage-node" data-node-alias={g.alias}>76                <header className="row-between">77                  <h3 id={`sto-n-${g.nodeId}`}><NodeLink id={g.nodeId} alias={g.alias} /></h3>78                  <span className="mcc-hint num">{g.counted > 0 ? t("storage.volumes.nodeTotal", { used: fmt.bytes(g.usedBytes), total: fmt.bytes(g.totalBytes), count: g.counted }) : t("storage.volumes.nodeTotalNone")}</span>79                </header>80                <DataTable caption={t("storage.volumes.caption", { node: g.alias })} columns={columns} rows={g.volumes} rowKey={(v) => v.id} compact />81              </article>82            ))}83          </div>84          <LoadMore hasMore={list.hasMore} loading={list.loadingMore} onMore={list.loadMore} />85        </>86      )}87    </section>88  );89}9091function NasDialog({ onClose }: { onClose: () => void }) {92  const { t } = useI18n();93  const qc = useQueryClient();94  const toast = useToast();95  const explain = useErrorMessage();96  const [name, setName] = useState("");97  const [host, setHost] = useState("");98  const [share, setShare] = useState("");99  const [protocol, setProtocol] = useState<(typeof PROTOCOLS)[number]>("smb");100  const [note, setNote] = useState("");101  const [shown, setShown] = useState(false);102  const [busy, setBusy] = useState(false);103  const [failure, setFailure] = useState<string | null>(null);104  const errName = name.trim() === "" || name.trim().length > 64;105  const errHost = !isIpAddress(host);106  const save = async () => {107    setShown(true);108    if (errName || errHost) return;109    setBusy(true);110    setFailure(null);111    try {112      await apiPost("/storage/nas", { body: { name: name.trim(), host: host.trim(), protocol, ...(share.trim() ? { share: share.trim() } : {}), ...(note.trim() ? { note: note.trim() } : {}) } });113      await invalidatePaths(qc, "/storage/nas", "/cluster/overview");114      toast({ tone: "ok", title: t("storage.nas.registered", { name: name.trim() }) });115      onClose();116    } catch (e) {117      setBusy(false);118      const m = explain(e);119      setFailure(e instanceof ApiError && e.code === "conflict" ? t("storage.nas.conflict") : [m.title, m.detail].filter(Boolean).join(" — "));120    }121  };122  return (123    <Dialog open onClose={onClose} title={t("storage.nas.registerTitle")} description={t("storage.nas.registerBody")} dismissable={!busy}124      footer={<><Button onClick={onClose} disabled={busy}>{t("common.cancel")}</Button><Button variant="primary" loading={busy} onClick={() => void save()} data-testid="nas-save">{t("storage.nas.register")}</Button></>}>125      <form className="mcc-form" onSubmit={(e) => { e.preventDefault(); void save(); }} data-testid="nas-form" noValidate>126        <TextField label={t("common.name")} required value={name} onChange={setName} maxLength={64} disabled={busy} error={shown && errName ? t("ui.schema.required", { limit: "" }) : undefined} />127        <div className="mcc-form-row">128          <TextField label={t("storage.nas.host")} hint={t("storage.nas.hostHint")} required mono value={host} onChange={setHost} disabled={busy} autoCapitalize="none" spellCheck={false} error={shown && errHost ? t("storage.nas.hostInvalid") : undefined} />129          <SelectField label={t("storage.nas.protocol")} value={protocol} onChange={setProtocol} disabled={busy} options={PROTOCOLS.map((p) => ({ value: p, label: p.toUpperCase() }))} />130        </div>131        <TextField label={t("storage.nas.share")} value={share} onChange={setShare} maxLength={120} mono disabled={busy} />132        <TextAreaField label={t("storage.nas.note")} value={note} onChange={setNote} maxLength={500} disabled={busy} />133        {failure ? <Banner tone="critical" role="alert">{failure}</Banner> : null}134      </form>135    </Dialog>136  );137}138139function NasSection() {140  const { t, fmt } = useI18n();141  const { can } = useSession();142  const qc = useQueryClient();143  const toast = useToast();144  const explain = useErrorMessage();145  const allowed = can("cluster.read");146  const admin = can("settings.manage");147  const q = useApiQuery("/storage/nas", undefined, { enabled: allowed, refetchInterval: 60_000 });148  const [adding, setAdding] = useState(false);149  const [removing, setRemoving] = useState<Nas | null>(null);150  const [busy, setBusy] = useState(false);151  const remove = async (n: Nas) => {152    setBusy(true);153    try {154      await apiDelete("/storage/nas/{id}", { path: { id: n.id } });155      await invalidatePaths(qc, "/storage/nas", "/cluster/overview");156      toast({ tone: "ok", title: t("storage.nas.removed", { name: n.name }) });157      setRemoving(null);158    } catch (e) {159      toast({ tone: "critical", ...explain(e) });160    } finally {161      setBusy(false);162    }163  };164  const columns: Column<Nas>[] = [165    { id: "name", header: t("common.name"), sortValue: (n) => n.name, cell: (n) => <span className="stack-sm"><strong>{n.name}</strong>{n.note ? <span className="muted pre">{n.note}</span> : null}</span> },166    { id: "state", header: t("common.state"), sortValue: (n) => n.state, cell: (n) => (167      <span className="stack-sm" data-testid="nas-state" data-state={n.state}>168        <StateDot tone={n.state === "online" ? "ok" : n.state === "offline" ? "offline" : "stale"} label={t(`storage.nas.state.${n.state}`)} />169        <span className="faint">{n.state_at ? <>{t("storage.nas.since")} <When at={n.state_at} /></> : t("storage.nas.neverObserved")}</span>170      </span>171    ) },172    { id: "proto", header: t("storage.nas.protocol"), sortValue: (n) => n.protocol, cell: (n) => <Tag>{n.protocol.toUpperCase()}</Tag>, hide: "sm" },173    { id: "target", header: t("storage.nas.target"), mono: true, cell: (n) => (n.host ? `${n.host}${n.share ? ` / ${n.share}` : ""}` : <span className="row gap-2">{n.share ? <span>{n.share}</span> : null}<span className="faint" title={t("storage.nas.hostHidden")}>{t("storage.nas.hostHiddenShort")}</span></span>), hide: "md" },174    { id: "capacity", header: t("storage.nas.capacity"), sortValue: (n) => usedPct(n), cell: (n) => <Usage used={n.used_bytes} total={n.total_bytes} label={t("storage.usageOf", { mount: n.name })} /> },175    { id: "latency", header: t("storage.nas.latency"), align: "right", sortValue: (n) => n.latency_ms, cell: (n) => <Observed value={n.latency_ms}>{(v) => fmt.ms(v)}</Observed>, hide: "md" },176    { id: "mounted", header: t("storage.nas.mountedOn"), align: "right", sortValue: (n) => n.mounted_on, cell: (n) => t("storage.nas.mountedCount", { count: n.mounted_on }), hide: "sm" },177    { id: "by", header: t("storage.nas.observedBy"), cell: (n) => <Observed value={n.observed_by}>{(v) => <span className="mono">{v}</span>}</Observed>, hide: "md" },178    ...(admin ? [{ id: "actions", header: t("common.actions"), srOnlyHeader: true, shrink: true, cell: (n: Nas) => <IconButton size="sm" icon="trash" label={t("storage.nas.removeLabel", { name: n.name })} onClick={() => setRemoving(n)} /> } satisfies Column<Nas>] : []),179  ];180  return (181    <section className="section" aria-labelledby="sto-nas-h" data-testid="storage-nas">182      <div className="section-head">183        <h2 id="sto-nas-h">{t("storage.nas.title")}</h2>184        <div className="row-wrap"><DataStamp at={q.data ? q.dataUpdatedAt : undefined} />{admin ? <Button icon="plus" onClick={() => setAdding(true)} data-testid="nas-register">{t("storage.nas.register")}</Button> : null}</div>185      </div>186      <p className="mcc-hint">{t("storage.nas.intro")}</p>187      {!allowed ? <ForbiddenState permission="cluster.read" /> : (188        <QueryBoundary query={q} skeleton={<SkeletonRows rows={2} />} compact>189          {(d) => <DataTable caption={t("storage.nas.title")} columns={columns} rows={d.items} rowKey={(n) => n.id} initialSort={{ id: "name", dir: "asc" }} empty={<EmptyState compact icon="storage" title={t("storage.nas.emptyTitle")}>{admin ? t("storage.nas.emptyBodyAdmin") : t("storage.nas.emptyBody")}</EmptyState>} />}190        </QueryBoundary>191      )}192      {adding ? <NasDialog onClose={() => setAdding(false)} /> : null}193      <ConfirmDialog open={removing !== null} danger busy={busy} onClose={() => setRemoving(null)} onConfirm={() => { if (removing) void remove(removing); }} title={t("storage.nas.removeTitle")} body={removing ? t("storage.nas.removeBody", { name: removing.name }) : undefined} confirmLabel={t("common.remove")} />194    </section>195  );196}197198function BackupsSection() {199  const { t, fmt } = useI18n();200  const { can } = useSession();201  const allowed = can("cluster.read");202  const q = useApiQuery("/storage/backups", undefined, { enabled: allowed, refetchInterval: 120_000 });203  const columns: Column<Backup>[] = [204    { id: "name", header: t("common.name"), sortValue: (b) => b.name, cell: (b) => <span className="stack-sm"><strong>{b.name}</strong>{b.detail ? <span className="muted pre">{b.detail}</span> : null}</span> },205    { id: "kind", header: t("storage.backups.kind"), sortValue: (b) => b.kind, cell: (b) => <Tag>{b.kind}</Tag>, hide: "sm" },206    { id: "node", header: t("common.node"), sortValue: (b) => b.node_alias, cell: (b) => (b.node_id ? <NodeLink id={b.node_id} alias={b.node_alias} /> : <span className="faint">{t("storage.backups.noNode")}</span>), hide: "sm" },207    { id: "status", header: t("storage.backups.lastStatus"), sortValue: (b) => b.last_status, cell: (b) => (208      <span data-testid="backup-status" data-status={b.last_status}>209        {b.last_status === "ok" ? <Badge tone="ok">{t("storage.backups.status.ok")}</Badge> : b.last_status === "failed" ? <Badge tone="critical">{t("storage.backups.status.failed")}</Badge> : <Badge tone="stale" icon="unknown">{t("storage.backups.status.unknown")}</Badge>}210      </span>211    ) },212    { id: "success", header: t("storage.backups.lastSuccess"), sortValue: (b) => b.last_success_at, cell: (b) => (b.last_success_at ? <span className="stack-sm"><When at={b.last_success_at} /><span className="faint num">{fmt.dateTime(b.last_success_at)}</span></span> : <Unmeasured availability="not_observed" reason={t("storage.backups.noSuccess")} />) },213    { id: "run", header: t("storage.backups.lastRun"), sortValue: (b) => b.last_run_at, cell: (b) => (b.last_run_at ? <When at={b.last_run_at} /> : <Unmeasured availability="not_observed" />), hide: "md" },214    { id: "size", header: t("storage.backups.size"), align: "right", sortValue: (b) => b.size_bytes, cell: (b) => <Observed value={b.size_bytes}>{(v) => fmt.bytes(v)}</Observed>, hide: "md" },215    { id: "observed", header: t("storage.backups.observed"), sortValue: (b) => b.observed_at, cell: (b) => (b.observed_at ? <When at={b.observed_at} /> : <Unmeasured availability="not_observed" />), hide: "md" },216  ];217  return (218    <section className="section" aria-labelledby="sto-bak-h" data-testid="storage-backups">219      <div className="section-head"><h2 id="sto-bak-h">{t("storage.backups.title")}</h2><DataStamp at={q.data ? q.dataUpdatedAt : undefined} /></div>220      <p className="mcc-hint" data-testid="backups-honesty">{t("storage.backups.intro")}</p>221      {!allowed ? <ForbiddenState permission="cluster.read" /> : (222        <QueryBoundary query={q} skeleton={<SkeletonRows rows={3} />} compact>223          {(d) => (224            <>225              {d.items.some((b) => b.last_status === "unknown") ? <Banner tone="stale" icon="unknown">{t("storage.backups.unknownNote")}</Banner> : null}226              <DataTable caption={t("storage.backups.title")} columns={columns} rows={d.items} rowKey={(b) => b.id} initialSort={{ id: "name", dir: "asc" }} empty={<EmptyState compact icon="storage" title={t("storage.backups.emptyTitle")}>{t("storage.backups.emptyBody")}</EmptyState>} />227            </>228          )}229        </QueryBoundary>230      )}231    </section>232  );233}234235export function StorageScreen() {236  const { t } = useI18n();237  return (238    <RequirePermission permission="nodes.read">239      <Page title={t("storage.title")} sub={t("storage.sub")}>240        <div data-testid="screen-storage" className="stack-lg">241          <Suspense fallback={null}><VolumesSection /></Suspense>242          <NasSection />243          <BackupsSection />244        </div>245      </Page>246    </RequirePermission>247  );248}249
Files main
Menu

Theme