feat: implement internet path functionality with backend support

Added internet path settings and snapshot management to the application. This includes new database tables for internet path settings and snapshots, API routes for fetching and managing internet path data, and integration into the dashboard and data collection pages. Enhanced the scheduler to support internet path jobs, ensuring regular data collection and updates. Updated relevant types and interfaces to accommodate the new functionality.
This commit is contained in:
Denozordec
2026-05-08 00:40:41 +07:00
parent 11ad94f67d
commit b9a75b6831
15 changed files with 1740 additions and 14 deletions
+164 -2
View File
@@ -10,6 +10,7 @@ import { StatusBadge } from "@/components/status-badge"
import { Sparkline } from "@/components/sparkline"
import { LatencyChart } from "@/components/dashboard/latency-chart"
import { BandwidthChart } from "@/components/dashboard/bandwidth-chart"
import { InternetPathMapCard } from "@/components/dashboard/internet-path-map"
import {
servers as mockServers,
pingProbes,
@@ -18,6 +19,7 @@ import {
serverFilterRulesets,
} from "@/lib/data"
import type { PingProbe, Server, ServerStatus, ServerType } from "@/lib/data"
import type { GreTunnel } from "@/lib/data"
import { useDataSource } from "@/lib/data-source"
import { Flag } from "@/components/flag"
import { AlertCircleIcon, AlertTriangleIcon, InfoIcon, FilterIcon, DownloadIcon } from "lucide-react"
@@ -25,6 +27,13 @@ import { Button, buttonVariants } from "@/components/ui/button"
import { cn } from "@/lib/utils"
import { requestJson } from "@/shared/api/http-client"
import { buildLatencySeriesByProbeSource } from "@/lib/dashboard-latency"
import {
buildDashboardInternetPath,
type HomeWanRuntime,
resolveDefaultRouteLookup,
type InternetPathViewModel,
} from "@/lib/dashboard-internet-path"
import type { FiltersRulesetRow, RouteOptimizerSpeedProbe } from "@/lib/route-optimizer-data"
import { listEvents } from "@/shared/api/events"
import type { EventItem } from "@/packages/contracts/src/events"
@@ -135,9 +144,85 @@ interface BackendServerRow {
os: string | null
model: string | null
sessions?: number
wanUplinks?: Array<{
id: string
name: string
isp: string
iface: string
ip: string
maxDl: number
maxUl: number
}>
}
interface ApiGreTunnelRow {
id: string
name: string
serverId: string
localAddress: string
remoteAddress: string
localInnerIp: string
remoteInnerIp: string
poolId: string
ipsec: null
mtu: number
keepaliveInterval: number
keepaliveRetries: number
dscp: "inherit" | number
clampTcpMss: boolean
allowFastPath: boolean
comment: string
enabled: boolean
status: "up" | "down" | "degraded"
}
interface InternetPathSnapshotPayload {
sampledAt: string
servers: BackendServerRow[]
greTunnels: ApiGreTunnelRow[]
filtersRulesets: FiltersRulesetRow[]
speedProbes: RouteOptimizerSpeedProbe[]
routeLookupByServerId: Record<string, { gateway: string | null; routingMark: string | null } | null>
wanRuntimeByHomeId: Record<string, HomeWanRuntime | null>
}
function apiGreToGreTunnel(t: ApiGreTunnelRow): GreTunnel {
return {
id: t.id,
name: t.name,
serverId: String(t.serverId),
localAddress: t.localAddress,
remoteAddress: t.remoteAddress,
localInnerIp: t.localInnerIp,
remoteInnerIp: t.remoteInnerIp,
poolId: t.poolId || "live",
ipsec: null,
mtu: t.mtu,
keepaliveInterval: t.keepaliveInterval,
keepaliveRetries: t.keepaliveRetries,
dscp: t.dscp,
clampTcpMss: t.clampTcpMss,
allowFastPath: t.allowFastPath,
comment: t.comment,
enabled: t.enabled,
status: t.status,
}
}
function mapBackendToServer(s: BackendServerRow): Server {
const wanUplinks = Array.isArray(s.wanUplinks)
? s.wanUplinks
.filter((w) => typeof w === "object" && w != null)
.map((w, idx) => ({
id: String(w.id || `wan-${s.id}-${idx + 1}`),
name: String(w.name || `WAN${idx + 1}`),
isp: String(w.isp || "—"),
iface: String(w.iface || ""),
ip: String(w.ip || ""),
maxDl: Math.max(1, Math.round(Number(w.maxDl) || 100)),
maxUl: Math.max(1, Math.round(Number(w.maxUl) || 100)),
}))
: []
return {
id: String(s.id),
name: s.name || s.host,
@@ -152,6 +237,7 @@ function mapBackendToServer(s: BackendServerRow): Server {
status: (s.status ?? "offline") as ServerStatus,
latency: s.latency != null ? Math.round(s.latency) : null,
sessions: s.sessions ?? 0,
wanUplinks,
}
}
@@ -215,6 +301,9 @@ export default function DashboardPage() {
const [recentEvents, setRecentEvents] = useState<EventItem[]>([])
const [eventsLoading, setEventsLoading] = useState(false)
const [eventsError, setEventsError] = useState<string | null>(null)
const [internetPath, setInternetPath] = useState<InternetPathViewModel | null>(null)
const [internetPathLoading, setInternetPathLoading] = useState(false)
const [internetPathError, setInternetPathError] = useState<string | null>(null)
const probeServerCatalog = useMemo(() => {
if (!isLive) return mockServers
@@ -224,20 +313,26 @@ export default function DashboardPage() {
const fetchProbes = useCallback(async (silent: boolean) => {
if (!isLive) return
if (!silent) setProbesLoading(true)
if (!silent) setInternetPathLoading(true)
try {
const overview = await apiFetch<{ probes: PingProbe[] }>("/api/uptime/overview?range=1h")
setLiveProbes(overview.probes)
setProbesError(null)
setInternetPathError(null)
let serversMapped: Server[] = []
try {
const backendServers = await apiFetch<BackendServerRow[]>("/api/servers")
setLiveServersResolved(backendServers.map(mapBackendToServer))
serversMapped = backendServers.map(mapBackendToServer)
setLiveServersResolved(serversMapped)
} catch {
serversMapped = []
setLiveServersResolved([])
}
const [fr, br] = await Promise.allSettled([
const [fr, br, ipRes] = await Promise.allSettled([
apiFetch<{ rulesets: Array<{ rules?: unknown[] }> }>("/api/filters/rules"),
apiFetch<Array<{ state?: string; prefixesRx?: number }>>("/api/bgp/sessions"),
apiFetch<{ snapshot: InternetPathSnapshotPayload | null }>("/api/internet-path/latest"),
])
let filtersPart: LiveKpiSnapshot["filters"] = null
@@ -263,16 +358,69 @@ export default function DashboardPage() {
}
setLiveKpi({ filters: filtersPart, bgp: bgpPart })
if (serversMapped.length > 0) {
const snap = ipRes.status === "fulfilled" ? ipRes.value.snapshot : null
if (snap) {
const snapshotServers = snap.servers.map(mapBackendToServer)
setInternetPath(buildDashboardInternetPath({
servers: snapshotServers,
greTunnels: (snap.greTunnels ?? []).map(apiGreToGreTunnel),
probes: snap.speedProbes ?? [],
filtersRulesets: snap.filtersRulesets ?? [],
routeLookupByServerId: snap.routeLookupByServerId ?? {},
wanRuntimeByHomeId: snap.wanRuntimeByHomeId ?? {},
}))
} else {
const filterRulesets: FiltersRulesetRow[] =
fr.status === "fulfilled"
? (fr.value.rulesets as FiltersRulesetRow[] ?? [])
: []
const homes = serversMapped.filter((s) => s.type === "home-router")
const lookups = await Promise.all(
homes.map(async (h) => ({
id: h.id,
lookup: await resolveDefaultRouteLookup(apiFetch, h.id),
})),
)
const wanRuntimeRows = await Promise.all(
homes.map(async (h) => {
try {
const rt = await apiFetch<HomeWanRuntime>(`/api/servers/${h.id}/wan-runtime`)
return { id: h.id, runtime: rt }
} catch {
return { id: h.id, runtime: null }
}
}),
)
const speedRes = await apiFetch<{ probes?: RouteOptimizerSpeedProbe[] }>("/api/uptime/speed-probes").catch(() => ({ probes: [] }))
const greRes = await apiFetch<{ tunnels?: ApiGreTunnelRow[] }>("/api/filters/gre-tunnels").catch(() => ({ tunnels: [] }))
const lookupById = Object.fromEntries(lookups.map((x) => [x.id, x.lookup]))
const wanRuntimeById = Object.fromEntries(wanRuntimeRows.map((x) => [x.id, x.runtime]))
setInternetPath(buildDashboardInternetPath({
servers: serversMapped,
greTunnels: (greRes.tunnels ?? []).map(apiGreToGreTunnel),
probes: speedRes.probes ?? [],
filtersRulesets: filterRulesets,
routeLookupByServerId: lookupById,
wanRuntimeByHomeId: wanRuntimeById,
}))
}
} else {
setInternetPath(null)
}
} catch (e) {
const msg = e instanceof Error ? e.message : "Не удалось загрузить пробы"
setProbesError(msg)
setLiveKpi(null)
setInternetPathError(msg)
if (!silent) {
setLiveProbes(null)
setLiveServersResolved(null)
setInternetPath(null)
}
} finally {
if (!silent) setProbesLoading(false)
if (!silent) setInternetPathLoading(false)
}
}, [apiFetch, isLive])
@@ -302,6 +450,8 @@ export default function DashboardPage() {
setLiveServersResolved(null)
setLiveKpi(null)
setProbesError(null)
setInternetPath(null)
setInternetPathError(null)
})
return
}
@@ -807,6 +957,18 @@ export default function DashboardPage() {
</Card>
</div>
<div className="grid grid-cols-1 gap-4">
{internetPathError && isLive && (
<div className="text-sm text-destructive">{internetPathError}</div>
)}
{internetPathLoading && isLive && !internetPath && (
<div className="h-24 rounded-md bg-muted/40 animate-pulse" />
)}
{(!isLive || internetPath || !internetPathLoading) && (
<InternetPathMapCard model={internetPath} />
)}
</div>
{/* Ping probes table */}
<Card>
<CardHeader className="pb-2">