298 lines
15 KiB
TypeScript
298 lines
15 KiB
TypeScript
"use client";
|
||
|
||
import { useEffect, useState } from "react";
|
||
import { Clock3Icon, DatabaseIcon, GlobeIcon, RefreshCwIcon, SaveIcon, SearchIcon } from "lucide-react";
|
||
import { toast } from "@/core/ui/feedback";
|
||
|
||
import { Badge } from "@/components/ui/badge";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Input } from "@/components/ui/input";
|
||
import { Switch } from "@/components/ui/switch";
|
||
import { getAuditRetentionStatus, setAuditRetentionPaused, type AuditRetentionStatus } from "@/core/admin/audit-retention";
|
||
import { apiFetch } from "@/core/api";
|
||
import { getBackendBaseURL } from "@/core/config";
|
||
|
||
type CacheCollection = {
|
||
id: string;
|
||
label: string;
|
||
paths: string[];
|
||
scope: string;
|
||
enabled: boolean;
|
||
ttl_seconds: number;
|
||
};
|
||
|
||
type ApiReadCacheStatus = {
|
||
enabled: boolean;
|
||
redis_configured: boolean;
|
||
ttl_seconds: number;
|
||
max_value_bytes: number;
|
||
browser_status_enabled: boolean;
|
||
collections: CacheCollection[];
|
||
};
|
||
|
||
type ApiReadCacheUpdate = {
|
||
enabled?: boolean;
|
||
ttl_seconds?: number;
|
||
browser_status_enabled?: boolean;
|
||
collection_overrides?: Record<string, boolean>;
|
||
};
|
||
|
||
async function requestStatus(update?: ApiReadCacheUpdate): Promise<ApiReadCacheStatus> {
|
||
const response = await apiFetch(`${getBackendBaseURL()}/api/system-settings/api-read-cache`, update ? {
|
||
method: "PUT",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify(update),
|
||
} : undefined);
|
||
const data = await response.json().catch(() => ({}));
|
||
if (!response.ok) {
|
||
throw new Error(typeof data.detail === "string" ? data.detail : `${update ? "保存" : "读取"}失败(${response.status})`);
|
||
}
|
||
return data as ApiReadCacheStatus;
|
||
}
|
||
|
||
function retentionLabel(status: string) {
|
||
switch (status) {
|
||
case "running": return "正在清理";
|
||
case "pausing": return "正在停止";
|
||
case "paused": return "已关闭";
|
||
case "error": return "本轮异常";
|
||
default: return "等待执行";
|
||
}
|
||
}
|
||
|
||
function dateTime(value?: string | number | null) {
|
||
if (!value) return "暂无";
|
||
const date = new Date(typeof value === "number" ? value * 1000 : value);
|
||
return Number.isNaN(date.getTime()) ? "暂无" : date.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai", hour12: false });
|
||
}
|
||
|
||
export function ApiReadCacheSettingsPage() {
|
||
const [status, setStatus] = useState<ApiReadCacheStatus>();
|
||
const [retention, setRetention] = useState<AuditRetentionStatus>();
|
||
const [ttlInput, setTtlInput] = useState("300");
|
||
const [search, setSearch] = useState("");
|
||
const [busy, setBusy] = useState(false);
|
||
const [error, setError] = useState("");
|
||
const [retentionError, setRetentionError] = useState("");
|
||
|
||
const refresh = async () => {
|
||
setBusy(true);
|
||
const [cacheResult, retentionResult] = await Promise.allSettled([
|
||
requestStatus(),
|
||
getAuditRetentionStatus(),
|
||
]);
|
||
if (cacheResult.status === "fulfilled") {
|
||
setStatus(cacheResult.value);
|
||
setTtlInput(String(cacheResult.value.ttl_seconds));
|
||
setError("");
|
||
} else {
|
||
setError(cacheResult.reason instanceof Error ? cacheResult.reason.message : "读取缓存设置失败");
|
||
}
|
||
if (retentionResult.status === "fulfilled") {
|
||
setRetention(retentionResult.value);
|
||
setRetentionError("");
|
||
} else {
|
||
setRetentionError(retentionResult.reason instanceof Error ? retentionResult.reason.message : "读取清理设置失败");
|
||
}
|
||
setBusy(false);
|
||
};
|
||
|
||
useEffect(() => { void refresh(); }, []);
|
||
|
||
const save = async (update: ApiReadCacheUpdate, message: string) => {
|
||
setBusy(true);
|
||
try {
|
||
const saved = await requestStatus(update);
|
||
setStatus(saved);
|
||
if (update.ttl_seconds !== undefined) setTtlInput(String(saved.ttl_seconds));
|
||
setError("");
|
||
toast.success(message);
|
||
} catch (err) {
|
||
toast.error(err instanceof Error ? err.message : "保存设置失败");
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
};
|
||
|
||
const toggleRetention = async (enabled: boolean) => {
|
||
setBusy(true);
|
||
try {
|
||
const saved = await setAuditRetentionPaused(!enabled);
|
||
setRetention(saved);
|
||
setRetentionError("");
|
||
toast.success(enabled ? "定时清理已开启" : saved.pause_requested ? "已关闭定时清理,当前批次结束后停止" : "定时清理已关闭");
|
||
} catch (err) {
|
||
toast.error(err instanceof Error ? err.message : "保存清理设置失败");
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
};
|
||
|
||
const parsedTtl = Number(ttlInput);
|
||
const validTtl = Number.isInteger(parsedTtl) && parsedTtl >= 1 && parsedTtl <= 3600;
|
||
const collections = status?.collections ?? [];
|
||
const searchText = search.trim().toLowerCase();
|
||
const visibleCollections = collections.filter((item) =>
|
||
[item.label, item.id, item.scope, ...item.paths].join(" ").toLowerCase().includes(searchText),
|
||
);
|
||
const enabledCount = collections.filter((item) => item.enabled).length;
|
||
|
||
return (
|
||
<section className="space-y-5" data-testid="api-read-cache-settings" aria-busy={busy}>
|
||
<header className="flex flex-wrap items-start justify-between gap-3">
|
||
<div>
|
||
<h2 className="flex items-center gap-2 text-xl font-semibold"><DatabaseIcon className="size-5 text-primary" />Redis 与性能管理</h2>
|
||
<p className="mt-1 text-sm text-muted-foreground">统一管理接口缓存、浏览器状态查询和历史数据定时清理。</p>
|
||
</div>
|
||
<Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void refresh()}>
|
||
<RefreshCwIcon className={`size-4 ${busy ? "animate-spin" : ""}`} />刷新状态
|
||
</Button>
|
||
</header>
|
||
|
||
{error && <p role="alert" className="rounded-lg border border-destructive/30 p-3 text-sm text-destructive">{error}</p>}
|
||
|
||
<div className="overflow-hidden rounded-xl border">
|
||
<div className="flex items-center justify-between gap-4 bg-muted/30 p-4">
|
||
<div>
|
||
<h3 className="font-medium">Redis 读取缓存总开关</h3>
|
||
<p className="mt-1 text-sm text-muted-foreground">开关和有效期保存在 MySQL,服务重启后仍生效。</p>
|
||
</div>
|
||
<Switch
|
||
checked={status?.enabled ?? false}
|
||
disabled={!status || busy}
|
||
onCheckedChange={(enabled) => void save({ enabled }, enabled ? "Redis 读取缓存已开启" : "Redis 读取缓存已关闭")}
|
||
aria-label="启用 Redis 读取缓存"
|
||
/>
|
||
</div>
|
||
<div className="space-y-3 border-t p-4">
|
||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||
<div>
|
||
<label htmlFor="api-cache-ttl" className="text-sm font-medium">默认缓存有效期</label>
|
||
<p id="api-cache-ttl-help" className="mt-1 text-xs text-muted-foreground">1–3600 秒,默认 300 秒;保存后刷新缓存。</p>
|
||
</div>
|
||
<div className="flex items-center gap-2">
|
||
<Input
|
||
id="api-cache-ttl"
|
||
type="number"
|
||
min={1}
|
||
max={3600}
|
||
step={1}
|
||
value={ttlInput}
|
||
disabled={!status || busy}
|
||
onChange={(event) => setTtlInput(event.target.value)}
|
||
aria-label="Redis 缓存有效期(秒)"
|
||
aria-describedby="api-cache-ttl-help"
|
||
aria-invalid={!validTtl}
|
||
className="w-24"
|
||
/>
|
||
<span className="text-sm text-muted-foreground">秒</span>
|
||
<Button type="button" size="sm" variant="outline" disabled={!status || busy || !validTtl || parsedTtl === status.ttl_seconds} onClick={() => void save({ ttl_seconds: parsedTtl }, "Redis 缓存有效期已保存")}>
|
||
<SaveIcon className="size-4" />保存有效期
|
||
</Button>
|
||
</div>
|
||
</div>
|
||
{status && <div className="flex flex-wrap items-center gap-x-3 gap-y-2 text-xs text-muted-foreground">
|
||
<Badge variant="secondary">Redis 地址{status.redis_configured ? "已配置" : "未配置"}</Badge>
|
||
<span>单条结果上限 {Math.round(status.max_value_bytes / 1024)} KiB</span>
|
||
<span>关闭或连接失败时自动使用原查询</span>
|
||
</div>}
|
||
{status && !status.redis_configured && <p className="text-xs text-amber-700 dark:text-amber-400">当前未配置 Redis 地址。可以保存开关,但配置连接后才会使用缓存。</p>}
|
||
</div>
|
||
</div>
|
||
|
||
<div className="rounded-xl border p-4" data-testid="browser-status-control">
|
||
<div className="flex items-start justify-between gap-4">
|
||
<div className="min-w-0">
|
||
<h3 className="flex items-center gap-2 font-medium"><GlobeIcon className="size-4 text-primary" />允许浏览器状态查询</h3>
|
||
<p className="mt-1 break-all font-mono text-xs text-muted-foreground">GET /api/browser-context/status</p>
|
||
<p className="mt-2 text-sm text-muted-foreground">控制浏览器插件能否访问状态接口;关闭后,服务器会拒绝该接口的查询。</p>
|
||
</div>
|
||
<Switch
|
||
checked={status?.browser_status_enabled ?? false}
|
||
disabled={!status || busy}
|
||
onCheckedChange={(enabled) => void save({ browser_status_enabled: enabled }, enabled ? "浏览器状态查询已允许" : "浏览器状态查询已关闭")}
|
||
aria-label="允许浏览器状态查询"
|
||
/>
|
||
</div>
|
||
</div>
|
||
|
||
<div className="space-y-3 rounded-xl border p-4" data-testid="audit-retention-control">
|
||
<div className="flex items-start justify-between gap-4">
|
||
<div>
|
||
<h3 className="flex items-center gap-2 font-medium"><Clock3Icon className="size-4 text-primary" />开启历史数据定时清理</h3>
|
||
<p className="mt-1 text-sm text-muted-foreground">分批清理超过 {retention?.retention_days ?? 90} 天的工具调用、模型调用、已结束任务摘要和排行榜快照。</p>
|
||
</div>
|
||
<Switch
|
||
checked={retention ? !retention.paused : false}
|
||
disabled={!retention || busy}
|
||
onCheckedChange={(enabled) => void toggleRetention(enabled)}
|
||
aria-label="开启历史数据定时清理"
|
||
/>
|
||
</div>
|
||
<p className="text-xs text-muted-foreground">包含 tool_call_metrics、llm_call_metrics;关闭后在当前小批次结束时停止,关闭状态在服务重启后保留。</p>
|
||
{retentionError && <p role="alert" className="text-sm text-destructive">{retentionError}</p>}
|
||
{retention && <div className="flex flex-wrap items-center gap-x-4 gap-y-2 rounded-lg bg-muted/40 px-3 py-2 text-xs">
|
||
<Badge variant={retention.display_status === "error" ? "destructive" : "secondary"}>{retentionLabel(retention.display_status)}</Badge>
|
||
<span className="text-muted-foreground">间隔 {Math.round((retention.interval_seconds ?? 900) / 60)} 分钟</span>
|
||
<span className="text-muted-foreground">下次执行:{retention.paused ? "已关闭" : dateTime(retention.next_run_at)}</span>
|
||
<span className="text-muted-foreground">最近完成:{dateTime(retention.last_sweep?.finished_at)}</span>
|
||
</div>}
|
||
{retention?.pause_requested && <p role="status" className="text-sm text-amber-700 dark:text-amber-400">关闭请求已保存,正在等待当前批次结束。可点击“刷新状态”查看结果。</p>}
|
||
{retention?.last_error && <p role="alert" className="text-sm text-destructive">{retention.last_error}</p>}
|
||
</div>
|
||
|
||
<div className="space-y-3" data-testid="cache-collection-list">
|
||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||
<div>
|
||
<h3 className="font-medium">已接入 Redis 的接口</h3>
|
||
<p className="mt-1 text-xs text-muted-foreground">共 {collections.length} 组,单项开启 {enabledCount} 组;同组接口共用开关。</p>
|
||
</div>
|
||
<div className="relative w-full sm:w-56">
|
||
<SearchIcon className="pointer-events-none absolute top-2.5 left-3 size-4 text-muted-foreground" />
|
||
<Input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="搜索名称或接口地址" aria-label="搜索缓存接口" className="pl-9" />
|
||
</div>
|
||
</div>
|
||
<p className="text-xs text-muted-foreground">每组可独立开关,数据修改后缓存失效。总开关关闭时仍可配置单项,重新开启总开关后生效;各接口实际有效期见列表。</p>
|
||
{status && !status.enabled && <p className="rounded-lg bg-muted px-3 py-2 text-sm">总开关已关闭,当前所有接口均使用原查询。</p>}
|
||
<div className="overflow-x-auto rounded-xl border">
|
||
<table className="w-full table-fixed text-left text-sm">
|
||
<thead className="bg-muted/40 text-xs text-muted-foreground">
|
||
<tr>
|
||
<th className="w-[56%] px-4 py-3 font-medium" scope="col">接口 / 缓存范围</th>
|
||
<th className="w-[18%] px-2 py-3 font-medium" scope="col">有效期</th>
|
||
<th className="w-[26%] px-4 py-3 text-right font-medium" scope="col">使用 Redis</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody className="divide-y">
|
||
{visibleCollections.map((item) => {
|
||
const effective = item.enabled && status?.enabled && status.redis_configured;
|
||
const description = !item.enabled ? "单项已关闭" : !status?.enabled ? "总开关关闭" : !status.redis_configured ? "待配置连接" : "缓存已启用";
|
||
return <tr key={item.id} data-testid={`cache-collection-${item.id}`}>
|
||
<td className="px-4 py-3 align-top">
|
||
<p className="font-medium">{item.label}</p>
|
||
<div className="mt-1 space-y-1 text-[11px] text-muted-foreground">
|
||
{item.paths.map((path) => <p key={path} className="break-all font-mono">{path}</p>)}
|
||
</div>
|
||
<p className="mt-1 text-xs text-muted-foreground">{item.scope}</p>
|
||
</td>
|
||
<td className="px-2 py-3 align-top text-xs">{item.ttl_seconds} 秒</td>
|
||
<td className="px-4 py-3 text-right align-top">
|
||
<Switch
|
||
checked={item.enabled}
|
||
disabled={busy}
|
||
onCheckedChange={(enabled) => void save({ collection_overrides: { [item.id]: enabled } }, `${item.label}缓存${enabled ? "已开启" : "已关闭"}`)}
|
||
aria-label={`${item.label}使用 Redis 缓存`}
|
||
/>
|
||
<p className={`mt-1 text-[11px] ${effective ? "text-primary" : "text-muted-foreground"}`}>{description}</p>
|
||
</td>
|
||
</tr>;
|
||
})}
|
||
{!visibleCollections.length && <tr><td colSpan={3} className="px-4 py-8 text-center text-muted-foreground">{!status ? error ? "接口列表读取失败,请刷新重试" : "正在读取接口列表…" : searchText ? "没有匹配的接口" : "暂无已接入的接口"}</td></tr>}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
);
|
||
}
|