import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { AlertTriangle, RefreshCw, RotateCcw, Save, Sparkles } from "lucide-react"; import { useMemo, useState } from "react"; import { Badge } from "../../components/ui/Badge"; import { Button } from "../../components/ui/Button"; import { Card } from "../../components/ui/Card"; import { Input } from "../../components/ui/Input"; import { Switch } from "../../components/ui/Switch"; import { Textarea } from "../../components/ui/Textarea"; import { ToastContainer } from "../../components/ui/Toast"; import { useToast } from "../../hooks/useToast"; import i18next, { useI18n } from "../../i18n"; import { formatApiErrorMessage } from "../../lib/error-message"; import { getEnvConfig, patchSystemConfig, getSystemConfig, getDefaultSystemConfig } from "./api"; import type { RuntimeConfig, RuntimeConfigPatch } from "./types"; type RuntimeConfigForm = { request_log_enabled: boolean; reverse_proxy_log_detail_enabled: boolean; reverse_proxy_log_req_headers_max_bytes: string; reverse_proxy_log_req_body_max_bytes: string; reverse_proxy_log_resp_headers_max_bytes: string; reverse_proxy_log_resp_body_max_bytes: string; max_consecutive_failures: string; max_latency_test_interval: string; max_authority_latency_test_interval: string; max_egress_test_interval: string; latency_test_url: string; latency_authorities_raw: string; p2c_latency_window: string; latency_decay_window: string; cache_flush_interval: string; cache_flush_dirty_threshold: string; }; const EDITABLE_FIELDS: Array = [ "request_log_enabled", "reverse_proxy_log_detail_enabled", "reverse_proxy_log_req_headers_max_bytes", "reverse_proxy_log_req_body_max_bytes", "reverse_proxy_log_resp_headers_max_bytes", "reverse_proxy_log_resp_body_max_bytes", "max_consecutive_failures", "max_latency_test_interval", "max_authority_latency_test_interval", "max_egress_test_interval", "latency_test_url", "latency_authorities", "p2c_latency_window", "latency_decay_window", "cache_flush_interval", "cache_flush_dirty_threshold", ]; const FIELD_LABELS: Record = { request_log_enabled: "启用请求日志", reverse_proxy_log_detail_enabled: "记录详细反代日志", reverse_proxy_log_req_headers_max_bytes: "请求头最大字节数", reverse_proxy_log_req_body_max_bytes: "请求体最大字节数", reverse_proxy_log_resp_headers_max_bytes: "响应头最大字节数", reverse_proxy_log_resp_body_max_bytes: "响应体最大字节数", max_consecutive_failures: "最大连续失败次数", max_latency_test_interval: "节点延迟最大测试间隔", max_authority_latency_test_interval: "权威域名最大测试间隔", max_egress_test_interval: "出口 IP 更新检查间隔", latency_test_url: "延迟测试目标 URL", latency_authorities: "延迟测试权威域名列表", p2c_latency_window: "P2C 延迟衰减窗口", latency_decay_window: "历史延迟衰减窗口", cache_flush_interval: "缓存异步刷盘间隔", cache_flush_dirty_threshold: "缓存刷盘脏阈值", }; const ALLOCATION_POLICY_LABELS: Record = { BALANCED: "均衡", PREFER_LOW_LATENCY: "优先低延迟", PREFER_IDLE_IP: "优先空闲出口 IP", }; const MISS_ACTION_LABELS: Record = { TREAT_AS_EMPTY: "按空账号处理", REJECT: "拒绝代理请求", }; const EMPTY_ACCOUNT_BEHAVIOR_LABELS: Record = { RANDOM: "随机路由", FIXED_HEADER: "提取指定请求头作为 Account", ACCOUNT_HEADER_RULE: "按照全局请求头规则提取 Account", }; function configToForm(config: RuntimeConfig): RuntimeConfigForm { return { request_log_enabled: config.request_log_enabled, reverse_proxy_log_detail_enabled: config.reverse_proxy_log_detail_enabled, reverse_proxy_log_req_headers_max_bytes: String(config.reverse_proxy_log_req_headers_max_bytes), reverse_proxy_log_req_body_max_bytes: String(config.reverse_proxy_log_req_body_max_bytes), reverse_proxy_log_resp_headers_max_bytes: String(config.reverse_proxy_log_resp_headers_max_bytes), reverse_proxy_log_resp_body_max_bytes: String(config.reverse_proxy_log_resp_body_max_bytes), max_consecutive_failures: String(config.max_consecutive_failures), max_latency_test_interval: config.max_latency_test_interval, max_authority_latency_test_interval: config.max_authority_latency_test_interval, max_egress_test_interval: config.max_egress_test_interval, latency_test_url: config.latency_test_url, latency_authorities_raw: config.latency_authorities.join("\n"), p2c_latency_window: config.p2c_latency_window, latency_decay_window: config.latency_decay_window, cache_flush_interval: config.cache_flush_interval, cache_flush_dirty_threshold: String(config.cache_flush_dirty_threshold), }; } function requiredFieldLabel(field: string): string { return i18next.t(field); } function parseNonNegativeInt(field: string, raw: string): number { const value = raw.trim(); if (!value) { throw new Error(i18next.t("{{field}} 不能为空", { field: requiredFieldLabel(field) })); } const parsed = Number(value); if (!Number.isInteger(parsed) || parsed < 0) { throw new Error(i18next.t("{{field}} 必须是非负整数", { field: requiredFieldLabel(field) })); } return parsed; } function parseDurationField(field: string, raw: string): string { const value = raw.trim(); if (!value) { throw new Error(i18next.t("{{field}} 不能为空", { field: requiredFieldLabel(field) })); } return value; } function parseAuthorities(raw: string): string[] { const items = raw .split(/[\n,]/) .map((item) => item.trim()) .filter(Boolean); return Array.from(new Set(items)); } function parseForm(form: RuntimeConfigForm): RuntimeConfig { const latencyURL = form.latency_test_url.trim(); if (!latencyURL) { throw new Error("延迟测试目标 URL 不能为空"); } if (!latencyURL.startsWith("http://") && !latencyURL.startsWith("https://")) { throw new Error("延迟测试目标 URL 必须是 http/https 地址"); } return { request_log_enabled: form.request_log_enabled, reverse_proxy_log_detail_enabled: form.reverse_proxy_log_detail_enabled, reverse_proxy_log_req_headers_max_bytes: parseNonNegativeInt( "请求头最大字节数", form.reverse_proxy_log_req_headers_max_bytes, ), reverse_proxy_log_req_body_max_bytes: parseNonNegativeInt("请求体最大字节数", form.reverse_proxy_log_req_body_max_bytes), reverse_proxy_log_resp_headers_max_bytes: parseNonNegativeInt( "响应头最大字节数", form.reverse_proxy_log_resp_headers_max_bytes, ), reverse_proxy_log_resp_body_max_bytes: parseNonNegativeInt( "响应体最大字节数", form.reverse_proxy_log_resp_body_max_bytes, ), max_consecutive_failures: parseNonNegativeInt("最大连续失败次数", form.max_consecutive_failures), max_latency_test_interval: parseDurationField("节点延迟最大测试间隔", form.max_latency_test_interval), max_authority_latency_test_interval: parseDurationField( "权威域名最大测试间隔", form.max_authority_latency_test_interval, ), max_egress_test_interval: parseDurationField("出口 IP 更新检查间隔", form.max_egress_test_interval), latency_test_url: latencyURL, latency_authorities: parseAuthorities(form.latency_authorities_raw), p2c_latency_window: parseDurationField("P2C 延迟衰减窗口", form.p2c_latency_window), latency_decay_window: parseDurationField("历史延迟衰减窗口", form.latency_decay_window), cache_flush_interval: parseDurationField("缓存异步刷盘间隔", form.cache_flush_interval), cache_flush_dirty_threshold: parseNonNegativeInt("缓存刷盘脏阈值", form.cache_flush_dirty_threshold), }; } function displayAllocationPolicy(value: string): string { return ALLOCATION_POLICY_LABELS[value] ?? value; } function displayMissAction(value: string): string { return MISS_ACTION_LABELS[value] ?? value; } function displayEmptyAccountBehavior(value: string): string { return EMPTY_ACCOUNT_BEHAVIOR_LABELS[value] ?? value; } function arrayEquals(a: string[], b: string[]): boolean { if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; i += 1) { if (a[i] !== b[i]) { return false; } } return true; } function buildPatch(current: RuntimeConfig, next: RuntimeConfig): RuntimeConfigPatch { const patch: RuntimeConfigPatch = {}; const patchMutable = patch as Record; for (const field of EDITABLE_FIELDS) { const currentValue = current[field]; const nextValue = next[field]; if (Array.isArray(currentValue) && Array.isArray(nextValue)) { if (!arrayEquals(currentValue, nextValue)) { patchMutable[field] = nextValue; } continue; } if (currentValue !== nextValue) { patchMutable[field] = nextValue; } } return patch; } export function SystemConfigPage() { const { t } = useI18n(); const [draftForm, setDraftForm] = useState(null); const [customPatchText, setCustomPatchText] = useState(null); const { toasts, showToast, dismissToast } = useToast(); const queryClient = useQueryClient(); const configQuery = useQuery({ queryKey: ["system-config"], queryFn: getSystemConfig, staleTime: 30_000, }); const defaultConfigQuery = useQuery({ queryKey: ["system-config-default"], queryFn: getDefaultSystemConfig, staleTime: 30_000, }); const envConfigQuery = useQuery({ queryKey: ["system-config-env"], queryFn: getEnvConfig, staleTime: Infinity, // Env config does not change at runtime }); const baseline = configQuery.data ?? null; const defaultBaseline = defaultConfigQuery.data ?? null; const envBaseline = envConfigQuery.data ?? null; const form = useMemo(() => { if (!baseline) { return null; } return draftForm ?? configToForm(baseline); }, [baseline, draftForm]); const parsedResult = useMemo(() => { if (!form) { return { config: null as RuntimeConfig | null, error: "" }; } try { return { config: parseForm(form), error: "" }; } catch (error) { return { config: null, error: formatApiErrorMessage(error, t) }; } }, [form, t]); const patchPreview = useMemo(() => { if (!baseline || !parsedResult.config) { return {}; } return buildPatch(baseline, parsedResult.config); }, [baseline, parsedResult.config]); const changedKeys = useMemo(() => Object.keys(patchPreview) as Array, [patchPreview]); const hasUnsavedChanges = changedKeys.length > 0; const saveMutation = useMutation({ mutationFn: async () => { if (!baseline || !form) { throw new Error("配置尚未加载完成"); } let patchToSend: RuntimeConfigPatch; if (customPatchText !== null) { try { patchToSend = JSON.parse(customPatchText); } catch { throw new Error("手动编辑的 JSON 格式有误,请检查"); } } else { const parsed = parseForm(form); patchToSend = buildPatch(baseline, parsed); } const changedCount = Object.keys(patchToSend).length; if (!changedCount) { throw new Error("没有可提交的变更"); } const updated = await patchSystemConfig(patchToSend); return { updated, changedCount }; }, onSuccess: ({ updated, changedCount }) => { queryClient.setQueryData(["system-config"], updated); setDraftForm(null); setCustomPatchText(null); showToast("success", t("配置已更新({{count}} 项变更)", { count: changedCount })); }, onError: (error) => { showToast("error", formatApiErrorMessage(error, t)); }, }); const setFormField = (key: K, value: RuntimeConfigForm[K]) => { setDraftForm((prev) => { if (!baseline) { return prev; } const source = prev ?? configToForm(baseline); return { ...source, [key]: value }; }); }; const handleRestoreDefault = (key: keyof RuntimeConfigForm) => { if (!defaultBaseline || !baseline) { showToast("error", "默认配置尚未加载"); return; } const defaultForm = configToForm(defaultBaseline); const value = defaultForm[key]; setDraftForm((prev) => { const source = prev ?? configToForm(baseline); return { ...source, [key]: value }; }); }; const renderRestoreButton = (fieldKey: keyof RuntimeConfigForm) => { const displayVal = defaultBaseline ? (() => { const val = configToForm(defaultBaseline)[fieldKey]; if (typeof val === "boolean") return val ? t("开启") : t("关闭"); if (val === "") return t("空"); return String(val); })() : ""; return ( ); }; const resetDraft = () => { setDraftForm(null); setCustomPatchText(null); }; const reloadFromServer = async () => { if (hasUnsavedChanges) { const confirmed = window.confirm(t("当前有未保存变更,确认丢弃并重新加载运行时配置?")); if (!confirmed) { return; } } setDraftForm(null); setCustomPatchText(null); const result = await configQuery.refetch(); if (result.data) { showToast("success", t("已加载最新运行时配置")); } }; const handlePatchEdit = (e: React.ChangeEvent) => { setCustomPatchText(e.target.value); }; const defaultPatchText = useMemo(() => { return JSON.stringify(patchPreview, null, 2); }, [patchPreview]); const displayedPatchText = customPatchText ?? defaultPatchText; const isSaveDisabled = saveMutation.isPending || (customPatchText === null && (Boolean(parsedResult.error) || !hasUnsavedChanges)); return (

{t("系统配置")}

{t("按需调整系统参数,保存后立即生效。")}

{!form ? ( {(configQuery.isLoading || envConfigQuery.isLoading) ?

{t("正在加载配置...")}

: null} {configQuery.isError ? (
{formatApiErrorMessage(configQuery.error, t)}
) : null} {envConfigQuery.isError ? (
{t("静态配置加载失败")}: {formatApiErrorMessage(envConfigQuery.error, t)}
) : null}
) : (

{t("运行时配置")}

{t("按分类查看和修改设置,可随时撤销未保存更改。")}

{t("基础与健康检查")}

{renderRestoreButton("max_consecutive_failures")}
setFormField("max_consecutive_failures", event.target.value)} />

{t("请求日志")}

{t("启用请求日志")} {renderRestoreButton("request_log_enabled")}
setFormField("request_log_enabled", event.target.checked)} />
{t("记录详细反代日志")} {renderRestoreButton("reverse_proxy_log_detail_enabled")}
setFormField("reverse_proxy_log_detail_enabled", event.target.checked)} />
{renderRestoreButton("reverse_proxy_log_req_headers_max_bytes")}
setFormField("reverse_proxy_log_req_headers_max_bytes", event.target.value)} />
{renderRestoreButton("reverse_proxy_log_req_body_max_bytes")}
setFormField("reverse_proxy_log_req_body_max_bytes", event.target.value)} />
{renderRestoreButton("reverse_proxy_log_resp_headers_max_bytes")}
setFormField("reverse_proxy_log_resp_headers_max_bytes", event.target.value)} />
{renderRestoreButton("reverse_proxy_log_resp_body_max_bytes")}
setFormField("reverse_proxy_log_resp_body_max_bytes", event.target.value)} />

{t("探测与路由")}

{renderRestoreButton("latency_test_url")}
setFormField("latency_test_url", event.target.value)} />
{renderRestoreButton("max_latency_test_interval")}
setFormField("max_latency_test_interval", event.target.value)} />
{renderRestoreButton("max_authority_latency_test_interval")}
setFormField("max_authority_latency_test_interval", event.target.value)} />
{renderRestoreButton("max_egress_test_interval")}
setFormField("max_egress_test_interval", event.target.value)} />
{renderRestoreButton("p2c_latency_window")}
setFormField("p2c_latency_window", event.target.value)} />
{renderRestoreButton("latency_decay_window")}
setFormField("latency_decay_window", event.target.value)} />
{renderRestoreButton("latency_authorities_raw")}