refactor(repo): consolidate openflare-server to root and move subprojects to internal/apps

- Merge all files inside openflare-server to the repository root directory.
- Relocate agent, relay, and flared subprojects from internal/ to internal/apps/.
- Combine docker-compose files and update build context paths to root.
- Update GitHub workflows and Dockerfiles to refer to new directories and package names.
- Rewrite Go package imports across all files.
- Resolve database renew test race condition and clean up docs.
This commit is contained in:
ryan
2026-06-19 14:23:29 +08:00
parent 19d476ed7f
commit 63cd906cfc
1064 changed files with 366 additions and 1397 deletions
@@ -0,0 +1,183 @@
import type {OptionItem} from "@/lib/services/openflare"
export type OpenFlareOpsFields = {
AgentHeartbeatInterval: string
AgentWebsocketUpgradeEnabled: boolean
NodeOfflineThreshold: string
AgentUpdateRepo: string
GeoIPProvider: string
ServerAddress: string
UptimeKumaEnabled: boolean
UptimeKumaUrl: string
UptimeKumaUsername: string
UptimeKumaPassword: string
UptimeKumaMonitorScope: string
UptimeKumaSelectedSites: string
UptimeKumaSyncInterval: string
UptimeKumaInterval: string
UptimeKumaRetry: string
UptimeKumaRetryInterval: string
UptimeKumaTimeout: string
DatabaseAutoCleanupEnabled: boolean
DatabaseAutoCleanupRetentionDays: string
}
export const defaultOpenFlareOpsFields: OpenFlareOpsFields = {
AgentHeartbeatInterval: "10000",
AgentWebsocketUpgradeEnabled: true,
NodeOfflineThreshold: "120000",
AgentUpdateRepo: "Rain-kl/OpenFlare",
GeoIPProvider: "ipinfo",
ServerAddress: "",
UptimeKumaEnabled: false,
UptimeKumaUrl: "",
UptimeKumaUsername: "",
UptimeKumaPassword: "",
UptimeKumaMonitorScope: "all",
UptimeKumaSelectedSites: "",
UptimeKumaSyncInterval: "5",
UptimeKumaInterval: "60",
UptimeKumaRetry: "0",
UptimeKumaRetryInterval: "60",
UptimeKumaTimeout: "48",
DatabaseAutoCleanupEnabled: false,
DatabaseAutoCleanupRetentionDays: "30",
}
export const INSTALLER_SCRIPT_URL =
"https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh"
export function optionsToMap(options: OptionItem[]) {
return options.reduce<Record<string, string>>((accumulator, option) => {
accumulator[option.key] = option.value
return accumulator
}, {})
}
function toBoolean(value: string | undefined, fallback: boolean) {
if (value === undefined) return fallback
return value === "true"
}
export function mapOptionsToOpsFields(
optionMap: Record<string, string>,
serverAddress = "",
): OpenFlareOpsFields {
return {
AgentHeartbeatInterval: optionMap.AgentHeartbeatInterval ?? "10000",
AgentWebsocketUpgradeEnabled: toBoolean(optionMap.AgentWebsocketUpgradeEnabled, true),
NodeOfflineThreshold: optionMap.NodeOfflineThreshold ?? "120000",
AgentUpdateRepo: optionMap.AgentUpdateRepo ?? "Rain-kl/OpenFlare",
GeoIPProvider: optionMap.GeoIPProvider ?? "ipinfo",
ServerAddress: optionMap.ServerAddress || serverAddress,
UptimeKumaEnabled: toBoolean(optionMap.UptimeKumaEnabled, false),
UptimeKumaUrl: optionMap.UptimeKumaUrl ?? "",
UptimeKumaUsername: optionMap.UptimeKumaUsername ?? "",
UptimeKumaPassword: "",
UptimeKumaMonitorScope: optionMap.UptimeKumaMonitorScope ?? "all",
UptimeKumaSelectedSites: optionMap.UptimeKumaSelectedSites ?? "",
UptimeKumaSyncInterval: optionMap.UptimeKumaSyncInterval ?? "5",
UptimeKumaInterval: optionMap.UptimeKumaInterval ?? "60",
UptimeKumaRetry: optionMap.UptimeKumaRetry ?? "0",
UptimeKumaRetryInterval: optionMap.UptimeKumaRetryInterval ?? "60",
UptimeKumaTimeout: optionMap.UptimeKumaTimeout ?? "48",
DatabaseAutoCleanupEnabled: toBoolean(optionMap.DatabaseAutoCleanupEnabled, false),
DatabaseAutoCleanupRetentionDays: optionMap.DatabaseAutoCleanupRetentionDays ?? "30",
}
}
export function formatDurationLabel(value: string) {
const milliseconds = Number.parseInt(value, 10)
if (Number.isNaN(milliseconds)) return value
if (milliseconds >= 60000) return `${milliseconds / 60000} 分钟`
return `${milliseconds / 1000} 秒`
}
export function normalizeServerUrl(value: string) {
return value.trim().replace(/\/+$/, "")
}
export function getBrowserOrigin() {
if (typeof window === "undefined") return ""
return normalizeServerUrl(window.location.origin)
}
export function buildDiscoveryCommand(serverUrl: string, discoveryToken: string) {
return [
`curl -fsSL ${INSTALLER_SCRIPT_URL} | bash -s -- \\`,
` --server-url ${normalizeServerUrl(serverUrl)} \\`,
` --discovery-token ${discoveryToken}`,
].join("\n")
}
export function validateAgentFields(fields: OpenFlareOpsFields) {
const heartbeat = Number.parseInt(fields.AgentHeartbeatInterval, 10)
const offline = Number.parseInt(fields.NodeOfflineThreshold, 10)
if (Number.isNaN(heartbeat) || heartbeat < 5000) {
throw new Error("心跳间隔不能小于 5000 毫秒。")
}
if (Number.isNaN(offline) || offline < 10000) {
throw new Error("离线阈值不能小于 10000 毫秒。")
}
}
export function validateUptimeKumaFields(fields: OpenFlareOpsFields) {
const syncInt = Number.parseInt(fields.UptimeKumaSyncInterval, 10)
const interval = Number.parseInt(fields.UptimeKumaInterval, 10)
const retry = Number.parseInt(fields.UptimeKumaRetry, 10)
const retryInt = Number.parseInt(fields.UptimeKumaRetryInterval, 10)
const timeout = Number.parseInt(fields.UptimeKumaTimeout, 10)
if (fields.UptimeKumaEnabled) {
if (!fields.UptimeKumaUrl.trim()) throw new Error("请输入 Uptime Kuma 地址。")
if (!fields.UptimeKumaUsername.trim()) throw new Error("请输入 Uptime Kuma 用户名。")
}
if (Number.isNaN(syncInt) || syncInt <= 0) throw new Error("同步间隔必须为正整数。")
if (Number.isNaN(interval) || interval <= 0) throw new Error("心跳间隔必须为正整数。")
if (Number.isNaN(retry) || retry < 0) throw new Error("重试次数必须为非负整数。")
if (Number.isNaN(retryInt) || retryInt <= 0) throw new Error("心跳重试间隔必须为正整数。")
if (Number.isNaN(timeout) || timeout <= 0) throw new Error("请求超时必须为正整数。")
}
export function validateDatabaseAutoCleanup(fields: OpenFlareOpsFields) {
const retentionDays = Number.parseInt(fields.DatabaseAutoCleanupRetentionDays, 10)
if (Number.isNaN(retentionDays) || retentionDays < 1) {
throw new Error("自动清理保留天数至少为 1 天。")
}
}
export function agentOptionEntries(fields: OpenFlareOpsFields): OptionItem[] {
validateAgentFields(fields)
return [
{ key: "AgentHeartbeatInterval", value: fields.AgentHeartbeatInterval },
{ key: "AgentWebsocketUpgradeEnabled", value: String(fields.AgentWebsocketUpgradeEnabled) },
{ key: "NodeOfflineThreshold", value: fields.NodeOfflineThreshold },
{ key: "AgentUpdateRepo", value: fields.AgentUpdateRepo.trim() },
{ key: "GeoIPProvider", value: fields.GeoIPProvider },
]
}
export function uptimeKumaOptionEntries(fields: OpenFlareOpsFields): OptionItem[] {
validateUptimeKumaFields(fields)
return [
{ key: "UptimeKumaEnabled", value: String(fields.UptimeKumaEnabled) },
{ key: "UptimeKumaUrl", value: fields.UptimeKumaUrl.trim() },
{ key: "UptimeKumaUsername", value: fields.UptimeKumaUsername.trim() },
{ key: "UptimeKumaPassword", value: fields.UptimeKumaPassword },
{ key: "UptimeKumaMonitorScope", value: fields.UptimeKumaMonitorScope },
{ key: "UptimeKumaSelectedSites", value: fields.UptimeKumaSelectedSites },
{ key: "UptimeKumaSyncInterval", value: fields.UptimeKumaSyncInterval },
{ key: "UptimeKumaInterval", value: fields.UptimeKumaInterval },
{ key: "UptimeKumaRetry", value: fields.UptimeKumaRetry },
{ key: "UptimeKumaRetryInterval", value: fields.UptimeKumaRetryInterval },
{ key: "UptimeKumaTimeout", value: fields.UptimeKumaTimeout },
]
}
export function databaseAutoCleanupEntries(fields: OpenFlareOpsFields): OptionItem[] {
validateDatabaseAutoCleanup(fields)
return [
{ key: "DatabaseAutoCleanupEnabled", value: String(fields.DatabaseAutoCleanupEnabled) },
{ key: "DatabaseAutoCleanupRetentionDays", value: fields.DatabaseAutoCleanupRetentionDays },
]
}
@@ -0,0 +1,772 @@
"use client"
import Link from "next/link"
import {useEffect, useMemo, useState} from "react"
import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query"
import {Copy, ExternalLink, Loader2, RefreshCw, RotateCw, Save, Server, Trash2,} from "lucide-react"
import {toast} from "sonner"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import {Badge} from "@/components/ui/badge"
import {Button} from "@/components/ui/button"
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from "@/components/ui/card"
import {Input} from "@/components/ui/input"
import {Label} from "@/components/ui/label"
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue,} from "@/components/ui/select"
import {Switch} from "@/components/ui/switch"
import {Textarea} from "@/components/ui/textarea"
import {ErrorInline} from "@/components/layout/error"
import {LoadingStateWithBorder} from "@/components/layout/loading"
import type {DatabaseCleanupTarget} from "@/lib/services/openflare"
import {AdminStatusService} from "@/lib/services/admin"
import {NodeService, OptionService, StatusService, UptimeKumaService,} from "@/lib/services/openflare"
import {VersionUpgradeDialog} from "@/app/(main)/components/version-upgrade-dialog"
import {adminUpdateStatusQueryKey, openflarePublicStatusQueryKey,} from "@/lib/hooks/use-openflare-server-upgrade"
import {
agentOptionEntries,
buildDiscoveryCommand,
databaseAutoCleanupEntries,
defaultOpenFlareOpsFields,
formatDurationLabel,
getBrowserOrigin,
mapOptionsToOpsFields,
type OpenFlareOpsFields,
optionsToMap,
uptimeKumaOptionEntries,
} from "./openflare-ops-utils"
import {UptimeKumaSiteSelectModal} from "./uptimekuma-site-modal"
const optionsQueryKey = ["openflare", "options"] as const
const cleanupTargets: Array<{
target: DatabaseCleanupTarget
label: string
description: string
}> = [
{
target: "node_access_logs",
label: "访问日志",
description: "清理 node_access_logs,影响访问明细与 IP 汇总。",
},
{
target: "node_metric_snapshots",
label: "性能快照",
description: "清理 node_metric_snapshots,影响节点资源趋势。",
},
{
target: "node_request_reports",
label: "请求聚合",
description: "清理 node_request_reports,影响请求量与错误量统计。",
},
]
async function copyText(value: string) {
await navigator.clipboard.writeText(value)
}
export function OpenFlareOpsSettings() {
const queryClient = useQueryClient()
const [fields, setFields] = useState<OpenFlareOpsFields>(defaultOpenFlareOpsFields)
const [savingSection, setSavingSection] = useState<string | null>(null)
const [geoIPTestIP, setGeoIPTestIP] = useState("8.8.8.8")
const [uptimeKumaModalOpen, setUptimeKumaModalOpen] = useState(false)
const [cleanupTarget, setCleanupTarget] = useState<{
target: DatabaseCleanupTarget
label: string
} | null>(null)
const [cleanupRetentionDays, setCleanupRetentionDays] = useState("")
const [versionDialogOpen, setVersionDialogOpen] = useState(false)
const optionsQuery = useQuery({
queryKey: optionsQueryKey,
queryFn: () => OptionService.list(),
})
const statusQuery = useQuery({
queryKey: openflarePublicStatusQueryKey,
queryFn: () => StatusService.getPublicStatus(),
})
const bootstrapQuery = useQuery({
queryKey: ["openflare", "bootstrap-token"],
queryFn: () => NodeService.getBootstrapToken(),
})
const releaseQuery = useQuery({
queryKey: adminUpdateStatusQueryKey,
queryFn: () => AdminStatusService.getUpdateStatus(),
})
useEffect(() => {
if (!optionsQuery.data) return
const optionMap = optionsToMap(optionsQuery.data)
const serverAddress =
optionMap.ServerAddress ||
statusQuery.data?.server_address ||
getBrowserOrigin()
setFields(mapOptionsToOpsFields(optionMap, serverAddress))
}, [optionsQuery.data, statusQuery.data?.server_address])
const geoIPMutation = useMutation({
mutationFn: () => OptionService.lookupGeoIP(fields.GeoIPProvider, geoIPTestIP.trim()),
})
const saveMutation = useMutation({
mutationFn: async ({
section,
entries,
}: {
section: string
entries: Array<{ key: string; value: string }>
}) => {
setSavingSection(section)
await OptionService.updateBatch(entries)
},
onSuccess: async () => {
toast.success("OpenFlare 运维设置已保存")
await queryClient.invalidateQueries({ queryKey: optionsQueryKey })
setSavingSection(null)
},
onError: (error) => {
setSavingSection(null)
toast.error(error instanceof Error ? error.message : "保存失败")
},
})
const rotateTokenMutation = useMutation({
mutationFn: () => NodeService.rotateBootstrapToken(),
onSuccess: async (data) => {
toast.success("Discovery Token 已重新生成")
await queryClient.invalidateQueries({ queryKey: ["openflare", "bootstrap-token"] })
if (data.discovery_token) {
try {
await copyText(data.discovery_token)
} catch {
// ignore clipboard errors
}
}
},
onError: (error) => {
toast.error(error instanceof Error ? error.message : "Token 轮换失败")
},
})
const syncUptimeKumaMutation = useMutation({
mutationFn: () => UptimeKumaService.sync(),
onSuccess: () => toast.success("Uptime Kuma 同步任务已执行"),
onError: (error) => toast.error(error instanceof Error ? error.message : "同步失败"),
})
const cleanupMutation = useMutation({
mutationFn: (payload: { target: DatabaseCleanupTarget; retention_days?: number }) =>
OptionService.cleanupDatabase(payload),
onSuccess: (result) => {
setCleanupTarget(null)
setCleanupRetentionDays("")
toast.success(
result.delete_all
? `已清空${result.target_label},共删除 ${result.deleted_count} 条。`
: `已清理${result.target_label},共删除 ${result.deleted_count} 条。`,
)
},
onError: (error) => {
toast.error(error instanceof Error ? error.message : "清理失败")
},
})
const discoveryToken = bootstrapQuery.data?.discovery_token ?? ""
const discoveryCommand = useMemo(() => {
if (!fields.ServerAddress || !discoveryToken) return ""
return buildDiscoveryCommand(fields.ServerAddress, discoveryToken)
}, [discoveryToken, fields.ServerAddress])
const updateField = <K extends keyof OpenFlareOpsFields>(
key: K,
value: OpenFlareOpsFields[K],
) => {
setFields((previous) => ({ ...previous, [key]: value }))
}
const saveAgentSettings = () => {
try {
saveMutation.mutate({
section: "agent",
entries: agentOptionEntries(fields),
})
} catch (error) {
toast.error(error instanceof Error ? error.message : "参数校验失败")
}
}
const saveUptimeKumaSettings = () => {
try {
saveMutation.mutate({
section: "uptimekuma",
entries: uptimeKumaOptionEntries(fields),
})
} catch (error) {
toast.error(error instanceof Error ? error.message : "参数校验失败")
}
}
const saveDatabaseAutoCleanup = () => {
try {
saveMutation.mutate({
section: "database-auto",
entries: databaseAutoCleanupEntries(fields),
})
} catch (error) {
toast.error(error instanceof Error ? error.message : "参数校验失败")
}
}
if (optionsQuery.isLoading) {
return <LoadingStateWithBorder icon={Server} description="加载 OpenFlare 运维设置..." />
}
if (optionsQuery.isError) {
return (
<ErrorInline
message={
optionsQuery.error instanceof Error ? optionsQuery.error.message : "加载失败"
}
onRetry={() => void optionsQuery.refetch()}
/>
)
}
return (
<div className="space-y-6">
<div className="grid gap-6 xl:grid-cols-2">
<Card className="border-dashed shadow-none">
<CardHeader className="flex flex-row items-center justify-between gap-4">
<div>
<CardTitle className="text-base">Agent 运行参数</CardTitle>
<CardDescription>心跳间隔与离线阈值会在下个心跳周期同步到节点。</CardDescription>
</div>
<Button size="sm" disabled={savingSection === "agent"} onClick={saveAgentSettings}>
{savingSection === "agent" ? (
<Loader2 className="size-4 animate-spin mr-1" />
) : (
<Save className="size-3.5 mr-1" />
)}
保存
</Button>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-4 md:grid-cols-2">
<FieldInput
label={`心跳间隔 (${formatDurationLabel(fields.AgentHeartbeatInterval)})`}
value={fields.AgentHeartbeatInterval}
type="number"
onChange={(value) => updateField("AgentHeartbeatInterval", value)}
/>
<FieldInput
label={`离线阈值 (${formatDurationLabel(fields.NodeOfflineThreshold)})`}
value={fields.NodeOfflineThreshold}
type="number"
onChange={(value) => updateField("NodeOfflineThreshold", value)}
/>
</div>
<ToggleRow
label="开启 WS 连接升级"
description="HTTP 心跳成功后尝试升级为 WebSocket,配置发布可即时通知。"
checked={fields.AgentWebsocketUpgradeEnabled}
onChange={(value) => updateField("AgentWebsocketUpgradeEnabled", value)}
/>
<FieldInput
label="Agent 更新仓库"
value={fields.AgentUpdateRepo}
placeholder="Rain-kl/OpenFlare"
onChange={(value) => updateField("AgentUpdateRepo", value)}
/>
</CardContent>
</Card>
<Card className="border-dashed shadow-none">
<CardHeader className="flex flex-row items-center justify-between gap-4">
<div>
<CardTitle className="text-base">IP 归属解析</CardTitle>
<CardDescription>
控制节点地图等场景的 GeoIP 来源;访客访问记录归属地固定使用 MaxMind mmdb。
</CardDescription>
</div>
<Button size="sm" disabled={savingSection === "agent"} onClick={saveAgentSettings}>
{savingSection === "agent" ? (
<Loader2 className="size-4 animate-spin mr-1" />
) : (
<Save className="size-3.5 mr-1" />
)}
保存
</Button>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-1.5">
<Label>归属方式</Label>
<Select
value={fields.GeoIPProvider}
onValueChange={(value) => updateField("GeoIPProvider", value)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="disabled">关闭</SelectItem>
<SelectItem value="mmdb">MaxMind mmdb</SelectItem>
<SelectItem value="ip-api">ip-api.com</SelectItem>
<SelectItem value="geojs">geojs.io</SelectItem>
<SelectItem value="ipinfo">ipinfo.io</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-3 rounded-lg border border-dashed p-3 sm:flex-row sm:items-end">
<FieldInput
label="测试 IP"
value={geoIPTestIP}
onChange={setGeoIPTestIP}
placeholder="8.8.8.8"
/>
<Button
type="button"
variant="outline"
disabled={geoIPMutation.isPending}
onClick={() => geoIPMutation.mutate()}
>
{geoIPMutation.isPending ? "查询中..." : "查询归属"}
</Button>
</div>
{geoIPMutation.data ? (
<div className="grid gap-2 text-sm sm:grid-cols-2">
<InfoCell label="国家/地区" value={geoIPMutation.data.name || "—"} />
<InfoCell label="ISO Code" value={geoIPMutation.data.iso_code || "—"} />
</div>
) : null}
</CardContent>
</Card>
</div>
<Card className="border-dashed shadow-none">
<CardHeader className="flex flex-row items-center justify-between gap-4">
<div>
<CardTitle className="text-base">Discovery Token 与部署</CardTitle>
<CardDescription>
新节点首次接入使用 Discovery Token;轮换请前往节点管理或使用下方操作。
</CardDescription>
</div>
<div className="flex flex-wrap gap-2">
<Button variant="outline" size="sm" asChild>
<Link href="/nodes">
<ExternalLink className="size-3.5 mr-1" />
节点管理
</Link>
</Button>
<Button
variant="outline"
size="sm"
disabled={rotateTokenMutation.isPending}
onClick={() => rotateTokenMutation.mutate()}
>
<RotateCw className="size-3.5 mr-1" />
轮换 Token
</Button>
</div>
</CardHeader>
<CardContent className="space-y-4">
<FieldInput
label="Server URL"
value={fields.ServerAddress}
onChange={(value) => updateField("ServerAddress", value)}
placeholder="https://yourdomain.com"
/>
<div className="rounded-lg border border-dashed p-3">
<p className="text-[10px] uppercase tracking-wider text-muted-foreground">
Discovery Token(只读)
</p>
<p className="mt-2 break-all text-sm font-mono">
{bootstrapQuery.isLoading ? "加载中..." : discoveryToken || "未生成"}
</p>
</div>
<div className="space-y-1.5">
<Label>一键部署命令</Label>
<Textarea
readOnly
value={discoveryCommand || "请先填写可访问的 Server URL 并获取 Token。"}
className="min-h-24 font-mono text-xs"
/>
{discoveryCommand ? (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => void copyText(discoveryCommand).then(() => toast.success("命令已复制"))}
>
<Copy className="size-3.5 mr-1" />
复制命令
</Button>
) : null}
</div>
</CardContent>
</Card>
<Card className="border-dashed shadow-none">
<CardHeader className="flex flex-row items-center justify-between gap-4">
<div>
<CardTitle className="text-base">Uptime Kuma 集成</CardTitle>
<CardDescription>将反代站点差分同步至 Uptime Kuma 监控实例。</CardDescription>
</div>
<div className="flex flex-wrap gap-2">
<Button
variant="outline"
size="sm"
disabled={!fields.UptimeKumaEnabled || syncUptimeKumaMutation.isPending}
onClick={() => syncUptimeKumaMutation.mutate()}
>
<RefreshCw className="size-3.5 mr-1" />
立即同步
</Button>
<Button
size="sm"
disabled={savingSection === "uptimekuma"}
onClick={saveUptimeKumaSettings}
>
保存
</Button>
</div>
</CardHeader>
<CardContent className="space-y-4">
<ToggleRow
label="开启 Uptime Kuma"
checked={fields.UptimeKumaEnabled}
onChange={(value) => updateField("UptimeKumaEnabled", value)}
/>
{fields.UptimeKumaEnabled ? (
<>
<div className="grid gap-4 md:grid-cols-2">
<FieldInput
label="Uptime Kuma 地址"
value={fields.UptimeKumaUrl}
onChange={(value) => updateField("UptimeKumaUrl", value)}
placeholder="http://localhost:3001"
/>
<FieldInput
label="用户名"
value={fields.UptimeKumaUsername}
onChange={(value) => updateField("UptimeKumaUsername", value)}
/>
<FieldInput
label="密码"
value={fields.UptimeKumaPassword}
type="password"
onChange={(value) => updateField("UptimeKumaPassword", value)}
placeholder="留空表示不更新"
/>
<FieldInput
label="同步间隔 (分钟)"
value={fields.UptimeKumaSyncInterval}
type="number"
onChange={(value) => updateField("UptimeKumaSyncInterval", value)}
/>
<div className="space-y-1.5">
<Label>监控范围</Label>
<Select
value={fields.UptimeKumaMonitorScope}
onValueChange={(value) => updateField("UptimeKumaMonitorScope", value)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">全部站点</SelectItem>
<SelectItem value="selected">选择站点</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{fields.UptimeKumaMonitorScope === "selected" ? (
<div className="rounded-lg border border-dashed p-3">
<div className="flex items-center justify-between gap-2">
<p className="text-sm font-medium">已选站点</p>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setUptimeKumaModalOpen(true)}
>
选择监控站点
</Button>
</div>
<p className="mt-2 break-all text-xs text-muted-foreground">
{fields.UptimeKumaSelectedSites
? fields.UptimeKumaSelectedSites.split(",").join(", ")
: "未选择任何站点"}
</p>
</div>
) : null}
<div className="grid gap-4 md:grid-cols-2">
<FieldInput
label="检测频率 (秒)"
value={fields.UptimeKumaInterval}
type="number"
onChange={(value) => updateField("UptimeKumaInterval", value)}
/>
<FieldInput
label="重试次数"
value={fields.UptimeKumaRetry}
type="number"
onChange={(value) => updateField("UptimeKumaRetry", value)}
/>
<FieldInput
label="重试间隔 (秒)"
value={fields.UptimeKumaRetryInterval}
type="number"
onChange={(value) => updateField("UptimeKumaRetryInterval", value)}
/>
<FieldInput
label="请求超时 (秒)"
value={fields.UptimeKumaTimeout}
type="number"
onChange={(value) => updateField("UptimeKumaTimeout", value)}
/>
</div>
</>
) : null}
</CardContent>
</Card>
<div className="grid gap-6 xl:grid-cols-2">
<Card className="border-dashed shadow-none">
<CardHeader className="flex flex-row items-center justify-between gap-4">
<div>
<CardTitle className="text-base">数据库自动清理</CardTitle>
<CardDescription>每天凌晨 3 点清理超出保留期的观测数据。</CardDescription>
</div>
<Button
size="sm"
disabled={savingSection === "database-auto"}
onClick={saveDatabaseAutoCleanup}
>
保存
</Button>
</CardHeader>
<CardContent className="space-y-4">
<ToggleRow
label="启用每日自动清理"
checked={fields.DatabaseAutoCleanupEnabled}
onChange={(value) => updateField("DatabaseAutoCleanupEnabled", value)}
/>
<FieldInput
label="保留天数"
value={fields.DatabaseAutoCleanupRetentionDays}
type="number"
onChange={(value) => updateField("DatabaseAutoCleanupRetentionDays", value)}
/>
</CardContent>
</Card>
<Card className="border-dashed shadow-none">
<CardHeader>
<CardTitle className="text-base">手动数据清理</CardTitle>
<CardDescription>保留天数留空时将删除该类数据的全部历史记录。</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
{cleanupTargets.map((item) => (
<div
key={item.target}
className="flex items-start justify-between gap-3 rounded-lg border border-dashed p-3"
>
<div>
<p className="text-sm font-medium">{item.label}</p>
<p className="mt-1 text-xs text-muted-foreground">{item.description}</p>
</div>
<Button
type="button"
variant="destructive"
size="sm"
onClick={() =>
setCleanupTarget({ target: item.target, label: item.label })
}
>
<Trash2 className="size-3.5 mr-1" />
清理
</Button>
</div>
))}
</CardContent>
</Card>
</div>
<Card className="border-dashed shadow-none">
<CardHeader className="flex flex-row items-center justify-between gap-4">
<div>
<CardTitle className="text-base">版本信息</CardTitle>
<CardDescription>
检查上游 GitHub Release 并升级当前服务。
</CardDescription>
</div>
<Button type="button" size="sm" onClick={() => setVersionDialogOpen(true)}>
管理升级
</Button>
</CardHeader>
<CardContent className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<InfoCell label="当前版本" value={statusQuery.data?.version ?? releaseQuery.data?.current_version ?? "—"} />
<InfoCell
label="最新 Release"
value={releaseQuery.data?.latest_version ?? "—"}
/>
<div className="rounded-lg border border-dashed px-3 py-2">
<p className="text-[10px] uppercase tracking-wider text-muted-foreground">更新状态</p>
<div className="mt-2">
{releaseQuery.data?.update_available ? (
<Badge variant="secondary">有新版本</Badge>
) : (
<Badge variant="outline">已是最新</Badge>
)}
</div>
</div>
<InfoCell
label="启动时间"
value={
statusQuery.data?.start_time
? new Date(statusQuery.data.start_time * 1000).toLocaleString()
: "—"
}
/>
</CardContent>
</Card>
<VersionUpgradeDialog
open={versionDialogOpen}
onOpenChange={setVersionDialogOpen}
canUpgrade
/>
<UptimeKumaSiteSelectModal
open={uptimeKumaModalOpen}
selectedSites={
fields.UptimeKumaSelectedSites
? fields.UptimeKumaSelectedSites.split(",")
: []
}
onOpenChange={setUptimeKumaModalOpen}
onSave={(sites) => updateField("UptimeKumaSelectedSites", sites.join(","))}
/>
<AlertDialog
open={cleanupTarget !== null}
onOpenChange={(open) => !open && setCleanupTarget(null)}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>清理{cleanupTarget?.label}</AlertDialogTitle>
<AlertDialogDescription>
输入保留天数后仅删除超出范围的数据;留空则删除全部历史记录,操作不可恢复。
</AlertDialogDescription>
</AlertDialogHeader>
<FieldInput
label="保留天数"
value={cleanupRetentionDays}
type="number"
onChange={setCleanupRetentionDays}
placeholder="留空则全部删除"
/>
<AlertDialogFooter>
<AlertDialogCancel disabled={cleanupMutation.isPending}>取消</AlertDialogCancel>
<AlertDialogAction
disabled={cleanupMutation.isPending}
onClick={(event) => {
event.preventDefault()
if (!cleanupTarget) return
const trimmed = cleanupRetentionDays.trim()
if (trimmed !== "") {
const retentionDays = Number.parseInt(trimmed, 10)
if (Number.isNaN(retentionDays) || retentionDays < 1) {
toast.error("保留天数至少为 1 天")
return
}
cleanupMutation.mutate({
target: cleanupTarget.target,
retention_days: retentionDays,
})
return
}
cleanupMutation.mutate({ target: cleanupTarget.target })
}}
>
{cleanupMutation.isPending ? "清理中..." : "确认清理"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
function FieldInput({
label,
value,
onChange,
type = "text",
placeholder,
}: {
label: string
value: string
onChange: (value: string) => void
type?: string
placeholder?: string
}) {
return (
<div className="space-y-1.5">
<Label>{label}</Label>
<Input
type={type}
value={value}
placeholder={placeholder}
onChange={(event) => onChange(event.target.value)}
className="h-9 text-xs"
/>
</div>
)
}
function ToggleRow({
label,
description,
checked,
onChange,
}: {
label: string
description?: string
checked: boolean
onChange: (value: boolean) => void
}) {
return (
<div className="flex items-center justify-between gap-3 rounded-lg border border-dashed px-3 py-2">
<div>
<Label className="text-xs">{label}</Label>
{description ? (
<p className="mt-0.5 text-[11px] text-muted-foreground">{description}</p>
) : null}
</div>
<Switch checked={checked} onCheckedChange={onChange} />
</div>
)
}
function InfoCell({ label, value }: { label: string; value: string }) {
return (
<div className="rounded-lg border border-dashed px-3 py-2">
<p className="text-[10px] uppercase tracking-wider text-muted-foreground">{label}</p>
<p className="mt-2 text-sm font-medium break-all">{value}</p>
</div>
)
}
@@ -0,0 +1,338 @@
"use client"
import * as React from "react"
import {useCallback, useEffect, useRef, useState} from "react"
import {toast} from "sonner"
import {Activity, Cpu, Database, HardDrive, Layers, RefreshCw} from "lucide-react"
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from "@/components/ui/card"
import {Button} from "@/components/ui/button"
import {Switch} from "@/components/ui/switch"
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue,} from "@/components/ui/select"
import {Badge} from "@/components/ui/badge"
import {Progress} from "@/components/ui/progress"
import {Skeleton} from "@/components/ui/skeleton"
import type {SystemStatus} from "@/lib/services/admin"
import services from "@/lib/services"
/**
* 格式化数字,每3位加逗号
*/
const formatNumber = (num: number | string) => {
if (num === undefined || num === null) return "0"
return num.toString().replace(/\B(?=(\d{3})+(?!\B))/g, ",")
}
/**
* 运行时系统状态展示与管理组件
*/
export function SystemStatusManager() {
const [status, setStatus] = useState<SystemStatus | null>(null)
const [loading, setLoading] = useState(true)
const [wavelet, setWavelet] = useState(false)
const [autoRefresh, setAutoRefresh] = useState(true)
const [intervalTime, setIntervalTime] = useState("5000") // 默认5秒
const intervalRef = useRef<NodeJS.Timeout | null>(null)
const prevStatusRef = useRef<SystemStatus | null>(null)
const [changedFields, setChangedFields] = useState<Record<string, boolean>>({})
// 获取状态数据
const fetchStatus = useCallback(async (isSilent = false) => {
if (!isSilent) setWavelet(true)
try {
const data = await services.adminStatus.getSystemStatus()
// 检测变化的字段用于微动画效果
if (prevStatusRef.current) {
const changes: Record<string, boolean> = {}
Object.keys(data).forEach((key) => {
const k = key as keyof SystemStatus
if (prevStatusRef.current && prevStatusRef.current[k] !== data[k]) {
changes[k] = true
}
})
setChangedFields(changes)
// 1秒后清除变化状态
setTimeout(() => {
setChangedFields({})
}, 1000)
}
setStatus(data)
prevStatusRef.current = data
} catch (err) {
toast.error("获取系统状态失败", {
description: err instanceof Error ? err.message : "请求时发生未知错误"
})
} finally {
setLoading(false)
setWavelet(false)
}
}, [])
// 轮询逻辑
useEffect(() => {
// 首次加载
fetchStatus()
}, [fetchStatus])
useEffect(() => {
if (intervalRef.current) {
clearInterval(intervalRef.current)
}
if (autoRefresh) {
const time = parseInt(intervalTime, 10)
intervalRef.current = setInterval(() => {
fetchStatus(true)
}, time)
}
return () => {
if (intervalRef.current) {
clearInterval(intervalRef.current)
}
}
}, [autoRefresh, intervalTime, fetchStatus])
// 计算内存分配百分比 (Alloc / Sys)
const getMemoryUsagePercent = () => {
if (!status) return 0
const parseSizeToBytes = (sizeStr: string): number => {
const parts = sizeStr.split(" ")
if (parts.length < 2) return 0
const value = parseFloat(parts[0])
const unit = parts[1].toLowerCase()
if (unit.startsWith("gib")) return value * 1024 * 1024 * 1024
if (unit.startsWith("mib")) return value * 1024 * 1024
if (unit.startsWith("kib")) return value * 1024
return value
}
const alloc = parseSizeToBytes(status.alloc)
const sys = parseSizeToBytes(status.sys)
if (sys === 0) return 0
return Math.min(Math.round((alloc / sys) * 100), 100)
}
// 闪烁动画类
const getPulseClass = (field: string) => {
return changedFields[field] ? "animate-pulse text-primary font-bold transition-all duration-300 scale-105 inline-block" : "transition-all duration-300"
}
const RenderMetricRow = ({ label, value, field }: { label: string; value: string | number; field?: string }) => (
<div className="flex items-center justify-between py-2 border-b border-dashed border-border/40 last:border-b-0 hover:bg-muted/30 px-2 rounded-sm transition-colors duration-150">
<span className="text-xs font-medium text-muted-foreground">{label}</span>
<span className={`text-xs font-mono font-medium ${field ? getPulseClass(field) : ""}`}>
{typeof value === "number" ? formatNumber(value) : value}
</span>
</div>
)
if (loading) {
return (
<div className="space-y-6 p-1">
<div className="flex items-center justify-between border-b border-border/40 pb-4">
<div className="space-y-1">
<Skeleton className="h-6 w-32" />
<Skeleton className="h-4 w-48" />
</div>
<div className="flex items-center gap-3">
<Skeleton className="h-8 w-24" />
<Skeleton className="h-8 w-16" />
<Skeleton className="h-8 w-8" />
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<Skeleton className="h-48 w-full" />
<Skeleton className="h-48 w-full" />
<Skeleton className="h-48 w-full" />
<Skeleton className="h-48 w-full" />
<Skeleton className="h-48 w-full" />
</div>
</div>
)
}
return (
<div className="py-6 px-1 space-y-6">
{/* 顶部控制栏 */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between pb-4 gap-4">
<div className="flex items-center gap-2">
<Activity className="size-5 text-primary" />
<div>
<h1 className="text-2xl font-semibold tracking-tight">系统状态</h1>
</div>
</div>
<div className="flex items-center flex-wrap gap-4 bg-muted/30 p-1.5 rounded-lg border border-border/40 backdrop-blur-sm">
<div className="flex items-center gap-2 px-1">
<Switch
id="auto-refresh"
checked={autoRefresh}
onCheckedChange={setAutoRefresh}
/>
<label htmlFor="auto-refresh" className="text-xs font-medium cursor-pointer select-none">
自动刷新
</label>
</div>
{autoRefresh && (
<Select value={intervalTime} onValueChange={setIntervalTime}>
<SelectTrigger className="h-7 w-20 text-[11px] bg-background border-border/40">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="1000">1s</SelectItem>
<SelectItem value="2000">2s</SelectItem>
<SelectItem value="5000">5s</SelectItem>
<SelectItem value="10000">10s</SelectItem>
</SelectContent>
</Select>
)}
<Button
size="sm"
variant="secondary"
className="h-7 text-[11px] gap-1.5"
onClick={() => fetchStatus()}
disabled={wavelet}
>
<RefreshCw className={`size-3 ${wavelet ? "animate-spin" : ""}`} />
刷新
</Button>
</div>
</div>
{status && (
<>
{/* 主网格排版 */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{/* 1. 服务概览 */}
<Card className="shadow-sm border-border/40 bg-card/50 backdrop-blur-md hover:border-primary/20 transition-all duration-300">
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
<div className="space-y-0.5">
<CardTitle className="text-sm font-semibold">服务概览</CardTitle>
<CardDescription className="text-[10px]">服务的基础生命指标</CardDescription>
</div>
<Badge variant="secondary" className="p-1 rounded-full bg-primary/10 text-primary border-none">
<Activity className="size-4" />
</Badge>
</CardHeader>
<CardContent className="space-y-1">
<RenderMetricRow label="服务运行时间" value={status.uptime} field="uptime" />
<RenderMetricRow label="当前 Goroutines 数量" value={status.num_goroutine} field="num_goroutine" />
<RenderMetricRow label="Heap 对象数量" value={status.heap_objects} field="heap_objects" />
</CardContent>
</Card>
{/* 2. 内存统计 */}
<Card className="shadow-sm border-border/40 bg-card/50 backdrop-blur-md hover:border-primary/20 transition-all duration-300">
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
<div className="space-y-0.5">
<CardTitle className="text-sm font-semibold">内存统计</CardTitle>
<CardDescription className="text-[10px]">主内存消耗概览</CardDescription>
</div>
<Badge variant="secondary" className="p-1 rounded-full bg-primary/10 text-primary border-none">
<Cpu className="size-4" />
</Badge>
</CardHeader>
<CardContent className="space-y-3">
<div className="space-y-1">
<RenderMetricRow label="当前内存使用量" value={status.alloc} field="alloc" />
<RenderMetricRow label="所有已分配的内存" value={status.total_alloc} field="total_alloc" />
<RenderMetricRow label="内存占用量" value={status.sys} field="sys" />
<RenderMetricRow label="下次 GC 内存回收量" value={status.next_gc} field="next_gc" />
</div>
{/* 物理内存水位比例 */}
<div className="space-y-1 px-1 pt-1">
<div className="flex justify-between text-[10px] text-muted-foreground">
<span>当前使用率 (Alloc / Sys)</span>
<span className="font-mono">{getMemoryUsagePercent()}%</span>
</div>
<Progress value={getMemoryUsagePercent()} className="h-1.5" />
</div>
</CardContent>
</Card>
{/* 3. 堆/栈详情 */}
<Card className="shadow-sm border-border/40 bg-card/50 backdrop-blur-md hover:border-primary/20 transition-all duration-300">
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
<div className="space-y-0.5">
<CardTitle className="text-sm font-semibold">堆/栈详情</CardTitle>
<CardDescription className="text-[10px]">运行时堆栈内存空间细节</CardDescription>
</div>
<Badge variant="secondary" className="p-1 rounded-full bg-primary/10 text-primary border-none">
<Database className="size-4" />
</Badge>
</CardHeader>
<CardContent className="space-y-1">
<RenderMetricRow label="当前 Heap 内存使用量" value={status.heap_alloc} field="heap_alloc" />
<RenderMetricRow label="Heap 内存占用量" value={status.heap_sys} field="heap_sys" />
<RenderMetricRow label="Heap 内存空闲量" value={status.heap_idle} field="heap_idle" />
<RenderMetricRow label="正在使用的 Heap 内存" value={status.heap_inuse} field="heap_inuse" />
<RenderMetricRow label="已释放的 Heap 内存" value={status.heap_released} field="heap_released" />
<RenderMetricRow label="启动 Stack 使用量" value={status.stack_inuse} field="stack_inuse" />
<RenderMetricRow label="已分配的 Stack 内存" value={status.stack_sys} field="stack_sys" />
</CardContent>
</Card>
{/* 4. 底层组件与结构体 */}
<Card className="shadow-sm border-border/40 bg-card/50 backdrop-blur-md hover:border-primary/20 transition-all duration-300">
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
<div className="space-y-0.5">
<CardTitle className="text-sm font-semibold">底层及结构体内存</CardTitle>
<CardDescription className="text-[10px]">运行时底层管理结构体开销</CardDescription>
</div>
<Badge variant="secondary" className="p-1 rounded-full bg-primary/10 text-primary border-none">
<HardDrive className="size-4" />
</Badge>
</CardHeader>
<CardContent className="space-y-1">
<RenderMetricRow label="MSpan 结构内存使用量" value={status.mspan_inuse} field="mspan_inuse" />
<RenderMetricRow label="已分配的 MSpan 结构内存" value={status.mspan_sys} field="mspan_sys" />
<RenderMetricRow label="MCache 结构内存使用量" value={status.mcache_inuse} field="mcache_inuse" />
<RenderMetricRow label="已分配的 MCache 结构内存" value={status.mcache_sys} field="mcache_sys" />
<RenderMetricRow label="已分配的剖析哈希表内存" value={status.buck_hash_sys} field="buck_hash_sys" />
<RenderMetricRow label="已分配的 GC 元数据内存" value={status.gc_sys} field="gc_sys" />
<RenderMetricRow label="其它已分配的系统内存" value={status.other_sys} field="other_sys" />
</CardContent>
</Card>
{/* 5. 垃圾回收与分配计数 */}
<Card className="shadow-sm border-border/40 bg-card/50 backdrop-blur-md hover:border-primary/20 transition-all duration-300 md:col-span-2">
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
<div className="space-y-0.5">
<CardTitle className="text-sm font-semibold">垃圾回收与分配计数</CardTitle>
<CardDescription className="text-[10px]">GC 历史数据与分配频次</CardDescription>
</div>
<Badge variant="secondary" className="p-1 rounded-full bg-primary/10 text-primary border-none">
<Layers className="size-4" />
</Badge>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6">
<div>
<RenderMetricRow label="GC 执行次数" value={status.num_gc} field="num_gc" />
<RenderMetricRow label="距离上次 GC 时间" value={status.last_gc_time} field="last_gc_time" />
<RenderMetricRow label="GC 暂停时间总量" value={status.pause_total_ns} field="pause_total_ns" />
<RenderMetricRow label="上次 GC 暂停时间" value={status.last_pause} field="last_pause" />
</div>
<div>
<RenderMetricRow label="内存分配次数" value={status.mallocs} field="mallocs" />
<RenderMetricRow label="内存释放次数" value={status.frees} field="frees" />
<RenderMetricRow label="指针查找次数" value={status.lookups} field="lookups" />
</div>
</div>
</CardContent>
</Card>
</div>
</>
)}
</div>
)
}
@@ -0,0 +1,181 @@
"use client"
import {useEffect, useMemo, useState} from "react"
import {useQuery} from "@tanstack/react-query"
import {Button} from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import {Input} from "@/components/ui/input"
import {Label} from "@/components/ui/label"
import {ProxyRouteService} from "@/lib/services/openflare"
type UptimeKumaSiteSelectModalProps = {
open: boolean
selectedSites: string[]
onOpenChange: (open: boolean) => void
onSave: (sites: string[]) => void
}
export function UptimeKumaSiteSelectModal({
open,
selectedSites,
onOpenChange,
onSave,
}: UptimeKumaSiteSelectModalProps) {
const [searchTerm, setSearchTerm] = useState("")
const [tempSelected, setTempSelected] = useState<Set<string>>(new Set())
const routesQuery = useQuery({
queryKey: ["openflare", "proxy-routes"],
queryFn: () => ProxyRouteService.list(),
enabled: open,
})
useEffect(() => {
if (!open) return
setTempSelected(new Set(selectedSites.map((site) => site.trim()).filter(Boolean)))
setSearchTerm("")
}, [open, selectedSites])
const filteredRoutes = useMemo(() => {
const routes = routesQuery.data ?? []
const keyword = searchTerm.trim().toLowerCase()
if (!keyword) return routes
return routes.filter(
(route) =>
route.site_name.toLowerCase().includes(keyword) ||
route.primary_domain.toLowerCase().includes(keyword),
)
}, [routesQuery.data, searchTerm])
const toggleSite = (siteName: string) => {
setTempSelected((previous) => {
const next = new Set(previous)
if (next.has(siteName)) next.delete(siteName)
else next.add(siteName)
return next
})
}
const handleSelectAll = () => {
setTempSelected((previous) => {
const next = new Set(previous)
filteredRoutes.forEach((route) => next.add(route.site_name))
return next
})
}
const handleDeselectAll = () => {
setTempSelected((previous) => {
const next = new Set(previous)
filteredRoutes.forEach((route) => next.delete(route.site_name))
return next
})
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>选择监控站点</DialogTitle>
<DialogDescription>
选择要同步到 Uptime Kuma 的反代站点,支持按站点名称和域名搜索。
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-1.5">
<Label>搜索站点</Label>
<Input
value={searchTerm}
onChange={(event) => setSearchTerm(event.target.value)}
placeholder="按名称或域名搜索..."
/>
</div>
<div className="flex flex-wrap gap-2">
<Button type="button" variant="outline" size="sm" onClick={handleSelectAll}>
全选过滤项
</Button>
<Button type="button" variant="outline" size="sm" onClick={handleDeselectAll}>
清空过滤项
</Button>
</div>
<div className="max-h-72 overflow-y-auto rounded-lg border">
{routesQuery.isLoading ? (
<p className="p-4 text-sm text-muted-foreground">加载站点列表...</p>
) : routesQuery.isError ? (
<p className="p-4 text-sm text-destructive">
{routesQuery.error instanceof Error
? routesQuery.error.message
: "加载站点失败"}
</p>
) : filteredRoutes.length === 0 ? (
<p className="p-4 text-sm text-muted-foreground">无匹配的站点</p>
) : (
<table className="w-full text-left text-sm">
<thead className="sticky top-0 bg-muted/60 text-xs uppercase text-muted-foreground">
<tr>
<th className="w-12 px-3 py-2">选择</th>
<th className="px-3 py-2">站点名称</th>
<th className="px-3 py-2">主域名</th>
</tr>
</thead>
<tbody className="divide-y">
{filteredRoutes.map((route) => {
const checked = tempSelected.has(route.site_name)
return (
<tr
key={route.id}
className="cursor-pointer hover:bg-muted/30"
onClick={() => toggleSite(route.site_name)}
>
<td className="px-3 py-2" onClick={(event) => event.stopPropagation()}>
<input
type="checkbox"
checked={checked}
onChange={() => toggleSite(route.site_name)}
className="size-4 rounded border-input"
/>
</td>
<td className="px-3 py-2 font-medium">{route.site_name}</td>
<td className="px-3 py-2 text-muted-foreground">{route.primary_domain}</td>
</tr>
)
})}
</tbody>
</table>
)}
</div>
<p className="text-right text-xs text-muted-foreground">
已选择 {tempSelected.size} 个监控站点
</p>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
取消
</Button>
<Button
type="button"
onClick={() => {
onSave(Array.from(tempSelected))
onOpenChange(false)
}}
>
保存选择
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}