SPB Git

Repository Public

health.tsx 9.8 KB 143 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Music SP8 * File             : src/components/admin/health.tsx9 * Module           : components10 * Repository       : https://git.spboucher.ai/sp-music11 * Project Website  : https://music.spboucher.ai12 * Created          : 2026-11-1713 * Last Modified    : 2026-11-1714 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243"use client";44import { useEffect, useState } from "react";45import { fmtBytes, fmtDate, fmtDuration } from "@/lib/format";46import { useLocale, useT } from "@/i18n";47import type { Key } from "@/i18n/messages";48import { Async, useApi } from "@/components/ui";49import { IRefresh } from "@/components/icons";5051interface Health {52  storage: { driver: string; available: boolean; freeBytes: number | null; totalBytes: number | null; usedBytes: number; quotaBytes: number; byKind: { kind: string; files: number; bytes: number }[] };53  library: { tracks: number; albums: number; artists: number; durationMs: number; notPlayableInBrowser: number; renditionsPending: number; renditionErrors: number };54  imports: { counts: Record<string, number>; recentErrors: { id: string; filename: string; errorCode: string; errorDetail: string | null; updatedAt: string }[] };55  worker: { ok: boolean; ageSec: number | null };56  backup: { configured: boolean; last: { at: string; database: boolean; library: boolean; files?: number; bytes?: number } | null };57  config: { renditions: string; renditionBitrateKbps: number; transcodeDsd: boolean; maxFileBytes: number; uploadRetentionDays: number; rpId: string; origin: string };58}5960function Stat({ label, value, tone }: { label: string; value: string; tone?: "ok" | "warn" | "err" }) {61  return <div className="card p-4"><p className="text-xs font-semibold text-muted">{label}</p><p className={`mt-1 text-xl font-extrabold tracking-tight ${tone === "ok" ? "text-ok" : tone === "warn" ? "text-warn" : tone === "err" ? "text-danger" : ""}`}>{value}</p></div>;62}63const Row = ({ k, v }: { k: string; v: string }) => <div className="flex justify-between gap-4 py-1.5 text-sm"><dt className="text-muted">{k}</dt><dd className="text-right font-medium">{v}</dd></div>;6465export function HealthPanel() {66  const t = useT(); const locale = useLocale();67  const res = useApi<Health>("/api/v1/admin/health");68  useEffect(() => { const iv = setInterval(res.reload, 15_000); return () => clearInterval(iv); }, [res.reload]);69  return (70    <div className="max-w-4xl">71      <div className="mb-3 flex justify-end"><button className="btn btn-sm" onClick={res.reload}><IRefresh size={14} />{t("health.refresh")}</button></div>72      <Async res={res}>{(h) => {73        const backupAge = h.backup.last ? (Date.now() - new Date(h.backup.last.at).getTime()) / 3600_000 : null;74        const pending = (h.imports.counts.received ?? 0) + (h.imports.counts.validating ?? 0) + (h.imports.counts.extracting ?? 0);75        return (<>76          <div className="grid grid-cols-2 gap-3 md:grid-cols-4">77            <Stat label={t("health.storage")} value={t(h.storage.available ? "health.available" : "health.unavailable")} tone={h.storage.available ? "ok" : "err"} />78            <Stat label={t("health.worker")} value={h.worker.ok ? t("health.running") : t("health.stopped")} tone={h.worker.ok ? "ok" : "err"} />79            <Stat label={t("health.analysis")} value={pending ? t("health.pendingN", { n: pending }) : t("health.idle")} tone={pending ? "warn" : "ok"} />80            <Stat label={t("health.lastBackup")} value={!h.backup.configured ? t("health.backupOff") : h.backup.last ? fmtDate(h.backup.last.at, locale) : t("health.backupNever")} tone={!h.backup.last ? "warn" : backupAge! > 36 ? "warn" : "ok"} />81            <Stat label={t("lib.tracks")} value={String(h.library.tracks)} />82            <Stat label={t("lib.albums")} value={String(h.library.albums)} />83            <Stat label={t("health.used")} value={fmtBytes(h.storage.usedBytes, locale)} />84            <Stat label={t("health.free")} value={fmtBytes(h.storage.freeBytes, locale)} tone={h.storage.freeBytes !== null && h.storage.freeBytes < 5 * 1024 ** 3 ? "warn" : undefined} />85          </div>86          <div className="mt-5 grid gap-5 md:grid-cols-2">87            <section className="card p-5"><h2 className="h-section mb-2">{t("health.library")}</h2><dl className="divide-y divide-line/60">88              <Row k={t("lib.artists")} v={String(h.library.artists)} />89              <Row k={t("health.totalDuration")} v={fmtDuration(h.library.durationMs, locale)} />90              {h.storage.byKind.map((k) => <Row key={k.kind} k={t(`health.kind.${k.kind}` as Key)} v={`${k.files} · ${fmtBytes(k.bytes, locale)}`} />)}91              <Row k={t("health.quota")} v={h.storage.quotaBytes ? fmtBytes(h.storage.quotaBytes, locale) : t("health.noQuota")} />92              <Row k={t("health.volume")} v={`${fmtBytes(h.storage.totalBytes, locale)} (${h.storage.driver})`} />93              <Row k={t("health.notPlayable")} v={String(h.library.notPlayableInBrowser)} />94              <Row k={t("health.renditions")} v={`${t("health.pendingN", { n: h.library.renditionsPending })} · ${t("health.errorsN", { n: h.library.renditionErrors })}`} />95            </dl></section>96            <section className="card p-5"><h2 className="h-section mb-2">{t("health.config")}</h2><dl className="divide-y divide-line/60">97              <Row k={t("health.origin")} v={h.config.origin} />98              <Row k="RP ID (WebAuthn)" v={h.config.rpId} />99              <Row k={t("health.maxFile")} v={fmtBytes(h.config.maxFileBytes, locale)} />100              <Row k={t("health.renditionPolicy")} v={`${h.config.renditions} · AAC ${h.config.renditionBitrateKbps} kb/s`} />101              <Row k="DSD → AAC" v={t(h.config.transcodeDsd ? "common.yes" : "common.no")} />102              <Row k={t("health.retention")} v={t("health.days", { n: h.config.uploadRetentionDays })} />103              <Row k={t("health.backupContent")} v={h.backup.last ? `${h.backup.last.files ?? "?"} ${t("health.originals")} · ${fmtBytes(h.backup.last.bytes ?? null, locale)}` : "—"} />104            </dl>105            <p className="mt-3 text-xs leading-relaxed text-faint">{t("health.retentionNote", { n: h.config.uploadRetentionDays })}</p></section>106          </div>107          <section className="card mt-5 p-5"><h2 className="h-section mb-2">{t("health.errors")}</h2>108            {h.imports.recentErrors.length === 0 ? <p className="text-sm text-muted">{t("health.noErrors")}</p> : (109              <ul className="divide-y divide-line/60">{h.imports.recentErrors.map((e) => <li key={e.id} className="py-2 text-sm"><span className="font-medium">{e.filename}</span> <span className="chip chip-err ml-1">{e.errorCode}</span><span className="block text-xs text-muted">{fmtDate(e.updatedAt, locale)}{e.errorDetail ? ` · ${e.errorDetail}` : ""}</span></li>)}</ul>)}110          </section>111        </>);112      }}</Async>113    </div>114  );115}116117interface AuditEvent { id: string; at: string; actor: string; action: string; entity: string; entityId: string; meta: Record<string, unknown>; userName: string | null }118export function AuditPanel() {119  const t = useT(); const locale = useLocale();120  const [offset, setOffset] = useState(0);121  const res = useApi<{ items: AuditEvent[]; total: number; limit: number }>(`/api/v1/admin/audit?limit=50&offset=${offset}`);122  return (123    <div className="max-w-4xl">124      <p className="mb-3 text-sm leading-relaxed text-muted">{t("audit.help")}</p>125      <Async res={res}>{(d) => (<>126        <ul className="card divide-y divide-line">{d.items.map((e) => {127          const meta = Object.entries(e.meta).filter(([, v]) => v != null && v !== "").map(([k, v]) => `${k}: ${typeof v === "object" ? JSON.stringify(v) : String(v)}`).join(" · ");128          return (129            <li key={e.id} className="px-4 py-2.5 text-sm">130              <div className="flex flex-wrap items-baseline justify-between gap-x-3"><span className="font-mono text-[0.8rem] font-semibold">{e.action}</span><span className="text-xs text-muted">{fmtDate(e.at, locale)}</span></div>131              <p className="break-words text-xs text-muted">{e.userName ?? e.actor}{meta ? ` · ${meta}` : ""}</p>132            </li>);133        })}</ul>134        <div className="mt-4 flex items-center justify-between text-sm">135          <button className="btn btn-sm" disabled={offset === 0} onClick={() => setOffset(Math.max(0, offset - d.limit))}>{t("audit.newer")}</button>136          <span className="text-xs text-muted">{offset + 1}–{Math.min(offset + d.limit, d.total)} / {d.total}</span>137          <button className="btn btn-sm" disabled={offset + d.limit >= d.total} onClick={() => setOffset(offset + d.limit)}>{t("audit.older")}</button>138        </div>139      </>)}</Async>140    </div>141  );142}143
Files main
Menu

Theme