mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-12 02:06:37 +08:00
migrate frontend
This commit is contained in:
@@ -0,0 +1,173 @@
|
||||
'use client';
|
||||
|
||||
import {useEffect, useMemo, useState} from 'react';
|
||||
import {Copy} from 'lucide-react';
|
||||
import {toast} from 'sonner';
|
||||
|
||||
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 type {NodeItem} from '@/lib/services/openflare';
|
||||
|
||||
import {
|
||||
buildRelayDockerInstallCommand,
|
||||
buildRelayInstallCommand,
|
||||
buildTunnelDockerInstallCommand,
|
||||
buildTunnelInstallCommand,
|
||||
getServerUrl,
|
||||
} from './node-utils';
|
||||
|
||||
type InstallVariant = 'relay' | 'tunnel';
|
||||
|
||||
const variantMeta: Record<
|
||||
InstallVariant,
|
||||
{
|
||||
title: string;
|
||||
description: string;
|
||||
tokenLabel: string;
|
||||
scriptLabel: string;
|
||||
dockerLabel: string;
|
||||
}
|
||||
> = {
|
||||
relay: {
|
||||
title: '中继部署命令',
|
||||
description: '使用 Discovery Token 将 frps 中继节点接入控制端。',
|
||||
tokenLabel: 'Discovery Token',
|
||||
scriptLabel: '一键脚本部署 (Linux / macOS)',
|
||||
dockerLabel: 'Docker 容器部署',
|
||||
},
|
||||
tunnel: {
|
||||
title: '隧道部署命令',
|
||||
description: '使用 Tunnel Token 将 openflared 客户端接入控制端。',
|
||||
tokenLabel: 'Tunnel Token',
|
||||
scriptLabel: '一键脚本部署 (Linux / macOS)',
|
||||
dockerLabel: 'Docker 容器部署',
|
||||
},
|
||||
};
|
||||
|
||||
export function InstallCommand({
|
||||
node,
|
||||
variant,
|
||||
}: {
|
||||
node: NodeItem;
|
||||
variant: InstallVariant;
|
||||
}) {
|
||||
const [serverUrl, setServerUrl] = useState('');
|
||||
const meta = variantMeta[variant];
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window !== 'undefined' && !serverUrl) {
|
||||
setServerUrl(window.location.origin);
|
||||
}
|
||||
}, [serverUrl]);
|
||||
|
||||
const normalizedServerUrl = getServerUrl(serverUrl);
|
||||
const scriptCommand = useMemo(() => {
|
||||
if (!normalizedServerUrl || !node.access_token) {
|
||||
return '';
|
||||
}
|
||||
return variant === 'relay'
|
||||
? buildRelayInstallCommand(normalizedServerUrl, node.access_token)
|
||||
: buildTunnelInstallCommand(normalizedServerUrl, node.access_token);
|
||||
}, [normalizedServerUrl, node.access_token, variant]);
|
||||
|
||||
const dockerCommand = useMemo(() => {
|
||||
if (!normalizedServerUrl || !node.access_token) {
|
||||
return '';
|
||||
}
|
||||
return variant === 'relay'
|
||||
? buildRelayDockerInstallCommand(normalizedServerUrl, node.access_token)
|
||||
: buildTunnelDockerInstallCommand(normalizedServerUrl, node.access_token);
|
||||
}, [normalizedServerUrl, node.access_token, variant]);
|
||||
|
||||
const handleCopy = async (value: string, message: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
toast.success(message);
|
||||
} catch {
|
||||
toast.error('复制失败,请手动选择命令文本。');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="flex-row items-start justify-between space-y-0 gap-4">
|
||||
<div>
|
||||
<CardTitle className="text-base font-semibold">{meta.title}</CardTitle>
|
||||
<CardDescription>{meta.description}</CardDescription>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{scriptCommand ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="h-7 text-xs"
|
||||
onClick={() => void handleCopy(scriptCommand, '部署脚本命令已复制')}
|
||||
>
|
||||
<Copy className="size-3.5 mr-1" />
|
||||
复制脚本
|
||||
</Button>
|
||||
) : null}
|
||||
{dockerCommand ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="h-7 text-xs"
|
||||
onClick={() => void handleCopy(dockerCommand, 'Docker 部署命令已复制')}
|
||||
>
|
||||
<Copy className="size-3.5 mr-1" />
|
||||
复制 Docker
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="rounded-lg border px-3 py-3">
|
||||
<p className="text-xs text-muted-foreground">Node ID</p>
|
||||
<p className="mt-1 text-sm break-all font-medium">{node.node_id}</p>
|
||||
</div>
|
||||
<div className="rounded-lg border px-3 py-3">
|
||||
<p className="text-xs text-muted-foreground">{meta.tokenLabel}</p>
|
||||
<p className="mt-1 text-sm break-all font-medium">{node.access_token || '暂无'}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={`server-url-${variant}`}>Server URL(控制端地址)</Label>
|
||||
<Input
|
||||
id={`server-url-${variant}`}
|
||||
value={serverUrl}
|
||||
onChange={(event) => setServerUrl(event.target.value)}
|
||||
placeholder="https://openflare.example.com"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
部署脚本和容器将使用此地址连接 OpenFlare 控制端。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{!node.access_token ? (
|
||||
<p className="text-sm text-muted-foreground">节点尚未生成接入 Token,请稍后刷新。</p>
|
||||
) : !normalizedServerUrl ? (
|
||||
<p className="text-sm text-muted-foreground">请填写有效的 Server URL 以生成部署命令。</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium">{meta.scriptLabel}</p>
|
||||
<pre className="overflow-x-auto rounded-lg border bg-muted/40 p-3 text-xs whitespace-pre-wrap">
|
||||
{scriptCommand}
|
||||
</pre>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium">{meta.dockerLabel}</p>
|
||||
<pre className="overflow-x-auto rounded-lg border bg-muted/40 p-3 text-xs whitespace-pre-wrap">
|
||||
{dockerCommand}
|
||||
</pre>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
'use client';
|
||||
|
||||
import {useMemo, useState} from 'react';
|
||||
import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query';
|
||||
import {Loader2, Trash2} from 'lucide-react';
|
||||
import {toast} from 'sonner';
|
||||
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import {Button} from '@/components/ui/button';
|
||||
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from '@/components/ui/card';
|
||||
import {formatDateTime} from '@/lib/utils';
|
||||
import {NodeService} from '@/lib/services/openflare';
|
||||
|
||||
import {NodeStatusBadge} from './node-status-badge';
|
||||
import {
|
||||
formatBytes,
|
||||
formatRelativeTime,
|
||||
formatUptime,
|
||||
formatUsageRatio,
|
||||
getErrorMessage,
|
||||
getHealthEventLabel,
|
||||
getHealthEventTone,
|
||||
isMeaningfulTime,
|
||||
} from './node-utils';
|
||||
|
||||
type HealthEventFilter = 'all' | 'active' | 'resolved';
|
||||
|
||||
function MetricBar({
|
||||
label,
|
||||
value,
|
||||
progress,
|
||||
hint,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
progress?: number | null;
|
||||
hint?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-2 rounded-lg border px-3 py-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground uppercase tracking-wide">{label}</p>
|
||||
{hint ? <p className="mt-1 text-xs text-muted-foreground">{hint}</p> : null}
|
||||
</div>
|
||||
<p className="text-sm font-medium">{value}</p>
|
||||
</div>
|
||||
{progress !== null && progress !== undefined ? (
|
||||
<div className="h-2 overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
className="h-full rounded-full bg-primary transition-[width]"
|
||||
style={{ width: `${progress}%` }}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function NodeObservability({
|
||||
nodeId,
|
||||
connectionHint = '活动连接数',
|
||||
}: {
|
||||
nodeId: number;
|
||||
connectionHint?: string;
|
||||
}) {
|
||||
const queryClient = useQueryClient();
|
||||
const [healthEventFilter, setHealthEventFilter] = useState<HealthEventFilter>('all');
|
||||
const [cleanupOpen, setCleanupOpen] = useState(false);
|
||||
|
||||
const observabilityQuery = useQuery({
|
||||
queryKey: ['openflare', 'node-observability', nodeId],
|
||||
queryFn: () => NodeService.getObservability(nodeId, { hours: 24, limit: 48 }),
|
||||
refetchInterval: 10000,
|
||||
});
|
||||
|
||||
const cleanupMutation = useMutation({
|
||||
mutationFn: () => NodeService.cleanupHealthEvents(nodeId),
|
||||
onSuccess: async (result) => {
|
||||
toast.success(
|
||||
result.deleted_count > 0
|
||||
? `已清理 ${result.deleted_count} 条健康事件日志`
|
||||
: '当前没有可清理的健康事件日志',
|
||||
);
|
||||
setCleanupOpen(false);
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: ['openflare', 'node-observability', nodeId],
|
||||
});
|
||||
},
|
||||
onError: (error) => toast.error(getErrorMessage(error)),
|
||||
});
|
||||
|
||||
const observability = observabilityQuery.data ?? null;
|
||||
const profile = observability?.profile ?? null;
|
||||
const latestMetric = observability?.metric_snapshots?.[0] ?? null;
|
||||
const activeHealthEvents = useMemo(
|
||||
() => observability?.health_events.filter((event) => event.status === 'active') ?? [],
|
||||
[observability?.health_events],
|
||||
);
|
||||
const resolvedHealthEvents = useMemo(
|
||||
() => observability?.health_events.filter((event) => event.status === 'resolved') ?? [],
|
||||
[observability?.health_events],
|
||||
);
|
||||
const filteredHealthEvents = useMemo(() => {
|
||||
switch (healthEventFilter) {
|
||||
case 'active':
|
||||
return activeHealthEvents;
|
||||
case 'resolved':
|
||||
return resolvedHealthEvents;
|
||||
default:
|
||||
return observability?.health_events ?? [];
|
||||
}
|
||||
}, [activeHealthEvents, healthEventFilter, observability?.health_events, resolvedHealthEvents]);
|
||||
|
||||
const memoryUsageRatio = formatUsageRatio(
|
||||
latestMetric?.memory_used_bytes,
|
||||
latestMetric?.memory_total_bytes,
|
||||
);
|
||||
const storageUsageRatio = formatUsageRatio(
|
||||
latestMetric?.storage_used_bytes,
|
||||
latestMetric?.storage_total_bytes,
|
||||
);
|
||||
|
||||
if (observabilityQuery.isLoading) {
|
||||
return (
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardContent className="flex items-center justify-center py-10 text-sm text-muted-foreground">
|
||||
<Loader2 className="size-4 mr-2 animate-spin" />
|
||||
加载运行观测数据中...
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (observabilityQuery.isError) {
|
||||
return (
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardContent className="py-6">
|
||||
<p className="text-sm text-destructive">{getErrorMessage(observabilityQuery.error)}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>运行诊断</CardDescription>
|
||||
<CardTitle className="text-base font-semibold">
|
||||
{activeHealthEvents.length ? `${activeHealthEvents.length} 个活动异常` : '运行稳定'}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>系统核心</CardDescription>
|
||||
<CardTitle className="text-base font-semibold">
|
||||
{profile?.hostname || '—'}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>在线时长</CardDescription>
|
||||
<CardTitle className="text-base font-semibold">
|
||||
{formatUptime(profile?.uptime_seconds)}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 xl:grid-cols-2">
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base font-semibold">系统画像</CardTitle>
|
||||
<CardDescription>节点上报的主机与硬件信息</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3 text-sm">
|
||||
{profile ? (
|
||||
<>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">操作系统</span>
|
||||
<span>
|
||||
{profile.os_name || 'unknown'}
|
||||
{profile.os_version ? ` ${profile.os_version}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">内核 / 架构</span>
|
||||
<span>
|
||||
{profile.kernel_version || 'unknown'} · {profile.architecture || 'unknown'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">CPU</span>
|
||||
<span>
|
||||
{profile.cpu_model || 'unknown'}({profile.cpu_cores || 0} 核)
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">总内存</span>
|
||||
<span>{formatBytes(profile.total_memory_bytes)}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">总存储</span>
|
||||
<span>{formatBytes(profile.total_disk_bytes)}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">上报时间</span>
|
||||
<span>
|
||||
{isMeaningfulTime(profile.reported_at)
|
||||
? formatDateTime(profile.reported_at)
|
||||
: '—'}
|
||||
</span>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-muted-foreground">节点已接入,但尚未上报完整系统画像。</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base font-semibold">实时资源快照</CardTitle>
|
||||
<CardDescription>最近一次 metrics 上报</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{latestMetric ? (
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<MetricBar
|
||||
label="CPU"
|
||||
value={`${latestMetric.cpu_usage_percent.toFixed(1)}%`}
|
||||
progress={latestMetric.cpu_usage_percent}
|
||||
hint={
|
||||
isMeaningfulTime(latestMetric.captured_at)
|
||||
? `快照 ${formatRelativeTime(latestMetric.captured_at)}`
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<MetricBar
|
||||
label="内存"
|
||||
value={`${formatBytes(latestMetric.memory_used_bytes)} / ${formatBytes(latestMetric.memory_total_bytes)}`}
|
||||
progress={memoryUsageRatio}
|
||||
/>
|
||||
<MetricBar
|
||||
label="存储"
|
||||
value={`${formatBytes(latestMetric.storage_used_bytes)} / ${formatBytes(latestMetric.storage_total_bytes)}`}
|
||||
progress={storageUsageRatio}
|
||||
/>
|
||||
<MetricBar
|
||||
label="活动连接"
|
||||
value={
|
||||
latestMetric.openresty_connections
|
||||
? String(latestMetric.openresty_connections)
|
||||
: '—'
|
||||
}
|
||||
progress={null}
|
||||
hint={connectionHint}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">节点已接入,但尚未上报资源快照。</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="flex-row items-center justify-between space-y-0">
|
||||
<div>
|
||||
<CardTitle className="text-base font-semibold">健康事件时间线</CardTitle>
|
||||
<CardDescription>保留活动与已恢复事件,用于运行异常诊断</CardDescription>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 text-xs text-destructive hover:text-destructive"
|
||||
disabled={cleanupMutation.isPending || !observability?.health_events.length}
|
||||
onClick={() => setCleanupOpen(true)}
|
||||
>
|
||||
<Trash2 className="size-3.5 mr-1" />
|
||||
清理日志
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{observability?.health_events.length ? (
|
||||
<>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{(['all', 'active', 'resolved'] as const).map((filter) => (
|
||||
<Button
|
||||
key={filter}
|
||||
type="button"
|
||||
variant={healthEventFilter === filter ? 'secondary' : 'outline'}
|
||||
size="sm"
|
||||
className="h-7 text-xs rounded-full"
|
||||
onClick={() => setHealthEventFilter(filter)}
|
||||
>
|
||||
{filter === 'all' ? '全部' : filter === 'active' ? '活动中' : '已恢复'}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{filteredHealthEvents.slice(0, 8).map((event) => (
|
||||
<div key={`${event.event_type}-${event.last_triggered_at}-${event.status}`} className="rounded-lg border px-4 py-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<NodeStatusBadge
|
||||
label={getHealthEventLabel(event)}
|
||||
tone={getHealthEventTone(event)}
|
||||
/>
|
||||
<NodeStatusBadge
|
||||
label={event.status === 'active' ? '活动中' : '已恢复'}
|
||||
tone={event.status === 'active' ? 'warning' : 'success'}
|
||||
/>
|
||||
</div>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
{event.message || '暂无详细消息'}
|
||||
</p>
|
||||
<div className="mt-2 grid gap-1 text-xs text-muted-foreground md:grid-cols-3">
|
||||
<p>
|
||||
首次触发:
|
||||
{isMeaningfulTime(event.first_triggered_at)
|
||||
? ` ${formatDateTime(event.first_triggered_at)}`
|
||||
: ' —'}
|
||||
</p>
|
||||
<p>
|
||||
最近触发:
|
||||
{isMeaningfulTime(event.last_triggered_at)
|
||||
? ` ${formatDateTime(event.last_triggered_at)}`
|
||||
: ' —'}
|
||||
</p>
|
||||
<p>
|
||||
恢复时间:
|
||||
{isMeaningfulTime(event.resolved_at) && event.resolved_at
|
||||
? ` ${formatDateTime(event.resolved_at)}`
|
||||
: ' —'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{filteredHealthEvents.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">当前筛选下没有健康事件。</p>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">节点当前还没有上报健康事件记录。</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<AlertDialog open={cleanupOpen} onOpenChange={setCleanupOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>清理健康事件日志</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
该操作会删除此节点在控制端记录的所有健康诊断事件历史,不会影响后续新事件上报。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={cleanupMutation.isPending}>取消</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-white hover:bg-destructive/90"
|
||||
disabled={cleanupMutation.isPending}
|
||||
onClick={() => cleanupMutation.mutate()}
|
||||
>
|
||||
{cleanupMutation.isPending ? '清理中...' : '确认清理'}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -9,7 +9,7 @@ export function isWSConnectedLastSeen(value: string | null | undefined) {
|
||||
return value === WS_CONNECTED_LAST_SEEN || value === FLARED_WS_CONNECTED_LAST_SEEN;
|
||||
}
|
||||
|
||||
export function isMeaningfulTime(value: string | null | undefined) {
|
||||
export function isMeaningfulTime(value: string | null | undefined): value is string {
|
||||
return (
|
||||
Boolean(value) &&
|
||||
!isWSConnectedLastSeen(value) &&
|
||||
@@ -96,3 +96,133 @@ export function getNodeTypeLabel(nodeType: NodeItem['node_type']) {
|
||||
export function getErrorMessage(error: unknown) {
|
||||
return error instanceof Error ? error.message : '请求失败,请稍后重试。';
|
||||
}
|
||||
|
||||
export function getServerUrl(value: string) {
|
||||
return value.trim().replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
const relayInstallerScriptUrl =
|
||||
'https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-relay.sh';
|
||||
|
||||
const flaredInstallerScriptUrl =
|
||||
'https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-flared.sh';
|
||||
|
||||
export function buildRelayInstallCommand(serverUrl: string, discoveryToken: string) {
|
||||
return [
|
||||
`curl -fsSL ${relayInstallerScriptUrl} | bash -s -- \\`,
|
||||
` --server-url ${serverUrl} \\`,
|
||||
` --discovery-token ${discoveryToken}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
export function buildRelayDockerInstallCommand(serverUrl: string, discoveryToken: string) {
|
||||
const image = 'ghcr.io/rain-kl/openflare-relay:latest';
|
||||
|
||||
return [
|
||||
`docker pull ${image}`,
|
||||
`docker rm -f openflare-relay 2>/dev/null || true`,
|
||||
`docker run -d --name openflare-relay --net host --restart unless-stopped \\`,
|
||||
` -e OPENFLARE_SERVER_URL=${serverUrl} \\`,
|
||||
` -e OPENFLARE_DISCOVERY_TOKEN=${discoveryToken} \\`,
|
||||
` ${image}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
export function buildTunnelInstallCommand(serverUrl: string, tunnelToken: string) {
|
||||
return [
|
||||
`curl -fsSL ${flaredInstallerScriptUrl} | bash -s -- \\`,
|
||||
` --server-url ${serverUrl} \\`,
|
||||
` --tunnel-token ${tunnelToken}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
export function buildTunnelDockerInstallCommand(serverUrl: string, tunnelToken: string) {
|
||||
const image = 'ghcr.io/rain-kl/openflared:latest';
|
||||
|
||||
return [
|
||||
`docker pull ${image}`,
|
||||
`docker rm -f openflared 2>/dev/null || true`,
|
||||
`docker run -d --name openflared --restart unless-stopped \\`,
|
||||
` -e OPENFLARE_SERVER_URL=${serverUrl} \\`,
|
||||
` -e OPENFLARE_TUNNEL_TOKEN=${tunnelToken} \\`,
|
||||
` ${image}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
export function formatBytes(bytes?: number | null, decimals = 1) {
|
||||
if (!bytes || !Number.isFinite(bytes) || bytes <= 0) {
|
||||
return '—';
|
||||
}
|
||||
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
const index = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
|
||||
const value = bytes / 1024 ** index;
|
||||
return `${value.toFixed(decimals)} ${units[index]}`;
|
||||
}
|
||||
|
||||
export function formatUsageRatio(used?: number | null, total?: number | null) {
|
||||
if (!used || !total || total <= 0) {
|
||||
return null;
|
||||
}
|
||||
return Math.max(0, Math.min(100, (used / total) * 100));
|
||||
}
|
||||
|
||||
export function formatUptime(seconds?: number | null) {
|
||||
if (!seconds || seconds <= 0) {
|
||||
return '—';
|
||||
}
|
||||
|
||||
const days = Math.floor(seconds / 86400);
|
||||
const hours = Math.floor((seconds % 86400) / 3600);
|
||||
const minutes = Math.floor((seconds % 3600) / 60);
|
||||
|
||||
if (days > 0) {
|
||||
return `${days} 天 ${hours} 小时`;
|
||||
}
|
||||
if (hours > 0) {
|
||||
return `${hours} 小时 ${minutes} 分钟`;
|
||||
}
|
||||
return `${minutes} 分钟`;
|
||||
}
|
||||
|
||||
export function getHealthEventTone(
|
||||
event: { status: string; severity: string },
|
||||
): StatusTone {
|
||||
if (event.status === 'resolved') {
|
||||
return 'success';
|
||||
}
|
||||
if (event.severity === 'critical') {
|
||||
return 'danger';
|
||||
}
|
||||
if (event.severity === 'warning') {
|
||||
return 'warning';
|
||||
}
|
||||
return 'info';
|
||||
}
|
||||
|
||||
export function getHealthEventLabel(event: { event_type: string }) {
|
||||
return event.event_type.replaceAll('_', ' ');
|
||||
}
|
||||
|
||||
export function getFlaredStatusLabel(node: NodeItem) {
|
||||
if (isWSConnectedLastSeen(node.last_seen_at)) {
|
||||
return 'WS 已连接';
|
||||
}
|
||||
if (node.status === 'online') {
|
||||
return '运行中';
|
||||
}
|
||||
if (node.status === 'pending') {
|
||||
return '待接入';
|
||||
}
|
||||
return '离线';
|
||||
}
|
||||
|
||||
export function getFlaredStatusTone(node: NodeItem): StatusTone {
|
||||
if (isWSConnectedLastSeen(node.last_seen_at) || node.status === 'online') {
|
||||
return 'success';
|
||||
}
|
||||
if (node.status === 'pending') {
|
||||
return 'warning';
|
||||
}
|
||||
return 'danger';
|
||||
}
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import {useRouter} from 'next/navigation';
|
||||
import {useMutation, useQueryClient} from '@tanstack/react-query';
|
||||
import {useState} from 'react';
|
||||
import {ArrowLeft, ExternalLink, FileText, RefreshCw, RotateCcw, Trash2, Upload,} from 'lucide-react';
|
||||
import {toast} from 'sonner';
|
||||
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import {Button} from '@/components/ui/button';
|
||||
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from '@/components/ui/card';
|
||||
import {Label} from '@/components/ui/label';
|
||||
import {Switch} from '@/components/ui/switch';
|
||||
import {formatDateTime} from '@/lib/utils';
|
||||
import type {NodeAgentReleaseInfo, NodeItem, ReleaseChannel} from '@/lib/services/openflare';
|
||||
import {NodeService} from '@/lib/services/openflare';
|
||||
|
||||
import {AgentUpdateDialog} from './agent-update-dialog';
|
||||
import {InstallCommand} from './install-command';
|
||||
import {NodeEditorDialog} from './node-editor-dialog';
|
||||
import {NodeObservability} from './node-observability';
|
||||
import {NodeStatusBadge} from './node-status-badge';
|
||||
import {
|
||||
formatRelativeTime,
|
||||
getApplyLabel,
|
||||
getApplyTone,
|
||||
getErrorMessage,
|
||||
getNodeStatusLabel,
|
||||
getNodeStatusTone,
|
||||
getRelayStatusLabel,
|
||||
getRelayStatusTone,
|
||||
isMeaningfulTime,
|
||||
isWSConnectedLastSeen,
|
||||
} from './node-utils';
|
||||
|
||||
const nodesQueryKey = ['openflare', 'nodes'];
|
||||
|
||||
export function RelayNodeDetail({ node }: { node: NodeItem }) {
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const [editorOpen, setEditorOpen] = useState(false);
|
||||
const [upgradeOpen, setUpgradeOpen] = useState(false);
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (payload: Parameters<typeof NodeService.updateNode>[1]) =>
|
||||
NodeService.updateNode(node.id, payload),
|
||||
onSuccess: async () => {
|
||||
toast.success('中继节点已更新');
|
||||
setEditorOpen(false);
|
||||
await queryClient.invalidateQueries({ queryKey: nodesQueryKey });
|
||||
},
|
||||
onError: (error) => toast.error(getErrorMessage(error)),
|
||||
});
|
||||
|
||||
const webServerMutation = useMutation({
|
||||
mutationFn: (enabled: boolean) =>
|
||||
NodeService.updateNode(node.id, {
|
||||
node_type: node.node_type,
|
||||
name: node.name,
|
||||
ip: node.ip,
|
||||
ip_manual_override: node.ip_manual_override,
|
||||
auto_update_enabled: node.auto_update_enabled,
|
||||
geo_name: node.geo_name,
|
||||
geo_latitude: node.geo_latitude ?? null,
|
||||
geo_longitude: node.geo_longitude ?? null,
|
||||
geo_manual_override: node.geo_manual_override,
|
||||
relay_bind_port: node.relay_bind_port,
|
||||
relay_vhost_http_port: node.relay_vhost_http_port,
|
||||
relay_web_server_enabled: enabled,
|
||||
}),
|
||||
onSuccess: async () => {
|
||||
toast.success('FRPS WebUI 设置已更新');
|
||||
await queryClient.invalidateQueries({ queryKey: nodesQueryKey });
|
||||
},
|
||||
onError: (error) => toast.error(getErrorMessage(error)),
|
||||
});
|
||||
|
||||
const forceSyncMutation = useMutation({
|
||||
mutationFn: () => NodeService.requestForceSync(node.id),
|
||||
onSuccess: async (updated) => {
|
||||
toast.success(`已向中继节点 ${updated.name} 下发强制同步指令`);
|
||||
await queryClient.invalidateQueries({ queryKey: nodesQueryKey });
|
||||
},
|
||||
onError: (error) => toast.error(getErrorMessage(error)),
|
||||
});
|
||||
|
||||
const upgradeMutation = useMutation({
|
||||
mutationFn: ({
|
||||
release,
|
||||
channel,
|
||||
}: {
|
||||
release: NodeAgentReleaseInfo | null;
|
||||
channel: ReleaseChannel;
|
||||
}) =>
|
||||
NodeService.requestAgentUpdate(node.id, {
|
||||
channel: release?.channel ?? channel,
|
||||
tag_name: release?.channel === 'preview' ? release.tag_name || undefined : undefined,
|
||||
}),
|
||||
onSuccess: async (updated) => {
|
||||
toast.success(
|
||||
`已向中继节点 ${updated.name} 下发${updated.update_channel === 'preview' ? '预览版' : '正式版'}升级指令`,
|
||||
);
|
||||
setUpgradeOpen(false);
|
||||
await queryClient.invalidateQueries({ queryKey: nodesQueryKey });
|
||||
},
|
||||
onError: (error) => toast.error(getErrorMessage(error)),
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: () => NodeService.deleteNode(node.id),
|
||||
onSuccess: async () => {
|
||||
toast.success('中继节点已删除');
|
||||
await queryClient.invalidateQueries({ queryKey: nodesQueryKey });
|
||||
router.push('/openflare/nodes');
|
||||
},
|
||||
onError: (error) => toast.error(getErrorMessage(error)),
|
||||
});
|
||||
|
||||
const handleRefresh = () => {
|
||||
void Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: nodesQueryKey }),
|
||||
queryClient.invalidateQueries({ queryKey: ['openflare', 'node-observability', node.id] }),
|
||||
]);
|
||||
};
|
||||
|
||||
const webUiUrl =
|
||||
node.relay_web_server_enabled && node.relay_bind_port
|
||||
? `http://${node.ip || '127.0.0.1'}:${node.relay_bind_port + 500}`
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div className="py-6 px-1 space-y-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="ghost" size="sm" className="h-8 px-2" asChild>
|
||||
<Link href="/openflare/nodes">
|
||||
<ArrowLeft className="size-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">{node.name}</h1>
|
||||
<NodeStatusBadge
|
||||
label={getNodeStatusLabel(node.status)}
|
||||
tone={getNodeStatusTone(node.status)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => setEditorOpen(true)}>
|
||||
编辑
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={handleRefresh}>
|
||||
<RefreshCw className="size-3.5 mr-1" />
|
||||
刷新
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 text-xs"
|
||||
disabled={forceSyncMutation.isPending}
|
||||
onClick={() => forceSyncMutation.mutate()}
|
||||
>
|
||||
<RotateCcw className="size-3.5 mr-1" />
|
||||
{forceSyncMutation.isPending ? '同步中...' : '强制同步'}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="h-7 text-xs"
|
||||
onClick={() => setUpgradeOpen(true)}
|
||||
>
|
||||
<Upload className="size-3.5 mr-1" />
|
||||
{node.update_requested ? '查看升级' : '升级 Relay'}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 text-xs text-destructive hover:text-destructive"
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
>
|
||||
<Trash2 className="size-3.5 mr-1" />
|
||||
删除
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>节点 ID</CardDescription>
|
||||
<CardTitle className="text-sm font-medium break-all">{node.node_id}</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>Relay 版本</CardDescription>
|
||||
<CardTitle className="text-sm font-medium">{node.version || 'unknown'}</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>frps 核心版本</CardDescription>
|
||||
<CardTitle className="text-sm font-medium">{node.ext_version || 'unknown'}</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>最近心跳</CardDescription>
|
||||
<CardTitle className="text-sm font-medium">
|
||||
{isWSConnectedLastSeen(node.last_seen_at)
|
||||
? 'WS 已连接'
|
||||
: isMeaningfulTime(node.last_seen_at)
|
||||
? formatRelativeTime(node.last_seen_at)
|
||||
: '暂无'}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 xl:grid-cols-2">
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base font-semibold">中继网络</CardTitle>
|
||||
<CardDescription>隧道中继节点 (tunnel_relay / frps)</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3 text-sm">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">运行状态</span>
|
||||
<NodeStatusBadge
|
||||
label={getNodeStatusLabel(node.status)}
|
||||
tone={getNodeStatusTone(node.status)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">中继健康</span>
|
||||
<NodeStatusBadge
|
||||
label={getRelayStatusLabel(node.relay_status)}
|
||||
tone={getRelayStatusTone(node.relay_status)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">绑定控制端口</span>
|
||||
<span>{node.relay_bind_port || '—'}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">VHost HTTP 端口</span>
|
||||
<span>{node.relay_vhost_http_port || '—'}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">Agent 接入地址</span>
|
||||
<span className="text-right break-all">{node.relay_agent_access_addr || '—'}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">活动连接 / 代理数</span>
|
||||
<span>
|
||||
{node.relay_frps_connections ?? '—'} / {node.relay_frps_proxy_count ?? '—'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">IP 地址</span>
|
||||
<span>
|
||||
{node.ip || '—'}
|
||||
{node.ip_manual_override ? '(已锁定)' : ''}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">最近应用</span>
|
||||
<NodeStatusBadge
|
||||
label={getApplyLabel(node.latest_apply_result)}
|
||||
tone={getApplyTone(node.latest_apply_result)}
|
||||
/>
|
||||
</div>
|
||||
{node.last_error ? (
|
||||
<div className="rounded-lg border border-destructive/20 bg-destructive/5 p-3 text-destructive">
|
||||
{node.last_error}
|
||||
</div>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="flex-row items-center justify-between space-y-0">
|
||||
<div>
|
||||
<CardTitle className="text-base font-semibold">FRPS WebUI</CardTitle>
|
||||
<CardDescription>控制 frps 内置 Web 管理界面是否启用</CardDescription>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" className="h-7 text-xs" asChild>
|
||||
<Link href={`/openflare/apply-logs?node_id=${encodeURIComponent(node.node_id)}`}>
|
||||
<FileText className="size-3.5 mr-1" />
|
||||
应用记录
|
||||
</Link>
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between rounded-lg border px-3 py-3">
|
||||
<div className="space-y-1">
|
||||
<Label>启用 Web 管理界面</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
默认监听绑定端口 + 500,例如 {node.relay_bind_port || 7000} →{' '}
|
||||
{(node.relay_bind_port || 7000) + 500}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={node.relay_web_server_enabled}
|
||||
disabled={webServerMutation.isPending}
|
||||
onCheckedChange={(checked) => webServerMutation.mutate(checked)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{webUiUrl ? (
|
||||
<a
|
||||
href={webUiUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="inline-flex items-center text-sm text-primary hover:underline"
|
||||
>
|
||||
打开 FRPS WebUI
|
||||
<ExternalLink className="size-3 ml-1" />
|
||||
</a>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">WebUI 已禁用或未配置绑定端口。</p>
|
||||
)}
|
||||
|
||||
<div className="space-y-2 text-sm text-muted-foreground">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span>创建时间</span>
|
||||
<span>{formatDateTime(node.created_at)}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span>更新时间</span>
|
||||
<span>{formatDateTime(node.updated_at)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<InstallCommand node={node} variant="relay" />
|
||||
|
||||
<NodeObservability nodeId={node.id} connectionHint="中继承载活动连接数" />
|
||||
|
||||
<NodeEditorDialog
|
||||
open={editorOpen}
|
||||
node={node}
|
||||
submitting={saveMutation.isPending}
|
||||
onClose={() => setEditorOpen(false)}
|
||||
onSubmit={async (payload) => {
|
||||
await saveMutation.mutateAsync(payload);
|
||||
}}
|
||||
/>
|
||||
|
||||
<AgentUpdateDialog
|
||||
open={upgradeOpen}
|
||||
node={node}
|
||||
submitting={upgradeMutation.isPending}
|
||||
onClose={() => setUpgradeOpen(false)}
|
||||
onConfirm={async (release, channel) => {
|
||||
await upgradeMutation.mutateAsync({ release, channel });
|
||||
}}
|
||||
/>
|
||||
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>确认删除中继节点</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
确认删除中继节点「{node.name}」吗?删除后该节点需要重新创建并重新接入。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleteMutation.isPending}>取消</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-white hover:bg-destructive/90"
|
||||
disabled={deleteMutation.isPending}
|
||||
onClick={() => deleteMutation.mutate()}
|
||||
>
|
||||
{deleteMutation.isPending ? '删除中...' : '确认删除'}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import {useRouter} from 'next/navigation';
|
||||
import {useMutation, useQueryClient} from '@tanstack/react-query';
|
||||
import {useState} from 'react';
|
||||
import {ArrowLeft, FileText, RefreshCw, RotateCcw, Trash2, Upload,} from 'lucide-react';
|
||||
import {toast} from 'sonner';
|
||||
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import {Button} from '@/components/ui/button';
|
||||
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from '@/components/ui/card';
|
||||
import {formatDateTime} from '@/lib/utils';
|
||||
import type {NodeAgentReleaseInfo, NodeItem, ReleaseChannel} from '@/lib/services/openflare';
|
||||
import {NodeService} from '@/lib/services/openflare';
|
||||
|
||||
import {AgentUpdateDialog} from './agent-update-dialog';
|
||||
import {InstallCommand} from './install-command';
|
||||
import {NodeEditorDialog} from './node-editor-dialog';
|
||||
import {NodeObservability} from './node-observability';
|
||||
import {NodeStatusBadge} from './node-status-badge';
|
||||
import {
|
||||
formatRelativeTime,
|
||||
getApplyLabel,
|
||||
getApplyTone,
|
||||
getErrorMessage,
|
||||
getFlaredStatusLabel,
|
||||
getFlaredStatusTone,
|
||||
getNodeStatusLabel,
|
||||
getNodeStatusTone,
|
||||
isMeaningfulTime,
|
||||
isWSConnectedLastSeen,
|
||||
} from './node-utils';
|
||||
|
||||
const nodesQueryKey = ['openflare', 'nodes'];
|
||||
|
||||
export function TunnelNodeDetail({ node }: { node: NodeItem }) {
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const [editorOpen, setEditorOpen] = useState(false);
|
||||
const [upgradeOpen, setUpgradeOpen] = useState(false);
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (payload: Parameters<typeof NodeService.updateNode>[1]) =>
|
||||
NodeService.updateNode(node.id, payload),
|
||||
onSuccess: async () => {
|
||||
toast.success('隧道节点已更新');
|
||||
setEditorOpen(false);
|
||||
await queryClient.invalidateQueries({ queryKey: nodesQueryKey });
|
||||
},
|
||||
onError: (error) => toast.error(getErrorMessage(error)),
|
||||
});
|
||||
|
||||
const forceSyncMutation = useMutation({
|
||||
mutationFn: () => NodeService.requestForceSync(node.id),
|
||||
onSuccess: async (updated) => {
|
||||
toast.success(`已向隧道节点 ${updated.name} 下发强制同步指令`);
|
||||
await queryClient.invalidateQueries({ queryKey: nodesQueryKey });
|
||||
},
|
||||
onError: (error) => toast.error(getErrorMessage(error)),
|
||||
});
|
||||
|
||||
const upgradeMutation = useMutation({
|
||||
mutationFn: ({
|
||||
release,
|
||||
channel,
|
||||
}: {
|
||||
release: NodeAgentReleaseInfo | null;
|
||||
channel: ReleaseChannel;
|
||||
}) =>
|
||||
NodeService.requestAgentUpdate(node.id, {
|
||||
channel: release?.channel ?? channel,
|
||||
tag_name: release?.channel === 'preview' ? release.tag_name || undefined : undefined,
|
||||
}),
|
||||
onSuccess: async (updated) => {
|
||||
toast.success(
|
||||
`已向隧道节点 ${updated.name} 下发${updated.update_channel === 'preview' ? '预览版' : '正式版'}升级指令`,
|
||||
);
|
||||
setUpgradeOpen(false);
|
||||
await queryClient.invalidateQueries({ queryKey: nodesQueryKey });
|
||||
},
|
||||
onError: (error) => toast.error(getErrorMessage(error)),
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: () => NodeService.deleteNode(node.id),
|
||||
onSuccess: async () => {
|
||||
toast.success('隧道节点已删除');
|
||||
await queryClient.invalidateQueries({ queryKey: nodesQueryKey });
|
||||
router.push('/openflare/nodes');
|
||||
},
|
||||
onError: (error) => toast.error(getErrorMessage(error)),
|
||||
});
|
||||
|
||||
const handleRefresh = () => {
|
||||
void Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: nodesQueryKey }),
|
||||
queryClient.invalidateQueries({ queryKey: ['openflare', 'node-observability', node.id] }),
|
||||
]);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="py-6 px-1 space-y-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="ghost" size="sm" className="h-8 px-2" asChild>
|
||||
<Link href="/openflare/nodes">
|
||||
<ArrowLeft className="size-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">{node.name}</h1>
|
||||
<NodeStatusBadge
|
||||
label={getNodeStatusLabel(node.status)}
|
||||
tone={getNodeStatusTone(node.status)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => setEditorOpen(true)}>
|
||||
编辑
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={handleRefresh}>
|
||||
<RefreshCw className="size-3.5 mr-1" />
|
||||
刷新
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 text-xs"
|
||||
disabled={forceSyncMutation.isPending}
|
||||
onClick={() => forceSyncMutation.mutate()}
|
||||
>
|
||||
<RotateCcw className="size-3.5 mr-1" />
|
||||
{forceSyncMutation.isPending ? '同步中...' : '强制同步'}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="h-7 text-xs"
|
||||
onClick={() => setUpgradeOpen(true)}
|
||||
>
|
||||
<Upload className="size-3.5 mr-1" />
|
||||
{node.update_requested ? '查看升级' : '升级 openflared'}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 text-xs text-destructive hover:text-destructive"
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
>
|
||||
<Trash2 className="size-3.5 mr-1" />
|
||||
删除
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>节点 ID</CardDescription>
|
||||
<CardTitle className="text-sm font-medium break-all">{node.node_id}</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>openflared 版本</CardDescription>
|
||||
<CardTitle className="text-sm font-medium">{node.version || 'unknown'}</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>当前配置版本</CardDescription>
|
||||
<CardTitle className="text-sm font-medium">{node.current_version || '未应用'}</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>最近心跳</CardDescription>
|
||||
<CardTitle className="text-sm font-medium">
|
||||
{isWSConnectedLastSeen(node.last_seen_at)
|
||||
? 'WS 已连接'
|
||||
: isMeaningfulTime(node.last_seen_at)
|
||||
? formatRelativeTime(node.last_seen_at)
|
||||
: '暂无'}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 xl:grid-cols-2">
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base font-semibold">隧道客户端</CardTitle>
|
||||
<CardDescription>隧道客户端节点 (tunnel_client / openflared)</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3 text-sm">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">运行状态</span>
|
||||
<NodeStatusBadge
|
||||
label={getNodeStatusLabel(node.status)}
|
||||
tone={getNodeStatusTone(node.status)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">flared 状态</span>
|
||||
<NodeStatusBadge
|
||||
label={getFlaredStatusLabel(node)}
|
||||
tone={getFlaredStatusTone(node)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">Tunnel Token</span>
|
||||
<span className="text-right break-all max-w-[60%]">
|
||||
{node.access_token || '暂无'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">IP 地址</span>
|
||||
<span>
|
||||
{node.ip || '—'}
|
||||
{node.ip_manual_override ? '(已锁定)' : ''}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">最近应用</span>
|
||||
<NodeStatusBadge
|
||||
label={getApplyLabel(node.latest_apply_result)}
|
||||
tone={getApplyTone(node.latest_apply_result)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">自动更新</span>
|
||||
<span>{node.auto_update_enabled ? '已启用' : '手动'}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">创建时间</span>
|
||||
<span>{formatDateTime(node.created_at)}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">更新时间</span>
|
||||
<span>{formatDateTime(node.updated_at)}</span>
|
||||
</div>
|
||||
{node.last_error ? (
|
||||
<div className="rounded-lg border border-destructive/20 bg-destructive/5 p-3 text-destructive">
|
||||
{node.last_error}
|
||||
</div>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="flex-row items-center justify-between space-y-0">
|
||||
<div>
|
||||
<CardTitle className="text-base font-semibold">同步状态</CardTitle>
|
||||
<CardDescription>配置追平与应用结果</CardDescription>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" className="h-7 text-xs" asChild>
|
||||
<Link href={`/openflare/apply-logs?node_id=${encodeURIComponent(node.node_id)}`}>
|
||||
<FileText className="size-3.5 mr-1" />
|
||||
应用记录
|
||||
</Link>
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3 text-sm">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">最近应用结果</span>
|
||||
<NodeStatusBadge
|
||||
label={getApplyLabel(node.latest_apply_result)}
|
||||
tone={getApplyTone(node.latest_apply_result)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">最近应用时间</span>
|
||||
<span>
|
||||
{isMeaningfulTime(node.latest_apply_at) && node.latest_apply_at
|
||||
? `${formatRelativeTime(node.latest_apply_at)} · ${formatDateTime(node.latest_apply_at)}`
|
||||
: '暂无'}
|
||||
</span>
|
||||
</div>
|
||||
{node.latest_apply_checksum ? (
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">同步文件数</span>
|
||||
<span>{node.latest_support_file_count} 个</span>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">升级状态</span>
|
||||
<NodeStatusBadge
|
||||
label={
|
||||
node.update_requested
|
||||
? node.update_channel === 'preview'
|
||||
? '等待预览更新'
|
||||
: '等待更新'
|
||||
: '未下发'
|
||||
}
|
||||
tone={node.update_requested ? 'warning' : 'info'}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-muted-foreground">最近心跳详情</span>
|
||||
<span className="text-right">
|
||||
{isWSConnectedLastSeen(node.last_seen_at)
|
||||
? 'WebSocket 长连接已建立'
|
||||
: isMeaningfulTime(node.last_seen_at)
|
||||
? formatDateTime(node.last_seen_at)
|
||||
: '暂无'}
|
||||
</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<InstallCommand node={node} variant="tunnel" />
|
||||
|
||||
<NodeObservability nodeId={node.id} connectionHint="隧道并发连接数" />
|
||||
|
||||
<NodeEditorDialog
|
||||
open={editorOpen}
|
||||
node={node}
|
||||
submitting={saveMutation.isPending}
|
||||
onClose={() => setEditorOpen(false)}
|
||||
onSubmit={async (payload) => {
|
||||
await saveMutation.mutateAsync(payload);
|
||||
}}
|
||||
/>
|
||||
|
||||
<AgentUpdateDialog
|
||||
open={upgradeOpen}
|
||||
node={node}
|
||||
submitting={upgradeMutation.isPending}
|
||||
onClose={() => setUpgradeOpen(false)}
|
||||
onConfirm={async (release, channel) => {
|
||||
await upgradeMutation.mutateAsync({ release, channel });
|
||||
}}
|
||||
/>
|
||||
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>确认删除隧道节点</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
确认删除隧道节点「{node.name}」吗?删除后该节点需要重新创建并重新接入。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleteMutation.isPending}>取消</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-white hover:bg-destructive/90"
|
||||
disabled={deleteMutation.isPending}
|
||||
onClick={() => deleteMutation.mutate()}
|
||||
>
|
||||
{deleteMutation.isPending ? '删除中...' : '确认删除'}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user