Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d174bca5d6 | ||
|
|
2ca40fbb4d | ||
|
|
589fc782f9 | ||
|
|
fcbf219725 | ||
|
|
95a0ebeb18 | ||
|
|
2b0b9a5fa5 | ||
|
|
9b2c2327a6 | ||
|
|
ec2fb54e04 |
No files matched your search
@@ -22,7 +22,7 @@ export default function MainLayout({ children }: { children: ReactNode }) {
|
||||
К содержимому
|
||||
</a>
|
||||
<AppSidebar />
|
||||
<SidebarInset tabIndex={-1} id="main-content" className="h-svh overflow-hidden md:h-[calc(100svh-1rem)] md:peer-data-[variant=inset]:rounded-[calc(var(--radius)*1.6)] md:peer-data-[variant=inset]:border">
|
||||
<SidebarInset tabIndex={-1} id="main-content" className="h-svh overflow-hidden">
|
||||
{children}
|
||||
</SidebarInset>
|
||||
<CommandPalette />
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useMemo, useEffect, type ReactNode } from "react"
|
||||
import { Suspense, useState, useMemo, useEffect, type ReactNode } from "react"
|
||||
import Link from "next/link"
|
||||
import { useSearchParams } from "next/navigation"
|
||||
import { Alert, AlertTitle, AlertDescription } from "@/components/reui/alert"
|
||||
import { peakOfCombinedTraffic, projectTrafficObservations, sumObservedTraffic, type TrafficObservationMeta } from "@/lib/traffic-observations"
|
||||
import { projectTrafficBindingStatus } from "@/lib/traffic-binding-status"
|
||||
@@ -13,13 +15,13 @@ import { SectionFrame, ToneBadge, type Tone } from "@/components/reui-kit/ops-bl
|
||||
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
|
||||
import { TrafficMiniChart } from "@/components/reui-kit/traffic-mini-chart"
|
||||
import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
import { Sparkline } from "@/components/sparkline"
|
||||
import { StatusDot } from "@/components/status-dot"
|
||||
import { Flag } from "@/components/flag"
|
||||
import {
|
||||
RefreshCwIcon, TrendingUpIcon, ChartPieIcon,
|
||||
ArrowUpIcon, ArrowDownIcon, ActivityIcon, UsersIcon, CableIcon, ServerIcon, SearchIcon, GitBranchIcon, PlusIcon,
|
||||
ArrowUpIcon, ArrowDownIcon, ActivityIcon, UsersIcon, CableIcon, ServerIcon, SearchIcon, GitBranchIcon, PlusIcon, MapIcon,
|
||||
} from "lucide-react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { fmtGiB, fmtRate } from "@/lib/fmt-rate"
|
||||
@@ -37,6 +39,7 @@ import { Badge } from "@/components/reui/badge"
|
||||
import {
|
||||
IFACE_TYPE_LABEL,
|
||||
INIT_USERS,
|
||||
MOCK_IFACE_CATALOG,
|
||||
ROLE_LABEL,
|
||||
type InterfaceType,
|
||||
} from "@/lib/users"
|
||||
@@ -338,6 +341,7 @@ const TRAFFIC_RANGE_LABELS: Record<(typeof TRAFFIC_RANGE_KEYS)[number], string>
|
||||
|
||||
type GroupMode = "servers" | "users" | "ifaces" | "flows"
|
||||
type FlowScope = "servers" | "users"
|
||||
const ALL_EXPORTERS = "__all_exporters__"
|
||||
type SortField = "rx" | "tx" | "name" | "sessions"
|
||||
type SortDir = "asc" | "desc"
|
||||
|
||||
@@ -671,7 +675,7 @@ function ServerDetail({
|
||||
</div>
|
||||
</DetailHeader>
|
||||
<TrafficObservationStatus observations={sel.observations} unknown={sel.rxNow == null || sel.txNow == null} />
|
||||
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
|
||||
<TrafficRxTxChart key={range} rx={sel.rxSeries} tx={sel.txSeries} range={range} scrub embedded />
|
||||
<KvStats
|
||||
label="Скорость выбранного сервера"
|
||||
items={[
|
||||
@@ -703,7 +707,7 @@ function UserDetail({ sel, range, setRange }: { sel: UserTraffic; range: Range;
|
||||
<OfflinePlaceholder text="Нет привязанных интерфейсов у этого пользователя" />
|
||||
) : (
|
||||
<>
|
||||
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
|
||||
<TrafficRxTxChart key={range} rx={sel.rxSeries} tx={sel.txSeries} range={range} scrub embedded />
|
||||
<KvStats
|
||||
label="Скорость выбранного клиента"
|
||||
items={[
|
||||
@@ -742,7 +746,7 @@ function IfaceDetail({ sel, range, setRange }: { sel: BoundIfaceTraffic; range:
|
||||
<Flag code={sel.serverCountry} />{sel.serverSite}
|
||||
</span>
|
||||
</DetailHeader>
|
||||
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
|
||||
<TrafficRxTxChart key={range} rx={sel.rxSeries} tx={sel.txSeries} range={range} scrub embedded />
|
||||
<KvStats
|
||||
label="Скорость выбранного интерфейса"
|
||||
items={[
|
||||
@@ -818,6 +822,38 @@ const toLiveUser = (u: UserTraffic & { interfaces?: BoundIfaceTraffic[] }): User
|
||||
}
|
||||
|
||||
export default function TrafficPage() {
|
||||
return <Suspense fallback={<p role="status" className="p-4 text-sm">Загрузка трафика…</p>}><TrafficRoute /></Suspense>
|
||||
}
|
||||
|
||||
function TrafficRoute() {
|
||||
const params = useSearchParams()
|
||||
const read = (name: string, limit: number) => {
|
||||
const value = params.get(name)?.trim()
|
||||
return value && value.length <= limit ? value : undefined
|
||||
}
|
||||
const user = read("user", 128), server = read("server", 64)
|
||||
const service = read("service", 200)
|
||||
const map = new URLSearchParams()
|
||||
const ix = params.get("mapView") === "ix"
|
||||
if (ix) map.set("filter", "ix-node")
|
||||
const mapUser = read("mapUser", 128) ?? user
|
||||
if (mapUser) map.set("user", mapUser)
|
||||
const serviceId = read("serviceId", 240)
|
||||
if (serviceId) {
|
||||
map.set("service", serviceId)
|
||||
if (serviceId.startsWith("cc:")) map.set("dest", "countries")
|
||||
}
|
||||
else if (server) map.set("server", server)
|
||||
const view: GroupMode = params.get("view") === "flows" ? "flows" : user ? "users" : "servers"
|
||||
const ids = (name: string) => (params.get(name) ?? "").slice(0, 4096).split(",").filter(id => /^[1-9]\d*$/.test(id))
|
||||
const exporters = view === "flows" && params.has("exporters") ? ids("exporters") : undefined
|
||||
return <TrafficContent key={params.toString()} view={view} user={user} server={server} service={service} country={read("country", 32)}
|
||||
exporters={exporters} mapNodes={params.has("nodes") ? ids("nodes") : undefined} returnHref={params.get("from") === "map" ? `/network-map${map.size ? `?${map}` : ""}` : undefined} />
|
||||
}
|
||||
|
||||
function TrafficContent({ view, user, server, service, country, exporters: mapExporters, mapNodes, returnHref }: {
|
||||
view: GroupMode; user?: string; server?: string; service?: string; country?: string; exporters?: string[]; mapNodes?: string[]; returnHref?: string
|
||||
}) {
|
||||
const { mode, backendUrl } = useDataSource()
|
||||
const isLive = mode === "live"
|
||||
const [trafficClock, setTrafficClock] = useState(() => Date.now())
|
||||
@@ -828,11 +864,13 @@ export default function TrafficPage() {
|
||||
}, [isLive])
|
||||
const apiFetch = useMemo(() => makeApiFetch(backendUrl), [backendUrl])
|
||||
|
||||
const [groupMode, setGroupMode] = useState<GroupMode>("servers")
|
||||
const [groupMode, setGroupMode] = useState<GroupMode>(view)
|
||||
const [sortField, setSortField] = useState<SortField>("rx")
|
||||
const [sortDir, setSortDir] = useState<SortDir>("desc")
|
||||
const [selectedId, setSelectedId] = useState("srv1")
|
||||
const [range, setRange] = useState<Range>("1h")
|
||||
const linkedId = view === "servers" ? server : user ?? server
|
||||
const [selectedId, setSelectedId] = useState(linkedId ?? (view === "flows" ? mapExporters ? "" : ALL_EXPORTERS : "srv1"))
|
||||
const keptLink = groupMode === view && selectedId === linkedId
|
||||
const [range, setRange] = useState<Range>(view === "flows" ? "5m" : "1h")
|
||||
const [search, setSearch] = useState("")
|
||||
const [trafficRetry, setTrafficRetry] = useState(0)
|
||||
const [liveRetry, setLiveRetry] = useState(0)
|
||||
@@ -854,7 +892,7 @@ export default function TrafficPage() {
|
||||
const [detailResult, setDetailResult] = useState<{ key: string; server: ServerTraffic | null; receivedAt?: number; error: string | null } | null>(null)
|
||||
const [liveUsers, setLiveUsers] = useState<UserTraffic[]>([])
|
||||
const [liveBoundIfaces, setLiveBoundIfaces] = useState<BoundIfaceTraffic[]>([])
|
||||
const [flowScope, setFlowScope] = useState<FlowScope>("servers")
|
||||
const [flowScope, setFlowScope] = useState<FlowScope>(user ? "users" : "servers")
|
||||
const [flowRetry, setFlowRetry] = useState(0)
|
||||
const flowKey = JSON.stringify([isLive, groupMode, backendUrl, range, flowScope, flowRetry])
|
||||
const [flowResult, setFlowResult] = useState<{ key: string; receivedAt?: number; monthlyServers?: ServerRead[]; stats?: FlowStatsDto; exporters?: FlowEntityCard[]; clients?: FlowEntityCard[]; cardWindow?: FlowStatsDto["sourceWindow"]; error?: string } | null>(null)
|
||||
@@ -868,7 +906,7 @@ export default function TrafficPage() {
|
||||
&& trafficClock - collectorReading.receivedAt > 35_000
|
||||
? { ...collectorReading.status, listenerBound: false, collectorCountersSource: "last-known" }
|
||||
: collectorReading.status
|
||||
const flowExporters = useMemo(() => currentFlows?.exporters ?? [], [currentFlows])
|
||||
const flowExporters = useMemo(() => (currentFlows?.exporters ?? []).filter(card => !mapExporters || mapExporters.includes(card.id)), [currentFlows, mapExporters])
|
||||
const flowClients = useMemo(() => currentFlows?.clients ?? [], [currentFlows])
|
||||
const [flowMonth, setFlowMonth] = useState(() => new Date().toISOString().slice(0, 7))
|
||||
const flowMonthValid = /^(?!0000)\d{4}-(0[1-9]|1[0-2])$/.test(flowMonth) && flowMonth <= new Date().toISOString().slice(0, 7)
|
||||
@@ -884,6 +922,7 @@ export default function TrafficPage() {
|
||||
const [overlayOpen, setOverlayOpen] = useState(false)
|
||||
const [catalogServers, setCatalogServers] = useState<ServerRead[]>([])
|
||||
const effectiveMode: GroupMode = groupMode
|
||||
const allExporters = !mapExporters && flowScope === "servers" && selectedId === ALL_EXPORTERS && range !== "30d"
|
||||
const detailKey = JSON.stringify([isLive, backendUrl, effectiveMode, selectedId, range, selectedIface, detailRetry])
|
||||
const currentDetail = detailResult?.key === detailKey ? detailResult : null
|
||||
const detailBusy = isLive && effectiveMode === "servers" && Boolean(selectedId) && currentDetail === null
|
||||
@@ -898,7 +937,7 @@ export default function TrafficPage() {
|
||||
range === "30d"
|
||||
? /^[1-9]\d*$/.test(selectedId) && Number.isSafeInteger(Number(selectedId)) && Boolean(currentFlows?.monthlyServers?.some(server => String(server.id) === selectedId))
|
||||
: flowScope === "servers"
|
||||
? /^[1-9]\d*$/.test(selectedId) && Number.isSafeInteger(Number(selectedId)) && flowExporters.some(card => card.id === selectedId)
|
||||
? allExporters || /^[1-9]\d*$/.test(selectedId) && Number.isSafeInteger(Number(selectedId)) && flowExporters.some(card => card.id === selectedId)
|
||||
: Boolean(selectedId) && flowClients.some(card => card.id === selectedId)
|
||||
)
|
||||
const flowLiveEnabled = confirmedFlowSelection && effectiveMode === "flows" && range === "5m"
|
||||
@@ -906,7 +945,7 @@ export default function TrafficPage() {
|
||||
enabled: flowLiveEnabled,
|
||||
backendUrl,
|
||||
range,
|
||||
serverId: flowScope === "servers" ? selectedId : undefined,
|
||||
serverId: flowScope === "servers" && !allExporters ? selectedId : undefined,
|
||||
userId: flowScope === "users" ? selectedId : undefined,
|
||||
iface: flowIface,
|
||||
dedup: flowDedup,
|
||||
@@ -939,6 +978,7 @@ export default function TrafficPage() {
|
||||
setLiveBoundIfaces(liveIfaces)
|
||||
setTrafficState({ key, status: "ready", receivedAt: Date.now(), peaks: srvRes.peaks })
|
||||
setSelectedId((prev) => {
|
||||
if (groupMode === view && prev === linkedId) return prev
|
||||
if (groupMode === "users") return mappedUsers.some((x) => x.id === prev) ? prev : (mappedUsers[0]?.id ?? "")
|
||||
if (groupMode === "ifaces") return liveIfaces.some((x) => x.id === prev) ? prev : (liveIfaces[0]?.id ?? "")
|
||||
return mapped.some((x) => x.id === prev) ? prev : (mapped[0]?.id ?? "")
|
||||
@@ -949,7 +989,7 @@ export default function TrafficPage() {
|
||||
}
|
||||
void loadLiveTraffic(range)
|
||||
return () => { cancelled = true }
|
||||
}, [apiFetch, isLive, groupMode, backendUrl, trafficRetry, range])
|
||||
}, [apiFetch, isLive, groupMode, backendUrl, trafficRetry, range, view, linkedId])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLive || groupMode !== "flows" || range === "30d") return
|
||||
@@ -979,8 +1019,9 @@ export default function TrafficPage() {
|
||||
if (range === "30d") {
|
||||
void listServers(backendUrl).then(servers => {
|
||||
if (cancelled) return
|
||||
setFlowResult({ key: flowKey, receivedAt: Date.now(), monthlyServers: servers })
|
||||
setSelectedId(prev => servers.some(server => String(server.id) === prev) ? prev : String(servers[0]?.id ?? ""))
|
||||
const available = mapExporters ? servers.filter(server => mapExporters.includes(String(server.id))) : servers
|
||||
setFlowResult({ key: flowKey, receivedAt: Date.now(), monthlyServers: available })
|
||||
setSelectedId(prev => available.some(server => String(server.id) === prev) ? prev : String(available[0]?.id ?? ""))
|
||||
}).catch(error => {
|
||||
if (!cancelled) setFlowResult({ key: flowKey, error: error instanceof Error ? error.message : "Не удалось загрузить каталог серверов" })
|
||||
})
|
||||
@@ -997,7 +1038,9 @@ export default function TrafficPage() {
|
||||
setFlowResult({ key: flowKey, receivedAt: Date.now(), stats, exporters: exporters.exporters, clients: clients.clients,
|
||||
cardWindow: flowScope === "users" ? clients.sourceWindow : exporters.sourceWindow })
|
||||
setSelectedId(prev => {
|
||||
const list = flowScope === "users" ? clients.clients : exporters.exporters
|
||||
const list = flowScope === "users" ? clients.clients : exporters.exporters.filter(card => !mapExporters || mapExporters.includes(card.id))
|
||||
if (flowScope === "servers" && (prev === ALL_EXPORTERS || mapExporters && !prev)) return prev
|
||||
if (flowScope === (user ? "users" : "servers") && prev === linkedId) return prev
|
||||
return list.some(x => x.id === prev) ? prev : (list[0]?.id ?? "")
|
||||
})
|
||||
}
|
||||
@@ -1005,7 +1048,7 @@ export default function TrafficPage() {
|
||||
if (!cancelled) setFlowResult({ key: flowKey, error: e instanceof Error ? e.message : "Не удалось загрузить потоки" })
|
||||
})
|
||||
return () => { cancelled = true }
|
||||
}, [isLive, effectiveMode, backendUrl, range, flowScope, flowKey])
|
||||
}, [isLive, effectiveMode, backendUrl, range, flowScope, flowKey, user, linkedId, mapExporters])
|
||||
|
||||
const analyticsKey = JSON.stringify([flowKey, selectedId, flowIface, flowDedup, flowExcludeMesh, flowExcludeOverlay, analyticsRetry, range === "30d" ? flowMonth : null])
|
||||
const currentAnalytics = analyticsResult?.key === analyticsKey ? analyticsResult : null
|
||||
@@ -1016,7 +1059,7 @@ export default function TrafficPage() {
|
||||
const request = range === "30d"
|
||||
? getFlowMonthly(backendUrl, { month: flowMonth, serverId: flowScope === "servers" ? selectedId : undefined }).then(monthly => ({ monthly }))
|
||||
: getFlowAnalytics(backendUrl, {
|
||||
range, serverId: flowScope === "servers" ? selectedId : undefined,
|
||||
range, serverId: flowScope === "servers" && !allExporters ? selectedId : undefined,
|
||||
userId: flowScope === "users" ? selectedId : undefined,
|
||||
iface: flowIface, dedup: flowDedup, excludeMesh: flowExcludeMesh, excludeOverlay: flowExcludeOverlay,
|
||||
}).then(data => ({ data }))
|
||||
@@ -1026,7 +1069,7 @@ export default function TrafficPage() {
|
||||
if (!cancelled) setAnalyticsResult({ key: analyticsKey, error: e instanceof Error ? e.message : "Не удалось загрузить аналитику" })
|
||||
})
|
||||
return () => { cancelled = true }
|
||||
}, [confirmedFlowSelection, isLive, effectiveMode, selectedId, range, flowScope, flowIface, flowDedup, flowExcludeMesh, flowExcludeOverlay, backendUrl, analyticsKey, flowMonth, flowMonthValid])
|
||||
}, [confirmedFlowSelection, isLive, effectiveMode, selectedId, range, flowScope, allExporters, flowIface, flowDedup, flowExcludeMesh, flowExcludeOverlay, backendUrl, analyticsKey, flowMonth, flowMonthValid])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLive) return
|
||||
@@ -1036,26 +1079,22 @@ export default function TrafficPage() {
|
||||
const activeServerTraffic = useMemo(() => isLive ? (trafficReady ? liveServers.map(s => ({ ...s, ...projectTrafficObservations(s, trafficClock) })) : []) : serverTraffic, [isLive, trafficReady, liveServers, trafficClock])
|
||||
const activeUserTraffic = useMemo(() => isLive ? (trafficReady ? liveUsers.map(u => ({ ...u, ...projectTrafficObservations(u, trafficClock), interfaces: u.interfaces.map(toLiveBound) })) : []) : userTraffic, [isLive, trafficReady, liveUsers, trafficClock])
|
||||
const activeBoundIfaces = useMemo(() => isLive ? (trafficReady ? liveBoundIfaces.map(c => ({ ...c, ...projectTrafficObservations(c, trafficClock), status: projectTrafficBindingStatus(c.status,c.statusObservedAt,c.statusExpiresAt,trafficClock) })) : []) : boundIfaces, [isLive, trafficReady, liveBoundIfaces, trafficClock])
|
||||
const visibleIfaces = useMemo(
|
||||
() => hideDisabledIfaces ? serverIfaces.filter((i) => !i.disabled && i.running) : serverIfaces,
|
||||
[serverIfaces, hideDisabledIfaces],
|
||||
)
|
||||
const ifaceCatalog = isLive ? serverIfaces : MOCK_IFACE_CATALOG[selectedId] ?? []
|
||||
const visibleIfaces = hideDisabledIfaces ? ifaceCatalog.filter(i => !i.disabled && i.running) : ifaceCatalog
|
||||
|
||||
useEffect(() => {
|
||||
if (!confirmedLiveServer || effectiveMode !== "servers") {
|
||||
if (!isLive || !confirmedLiveServer || effectiveMode !== "servers") {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setServerIfaces([])
|
||||
setSelectedIface("__all__")
|
||||
return
|
||||
}
|
||||
let cancelled = false
|
||||
setServerIfaces([])
|
||||
setSelectedIface("__all__")
|
||||
apiFetch<{ interfaces: LiveTrafficInterface[] }>(`/api/traffic/servers/${encodeURIComponent(selectedId)}/interfaces`)
|
||||
.then((res) => { if (!cancelled) setServerIfaces(res.interfaces) })
|
||||
.catch(() => { if (!cancelled) setServerIfaces([]) })
|
||||
return () => { cancelled = true }
|
||||
}, [confirmedLiveServer, selectedId, effectiveMode, apiFetch])
|
||||
}, [isLive, confirmedLiveServer, selectedId, effectiveMode, apiFetch])
|
||||
|
||||
useEffect(() => {
|
||||
if (!confirmedLiveServer || effectiveMode !== "servers") {
|
||||
@@ -1078,6 +1117,7 @@ export default function TrafficPage() {
|
||||
|
||||
const handleModeChange = (next: GroupMode) => {
|
||||
setGroupMode(next)
|
||||
setSelectedIface("__all__")
|
||||
if (next === "servers") {
|
||||
setSelectedId(activeServerTraffic[0]?.id ?? "srv1")
|
||||
if (range === "30d") setRange("1h")
|
||||
@@ -1165,12 +1205,15 @@ export default function TrafficPage() {
|
||||
const monthlyServer = monthlyServers.find(server => String(server.id) === selectedId)
|
||||
const selFlowCard = range === "30d"
|
||||
? (monthlyServer ? { id: String(monthlyServer.id), name: monthlyServer.name, country: monthlyServer.country, site: monthlyServer.site } : null)
|
||||
: flowCards.find((c) => c.id === selectedId) ?? null
|
||||
: allExporters ? { id: ALL_EXPORTERS, name: "Все экспортёры", country: "", site: "" } : flowCards.find((c) => c.id === selectedId) ?? null
|
||||
const displayedFlow = currentFlows && !liveError ? (flowLiveSample ?? currentAnalytics?.data ?? null) : null
|
||||
|
||||
const selServer = useMemo(() => activeServerTraffic.find(s => s.id === selectedId) ?? activeServerTraffic[0], [selectedId, activeServerTraffic])
|
||||
const detailServer = isLive ? (currentDetail?.server ? { ...currentDetail.server, ...projectTrafficObservations(currentDetail.server, trafficClock), boundIfaces: currentDetail.server.boundIfaces.map(toLiveBound) } : null) : selServer
|
||||
const selUser = useMemo(() => activeUserTraffic.find(u => u.id === selectedId) ?? activeUserTraffic[0], [selectedId, activeUserTraffic])
|
||||
const selServer = activeServerTraffic.find(s => s.id === selectedId) ?? (keptLink ? undefined : activeServerTraffic[0])
|
||||
const demoIfaceRows = !isLive && selectedIface !== "__all__" ? selServer?.boundIfaces.filter(row => row.interfaceName === selectedIface && !row.peerPublicKey) ?? [] : []
|
||||
const detailServer = isLive ? (currentDetail?.server ? { ...currentDetail.server, ...projectTrafficObservations(currentDetail.server, trafficClock), boundIfaces: currentDetail.server.boundIfaces.map(toLiveBound) } : null)
|
||||
: selServer && selectedIface !== "__all__" ? demoIfaceRows.length === 1 ? { ...selServer, ...demoIfaceRows[0], id: selServer.id, name: selServer.name, status: selServer.status, boundIfaces: [] } : null
|
||||
: selServer
|
||||
const selUser = activeUserTraffic.find(u => u.id === selectedId) ?? (keptLink ? undefined : activeUserTraffic[0])
|
||||
const selIface = useMemo(() => activeBoundIfaces.find(c => c.id === selectedId) ?? activeBoundIfaces[0], [selectedId, activeBoundIfaces])
|
||||
|
||||
const kpiSource = effectiveMode === "users"
|
||||
@@ -1270,7 +1313,7 @@ export default function TrafficPage() {
|
||||
ifaces: (isLive ? liveBoundIfaces : boundIfaces).length,
|
||||
flows: null,
|
||||
}
|
||||
const refreshBusy = isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)
|
||||
const refreshBusy = isLive && (effectiveMode === "flows" ? liveBusy || analyticsLoading : trafficLoading || detailBusy && confirmedLiveServer)
|
||||
const listTitle = effectiveMode === "servers" ? "Серверы" : effectiveMode === "users" ? "Клиенты" : "Интерфейсы"
|
||||
const listShown = effectiveMode === "servers" ? sortedServers.length : effectiveMode === "users" ? sortedUsers.length : sortedIfaces.length
|
||||
|
||||
@@ -1286,14 +1329,19 @@ export default function TrafficPage() {
|
||||
description="Счётчики интерфейсов и потоки IPFIX по серверам, клиентам и интерфейсам"
|
||||
actions={
|
||||
<>
|
||||
{returnHref && <Link className={buttonVariants({variant:"outline"})} href={returnHref}><MapIcon aria-hidden />Вернуться на карту</Link>}
|
||||
<Button type="button" variant="outline" onClick={() => { handleModeChange("flows"); setRange("30d") }}>Месячный отчёт</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (effectiveMode === "flows") setFlowRetry(value => value + 1)
|
||||
else setTrafficRetry(value => value + 1)
|
||||
else {
|
||||
setTrafficRetry(value => value + 1)
|
||||
if (effectiveMode === "servers") { setDetailRetry(value => value + 1); setLiveRetry(value => value + 1) }
|
||||
}
|
||||
}}
|
||||
disabled={refreshBusy}
|
||||
aria-busy={refreshBusy}
|
||||
>
|
||||
<RefreshCwIcon className={cn("size-4", refreshBusy && "animate-spin")} />Обновить
|
||||
</Button>
|
||||
@@ -1315,6 +1363,12 @@ export default function TrafficPage() {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<details className="text-sm text-muted-foreground">
|
||||
<summary className="cursor-pointer font-medium text-foreground">Как читать трафик</summary>
|
||||
<p className="mt-2">Серверы, клиенты и интерфейсы показывают измеренные RX и TX. В «Потоках» скорость усреднена по доступному окну IPFIX. Месячный отчёт показывает накопленный объём.</p>
|
||||
</details>
|
||||
{keptLink && (effectiveMode === "flows" ? !liveBusy && !liveError && !selFlowCard : (trafficReady || !isLive) && (effectiveMode === "users" ? !selUser : !selServer)) &&
|
||||
<Alert><AlertTitle>Объект из ссылки недоступен</AlertTitle><AlertDescription>Выберите доступный объект в списке.</AlertDescription></Alert>}
|
||||
{!(effectiveMode === "flows" && range === "30d") && (!isLive || !(effectiveMode === "flows" ? liveError : trafficError)) && <KpiStatGrid
|
||||
isLoading={isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)}
|
||||
aria-label="Сводка трафика"
|
||||
@@ -1362,6 +1416,7 @@ export default function TrafficPage() {
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={flowScope === "users"}
|
||||
disabled={Boolean(mapExporters)}
|
||||
onClick={() => { setFlowScope("users"); setFlowIface("__all__"); if (range === "30d") setRange("1h") }}
|
||||
className={cn(
|
||||
"text-xs px-2 py-0.5 rounded border transition-colors",
|
||||
@@ -1403,6 +1458,8 @@ export default function TrafficPage() {
|
||||
</div>
|
||||
{range === "30d" && <p className="text-xs text-muted-foreground">Серверы из каталога, включая неактивные. Удалённые серверы в список не входят.</p>}
|
||||
<div className="flex flex-col gap-2">
|
||||
{!mapExporters && flowScope === "servers" && range !== "30d" && <Button type="button" size="sm" variant={allExporters ? "secondary" : "outline"} aria-pressed={allExporters} onClick={() => setSelectedId(ALL_EXPORTERS)}>Все экспортёры</Button>}
|
||||
{mapExporters && flowScope === "servers" && range !== "30d" && !selectedId && <p className="text-xs text-muted-foreground">{mapExporters.length ? "Выберите экспортёра этого сервиса." : "Экспортёр этого сервиса не подтверждён."}</p>}
|
||||
{range === "30d" ? visibleMonthlyServers.map(server => <Button key={server.id} variant="outline" className="justify-start whitespace-normal break-all h-auto py-2" aria-pressed={String(server.id) === selectedId} onClick={() => setSelectedId(String(server.id))}>{server.name}</Button>) : sortedFlowCards.map((card) => (
|
||||
<FlowEntityCardView
|
||||
key={card.id}
|
||||
@@ -1442,6 +1499,9 @@ export default function TrafficPage() {
|
||||
excludeOverlay={flowExcludeOverlay}
|
||||
onExcludeOverlay={setFlowExcludeOverlay}
|
||||
liveHint={flowLiveHint}
|
||||
initialService={view === "flows" ? service : undefined}
|
||||
initialCountry={country}
|
||||
mapNodes={mapNodes}
|
||||
emptyHint={analyticsLoading ? "Загрузка аналитики…" : currentAnalytics?.error ? "Не удалось получить данные выбранного среза" : flowEmptyHint(collectorStatus)}
|
||||
/>
|
||||
</FramePanel>
|
||||
@@ -1456,7 +1516,7 @@ export default function TrafficPage() {
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid min-w-0 grid-cols-1 xl:grid-cols-[300px_minmax(0,1fr)] gap-4 items-start">
|
||||
<div className="grid min-w-0 grid-cols-1 gap-3 items-start lg:grid-cols-[minmax(12rem,17rem)_minmax(0,1fr)]">
|
||||
{/* ── left panel ── */}
|
||||
<div className="flex min-w-0 flex-col gap-4">
|
||||
<SectionFrame title={listTitle} description={`${listShown} из ${modeCount[effectiveMode] ?? listShown} · сортировка и поиск`} panelClassName="flex flex-col gap-3 p-2.5">
|
||||
@@ -1494,9 +1554,9 @@ export default function TrafficPage() {
|
||||
</p>
|
||||
)}
|
||||
{/* entity list */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex max-h-72 flex-col gap-2 overflow-y-auto p-0.5 lg:max-h-[26rem]">
|
||||
{effectiveMode === "servers" && sortedServers.map(s => (
|
||||
<ServerCard key={s.id} s={s} selected={s.id === selectedId} onClick={() => setSelectedId(s.id)} />
|
||||
<ServerCard key={s.id} s={s} selected={s.id === selectedId} onClick={() => { if (s.id !== selectedId) setSelectedIface("__all__"); setSelectedId(s.id) }} />
|
||||
))}
|
||||
{effectiveMode === "users" && sortedUsers.map(u => (
|
||||
<UserCard key={u.id} u={u} selected={u.id === selectedId} onClick={() => setSelectedId(u.id)} />
|
||||
@@ -1513,13 +1573,13 @@ export default function TrafficPage() {
|
||||
<div className="flex min-w-0 flex-col gap-4">
|
||||
<SectionFrame bare className="w-full min-w-0">
|
||||
<FramePanel className="flex-1 min-w-0 p-3 sm:p-5">
|
||||
{isLive && effectiveMode === "servers" && (
|
||||
<div className="mb-3 pb-3 border-b">
|
||||
{effectiveMode === "servers" && (
|
||||
<div role="group" aria-label="Интерфейсы выбранного сервера" className="mb-3 pb-3 border-b">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-xs text-muted-foreground mr-1">Интерфейс:</span>
|
||||
<button
|
||||
type="button" aria-pressed={hideDisabledIfaces}
|
||||
onClick={() => setHideDisabledIfaces((v) => !v)}
|
||||
onClick={() => { if (!hideDisabledIfaces && ifaceCatalog.some(iface => iface.name === selectedIface && (iface.disabled || !iface.running))) setSelectedIface("__all__"); setHideDisabledIfaces(value => !value) }}
|
||||
className={cn(
|
||||
"inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium transition-all",
|
||||
hideDisabledIfaces
|
||||
@@ -1565,6 +1625,7 @@ export default function TrafficPage() {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{!isLive && effectiveMode === "servers" && selectedIface !== "__all__" && !detailServer && <OfflinePlaceholder text="В демоснимке нет замеров этого интерфейса" />}
|
||||
{isLive && effectiveMode === "servers" && !detailServer && <>
|
||||
<DetailHeader range={range} setRange={setRange}><h2 className="text-base font-semibold">{selServer?.name ?? "Трафик сервера"}</h2></DetailHeader>
|
||||
{detailBusy && <p role="status" className="text-sm text-muted-foreground">Загрузка выбранного периода и интерфейса…</p>}
|
||||
@@ -1583,6 +1644,7 @@ export default function TrafficPage() {
|
||||
</>}
|
||||
{effectiveMode === "servers" && detailServer && (
|
||||
<ServerDetail
|
||||
key={selectedId + ":" + selectedIface}
|
||||
sel={detailServer}
|
||||
range={range}
|
||||
setRange={setRange}
|
||||
@@ -1594,8 +1656,8 @@ export default function TrafficPage() {
|
||||
: liveSample ? "live" : isLive ? "История · ожидание live" : undefined}
|
||||
/>
|
||||
)}
|
||||
{effectiveMode === "users" && selUser && <UserDetail sel={selUser} range={range} setRange={setRange} />}
|
||||
{effectiveMode === "ifaces" && selIface && <IfaceDetail sel={selIface} range={range} setRange={setRange} />}
|
||||
{effectiveMode === "users" && selUser && <UserDetail key={selUser.id} sel={selUser} range={range} setRange={setRange} />}
|
||||
{effectiveMode === "ifaces" && selIface && <IfaceDetail key={selIface.id} sel={selIface} range={range} setRange={setRange} />}
|
||||
</FramePanel>
|
||||
</SectionFrame>
|
||||
{effectiveMode === "servers" && detailServer && detailServer.boundIfaces.length > 0 ? <ServerIfacesFrame server={detailServer} /> : null}
|
||||
|
||||
@@ -49,7 +49,7 @@ export function registerFlowMapActions(register: typeof add) {
|
||||
await authorize()
|
||||
const output = { serverId: server.id, userId: input.userId ?? null, interface: input.interface ?? null, map: projected, pages, sourceWindow,
|
||||
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false, listenerBound,
|
||||
source: "closed minutes for all rates; retained flows for services, exit exporter or observed GRE peer/next hop for paths; interfaceTraffic includes private routed traffic before top-N",
|
||||
source: "closed minutes for all rates; retained flows for services and user breakdowns; paths use an exit exporter or observed GRE peer/next hop, otherwise identify the observing exporter; interfaceTraffic includes private routed traffic before top-N",
|
||||
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,
|
||||
referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false,
|
||||
rowSumIsNetworkTotal: false, historicalOwnershipVerified: false,
|
||||
|
||||
@@ -210,7 +210,9 @@ const trafficFlowRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
|
||||
app.get("/traffic/flow/map-hops", async (req, reply) => {
|
||||
const query = analyticsQuery(req)
|
||||
return reply.send(await readFlowWindow(query.minutes, minutes => buildFlowMapHops({ ...query, minutes }), mcpDatabaseRequestSignal()))
|
||||
const includeCurrentMinute = (req.query as { range?: string }).range?.toLowerCase() === "1m"
|
||||
const requestedMinutes = includeCurrentMinute ? 1 : query.minutes
|
||||
return reply.send(await readFlowWindow(requestedMinutes, minutes => buildFlowMapHops({ ...query, minutes, includeCurrentMinute }), mcpDatabaseRequestSignal()))
|
||||
})
|
||||
|
||||
app.get("/traffic/flow/monthly", async (req, reply) => {
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
} from "../services/traffic-collector.js"
|
||||
import { refreshScheduler } from "../services/scheduler.js"
|
||||
import { collectTrafficManually } from "../services/manual-traffic-collection.js"
|
||||
import { readTrafficLiveSample, TrafficLiveSourceChanged } from "../services/traffic-live.js"
|
||||
import { readTrafficLiveInterfaces, readTrafficLiveSample, TrafficLiveSourceChanged } from "../services/traffic-live.js"
|
||||
import { MikrotikClient, MikrotikError } from "../services/mikrotik.js"
|
||||
import { getEnabledServerById } from "../services/wireguard-live.js"
|
||||
import { readTrafficCollectionContext } from "../services/traffic-collection-state.js"
|
||||
@@ -106,9 +106,15 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
})
|
||||
app.get("/traffic/servers/:id/live", async (req, reply) => {
|
||||
const p = req.params as { id?: string | number }
|
||||
const q = req.query as { iface?: string; once?: string }
|
||||
if (q.once === "1" && (typeof q.iface !== "string" || !q.iface.trim() ||
|
||||
q.iface.length > 128 || q.iface === "__all__" || /[,\x00-\x1f\x7f]/.test(q.iface))) {
|
||||
const q = req.query as { iface?: string; ifaces?: string; once?: string }
|
||||
const validIface = (name: unknown): name is string => typeof name === "string" && Boolean(name.trim()) &&
|
||||
name.length <= 128 && name !== "__all__" && !/[,\x00-\x1f\x7f]/.test(name)
|
||||
const interfaces = typeof q.ifaces === "string" ? q.ifaces.split(",") : []
|
||||
if (q.ifaces !== undefined && (q.once !== "1" || q.iface !== undefined || !interfaces.length ||
|
||||
interfaces.length > 16 || new Set(interfaces).size !== interfaces.length || !interfaces.every(validIface))) {
|
||||
return reply.code(400).send({ error: "Укажите до 16 разных интерфейсов для live-измерения" })
|
||||
}
|
||||
if (q.once === "1" && !interfaces.length && !validIface(q.iface)) {
|
||||
return reply.code(400).send({ error: "Укажите один интерфейс для live-измерения" })
|
||||
}
|
||||
const readServer = (id: string | number, signal?: AbortSignal) => withDatabaseApiRequest(async () => {
|
||||
@@ -123,11 +129,12 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
const onlyInterface = q.iface && q.iface !== "__all__" ? q.iface : undefined
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const cache = { names: onlyInterface ? [onlyInterface] : [] as string[], joinedFailed: false }
|
||||
const readSample = (signal: AbortSignal) => readTrafficLiveSample(client, onlyInterface, cache, signal, async () => {
|
||||
const assertSource = async (signal: AbortSignal) => {
|
||||
const current = await readServer(server.id, signal)
|
||||
if (!current) throw new TrafficLiveSourceChanged("Устройство выключено или удалено. Переподключите live-поток")
|
||||
if (Date.parse(current.updatedAt) !== Date.parse(server.updatedAt)) throw new TrafficLiveSourceChanged("Конфигурация устройства изменилась. Переподключите live-поток")
|
||||
})
|
||||
}
|
||||
const readSample = (signal: AbortSignal) => readTrafficLiveSample(client, onlyInterface, cache, signal, () => assertSource(signal))
|
||||
const abort = new AbortController()
|
||||
const onClose = () => abort.abort()
|
||||
registerDatabaseStreamAbort(req, onClose)
|
||||
@@ -136,7 +143,9 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
if (q.once === "1") {
|
||||
reply.raw.once("close", onClose)
|
||||
try {
|
||||
const sample = await readSample(abort.signal)
|
||||
const sample = interfaces.length
|
||||
? { interfaces: await readTrafficLiveInterfaces(client, interfaces, abort.signal, () => assertSource(abort.signal)) }
|
||||
: await readSample(abort.signal)
|
||||
return reply.header("Cache-Control", "no-store").send(sample)
|
||||
} catch {
|
||||
if (!reply.raw.destroyed) return reply.code(503).send({ error: "Live-измерение интерфейса недоступно" })
|
||||
|
||||
@@ -46,6 +46,8 @@ assert.equal(isNamedInternetService("DNS", "DNS"), false)
|
||||
assert.equal(mapServiceNodeId("AWS"), "svc:aws")
|
||||
assert.equal(mapServiceNodeId("Cloudflare"), "svc:cloudflare")
|
||||
assert.equal(mapServiceNodeId("Прочее"), "svc:other")
|
||||
assert.notEqual(mapServiceNodeId("Видео"), mapServiceNodeId("Игры"))
|
||||
assert.notEqual(mapServiceNodeId("Microsoft Работа"), mapServiceNodeId("Microsoft Игры"))
|
||||
assert.equal(mapCountryNodeId("US"), "cc:us")
|
||||
assert.equal(mapCountryNodeId("nl"), "cc:nl")
|
||||
assert.equal(mapCountryNodeId(""), "cc:other")
|
||||
|
||||
@@ -358,6 +358,7 @@ export function isNamedInternetService(service: string, category: string): boole
|
||||
export function mapServiceNodeId(label: string): string {
|
||||
const raw = label.trim()
|
||||
if (raw === OTHER_SERVICE) return "svc:other"
|
||||
if (/[^\x00-\x7f]/.test(raw)) return `svc:label:${encodeURIComponent(raw.normalize("NFC").toLowerCase())}`
|
||||
const slug = raw
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
|
||||
@@ -5,12 +5,16 @@ import { classifyFlowDst, disableCatalogFetchForTests, resetFlowCatalogForTests,
|
||||
disableCatalogFetchForTests()
|
||||
resetFlowCatalogForTests()
|
||||
seedFlowCatalogForTests({
|
||||
cidrs: [{ cidr: "192.0.2.0/24", purpose: "steam-gaming" }],
|
||||
cidrs: [{ cidr: "192.0.2.0/24", purpose: "steam-gaming" },
|
||||
{ cidr: "198.51.100.0/25", purpose: "Игры" },
|
||||
{ cidr: "198.51.100.128/25", purpose: "Видео / стриминг" }],
|
||||
})
|
||||
|
||||
const hit = classifyFlowDst("192.0.2.10", 6, 443, 50000, null)
|
||||
assert.equal(hit.category, "Игры")
|
||||
assert.equal(hit.service, "steam-gaming")
|
||||
assert.equal(classifyFlowDst("198.51.100.10", 6, 443, 50000, null).category, "Игры")
|
||||
assert.equal(classifyFlowDst("198.51.100.150", 6, 443, 50000, null).category, "Видео / стриминг")
|
||||
|
||||
const miss = classifyFlowDst("203.0.113.9", 17, 53, 53000, null)
|
||||
assert.equal(miss.category, "DNS")
|
||||
|
||||
@@ -50,12 +50,12 @@ export function seedFlowCatalogForTests(input: {
|
||||
}
|
||||
|
||||
export function categoryFromPurpose(purpose: string, proto: number, dstPort: number, srcPort: number): string {
|
||||
const p = purpose.toLowerCase()
|
||||
if (/gaming|steam|epic|riot|playstation|roblox|ubisoft/.test(p)) return "Игры"
|
||||
if (/streaming|youtube|netflix|twitch|video|spotify|instagram/.test(p)) return "Видео / стриминг"
|
||||
const p = purpose.trim().toLowerCase()
|
||||
if (/игры|gaming|steam|epic|riot|playstation|roblox|ubisoft/.test(p)) return "Игры"
|
||||
if (/видео|стриминг|streaming|youtube|netflix|twitch|video|spotify|instagram/.test(p)) return "Видео / стриминг"
|
||||
if (/cdn|cloudflare|akamai|fastly|hetzner|ovh|apple/.test(p)) return "CDN"
|
||||
if (/voip|discord|zoom/.test(p)) return "Голос"
|
||||
if (/openai|chatgpt|\bai\b/.test(p)) return "ИИ"
|
||||
if (/голос|voip|discord|zoom/.test(p)) return "Голос"
|
||||
if (p === "ии" || /openai|chatgpt|\bai\b/.test(p)) return "ИИ"
|
||||
if (/quad9|opendns/.test(p)) return "DNS"
|
||||
if (/веб|web|google|github|paypal|vk|linkedin/.test(p)) return "Веб"
|
||||
const app = applicationName(proto, dstPort, srcPort)
|
||||
|
||||
@@ -142,6 +142,7 @@ assert.equal(classifyInternetBrand("8.8.8.8", 6, 443, 51234, {
|
||||
fetchedAt: Date.now(),
|
||||
})?.service, "Google")
|
||||
assert.equal(mapInternetBrand("203.0.113.50", 6, 443, 51234, null).service, "Прочее")
|
||||
assert.deepEqual(mapInternetBrand("185.246.117.91", 17, 53, 53000, null), { service: "DNS", category: "DNS" })
|
||||
assert.equal(mapInternetBrand("8.8.8.8", 47, 0, 0, null).service, "Прочее")
|
||||
assert.equal(mapInternetBrand("8.8.8.8", 6, 443, 51234, {
|
||||
prefix: "8.8.8.0/24",
|
||||
|
||||
@@ -105,7 +105,7 @@ export function mapInternetBrand(
|
||||
if (isTunnelProto(proto, dstPort, srcPort)) return OTHER_BRAND
|
||||
const classified = classifyFlowDst(dst, proto, dstPort, srcPort, ripe, { ignoreTunnelProto: true })
|
||||
if (isNamedInternetService(classified.service, classified.category)) return classified
|
||||
return OTHER_BRAND
|
||||
return { service: classified.category, category: classified.category }
|
||||
}
|
||||
|
||||
export function resolveInternetDest(opts: {
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
resetFlowMapHopsCacheForTests,
|
||||
} from "./traffic-flow-map-hops.js"
|
||||
import { withPgOrSkip } from "../test/pg.js"
|
||||
import { seedFlowTopologyForTests, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { loadFlowTopology, resolveClient, seedFlowTopologyForTests, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { disableCatalogFetchForTests, resetFlowCatalogForTests } from "./traffic-flow-classify.js"
|
||||
import {
|
||||
disableRipeEnqueueForTests,
|
||||
@@ -698,7 +698,7 @@ try {
|
||||
const googleEdge = wan.serviceEdges?.find((e) => e.toId === "svc:google")
|
||||
assert.ok(googleEdge, "Google с WAN JH")
|
||||
assert.equal(googleEdge.fromId, "9", "якорь на EN, не на JH")
|
||||
assert.ok(!(wan.serviceEdges ?? []).some((e) => e.fromId === "7"), "нет пунктира с JH")
|
||||
assert.ok(!(wan.serviceEdges ?? []).some((e) => e.fromId === "7"), "исторический снимок сопоставил GRE с Exit")
|
||||
const viaGre = wan.serviceEdges?.find((e) => e.toId === "svc:google")
|
||||
assert.ok(viaGre?.clients?.some((c) => c.name === "Alice") || viaGre?.clientName === "Alice")
|
||||
} finally {
|
||||
@@ -730,15 +730,20 @@ ingestClosed(7, [
|
||||
outIface: "1",
|
||||
nextHop: "",
|
||||
},
|
||||
{ ...payloadFlow("1.2.3.4", 6000), proto: 17, dstPort: 53, inIface: "gre-client", outIface: "ether1", nextHop: "" },
|
||||
])
|
||||
try {
|
||||
resetFlowMapHopsCacheForTests()
|
||||
const wanOnly = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
|
||||
assert.equal(wanOnly.services?.find(s => s.id === "svc:youtube")?.bytes, 9000)
|
||||
assert.deepEqual(wanOnly.serviceEdges, [])
|
||||
assert.deepEqual(wanOnly.servicePaths, [])
|
||||
assert.deepEqual(wanOnly.countryEdges, [])
|
||||
assert.ok(wanOnly.countryServiceGroups?.every(group => !group.edges.length && !group.paths.length))
|
||||
const dns = wanOnly.serviceEdges?.find(e => e.toId === "svc:dns")
|
||||
assert.deepEqual(dns && [dns.fromId, dns.observedOnly, dns.bytes], ["7", true, 6000])
|
||||
const dnsPath = wanOnly.servicePaths?.find(p => p.serviceId === "svc:dns")
|
||||
assert.deepEqual(dnsPath && [dnsPath.viaId, dnsPath.viaIface, dnsPath.enId, dnsPath.clientName], ["7", "ether1", "", "Alice"])
|
||||
assert.ok(wanOnly.countryEdges?.every(e => e.observedOnly && e.fromId === "7"))
|
||||
assert.ok(wanOnly.countryServiceGroups?.some(group => group.edges.some(e => e.toId.endsWith("|svc:dns"))))
|
||||
assert.deepEqual(wanOnly.nodeUsers?.["7"]?.map(u => [u.clientName, u.bytes]), [["—", 9000], ["Alice", 6000]])
|
||||
assert.equal(wanOnly.nodeUsers?.["9"], undefined)
|
||||
|
||||
} finally {
|
||||
seedFlowTopologyForTests(null)
|
||||
@@ -768,7 +773,7 @@ ingestClosed(9, [{
|
||||
proto: 6,
|
||||
srcPort: 51234,
|
||||
dstPort: 443,
|
||||
bytes: 12_000,
|
||||
bytes: 120_000,
|
||||
packets: 10,
|
||||
inIface: "1",
|
||||
outIface: "1",
|
||||
@@ -786,7 +791,10 @@ try {
|
||||
assert.equal(googlePaths[0]?.viaId, "7")
|
||||
const googleEdge = dual.serviceEdges?.find((e) => e.toId === "svc:google" && e.fromId === "9")
|
||||
assert.ok(googleEdge)
|
||||
assert.equal(googleEdge.bytes, 12_000)
|
||||
assert.equal(googleEdge.bytes, 120_000)
|
||||
assert.equal(dual.totalBytes, 120_000, "объём крупнейшей копии с атрибуцией маршрута JH")
|
||||
assert.equal(dual.nodeUsers?.["7"]?.find(u => u.clientName === "Alice")?.bytes, 12_000)
|
||||
assert.equal(dual.nodeUsers?.["9"]?.find(u => u.clientName === "Alice")?.bytes, 120_000)
|
||||
assert.equal(googleEdge.bps, googlePaths[0]?.bps)
|
||||
} finally {
|
||||
seedFlowTopologyForTests(null)
|
||||
@@ -1031,12 +1039,21 @@ try {
|
||||
{ ...flow, src: "10.0.0.2", bytes: 2000, outIface: "gre-second" },
|
||||
{ ...flow, src: "10.0.0.3", bytes: 9000, outIface: "ether1" },
|
||||
])
|
||||
// This open minute must affect neither the service nor the link rate.
|
||||
ingestParsedFlowsForServerForTests(7, [{ ...flow, bytes: 90000, outIface: "SWE-VEESP" }])
|
||||
const map = await buildFlowMapHops({ serverId: 7, minutes: 5, minSharePct: 0 })
|
||||
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.bytes, 12000)
|
||||
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes]), [["10", 2000], ["9", 1000]])
|
||||
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 3000)
|
||||
ingestClosed(7, [{ ...flow, bytes: 900_000_000, outIface: "SWE-VEESP" }], bucket + 90_000)
|
||||
const clock = mock.method(Date, "now", () => bucket + 90_000)
|
||||
try {
|
||||
const map = await buildFlowMapHops({ serverId: 7, minutes: 5, minSharePct: 0 })
|
||||
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.bytes, 12000)
|
||||
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes, Boolean(e.observedOnly)]), [["7", 9000, true], ["10", 2000, false], ["9", 1000, false]])
|
||||
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 12000)
|
||||
assert.equal(map.nodeUsers?.["7"]?.find(u => u.clientName === "Alice")?.bytes, 12000)
|
||||
assert.equal(map.nodeUsers?.["9"]?.find(u => u.clientName === "Alice")?.bytes, 1000)
|
||||
|
||||
const recent = await buildFlowMapHops({ serverId: 7, minutes: 1, includeCurrentMinute: true, minSharePct: 0 })
|
||||
assert.equal(recent.windowSec, 90)
|
||||
assert.equal(recent.services?.find(s => s.id === "svc:youtube")?.bps, 900_012_000 * 8 / 90)
|
||||
assert.equal(recent.serviceEdges?.find(edge => edge.fromId === "9")?.bps, 900_001_000 * 8 / 90)
|
||||
} finally { clock.mock.restore() }
|
||||
} finally {
|
||||
await dbQuery("DELETE FROM internet_path_snapshots WHERE id=?", [snapshot.id])
|
||||
resetFlowRingsForTests()
|
||||
@@ -1096,12 +1113,28 @@ try {
|
||||
ingestClosed(sid, [split], bucket - 60000)
|
||||
const mixed = await buildFlowMapHops({serverId: sid, minutes: 5, iface: "mixed-lan"})
|
||||
assert.equal(mixed.totalBytes, 6000)
|
||||
assert.deepEqual(mixed.serviceEdges, [])
|
||||
assert.ok(mixed.serviceEdges?.every(e => e.observedOnly && e.fromId === String(sid)))
|
||||
assert.ok(mixed.servicePaths?.every(p => !p.enId))
|
||||
await flushEngineNow({ prune: false })
|
||||
assert.deepEqual((await dbQuery("SELECT out_iface,next_hop FROM flow_buckets WHERE server_id=? AND in_iface='mixed-lan'", [sid])).rows,
|
||||
[{out_iface: "", next_hop: null}, {out_iface: "", next_hop: null}])
|
||||
const user = await buildFlowMapHops({serverId: sid, minutes: 5, userId: "no-interface-binding"})
|
||||
assert.equal(user.interfaceTraffic, undefined)
|
||||
const alice = `map-alice-${sid}`, bob = `map-bob-${sid}`
|
||||
try {
|
||||
await dbQuery("INSERT INTO app_users(id,login,name) VALUES (?,?,'Alice'),(?,?,'Bob')", [alice, alice, bob, bob])
|
||||
await dbQuery(`
|
||||
INSERT INTO user_interface_bindings(id,user_id,server_id,interface_name,interface_type,peer_public_key)
|
||||
VALUES (?, ?, ?, 'wg-shared', 'wg', 'alice-key'), (?, ?, ?, 'wg-shared', 'wg', 'bob-key'), (?, ?, ?, 'gre-owner', 'gre', '')
|
||||
`, [alice + "-wg", alice, sid, bob + "-wg", bob, sid, alice + "-gre", alice, sid])
|
||||
seedFlowTopologyForTests(null)
|
||||
for (const topology of [await loadFlowTopology(), await loadFlowTopology([sid])]) {
|
||||
assert.equal(resolveClient(topology, sid, "wg-shared"), null, "общий WG не присваивается одному пользователю")
|
||||
assert.equal(resolveClient(topology, sid, "gre-owner")?.userId, alice)
|
||||
}
|
||||
} finally {
|
||||
await dbQuery("DELETE FROM app_users WHERE id IN (?,?)", [alice, bob])
|
||||
}
|
||||
console.log("CHR NetFlow v5 through PostgreSQL and map: GRE A RX / GRE B TX both 192 B, 3 packets; Top-200 and GRE encapsulation verified")
|
||||
} finally {
|
||||
await dbQuery("DELETE FROM servers WHERE id=?", [sid])
|
||||
|
||||
@@ -17,7 +17,7 @@ import { destCtxForIface, flowRateDirection, mapInternetBrand } from "./traffic-
|
||||
import { resolveFlowEndpoints } from "./traffic-flow-ip.js"
|
||||
import { geoipReadersStatus, resolveFlowIp } from "./traffic-flow-geoip.js"
|
||||
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
|
||||
import { loadFlowTopology, resolveClient, getServerCatalog, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { loadFlowTopology, resolveClient, getServerCatalog, type FlowClientBinding, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM } from "./traffic-flow-engine.js"
|
||||
|
||||
export const DEFAULT_MAP_SERVICE_MIN_SHARE_PCT = 5
|
||||
@@ -33,6 +33,7 @@ const HOPS_CACHE_TTL_MS = 2000
|
||||
|
||||
export interface FlowMapHopsQuery {
|
||||
minutes: number
|
||||
includeCurrentMinute?: boolean
|
||||
serverId?: number
|
||||
userId?: string
|
||||
iface?: string
|
||||
@@ -63,6 +64,7 @@ interface ClientAcc {
|
||||
interface FromAcc {
|
||||
exporterId: string
|
||||
enId: string
|
||||
viaIface?: string
|
||||
reverseBytes: number
|
||||
bytes: number
|
||||
clients: Map<string, ClientAcc>
|
||||
@@ -90,6 +92,7 @@ interface DestEdgeAcc {
|
||||
bytesFwd: number
|
||||
bytesRev: number
|
||||
clients: Map<string, string>
|
||||
observedOnly?: true
|
||||
}
|
||||
|
||||
interface DestPathAcc {
|
||||
@@ -97,6 +100,7 @@ interface DestPathAcc {
|
||||
clientName: string
|
||||
viaId: string
|
||||
viaName: string
|
||||
viaIface?: string
|
||||
enId: string
|
||||
enName: string
|
||||
serviceId: string
|
||||
@@ -114,12 +118,12 @@ function bumpClient(clients: Map<string, ClientAcc>, bytes: number, client: { us
|
||||
clients.set(id, { name, bytes })
|
||||
}
|
||||
|
||||
function bumpFrom(acc: DstAcc, exporterId: string, enId: string, bytes: number, reverse: boolean, client: { userId: string; name: string } | null): void {
|
||||
const key = exporterId + "|" + enId
|
||||
const from = acc.fromBytes.get(key) ?? { exporterId, enId, bytes: 0, reverseBytes: 0, clients: new Map<string, ClientAcc>() }
|
||||
function bumpFrom(acc: DstAcc, exporterId: string, enId: string, viaIface: string | undefined, bytes: number, reverse: boolean, client: FlowClientBinding | null | undefined): void {
|
||||
const key = JSON.stringify([exporterId, enId, viaIface])
|
||||
const from = acc.fromBytes.get(key) ?? { exporterId, enId, viaIface, bytes: 0, reverseBytes: 0, clients: new Map<string, ClientAcc>() }
|
||||
from.bytes += bytes
|
||||
if (reverse) from.reverseBytes += bytes
|
||||
bumpClient(from.clients, bytes, client)
|
||||
bumpClient(from.clients, bytes, client ?? null)
|
||||
acc.fromBytes.set(key, from)
|
||||
}
|
||||
|
||||
@@ -170,7 +174,7 @@ function bumpDestFrom(
|
||||
enName: string,
|
||||
viaName: string,
|
||||
/** fromId ребра, если отличается от EN (вложенный слой: страна → сервис). */
|
||||
edgeFromId: string = fromId,
|
||||
edgeFromId: string = fromId || exporterId,
|
||||
): void {
|
||||
const edgeKey = `${edgeFromId}|${toId}`
|
||||
const prevEdge = edges.get(edgeKey)
|
||||
@@ -191,10 +195,11 @@ function bumpDestFrom(
|
||||
bytesFwd: from.bytes - from.reverseBytes,
|
||||
bytesRev: from.reverseBytes,
|
||||
clients: namedClients,
|
||||
...(!fromId && edgeFromId === exporterId ? { observedOnly: true as const } : {}),
|
||||
})
|
||||
}
|
||||
for (const [clientId, c] of from.clients) {
|
||||
const pathKey = `${clientId}|${exporterId}|${fromId}|${toId}`
|
||||
const pathKey = JSON.stringify([clientId, exporterId, fromId, toId, from.viaIface])
|
||||
const prevPath = paths.get(pathKey)
|
||||
if (prevPath) {
|
||||
prevPath.bytes += c.bytes
|
||||
@@ -205,6 +210,7 @@ function bumpDestFrom(
|
||||
clientName: c.name,
|
||||
viaId: exporterId,
|
||||
viaName,
|
||||
...(from.viaIface ? { viaIface: from.viaIface } : {}),
|
||||
enId: fromId,
|
||||
enName,
|
||||
serviceId: toId,
|
||||
@@ -252,6 +258,7 @@ function finalizeDestLayer(
|
||||
bps: (e.bytes * 8) / windowSec,
|
||||
bpsFwd: (e.bytesFwd * 8) / windowSec,
|
||||
bpsRev: (e.bytesRev * 8) / windowSec,
|
||||
...(e.observedOnly ? { observedOnly: e.observedOnly } : {}),
|
||||
...(first ? { clientId: first.id, clientName: first.name } : {}),
|
||||
...(clients.length ? { clients } : {}),
|
||||
}
|
||||
@@ -264,6 +271,7 @@ function finalizeDestLayer(
|
||||
clientName: p.clientName,
|
||||
viaId: p.viaId,
|
||||
viaName: p.viaName,
|
||||
...(p.viaIface ? { viaIface: p.viaIface } : {}),
|
||||
enId: p.enId,
|
||||
enName: p.enName,
|
||||
serviceId: p.serviceId,
|
||||
@@ -329,6 +337,7 @@ function hopsQueryKey(q: FlowMapHopsQuery, minSharePct: number): string {
|
||||
return JSON.stringify({
|
||||
epoch: flowDataEpoch(),
|
||||
minutes: q.minutes,
|
||||
includeCurrentMinute: q.includeCurrentMinute === true,
|
||||
serverId: q.serverId ?? null,
|
||||
userId: q.userId ?? null,
|
||||
iface: q.iface ?? null,
|
||||
@@ -339,18 +348,6 @@ function hopsQueryKey(q: FlowMapHopsQuery, minSharePct: number): string {
|
||||
})
|
||||
}
|
||||
|
||||
async function userIfaceAllow(userId: string): Promise<Map<number, Set<string>> | null> {
|
||||
if (!userId) return null
|
||||
const binds = await flowReadDbAll<{serverId:number;interfaceName:string}>('SELECT server_id AS "serverId",interface_name AS "interfaceName" FROM user_interface_bindings WHERE user_id=?',[userId])
|
||||
const allow = new Map<number, Set<string>>()
|
||||
for (const b of binds) {
|
||||
const set = allow.get(b.serverId) ?? new Set<string>()
|
||||
set.add(b.interfaceName)
|
||||
allow.set(b.serverId, set)
|
||||
}
|
||||
return allow
|
||||
}
|
||||
|
||||
function ifaceUsable(name: string): boolean {
|
||||
return Boolean(name) && name !== "—"
|
||||
}
|
||||
@@ -360,9 +357,11 @@ function resolveMapClient(
|
||||
serverId: number,
|
||||
inName: string,
|
||||
outName: string,
|
||||
) {
|
||||
return resolveClient(topo, serverId, inName)
|
||||
?? (ifaceUsable(outName) ? resolveClient(topo, serverId, outName) : null)
|
||||
): FlowClientBinding | null | undefined {
|
||||
const ingress = resolveClient(topo, serverId, inName)
|
||||
const egress = resolveClient(topo, serverId, outName)
|
||||
if (ingress && egress && ingress.userId !== egress.userId) return null
|
||||
return ingress ?? egress ?? undefined
|
||||
}
|
||||
|
||||
function bump(acc: Map<string, HopAcc>, key: string, seed: Omit<HopAcc, "bytes" | "bytesFwd" | "bytesRev">, bytes: number, dir: "fwd" | "rev" | "both"): void {
|
||||
@@ -409,21 +408,19 @@ async function resolveMinSharePct(q: FlowMapHopsQuery): Promise<number> {
|
||||
}
|
||||
}
|
||||
|
||||
// Closed minute buckets from every admitted export. Keep an hour of last-seen context for idle links.
|
||||
async function readInterfaceTraffic(serverIds: number[], iface: string, q: FlowMapHopsQuery, end: number): Promise<FlowMapInterfaceTraffic[]> {
|
||||
// Keep an hour of last-seen context for idle links.
|
||||
async function readInterfaceTraffic(serverIds: number[], iface: string, q: FlowMapHopsQuery, start: string, end: number): Promise<FlowMapInterfaceTraffic[]> {
|
||||
if (!serverIds.length) return []
|
||||
const { minutes } = q
|
||||
// Private site-to-site flows are traffic on the link even when the destination graph hides mesh paths.
|
||||
const planes = q.excludeOverlay === false ? ["payload", "client_mesh", "overlay"] : ["payload", "client_mesh"]
|
||||
const dimensions = planes.flatMap(plane => [FLOW_IFACE_RX_DIM + ":" + plane, FLOW_IFACE_TX_DIM + ":" + plane])
|
||||
const start = new Date(end - minutes * 60000).toISOString()
|
||||
const rows = await flowReadDbAll<{server_id: number; key: string; dim: string; bytes: string; packets: string; last_at: Date | string}>(`
|
||||
SELECT server_id, key, dim, COALESCE(SUM(bytes) FILTER (WHERE bucket_at >= ?), 0) AS bytes,
|
||||
COALESCE(SUM(packets) FILTER (WHERE bucket_at >= ?), 0) AS packets, MAX(bucket_at) AS last_at
|
||||
FROM flow_minute_dims
|
||||
WHERE server_id = ANY(?::bigint[]) AND bucket_at >= ? AND bucket_at < ? AND dim = ANY(?::text[])
|
||||
GROUP BY server_id, key, dim
|
||||
`, [start, start, serverIds, new Date(end - Math.max(minutes, 60) * 60000).toISOString(),
|
||||
`, [start, start, serverIds, new Date(Math.min(Date.parse(start), end - 60 * 60_000)).toISOString(),
|
||||
new Date(end).toISOString(), dimensions])
|
||||
const totals = new Map<string, FlowMapInterfaceTraffic>()
|
||||
for (const row of rows) {
|
||||
@@ -481,10 +478,13 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
if (!scope) refreshFlowCatalogInBackground()
|
||||
await authorize()
|
||||
const limits = scope ? await readFlowMapSourceLimits() : undefined
|
||||
const windowSec = Math.max(60, q.minutes * 60)
|
||||
const now = Date.now()
|
||||
const completeUntil = Math.floor(now / 60_000) * 60_000
|
||||
const startMs = completeUntil - Math.max(1, q.minutes) * 60_000
|
||||
const end = q.includeCurrentMinute ? now : completeUntil
|
||||
const windowSec = (end - startMs) / 1000
|
||||
await authorize()
|
||||
const end = Math.floor(Date.now() / 60000) * 60000
|
||||
const start = new Date(end - windowSec * 1000).toISOString()
|
||||
const start = new Date(startMs).toISOString()
|
||||
const raw = await listStoredFlowRows(start, q.serverId, { ...(scope ? { maxRows: scope.maxRows } : {}), untilIso: new Date(end - 1).toISOString() })
|
||||
if (scope && raw.some(row => row.serverId !== q.serverId)) throw new Error("Строка карты вне выбранного сервера")
|
||||
await authorize()
|
||||
@@ -496,21 +496,24 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const excludeOverlay = q.excludeOverlay !== false
|
||||
await authorize()
|
||||
const topo = await loadFlowTopology(scope?.serverIds, authorize)
|
||||
let allow: Map<number, Set<string>> | null = null
|
||||
if (q.userId) {
|
||||
if (!scope) allow = await userIfaceAllow(q.userId)
|
||||
else {
|
||||
allow = new Map()
|
||||
for (const binding of topo.clientByIface.values()) if (binding.userId === q.userId) {
|
||||
const names = allow.get(binding.serverId) ?? new Set<string>(); names.add(binding.interfaceName); allow.set(binding.serverId, names)
|
||||
}
|
||||
if (!allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
|
||||
const allow = q.userId ? new Map<number, Set<string>>() : null
|
||||
if (allow) {
|
||||
for (const binding of topo.clientByIface.values()) if (binding.userId === q.userId) {
|
||||
const names = allow.get(binding.serverId) ?? new Set<string>()
|
||||
names.add(binding.interfaceName)
|
||||
allow.set(binding.serverId, names)
|
||||
}
|
||||
if (scope && !allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
|
||||
}
|
||||
|
||||
function rowClient(r: (typeof raw)[number]) {
|
||||
return resolveMapClient(topo, r.serverId, resolveIfaceName(r.serverId, r.inIface).name, resolveIfaceName(r.serverId, r.outIface).name)
|
||||
}
|
||||
|
||||
const matches = (serverId: number, iface: string) =>
|
||||
flowRowMatchesFilter({ serverId, inIface: iface }, resolveIfaceName(serverId, iface).name, q, allow)
|
||||
const selected = raw.filter(r => matches(r.serverId, r.inIface) || matches(r.serverId, r.outIface))
|
||||
const selected = raw.filter(r => (!q.userId || rowClient(r)?.userId === q.userId) &&
|
||||
(matches(r.serverId, r.inIface) || matches(r.serverId, r.outIface)))
|
||||
const { rows } = collapseGreEspRows(selected, r => {
|
||||
if (ifaceFilter) {
|
||||
const ingress = matches(r.serverId, r.inIface), egress = matches(r.serverId, r.outIface)
|
||||
@@ -548,16 +551,14 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
}
|
||||
await authorize()
|
||||
const peers = await readMapGrePeers(working)
|
||||
const observed = new Map<(typeof working)[number], { endpoints: ReturnType<typeof resolveFlowEndpoints>; exitId?: number; reverse: boolean }>()
|
||||
const observed = new Map<(typeof working)[number], {
|
||||
endpoints: ReturnType<typeof resolveFlowEndpoints>; exitId?: number; viaIface?: string; reverse: boolean
|
||||
client: ReturnType<typeof rowClient>; nodeBytes: Map<number, number>
|
||||
}>()
|
||||
const nodeUsers = new Map<number, Map<string, ClientAcc>>()
|
||||
const enIds = new Set(topo.enNodes.map((n) => n.id))
|
||||
let totalBytes = 0
|
||||
|
||||
function rowClient(r: (typeof working)[number]) {
|
||||
const inName = resolveIfaceName(r.serverId, r.inIface).name
|
||||
const outName = resolveIfaceName(r.serverId, r.outIface).name
|
||||
return resolveMapClient(topo, r.serverId, inName, outName)
|
||||
}
|
||||
|
||||
for (const r of working) {
|
||||
const inRes = resolveIfaceName(r.serverId, r.inIface)
|
||||
const outRes = resolveIfaceName(r.serverId, r.outIface)
|
||||
@@ -623,7 +624,14 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const reverse = !!endpoints.internetPeer && (endpoints.internetPeer === endpoints.packetSrc || endpoints.internetPeer === r.natSrc)
|
||||
const serviceSide = endpoints.internetPeer ? (reverse ? inId : outId) : peerId
|
||||
const exitId = enIds.has(r.serverId) ? r.serverId : serviceSide ?? undefined
|
||||
observed.set(r, { endpoints, exitId, reverse })
|
||||
const serviceIface = reverse ? inName : outName
|
||||
const otherIface = reverse ? outName : inName
|
||||
const viaIface = exitId === undefined
|
||||
? ifaceUsable(serviceIface) ? serviceIface : ifaceUsable(otherIface) ? otherIface : undefined
|
||||
: undefined
|
||||
const nodeBytes = new Map([[r.serverId, r.bytes]])
|
||||
if (exitId !== undefined) nodeBytes.set(exitId, r.bytes)
|
||||
observed.set(r, { endpoints, exitId, viaIface, reverse, client: resolveMapClient(topo, r.serverId, inName, outName), nodeBytes })
|
||||
if (peerId && peerId !== r.serverId) {
|
||||
const toId = String(peerId)
|
||||
const dir = outId === peerId ? "fwd" : "rev"
|
||||
@@ -662,31 +670,47 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
}
|
||||
}
|
||||
|
||||
const payloadBytes = new Map<(typeof working)[number], number>()
|
||||
const payloadRows = wantDedup
|
||||
? dedupFlowRowsAcrossExporters(working, (a, b) => {
|
||||
const aRouted = observed.get(a)?.exitId !== undefined
|
||||
const bRouted = observed.get(b)?.exitId !== undefined
|
||||
if (aRouted !== bRouted) return aRouted ? a : b
|
||||
const aCli = Boolean(rowClient(a))
|
||||
const bCli = Boolean(rowClient(b))
|
||||
if (aCli !== bCli) return aCli ? a : b
|
||||
return a.bytes >= b.bytes ? a : b
|
||||
const observationA = observed.get(a)!
|
||||
const observationB = observed.get(b)!
|
||||
const aRouted = observationA.exitId !== undefined
|
||||
const bRouted = observationB.exitId !== undefined
|
||||
const aCli = Boolean(observationA.client)
|
||||
const bCli = Boolean(observationB.client)
|
||||
const attributed = aRouted !== bRouted ? (aRouted ? a : b)
|
||||
: aCli !== bCli ? (aCli ? a : b)
|
||||
: a.bytes >= b.bytes ? a : b
|
||||
// Route/client evidence and the largest byte observation can come from different exporters.
|
||||
payloadBytes.set(attributed, Math.max(payloadBytes.get(a) ?? a.bytes, b.bytes))
|
||||
const clientA = observationA.client, clientB = observationB.client
|
||||
const chosen = observed.get(attributed)!
|
||||
chosen.client = clientA === null || clientB === null || (clientA && clientB && clientA.userId !== clientB.userId)
|
||||
? null : clientA ?? clientB
|
||||
for (const [id, bytes] of (attributed === a ? observationB : observationA).nodeBytes) {
|
||||
chosen.nodeBytes.set(id, Math.max(chosen.nodeBytes.get(id) ?? 0, bytes))
|
||||
}
|
||||
return attributed
|
||||
})
|
||||
: working
|
||||
|
||||
for (const r of payloadRows) {
|
||||
const inName = resolveIfaceName(r.serverId, r.inIface).name
|
||||
const outName = resolveIfaceName(r.serverId, r.outIface).name
|
||||
totalBytes += r.bytes
|
||||
const { endpoints: ep, exitId, reverse } = observed.get(r)!
|
||||
const bytes = payloadBytes.get(r) ?? r.bytes
|
||||
totalBytes += bytes
|
||||
const { endpoints: ep, exitId, viaIface, reverse, client, nodeBytes } = observed.get(r)!
|
||||
for (const [id, observedBytes] of nodeBytes) {
|
||||
const users = nodeUsers.get(id) ?? new Map<string, ClientAcc>()
|
||||
bumpClient(users, observedBytes, client ?? null)
|
||||
nodeUsers.set(id, users)
|
||||
}
|
||||
const dst = ep.internetPeer
|
||||
const dstPort = ep.peerPort || r.dstPort
|
||||
const srcPort = ep.otherPort || r.srcPort
|
||||
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : ""
|
||||
const client = resolveMapClient(topo, r.serverId, inName, outName)
|
||||
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, proto: r.proto, dstPort, srcPort, fromBytes: new Map<string, FromAcc>() }
|
||||
acc.bytes += r.bytes
|
||||
if (exitId !== undefined) bumpFrom(acc, String(r.serverId), String(exitId), r.bytes, reverse, client)
|
||||
acc.bytes += bytes
|
||||
bumpFrom(acc, String(r.serverId), exitId === undefined ? "" : String(exitId), viaIface, bytes, reverse, client)
|
||||
dstAcc.set(destKey, acc)
|
||||
}
|
||||
|
||||
@@ -755,15 +779,19 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
if (scope && (!isDeepStrictEqual(topo, await loadFlowTopology(scope.serverIds, authorize)) || !isDeepStrictEqual(limits, await readFlowMapSourceLimits()))) throw new Error("Топология или пределы карты NetFlow изменились во время чтения")
|
||||
await authorize()
|
||||
// Whole-interface counters must never be exposed as per-user payload or added to totalBytes.
|
||||
const interfaceTraffic = q.userId ? undefined : await readInterfaceTraffic(q.serverId ? [q.serverId] : [...catalog.byId.keys()], ifaceFilter, q, end)
|
||||
const interfaceTraffic = q.userId ? undefined : await readInterfaceTraffic(q.serverId ? [q.serverId] : [...catalog.byId.keys()], ifaceFilter, q, start, end)
|
||||
await authorize()
|
||||
return {
|
||||
...(interfaceTraffic ? { interfaceTraffic } : {}),
|
||||
nodeUsers: Object.fromEntries([...nodeUsers].map(([id, users]) => [id, [...users].map(([clientId, { name, bytes }]) => (
|
||||
{ clientId, clientName: name, bytes, bps: bytes * 8 / windowSec }
|
||||
)).sort((a, b) => b.bytes - a.bytes)])),
|
||||
hops: [...hops.values()]
|
||||
.map((a) => toHop(a, windowSec))
|
||||
.sort((a, b) => a.bytes === b.bytes ? 0 : b.bytes - a.bytes),
|
||||
live: listener.bound,
|
||||
rangeMinutes: q.minutes,
|
||||
...(q.includeCurrentMinute ? { includesCurrentMinute: true as const } : {}),
|
||||
windowSec,
|
||||
totalBytes,
|
||||
namedBytes,
|
||||
|
||||
@@ -124,23 +124,37 @@ export async function loadFlowTopology(serverIds?: readonly number[], authorize:
|
||||
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=u.id AND NOT(hidden.server_id=ANY(?::bigint[]))) LIMIT 1001
|
||||
`, [serverIds, serverIds])
|
||||
await authorize()
|
||||
const binds = serverIds === undefined ? await flowReadDbAll<{userId:string;serverId:number;interfaceName:string}>('SELECT user_id AS "userId",server_id AS "serverId",interface_name AS "interfaceName" FROM user_interface_bindings') : await flowReadDbAll<{ userId: string; serverId: number; interfaceName: string }>(`
|
||||
const binds = serverIds === undefined ? await flowReadDbAll<{userId:string;serverId:number;interfaceName:string;peerPublicKey?:string}>(
|
||||
'SELECT user_id AS "userId",server_id AS "serverId",interface_name AS "interfaceName",peer_public_key AS "peerPublicKey" FROM user_interface_bindings',
|
||||
) : await flowReadDbAll<{ userId: string; serverId: number; interfaceName: string; peerPublicKey?: string }>(`
|
||||
SELECT b.user_id AS "userId",b.server_id AS "serverId",b.interface_name AS "interfaceName" FROM user_interface_bindings b
|
||||
WHERE b.server_id=ANY(?::bigint[]) AND b.peer_public_key='' AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=b.user_id AND NOT(hidden.server_id=ANY(?::bigint[]))) ORDER BY b.id
|
||||
WHERE b.server_id=ANY(?::bigint[]) AND b.peer_public_key=''
|
||||
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=b.user_id AND NOT(hidden.server_id=ANY(?::bigint[])))
|
||||
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings conflict WHERE conflict.server_id=b.server_id
|
||||
AND conflict.interface_name=b.interface_name AND (conflict.peer_public_key<>'' OR conflict.user_id<>b.user_id))
|
||||
ORDER BY b.id
|
||||
LIMIT 1001
|
||||
`, [serverIds, serverIds])
|
||||
if (serverIds !== undefined && (binds.length > 1000 || users.length > 1000)) throw new Error("Превышен предел топологии NetFlow")
|
||||
const loginById = new Map(users.map((u) => [u.id, u]))
|
||||
const clientIfaces = new Map<number, Set<string>>()
|
||||
const clientByIface = new Map<string, FlowClientBinding>()
|
||||
const ambiguousIfaces = new Set<string>()
|
||||
const allClientNames = new Set<string>()
|
||||
for (const b of binds) {
|
||||
const set = clientIfaces.get(b.serverId) ?? new Set<string>()
|
||||
set.add(b.interfaceName)
|
||||
clientIfaces.set(b.serverId, set)
|
||||
allClientNames.add(b.interfaceName)
|
||||
const key = ifaceKey(b.serverId, b.interfaceName)
|
||||
const previous = clientByIface.get(key)
|
||||
if (b.peerPublicKey || previous && previous.userId !== b.userId) {
|
||||
ambiguousIfaces.add(key)
|
||||
clientByIface.delete(key)
|
||||
}
|
||||
if (ambiguousIfaces.has(key)) continue
|
||||
const user = loginById.get(b.userId)
|
||||
clientByIface.set(ifaceKey(b.serverId, b.interfaceName), {
|
||||
clientByIface.set(key, {
|
||||
userId: b.userId,
|
||||
login: user?.login || b.userId,
|
||||
name: user?.name || user?.login || b.userId,
|
||||
|
||||
@@ -47,10 +47,18 @@ else {
|
||||
assert.equal(sample.headers["cache-control"], "no-store")
|
||||
assert.deepEqual(sample.json(), { rxMbps: 0, txMbps: 0, at: sample.json().at, timestampKind: "backend-receipt" })
|
||||
assert.equal(nativeRequests, beforeSample + 1)
|
||||
assert.equal((await app.inject(sampleUrl + "&ifaces=ether1,ether1")).statusCode, 400)
|
||||
assert.equal((await app.inject(sampleUrl + "&ifaces=ether1,ether2&iface=ether1")).statusCode, 400)
|
||||
assert.equal(nativeRequests, beforeSample + 1)
|
||||
const batch = await app.inject(sampleUrl + "&ifaces=ether1,ether2")
|
||||
assert.equal(batch.statusCode, 200)
|
||||
assert.equal(batch.headers["cache-control"], "no-store")
|
||||
assert.deepEqual(Object.keys(batch.json().interfaces), ["ether1", "ether2"])
|
||||
assert.equal(nativeRequests, beforeSample + 2)
|
||||
mode = "malformed"
|
||||
assert.equal((await app.inject(sampleUrl + "&iface=ether1")).statusCode, 503)
|
||||
mode = "zero"
|
||||
cases += 3
|
||||
cases += 6
|
||||
let stream=await open(),event=await stream.next();assert.equal(event?.event,"sample");assert.equal(event?.data.rxMbps,0);assert.equal(event?.data.timestampKind,"backend-receipt");stream.close();cases++
|
||||
for(const kind of ["empty","malformed","partial"]){mode=kind;two=kind==="partial";stream=await open();event=await stream.next();assert.equal(event?.event,"error");stream.close();cases++}
|
||||
mode="fallback";two=true;stream=await open();event=await stream.next();assert.equal(event?.event,"sample");assert.equal(event?.data.rxMbps,0);stream.close();cases++
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { parseMonitorTraffic, rateBpsFromDelta, bpsToMbps } from "./traffic-rate.js"
|
||||
import { readTrafficLiveSample, TrafficLiveSourceChanged } from "./traffic-live.js"
|
||||
import { readTrafficLiveInterfaces, readTrafficLiveSample, TrafficLiveSourceChanged } from "./traffic-live.js"
|
||||
import { MikrotikError, type MikrotikClient } from "./mikrotik.js"
|
||||
const point=(name="ether1",rx:unknown="0",tx:unknown="0")=>({name,"rx-bits-per-second":rx,"tx-bits-per-second":tx})
|
||||
for(const raw of [[],{},null,[null],[{...point(),"rx-bits-per-second":undefined}], [point("ether1","12bad")],[point("ether1",-1)], [point("ether1"),point("ether1")]]) {
|
||||
@@ -34,4 +34,18 @@ const many={get:async()=>Array.from({length:10},(_,i)=>({name:`ether${i}`,runnin
|
||||
}} as unknown as Pick<MikrotikClient,"get"|"post">
|
||||
const bounded=await readTrafficLiveSample(many,undefined,{names:[],joinedFailed:false},new AbortController().signal,async()=>{})
|
||||
assert.equal(bounded.rxMbps,0);assert.equal(maximum,4)
|
||||
|
||||
const batch = (testClient = cast) =>
|
||||
readTrafficLiveInterfaces(testClient, ["ether1", "ether2"], new AbortController().signal, async () => {})
|
||||
const joined = { ...cast, post: async () => [point("ether2", "0", "80000000"), point("ether1", "1300000", "0")] } as typeof cast
|
||||
const measurements = await batch(joined)
|
||||
assert.equal(measurements.ether1.rxMbps, 1.3)
|
||||
assert.equal(measurements.ether2.txMbps, 80)
|
||||
assert.equal(measurements.ether1.at, measurements.ether2.at)
|
||||
mode = "partial"
|
||||
assert.deepEqual(Object.keys(await batch()), ["ether1"])
|
||||
mode = "fallback"
|
||||
assert.deepEqual(Object.keys(await batch()), ["ether1", "ether2"])
|
||||
mode = "auth"
|
||||
await assert.rejects(batch(), /401/)
|
||||
console.log("traffic live completeness/fallback/auth/source/abort/positive-small-rate tests ok")
|
||||
@@ -1,14 +1,15 @@
|
||||
import { MikrotikError, type MikrotikClient } from "./mikrotik.js"
|
||||
import { isLoopbackName, parseMonitorTraffic, type MonitorLiveSample } from "./traffic-rate.js"
|
||||
import { isLoopbackName, parseMonitorTraffic, parseMonitorTrafficInterfaces, type MonitorLiveSample } from "./traffic-rate.js"
|
||||
|
||||
const TIMEOUT_MS = 4000
|
||||
export class TrafficLiveSourceChanged extends Error {}
|
||||
export interface TrafficLiveCache { names: string[]; joinedFailed: boolean }
|
||||
type Client = Pick<MikrotikClient, "get" | "post">
|
||||
type Monitor = (names: string) => Promise<unknown>
|
||||
|
||||
/** Never emit a partial sum, and check the source before every new native request. */
|
||||
export async function readTrafficLiveSample(client: Client, onlyInterface: string | undefined,
|
||||
cache: TrafficLiveCache, signal: AbortSignal, assertSource: () => Promise<void>): Promise<MonitorLiveSample> {
|
||||
/** Check the source before every new native request. */
|
||||
async function withTrafficMonitor<T>(client: Client, signal: AbortSignal, assertSource: () => Promise<void>,
|
||||
read: (monitor: Monitor, ensure: () => Promise<void>) => Promise<T>): Promise<T> {
|
||||
const parentSignal = signal, wave = new AbortController()
|
||||
const onAbort = () => wave.abort(parentSignal.reason)
|
||||
parentSignal.addEventListener("abort", onAbort, { once: true })
|
||||
@@ -16,52 +17,12 @@ export async function readTrafficLiveSample(client: Client, onlyInterface: strin
|
||||
const timeout = setTimeout(() => wave.abort(new Error("Не успели получить полный live-срез за 8 секунд. Выберите отдельный интерфейс")), 8000)
|
||||
signal = wave.signal
|
||||
try {
|
||||
const ensure = async () => { signal.throwIfAborted(); await assertSource(); signal.throwIfAborted() }
|
||||
const monitor = async (name: string) => {
|
||||
await ensure()
|
||||
return client.post<unknown>("/interface/monitor-traffic", { interface: name, once: "" }, TIMEOUT_MS, signal)
|
||||
}
|
||||
if (onlyInterface) {
|
||||
const raw = await monitor(onlyInterface)
|
||||
await ensure()
|
||||
return parseMonitorTraffic(raw, { onlyInterface })
|
||||
}
|
||||
await ensure()
|
||||
const raw = await client.get<unknown>("/interface", TIMEOUT_MS)
|
||||
if (!Array.isArray(raw)) throw new Error("Не получен каталог интерфейсов live")
|
||||
const names: string[] = []
|
||||
const flag = (value: unknown) => {
|
||||
if (value === true || value === "true" || value === "yes") return true
|
||||
if (value === false || value === "false" || value === "no") return false
|
||||
throw new Error("Неизвестное состояние интерфейса live")
|
||||
}
|
||||
for (const row of raw) {
|
||||
if (!row || typeof row !== "object" || Array.isArray(row) || typeof row.name !== "string" || !row.name.trim()) throw new Error("Некорректный каталог интерфейсов live")
|
||||
if (flag(row.running) && !flag(row.disabled) && !isLoopbackName(row.name)) names.push(row.name)
|
||||
}
|
||||
if (!names.length || new Set(names).size !== names.length) throw new Error("Нет достоверного набора активных интерфейсов live")
|
||||
if ([...names].sort().join("\0") !== [...cache.names].sort().join("\0")) cache.joinedFailed = false
|
||||
cache.names = names
|
||||
if (!cache.joinedFailed) {
|
||||
try {
|
||||
const result = await monitor(names.join(","))
|
||||
const ensure = async () => { signal.throwIfAborted(); await assertSource(); signal.throwIfAborted() }
|
||||
const monitor = async (name: string) => {
|
||||
await ensure()
|
||||
return parseMonitorTraffic(result, { expectedInterfaces: names })
|
||||
} catch (error) {
|
||||
// Unsupported joined command may fall back; auth/transport/invalid payload cannot become partial zero.
|
||||
if (!(error instanceof MikrotikError) || error.statusCode !== 400 || names.length < 2) throw error
|
||||
cache.joinedFailed = true
|
||||
return client.post<unknown>("/interface/monitor-traffic", { interface: name, once: "" }, TIMEOUT_MS, signal)
|
||||
}
|
||||
}
|
||||
const results: MonitorLiveSample[] = []
|
||||
for (let i = 0; i < names.length; i += 4) {
|
||||
results.push(...await Promise.all(names.slice(i, i + 4).map(async name =>
|
||||
parseMonitorTraffic(await monitor(name), { onlyInterface: name }))))
|
||||
}
|
||||
await ensure()
|
||||
const rxMbps = results.reduce((sum, r) => sum + r.rxMbps, 0), txMbps = results.reduce((sum, r) => sum + r.txMbps, 0)
|
||||
if (![rxMbps, txMbps].every(n => Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER / 1_000_000)) throw new Error("Суммарная live-скорость вне допустимого диапазона")
|
||||
return { rxMbps, txMbps, at: new Date().toISOString(), timestampKind: "backend-receipt" }
|
||||
return await read(monitor, ensure)
|
||||
} catch (error) {
|
||||
if (signal.aborted && !parentSignal.aborted && signal.reason instanceof Error) throw signal.reason
|
||||
throw error
|
||||
@@ -71,3 +32,71 @@ export async function readTrafficLiveSample(client: Client, onlyInterface: strin
|
||||
wave.abort()
|
||||
}
|
||||
}
|
||||
|
||||
export function readTrafficLiveInterfaces(client: Client, names: readonly string[], signal: AbortSignal, assertSource: () => Promise<void>) {
|
||||
return withTrafficMonitor(client, signal, assertSource, async (monitor, ensure) => {
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = await monitor(names.join(","))
|
||||
} catch (error) {
|
||||
if (!(error instanceof MikrotikError) || error.statusCode !== 400 || names.length < 2) throw error
|
||||
const samples = []
|
||||
for (let offset = 0; offset < names.length; offset += 4) {
|
||||
const reads = await Promise.allSettled(names.slice(offset, offset + 4).map(async name =>
|
||||
[name, parseMonitorTraffic(await monitor(name), { onlyInterface: name })] as const))
|
||||
for (const read of reads) if (read.status === "fulfilled") samples.push(read.value)
|
||||
}
|
||||
await ensure()
|
||||
return Object.fromEntries(samples)
|
||||
}
|
||||
await ensure()
|
||||
return parseMonitorTrafficInterfaces(raw, names)
|
||||
})
|
||||
}
|
||||
|
||||
export function readTrafficLiveSample(client: Client, onlyInterface: string | undefined,
|
||||
cache: TrafficLiveCache, signal: AbortSignal, assertSource: () => Promise<void>): Promise<MonitorLiveSample> {
|
||||
return withTrafficMonitor(client, signal, assertSource, async (monitor, ensure) => {
|
||||
if (onlyInterface) {
|
||||
const raw = await monitor(onlyInterface)
|
||||
await ensure()
|
||||
return parseMonitorTraffic(raw, { onlyInterface })
|
||||
}
|
||||
await ensure()
|
||||
const raw = await client.get<unknown>("/interface", TIMEOUT_MS)
|
||||
if (!Array.isArray(raw)) throw new Error("Не получен каталог интерфейсов live")
|
||||
const names: string[] = []
|
||||
const flag = (value: unknown) => {
|
||||
if (value === true || value === "true" || value === "yes") return true
|
||||
if (value === false || value === "false" || value === "no") return false
|
||||
throw new Error("Неизвестное состояние интерфейса live")
|
||||
}
|
||||
for (const row of raw) {
|
||||
if (!row || typeof row !== "object" || Array.isArray(row) || typeof row.name !== "string" || !row.name.trim()) throw new Error("Некорректный каталог интерфейсов live")
|
||||
if (flag(row.running) && !flag(row.disabled) && !isLoopbackName(row.name)) names.push(row.name)
|
||||
}
|
||||
if (!names.length || new Set(names).size !== names.length) throw new Error("Нет достоверного набора активных интерфейсов live")
|
||||
if ([...names].sort().join("\0") !== [...cache.names].sort().join("\0")) cache.joinedFailed = false
|
||||
cache.names = names
|
||||
if (!cache.joinedFailed) {
|
||||
try {
|
||||
const result = await monitor(names.join(","))
|
||||
await ensure()
|
||||
return parseMonitorTraffic(result, { expectedInterfaces: names })
|
||||
} catch (error) {
|
||||
// Unsupported joined command may fall back; auth/transport/invalid payload cannot become partial zero.
|
||||
if (!(error instanceof MikrotikError) || error.statusCode !== 400 || names.length < 2) throw error
|
||||
cache.joinedFailed = true
|
||||
}
|
||||
}
|
||||
const results: MonitorLiveSample[] = []
|
||||
for (let i = 0; i < names.length; i += 4) {
|
||||
results.push(...await Promise.all(names.slice(i, i + 4).map(async name =>
|
||||
parseMonitorTraffic(await monitor(name), { onlyInterface: name }))))
|
||||
}
|
||||
await ensure()
|
||||
const rxMbps = results.reduce((sum, r) => sum + r.rxMbps, 0), txMbps = results.reduce((sum, r) => sum + r.txMbps, 0)
|
||||
if (![rxMbps, txMbps].every(n => Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER / 1_000_000)) throw new Error("Суммарная live-скорость вне допустимого диапазона")
|
||||
return { rxMbps, txMbps, at: new Date().toISOString(), timestampKind: "backend-receipt" }
|
||||
})
|
||||
}
|
||||
@@ -360,14 +360,11 @@ export function mergeBuiltTraffic(parts: BuiltTrafficSeries[]): BuiltTrafficSeri
|
||||
} } : acc,waves)
|
||||
}
|
||||
|
||||
export function parseMonitorTraffic(
|
||||
raw: unknown,
|
||||
opts?: { onlyInterface?: string; expectedInterfaces?: readonly string[] },
|
||||
): MonitorLiveSample {
|
||||
type MonitorTrafficSelection = { onlyInterface?: string; expectedInterfaces?: readonly string[]; allowMissing?: boolean }
|
||||
|
||||
function monitorTrafficRates(raw: unknown, opts?: MonitorTrafficSelection) {
|
||||
const items = Array.isArray(raw) ? raw : raw != null ? [raw] : []
|
||||
let rxBps = 0
|
||||
let txBps = 0
|
||||
const seen = new Set<string>()
|
||||
const samples = new Map<string, { rxBps: number; txBps: number }>()
|
||||
const expected = opts?.expectedInterfaces ? new Set(opts.expectedInterfaces) : null
|
||||
const rate = (raw: unknown) => {
|
||||
if (typeof raw !== "number" && (typeof raw !== "string" || !/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(raw.trim()))) throw new Error("Некорректная скорость monitor-traffic")
|
||||
@@ -382,21 +379,33 @@ export function parseMonitorTraffic(
|
||||
if (typeof name !== "string" || !name.trim()) throw new Error("Не указан интерфейс monitor-traffic")
|
||||
if (opts?.onlyInterface) {
|
||||
if (name !== opts.onlyInterface) throw new Error("Ответ monitor-traffic относится к другому интерфейсу")
|
||||
} else if (isLoopbackName(name)) {
|
||||
} else if (isLoopbackName(name) && !expected?.has(name)) {
|
||||
continue
|
||||
}
|
||||
if (seen.has(name) || expected && !expected.has(name)) throw new Error("Некорректный набор интерфейсов monitor-traffic")
|
||||
seen.add(name)
|
||||
rxBps += rate(rec["rx-bits-per-second"])
|
||||
txBps += rate(rec["tx-bits-per-second"])
|
||||
}
|
||||
if (!seen.size || expected && (expected.size !== opts!.expectedInterfaces!.length ||
|
||||
[...expected].some(name => !seen.has(name)))) throw new Error("Не получены все live-измерения интерфейсов")
|
||||
if (![rxBps, txBps].every(n => Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER)) throw new Error("Суммарная live-скорость вне допустимого диапазона")
|
||||
return {
|
||||
rxMbps: rxBps / 1_000_000,
|
||||
txMbps: txBps / 1_000_000,
|
||||
at: new Date().toISOString(),
|
||||
timestampKind: "backend-receipt",
|
||||
if (samples.has(name) || expected && !expected.has(name)) throw new Error("Некорректный набор интерфейсов monitor-traffic")
|
||||
samples.set(name, {
|
||||
rxBps: rate(rec["rx-bits-per-second"]),
|
||||
txBps: rate(rec["tx-bits-per-second"]),
|
||||
})
|
||||
}
|
||||
if (!opts?.allowMissing && (!samples.size || expected && (expected.size !== opts!.expectedInterfaces!.length ||
|
||||
samples.size !== expected.size))) throw new Error("Не получены все live-измерения интерфейсов")
|
||||
return samples
|
||||
}
|
||||
|
||||
export function parseMonitorTrafficInterfaces(raw: unknown, expectedInterfaces: readonly string[]): Record<string, MonitorLiveSample> {
|
||||
const at = new Date().toISOString()
|
||||
return Object.fromEntries([...monitorTrafficRates(raw, { expectedInterfaces, allowMissing: true })].map(([name, sample]) =>
|
||||
[name, { rxMbps: sample.rxBps / 1_000_000, txMbps: sample.txBps / 1_000_000, at, timestampKind: "backend-receipt" }]))
|
||||
}
|
||||
|
||||
export function parseMonitorTraffic(
|
||||
raw: unknown,
|
||||
opts?: { onlyInterface?: string; expectedInterfaces?: readonly string[] },
|
||||
): MonitorLiveSample {
|
||||
const samples = [...monitorTrafficRates(raw, opts).values()]
|
||||
const rxBps = samples.reduce((sum, row) => sum + row.rxBps, 0)
|
||||
const txBps = samples.reduce((sum, row) => sum + row.txBps, 0)
|
||||
if (![rxBps, txBps].every(n => Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER)) throw new Error("Суммарная live-скорость вне допустимого диапазона")
|
||||
return { rxMbps: rxBps / 1_000_000, txMbps: txBps / 1_000_000, at: new Date().toISOString(), timestampKind: "backend-receipt" }
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { NavMain, type NavGroup } from "@/components/nav-main"
|
||||
import { NavMain, type NavGroup, type NavItem } from "@/components/nav-main"
|
||||
import { AppSwitcher } from "@/components/app-switcher"
|
||||
import { NavUser } from "@/components/nav-user"
|
||||
import {
|
||||
@@ -12,103 +12,43 @@ import {
|
||||
} from "@/components/ui/sidebar"
|
||||
import { navigationGroups } from "@/lib/navigation"
|
||||
import { useDataSource } from "@/lib/data-source"
|
||||
import { can,ensureAuthConfig } from "@/lib/auth"
|
||||
import { useEvoBGP } from "@/lib/evobgp-context"
|
||||
import {getSidebarCounts,getSidebarGreCount} from "@/shared/api/sidebar-counts"
|
||||
import {
|
||||
formatSidebarBadgeCount,
|
||||
mockSidebarBadgesByUrl,
|
||||
type SidebarCountsDto,
|
||||
} from "@/lib/sidebar-badges"
|
||||
import { pingProbes, servers } from "@/lib/data"
|
||||
|
||||
type LiveSidebarCounts = Partial<SidebarCountsDto> & {
|
||||
greTunnels?: number
|
||||
certificates?: number
|
||||
wireguard?: number
|
||||
ipsec?: number
|
||||
users?: number
|
||||
bgpSessions?: number
|
||||
vxlan?: number
|
||||
containers?: number
|
||||
/**
|
||||
* Точки проблем у разделов. В демо — из моков; живой источник проблем по разделам API пока не отдаёт,
|
||||
* поэтому в live-режиме точек нет (неизвестное не выдаём за «всё в норме» и не рисуем ложные сбои).
|
||||
*/
|
||||
function demoProblems(): Record<string, NavItem["problem"]> {
|
||||
const offline = servers.filter((s) => s.enabled && s.status === "offline").length
|
||||
const degraded = servers.filter((s) => s.enabled && s.status === "degraded").length
|
||||
const down = pingProbes.filter((p) => p.enabled && p.status === "down").length
|
||||
const warn = pingProbes.filter((p) => p.enabled && p.status === "warn").length
|
||||
return {
|
||||
"/servers": offline ? { tone: "er", label: `Не в сети: ${offline}` } : degraded ? { tone: "wn", label: `С ухудшением: ${degraded}` } : undefined,
|
||||
"/uptime": down ? { tone: "er", label: `Проверок с ошибкой: ${down}` } : warn ? { tone: "wn", label: `Проверок с предупреждением: ${warn}` } : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/** Боковое меню общего макета v2 и EvoBGP: переключатель приложений, поиск ⌘K, закреплённые, группы, профиль. */
|
||||
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
|
||||
const { mode, backendUrl, prefsHydrated } = useDataSource()
|
||||
const evo = useEvoBGP()
|
||||
const [mounted, setMounted] = React.useState(false)
|
||||
const [snapshot, setSnapshot] = React.useState<{source:string;counts:LiveSidebarCounts}|null>(null)
|
||||
const source=JSON.stringify([mode,backendUrl]),liveCounts=snapshot?.source===source?snapshot.counts:null
|
||||
const countsAllowed=can("mm:dashboard:read"),greAllowed=can("mm:filters:read")
|
||||
|
||||
const mockBadges = React.useMemo(() => mockSidebarBadgesByUrl(), [])
|
||||
|
||||
React.useEffect(() => {
|
||||
let cancelled=false
|
||||
void ensureAuthConfig().then(()=>{if(!cancelled)setMounted(true)})
|
||||
return()=>{cancelled=true}
|
||||
}, [])
|
||||
|
||||
React.useEffect(() => {
|
||||
if(!mounted||!prefsHydrated||mode!=="live")return
|
||||
let cancelled=false,revision=0,controller:AbortController|null=null
|
||||
const load=async()=>{
|
||||
controller?.abort();controller=new AbortController();const request=++revision,signal=AbortSignal.any([controller.signal,AbortSignal.timeout(30_000)])
|
||||
const publish=(counts:LiveSidebarCounts)=>{if(cancelled||request!==revision)return;setSnapshot(previous=>({source,counts:{...(previous?.source===source?previous.counts:{}),...counts}}))}
|
||||
await Promise.allSettled([
|
||||
can("mm:dashboard:read")?getSidebarCounts(backendUrl,signal).then(counts=>{if(can("mm:dashboard:read"))publish(counts)}):Promise.resolve(),
|
||||
can("mm:filters:read")?getSidebarGreCount(backendUrl,signal).then(greTunnels=>{if(can("mm:filters:read"))publish({greTunnels})}):Promise.resolve(),
|
||||
])
|
||||
}
|
||||
void load();const timer=window.setInterval(load,120_000)
|
||||
return()=>{cancelled=true;revision++;controller?.abort();window.clearInterval(timer)}
|
||||
},[mounted,mode,backendUrl,prefsHydrated,source,countsAllowed,greAllowed])
|
||||
const { mode, prefsHydrated } = useDataSource()
|
||||
|
||||
const navGroups = React.useMemo((): NavGroup[] => {
|
||||
function badgeFor(url: string): string | undefined {
|
||||
if (mode !== "live") return mockBadges[url]
|
||||
|
||||
if (url === "/domains" || url === "/ip-ranges" || url === "/asns") {
|
||||
if (!evo.settingsLoaded || !evo.enabled || !can("mm:settings:admin")) return undefined
|
||||
if (!evo.snapshot) return undefined
|
||||
if (url === "/domains") return formatSidebarBadgeCount(evo.snapshot.domains.length)
|
||||
if (url === "/ip-ranges") return formatSidebarBadgeCount(evo.snapshot.ipRanges.length)
|
||||
return formatSidebarBadgeCount(evo.snapshot.asns.length)
|
||||
}
|
||||
|
||||
if (!liveCounts||(!countsAllowed&&url!=="/gre")) return undefined
|
||||
const permission=({"/servers":"mm:servers:read","/users":"mm:users:read","/filters":"mm:filters:read","/uptime":"mm:uptime:read","/gre":"mm:filters:read","/certificates":"mm:certificates:read","/wireguard":"mm:network:read","/ipsec":"mm:network:read","/bgp":"mm:bgp:read","/vxlan":"mm:network:read","/containers":"mm:dashboard:read"} as Record<string,string>)[url]
|
||||
if(permission&&!can(permission))return undefined
|
||||
const format=(value:number|undefined)=>value===undefined?undefined:formatSidebarBadgeCount(value)
|
||||
|
||||
if (url === "/servers") return format(liveCounts.servers)
|
||||
if (url === "/users") return format(liveCounts.users )
|
||||
if (url === "/filters") return format(liveCounts.filterRules)
|
||||
if (url === "/uptime") return format(liveCounts.monitoringItems)
|
||||
if (url === "/gre") return format(liveCounts.greTunnels )
|
||||
if (url === "/certificates") return format(liveCounts.certificates )
|
||||
if (url === "/wireguard") return format(liveCounts.wireguard )
|
||||
if (url === "/ipsec") return format(liveCounts.ipsec )
|
||||
if (url === "/bgp") return format(liveCounts.bgpSessions )
|
||||
if (url === "/vxlan") return format(liveCounts.vxlan )
|
||||
if (url === "/containers") return format(liveCounts.containers )
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
const problems = prefsHydrated && mode !== "live" ? demoProblems() : {}
|
||||
return navigationGroups.map((g) => ({
|
||||
label: g.label,
|
||||
items: g.items.map((it) => ({
|
||||
title: it.title,
|
||||
url: it.url,
|
||||
icon: React.createElement(it.icon, { "aria-hidden": true }),
|
||||
badge: mounted ? badgeFor(it.url) : undefined,
|
||||
problem: problems[it.url],
|
||||
})),
|
||||
}))
|
||||
}, [mounted, mode, liveCounts, countsAllowed, mockBadges, evo.settingsLoaded, evo.enabled, evo.snapshot])
|
||||
}, [mode, prefsHydrated])
|
||||
|
||||
return (
|
||||
<Sidebar variant="inset" collapsible="icon" {...props}>
|
||||
<SidebarHeader>
|
||||
<Sidebar collapsible="icon" {...props}>
|
||||
<SidebarHeader className="pb-1.5">
|
||||
<AppSwitcher />
|
||||
</SidebarHeader>
|
||||
<SidebarContent>
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
import {
|
||||
APP_SWITCHER_ICONS,
|
||||
CURRENT_APP_ID,
|
||||
authPortalBaseUrl,
|
||||
getCurrentApp,
|
||||
} from "@/lib/app-switcher-config"
|
||||
import { useAppSwitcherConfig } from "@/hooks/use-app-switcher"
|
||||
@@ -26,6 +28,8 @@ export function AppSwitcher() {
|
||||
const { isMobile } = useSidebar()
|
||||
const { config, isLoading } = useAppSwitcherConfig()
|
||||
const current = getCurrentApp(config)
|
||||
const portalBase = authPortalBaseUrl()
|
||||
const portalAppsUrl = portalBase ? `${portalBase}/admin/apps` : null
|
||||
const CurrentIcon = APP_SWITCHER_ICONS[current.icon] ?? APP_SWITCHER_ICONS.server
|
||||
|
||||
return (
|
||||
@@ -34,7 +38,7 @@ export function AppSwitcher() {
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<SidebarMenuButton size="lg" className="aria-expanded:bg-muted" />
|
||||
<SidebarMenuButton size="lg" aria-label={`Переключатель приложений: ${current.name}`} className="aria-expanded:bg-muted" />
|
||||
}
|
||||
>
|
||||
<div
|
||||
@@ -89,6 +93,12 @@ export function AppSwitcher() {
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
})}
|
||||
{portalAppsUrl ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem render={<a href={portalAppsUrl} />}>Настроить на портале</DropdownMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</SidebarMenuItem>
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { LayoutGridIcon } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import {
|
||||
APP_SWITCHER_ICONS,
|
||||
CURRENT_APP_ID,
|
||||
authPortalBaseUrl,
|
||||
} from "@/lib/app-switcher-config"
|
||||
import { useAppSwitcherConfig } from "@/hooks/use-app-switcher"
|
||||
|
||||
/** Header apps grid — app-shell-12. @see https://reui.io/preview/base/app-shell-12 */
|
||||
export function AppsMenu() {
|
||||
const { config, isLoading } = useAppSwitcherConfig()
|
||||
const portalBase = authPortalBaseUrl()
|
||||
const portalAppsUrl = portalBase ? `${portalBase}/admin/apps` : null
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<Button variant="ghost" size="icon" aria-label="Приложения" />
|
||||
}
|
||||
>
|
||||
<LayoutGridIcon className="size-4.5" aria-hidden="true" />
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent
|
||||
side="bottom"
|
||||
align="end"
|
||||
sideOffset={8}
|
||||
className="w-72"
|
||||
>
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuLabel>
|
||||
{isLoading ? "Загрузка…" : config.menuLabel}
|
||||
</DropdownMenuLabel>
|
||||
<div className="grid grid-cols-3 gap-1 p-1">
|
||||
{config.apps.map((app) => {
|
||||
const Icon = APP_SWITCHER_ICONS[app.icon] ?? APP_SWITCHER_ICONS.server
|
||||
const isCurrent = app.id === CURRENT_APP_ID
|
||||
|
||||
if (isCurrent) {
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={app.id}
|
||||
disabled
|
||||
className="h-auto flex-col gap-1.5 py-3 text-center [&_svg]:size-5"
|
||||
>
|
||||
<span className="text-muted-foreground">
|
||||
<Icon aria-hidden="true" />
|
||||
</span>
|
||||
<span className="text-xs font-medium">{app.name}</span>
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={app.id}
|
||||
render={<a href={app.url} />}
|
||||
className="h-auto flex-col gap-1.5 py-3 text-center [&_svg]:size-5"
|
||||
>
|
||||
<span className="text-muted-foreground">
|
||||
<Icon aria-hidden="true" />
|
||||
</span>
|
||||
<span className="text-xs font-medium">{app.name}</span>
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{portalAppsUrl ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
render={<a href={portalAppsUrl} />}
|
||||
className="justify-center text-sm font-medium"
|
||||
>
|
||||
Настроить на портале
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
@@ -6,6 +6,13 @@ import { navigationGroups } from "@/lib/navigation"
|
||||
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command"
|
||||
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog"
|
||||
|
||||
const OPEN_EVENT = "mm:open-command-palette"
|
||||
|
||||
/** Открыть палитру из кнопки «Поиск и команды» (сайдбар) или поиска в шапке на телефоне. */
|
||||
export function openCommandPalette() {
|
||||
window.dispatchEvent(new Event(OPEN_EVENT))
|
||||
}
|
||||
|
||||
/** Keyboard search from the App Shell 12 composition, using installed Base UI primitives. */
|
||||
export function CommandPalette() {
|
||||
const [open, setOpen] = useState(false)
|
||||
@@ -26,8 +33,18 @@ export function CommandPalette() {
|
||||
setOpen(!open)
|
||||
}
|
||||
}
|
||||
function onOpen() {
|
||||
if (open) return
|
||||
returnFocusRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null
|
||||
setQuery("")
|
||||
setOpen(true)
|
||||
}
|
||||
window.addEventListener("keydown", onKey)
|
||||
return () => window.removeEventListener("keydown", onKey)
|
||||
window.addEventListener(OPEN_EVENT, onOpen)
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKey)
|
||||
window.removeEventListener(OPEN_EVENT, onOpen)
|
||||
}
|
||||
}, [open])
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,22 +1,30 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { usePathname } from "next/navigation"
|
||||
import { ChevronDownIcon, SearchIcon, StarIcon } from "lucide-react"
|
||||
import {
|
||||
SidebarGroup,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarSeparator,
|
||||
useSidebar,
|
||||
} from "@/components/ui/sidebar"
|
||||
import { Kbd } from "@/components/ui/kbd"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { openCommandPalette } from "@/components/command-palette"
|
||||
|
||||
export interface NavItem {
|
||||
title: string
|
||||
url: string
|
||||
icon?: React.ReactNode
|
||||
/** Если `undefined` — счётчик не показываем (нет данных или раздел без live-источника). */
|
||||
badge?: string
|
||||
/** Точка проблемы у пункта: сбой (er) или внимание (wn); без данных — не показываем. */
|
||||
problem?: { tone: "er" | "wn"; label: string }
|
||||
}
|
||||
|
||||
export interface NavGroup {
|
||||
@@ -24,36 +32,144 @@ export interface NavGroup {
|
||||
items: NavItem[]
|
||||
}
|
||||
|
||||
export function NavMain({ groups }: { groups: NavGroup[] }) {
|
||||
const PINS_KEY = "mm:sidebar-pins"
|
||||
const CLOSED_KEY = "mm:sidebar-closed-groups"
|
||||
const DOT_CLASS = { er: "bg-destructive", wn: "bg-warning" } as const
|
||||
|
||||
function readList(key: string): string[] {
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(key) ?? "[]")
|
||||
return Array.isArray(raw) ? raw.filter((v): v is string => typeof v === "string") : []
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function writeList(key: string, list: string[]) {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(list))
|
||||
} catch {
|
||||
/* хранилище недоступно — настройка действует до перезагрузки */
|
||||
}
|
||||
}
|
||||
|
||||
function NavEntry({ item, pinned, onTogglePin }: { item: NavItem; pinned: boolean; onTogglePin: () => void }) {
|
||||
const pathname = usePathname()
|
||||
const { setOpenMobile } = useSidebar()
|
||||
const active = pathname === item.url || pathname.startsWith(`${item.url}/`)
|
||||
return (
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
isActive={active}
|
||||
tooltip={item.problem ? `${item.title} · ${item.problem.label}` : item.title}
|
||||
className="relative pr-8 group-data-[collapsible=icon]:pr-2!"
|
||||
render={<Link href={item.url} aria-current={active ? "page" : undefined} onNavigate={() => setOpenMobile(false)} />}
|
||||
>
|
||||
{item.icon}
|
||||
<span>{item.title}</span>
|
||||
{item.problem ? (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={item.problem.label}
|
||||
className={cn(
|
||||
"ml-auto size-2 shrink-0 rounded-full group-data-[collapsible=icon]:absolute group-data-[collapsible=icon]:top-1 group-data-[collapsible=icon]:right-1 group-data-[collapsible=icon]:ml-0 group-data-[collapsible=icon]:size-1.5 group-data-[collapsible=icon]:ring-2 group-data-[collapsible=icon]:ring-sidebar",
|
||||
DOT_CLASS[item.problem.tone],
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
</SidebarMenuButton>
|
||||
<SidebarMenuAction
|
||||
showOnHover={!pinned}
|
||||
aria-label={pinned ? `Открепить ${item.title}` : `Закрепить ${item.title}`}
|
||||
aria-pressed={pinned}
|
||||
onClick={onTogglePin}
|
||||
>
|
||||
<StarIcon className={cn(pinned && "fill-current")} aria-hidden />
|
||||
</SidebarMenuAction>
|
||||
</SidebarMenuItem>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Навигация общего макета v2 (как в EvoBGP): поиск ⌘K, «Закреплённые», сворачиваемые группы,
|
||||
* точки проблем у разделов.
|
||||
*/
|
||||
export function NavMain({ groups }: { groups: NavGroup[] }) {
|
||||
const [pins, setPins] = useState<string[]>([])
|
||||
const [closed, setClosed] = useState<string[]>([])
|
||||
useEffect(() => {
|
||||
queueMicrotask(() => {
|
||||
setPins(readList(PINS_KEY))
|
||||
setClosed(readList(CLOSED_KEY))
|
||||
})
|
||||
}, [])
|
||||
|
||||
const items = groups.flatMap((g) => g.items)
|
||||
const pinned = pins.map((url) => items.find((i) => i.url === url)).filter((i): i is NavItem => Boolean(i))
|
||||
const togglePin = (url: string) => setPins((prev) => {
|
||||
const next = prev.includes(url) ? prev.filter((u) => u !== url) : [...prev, url]
|
||||
writeList(PINS_KEY, next)
|
||||
return next
|
||||
})
|
||||
const toggleGroup = (label: string) => setClosed((prev) => {
|
||||
const next = prev.includes(label) ? prev.filter((l) => l !== label) : [...prev, label]
|
||||
writeList(CLOSED_KEY, next)
|
||||
return next
|
||||
})
|
||||
|
||||
return (
|
||||
<nav aria-label="Основная навигация">
|
||||
{groups.map((group) => (
|
||||
<SidebarGroup key={group.label}>
|
||||
<SidebarGroupLabel>{group.label}</SidebarGroupLabel>
|
||||
<SidebarMenu>
|
||||
{group.items.map((item) => (
|
||||
<SidebarMenuItem key={item.title}>
|
||||
<SidebarMenuButton
|
||||
isActive={pathname === item.url}
|
||||
tooltip={item.title}
|
||||
render={<Link href={item.url} aria-current={pathname === item.url ? "page" : undefined} onNavigate={() => setOpenMobile(false)} />}
|
||||
>
|
||||
{item.icon}
|
||||
<span>{item.title}</span>
|
||||
{item.badge != null && item.badge !== "" && (
|
||||
<span className="ml-auto text-[10.5px] font-mono tabular-nums text-sidebar-foreground/50 group-data-[collapsible=icon]:hidden">
|
||||
{item.badge}
|
||||
</span>
|
||||
)}
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
))}
|
||||
</SidebarMenu>
|
||||
<nav aria-label="Основная навигация" className="flex flex-col">
|
||||
<SidebarGroup className="pb-1">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
tooltip="Поиск и команды"
|
||||
onClick={openCommandPalette}
|
||||
className="border-sidebar-border text-sidebar-foreground/70 border"
|
||||
>
|
||||
<SearchIcon aria-hidden />
|
||||
<span>Поиск и команды</span>
|
||||
<Kbd className="ml-auto group-data-[collapsible=icon]:hidden">⌘K</Kbd>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
|
||||
{pinned.length > 0 ? (
|
||||
<SidebarGroup className="py-0 group-data-[collapsible=icon]:hidden">
|
||||
<SidebarGroupLabel className="text-xs font-semibold tracking-wide uppercase">Закреплённые</SidebarGroupLabel>
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu className="gap-px">
|
||||
{pinned.map((item) => <NavEntry key={item.url} item={item} pinned onTogglePin={() => togglePin(item.url)} />)}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
))}
|
||||
) : null}
|
||||
|
||||
{groups.map((group, gi) => {
|
||||
const isClosed = closed.includes(group.label)
|
||||
return (
|
||||
<div key={group.label} className="flex flex-col">
|
||||
{gi > 0 ? <SidebarSeparator className="mx-2 my-1 hidden h-px shrink-0 group-data-[collapsible=icon]:block" /> : null}
|
||||
<SidebarGroup className="py-0">
|
||||
<SidebarGroupLabel
|
||||
render={<button type="button" aria-expanded={!isClosed} onClick={() => toggleGroup(group.label)} />}
|
||||
className="h-7 cursor-pointer justify-between text-xs font-semibold tracking-wide uppercase"
|
||||
>
|
||||
{group.label}
|
||||
<ChevronDownIcon className={cn("size-3.5 transition-transform", isClosed && "-rotate-90")} aria-hidden />
|
||||
</SidebarGroupLabel>
|
||||
<SidebarGroupContent className={cn(isClosed && "hidden group-data-[collapsible=icon]:block")}>
|
||||
<SidebarMenu className="gap-px">
|
||||
{group.items.map((item) => (
|
||||
<NavEntry key={item.url} item={item} pinned={pins.includes(item.url)} onTogglePin={() => togglePin(item.url)} />
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
@@ -1,51 +1,51 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useRef } from "react"
|
||||
import { InfoIcon } from "lucide-react"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { InfoIcon, LockIcon, UsersIcon } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
|
||||
|
||||
const STATUS = [["var(--success)", "Онлайн"], ["var(--warning)", "Внимание"], ["var(--destructive)", "Оффлайн"], ["var(--muted-foreground)", "Неизвестно"]] as const
|
||||
const ROLES = [["HR", "Home Router", "var(--chart-2)"], ["JH", "JumpHost", "var(--chart-1)"], ["EN", "Exit Node", "var(--chart-3)"], ["IX", "IX Node", "var(--chart-4)"]] as const
|
||||
|
||||
/** Легенда карты макета v3: статус, роли узлов, виды связей и что значат подписи. */
|
||||
export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
|
||||
const details = useRef<HTMLDetailsElement>(null)
|
||||
useEffect(() => {
|
||||
if (compact && details.current) details.current.open = false
|
||||
}, [compact])
|
||||
const head = "text-muted-foreground mt-1 text-[11px] font-semibold tracking-wider uppercase"
|
||||
return (
|
||||
<details ref={details} data-map-legend className="relative">
|
||||
<summary className="border-border/60 text-muted-foreground hover:text-foreground flex h-7 cursor-pointer list-none items-center gap-1.5 rounded-md border px-2.5 text-xs transition-colors focus-visible:outline-2 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">
|
||||
<InfoIcon aria-hidden="true" className="size-3.5" />Легенда
|
||||
</summary>
|
||||
<div role="region" aria-label="Легенда карты" className="bg-popover text-popover-foreground absolute top-full right-0 z-30 mt-1 max-sm:fixed max-sm:inset-x-4 max-sm:top-auto max-sm:w-auto flex max-h-[60vh] w-56 max-w-[calc(100vw-2rem)] flex-col gap-2 overflow-y-auto rounded-lg border px-3 py-2 text-xs shadow-md">
|
||||
<div>
|
||||
<p className="mb-1.5 font-medium text-muted-foreground">Статус устройства</p>
|
||||
<div className="grid grid-cols-2 gap-x-2 gap-y-1.5">
|
||||
{[["var(--status-online)", "Онлайн"], ["var(--status-degraded)", "Внимание"], ["var(--status-offline)", "Оффлайн"], ["var(--muted-foreground)", "Неизвестно"]].map(([color, label]) => (
|
||||
<span key={label} className="flex items-center gap-1.5"><span aria-hidden className="size-2 shrink-0 rounded-full" style={{ background: color }} />{label}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<p className="font-medium text-muted-foreground">Тип узла</p>
|
||||
{[["JH", "JumpHost", "var(--chart-1)"], ["EN", "Exit Node", "var(--chart-3)"], ["HR", "Home Router", "var(--chart-2)"], ["IX", "IX Node", "var(--chart-4)"]].map(([label, name, color]) => (
|
||||
<span key={label} className="flex items-center gap-2"><Badge variant="secondary" style={{ color }} className="min-w-8 justify-center text-xs">{label}</Badge><span>{name}</span></span>
|
||||
<Popover key={compact ? "compact" : "overview"}>
|
||||
<PopoverTrigger render={<Button type="button" variant="outline" className="text-[13px]" />}>
|
||||
<InfoIcon aria-hidden="true" className="size-4" />Легенда
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="end" role="region" aria-label="Легенда карты" className="max-h-[min(60vh,var(--available-height))] w-[310px] max-w-[calc(100vw-2rem)] gap-2 overflow-y-auto border p-3 text-xs">
|
||||
<p className={head}>Статус</p>
|
||||
<div className="grid grid-cols-2 gap-x-2.5 gap-y-1.5">
|
||||
{STATUS.map(([color, label]) => (
|
||||
<span key={label} className="flex items-center gap-2"><span aria-hidden className="size-2 shrink-0 rounded-full" style={{ background: color }} />{label}</span>
|
||||
))}
|
||||
<span className="flex items-center gap-2"><span aria-hidden className="mx-1 size-3 rounded-full border border-current" />WAN · аплинк</span>
|
||||
<span className="flex items-center gap-2"><span aria-hidden className="mx-1 size-3 rounded border border-current" />Сервис / страна</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<p className="font-medium text-muted-foreground">Связи и измерения</p>
|
||||
{[
|
||||
["GRE", "var(--status-online)", undefined],
|
||||
["GRE + IPsec", "var(--status-online)", "7 4"],
|
||||
["Поток NetFlow", "var(--chart-4)", "6 5"],
|
||||
["WAN → JH · модель", "var(--muted-foreground)", "5 4"],
|
||||
].map(([label, color, dash]) => (
|
||||
<span key={label} className="flex items-center gap-2"><svg aria-hidden width="28" height="12" className="shrink-0"><line x1="0" y1="6" x2="28" y2="6" stroke={color} strokeWidth="2" strokeDasharray={dash} /></svg>{label}</span>
|
||||
<p className={head}>Узлы</p>
|
||||
<div className="grid grid-cols-2 gap-x-2.5 gap-y-1.5">
|
||||
{ROLES.map(([label, name, color]) => (
|
||||
<span key={label} className="flex items-center gap-2">
|
||||
<b className="bg-muted inline-flex h-[18px] w-7 items-center justify-center rounded-[5px] font-mono text-[10.5px] font-semibold" style={{ color }}>{label}</b><span>{name}</span>
|
||||
</span>
|
||||
))}
|
||||
<p className="text-muted-foreground">RTT · задержка пробы. «—» · нет измерения.</p>
|
||||
<p className="text-muted-foreground">NetFlow · трафик за 5 минут, не пропускная способность канала.</p>
|
||||
<p className="text-muted-foreground">Live GRE · текущие RX/TX в деталях туннеля.</p>
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="28" height="16" viewBox="0 0 28 16"><rect x="1" y="2" width="26" height="12" rx="6" fill="none" stroke="var(--muted-foreground)" strokeWidth="1.5" /></svg>WAN-аплинк</span>
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="28" height="16" viewBox="0 0 28 16"><rect x="1" y="2" width="26" height="12" rx="3" fill="none" stroke="var(--muted-foreground)" strokeWidth="1.5" /></svg>Сервис / страна</span>
|
||||
<span className="flex items-center gap-2"><UsersIcon aria-hidden className="size-4" />Пользователи</span>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
<p className={head}>Связи</p>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--success)" strokeWidth="3" /></svg>GRE-туннель</span>
|
||||
<span className="flex items-center gap-2"><LockIcon aria-hidden className="mx-2 size-4" />GRE + IPsec</span>
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--destructive)" strokeWidth="3" /></svg>GRE · нет связи</span>
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeWidth="2" /></svg>Home Router → аплинк</span>
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeOpacity=".5" strokeWidth="2" /></svg>WAN → JH · модель связности</span>
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="12" viewBox="0 0 32 12"><path d="M0 3 C16 3 16 9 32 9" fill="none" stroke="var(--chart-4)" strokeWidth="2" /></svg>Связь с сервисом</span>
|
||||
<span className="flex items-center gap-2"><Badge variant="outline" size="xs">IPFIX</Badge>Наблюдение экспортёра · выход не подтверждён</span>
|
||||
</div>
|
||||
<p className="text-muted-foreground leading-snug">Подпись линии GRE показывает последний замер RX/TX интерфейса RouterOS. Скорость сервиса и знак «≈» показывают среднюю скорость по принятым записям IPFIX. RTT — задержка пробы, «—» означает, что нет измерения.</p>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, type ReactNode } from "react"
|
||||
import Link from "next/link"
|
||||
import { ChevronRightIcon, XIcon } from "lucide-react"
|
||||
import type { FlowAnalyticsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath, FlowMapUser } from "@mmapp/contracts/traffic-flow"
|
||||
import { flowMapHopsDtoSchema } from "@mmapp/contracts/traffic-flow"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Sparkline } from "@/components/sparkline"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { formatBytes, fmtRate } from "@/lib/fmt-rate"
|
||||
import { formatNetflowRate } from "@/lib/map-netflow-hops"
|
||||
import { servicePathKey } from "@/lib/format-service-path-label"
|
||||
import { projectTrafficObservations } from "@/lib/traffic-observations"
|
||||
import { getFlowAnalytics, getFlowMapHops } from "@/shared/api/traffic-flow"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
import { matchesMapService } from "@/lib/flow-map-service-match"
|
||||
|
||||
export function InspectorMetrics({ rows }: { rows: [string, ReactNode, string?][] }) {
|
||||
return <dl className="grid grid-cols-2 gap-px overflow-hidden rounded-t-lg border-b bg-border">
|
||||
{rows.map(([name, value, title]) => <div key={name} title={title} className="flex min-w-0 flex-col gap-0.5 bg-card px-3.5 py-2.5">
|
||||
<dt className="text-[11px] text-muted-foreground">{name}</dt>
|
||||
<dd className="font-mono text-sm font-semibold leading-tight [overflow-wrap:anywhere]">{value}</dd>
|
||||
</div>)}
|
||||
</dl>
|
||||
}
|
||||
|
||||
export function serviceUsers(service: FlowMapService, paths: FlowMapServicePath[]): FlowMapUser[] {
|
||||
const users = new Map<string, FlowMapUser>()
|
||||
function add(clientId: string, clientName: string, bytes: number, bps: number) {
|
||||
const user = users.get(clientId) ?? { clientId, clientName, bytes: 0, bps: 0 }
|
||||
user.bytes += bytes
|
||||
user.bps += bps
|
||||
users.set(clientId, user)
|
||||
}
|
||||
let attributedBytes = 0
|
||||
for (const p of paths) {
|
||||
add(p.clientId, p.clientName, p.bytes, p.bps)
|
||||
attributedBytes += p.bytes
|
||||
}
|
||||
if (service.bytes > attributedBytes) {
|
||||
const bytes = service.bytes - attributedBytes
|
||||
add("—", "—", bytes, service.bps * bytes / service.bytes)
|
||||
}
|
||||
return [...users.values()]
|
||||
}
|
||||
|
||||
export function InspectorUsers({ users, windowLabel }: { users?: FlowMapUser[]; windowLabel: string }) {
|
||||
const ranked = [...(users ?? [])].sort((a, b) => b.bytes - a.bytes || a.clientName.localeCompare(b.clientName))
|
||||
const total = ranked.reduce((sum, user) => sum + user.bytes, 0)
|
||||
return <section aria-label="Трафик по пользователям" title="Сохранённые потоки NetFlow и привязки интерфейсов. Узел может быть определён по наблюдаемому GRE-соседу." className="space-y-2 border-b px-3.5 py-3">
|
||||
<h3 className="flex justify-between gap-2 font-mono text-[11px] text-muted-foreground">
|
||||
<span>Пользователи</span><span>NetFlow · {windowLabel}</span>
|
||||
</h3>
|
||||
{!ranked.length && <p className="text-xs text-muted-foreground">{users ? "Нет сохранённых потоков в этом интервале" : "Разбивка в этом снимке недоступна"}</p>}
|
||||
{ranked.length > 0 && <ul className="max-h-52 space-y-2 overflow-y-auto">
|
||||
{ranked.map(user => <li key={user.clientId} className="flex items-start justify-between gap-2 text-xs">
|
||||
<span className="min-w-0 font-medium [overflow-wrap:anywhere]">{user.clientId === "—" ? "Без привязки к пользователю" : user.clientName}</span>
|
||||
<span className="shrink-0 text-right font-mono tabular-nums">
|
||||
{formatNetflowRate(user)}
|
||||
<span className="block text-[10px] text-muted-foreground">{formatBytes(user.bytes)}{total > 0 && ` · ${Math.round(user.bytes / total * 100)}%`}</span>
|
||||
</span>
|
||||
</li>)}
|
||||
</ul>}
|
||||
</section>
|
||||
}
|
||||
|
||||
export function NodeHistory({ base, id, refresh, degraded }: { base: string | null; id: string; refresh: number; degraded: boolean }) {
|
||||
const [sample, setSample] = useState<ReturnType<typeof projectTrafficObservations> | null>(null)
|
||||
const [unavailable, setUnavailable] = useState(false)
|
||||
useEffect(() => {
|
||||
if (base === null) return
|
||||
const controller = new AbortController()
|
||||
void requestJson<{ server?: { id?: string } }>(base, `/api/traffic/servers/${encodeURIComponent(id)}?range=24h`, { signal: controller.signal })
|
||||
.then(raw => {
|
||||
if (raw?.server?.id !== id) throw new Error("Не подтверждён сервер")
|
||||
const observations = projectTrafficObservations(raw.server)
|
||||
if (!controller.signal.aborted) { setSample(observations); setUnavailable(false) }
|
||||
})
|
||||
.catch(() => { if (!controller.signal.aborted) { setSample(null); setUnavailable(true) } })
|
||||
return () => controller.abort()
|
||||
}, [base, id, refresh])
|
||||
const points = sample?.rxSeries.map((rx, i) => {
|
||||
const tx = sample.txSeries[i]
|
||||
return rx != null && tx != null ? rx + tx : null
|
||||
}) ?? []
|
||||
const measured = points.filter((n): n is number => n !== null)
|
||||
const peak = measured.length ? Math.max(...measured) : null
|
||||
const obs = sample?.observations
|
||||
const warning = obs?.currentState === "error" ? obs.error : null
|
||||
return <>
|
||||
{(warning || degraded) && <div className="border-b px-3 py-2"><div className="rounded-md border border-warning/30 bg-warning/10 px-2.5 py-2 text-xs text-warning-foreground [overflow-wrap:anywhere]">
|
||||
{warning ? <>Сбор трафика{obs?.lastAttemptAt ? " · " + new Date(obs.lastAttemptAt).toLocaleString("ru-RU") : ""}. {warning}</> : "Последний опрос устройства вернул статус «Внимание»."}
|
||||
</div></div>}
|
||||
<section aria-label="История трафика устройства" title="Сумма RX и TX по сохранённым счётчикам интерфейсов за последние 24 часа" className="border-b px-3.5 py-3">
|
||||
<div className="flex justify-between gap-2 text-[11px] text-muted-foreground"><span>Трафик · 24 ч</span><span className="font-mono">{peak !== null ? "пик " + fmtRate(peak) : "—"}</span></div>
|
||||
{peak !== null ? <><div className="my-2 [&_svg]:h-12 [&_svg]:w-full"><Sparkline data={points} width={244} height={48} filled color="var(--chart-1)" /></div>
|
||||
<div className="flex justify-between font-mono text-[10px] text-muted-foreground"><span>−24 ч</span><span>−12 ч</span><span>конец окна</span></div></>
|
||||
: <p className="py-3 text-xs text-muted-foreground">{base !== null && !sample && !unavailable ? "Загрузка истории…" : "Нет подтверждённых измерений RX и TX"}</p>}
|
||||
</section>
|
||||
</>
|
||||
}
|
||||
|
||||
export function ServiceInspector({ service, paths, exits, exitName, country, base, refresh, windowLabel, flowAt, stale, activePath, onPath, onClose, filtered, onFilter, userId, ix, topology }: {
|
||||
service: FlowMapService; paths: FlowMapServicePath[]; exits: FlowMapServiceEdge[]; exitName: (id: string) => string
|
||||
country?: string; base: string | null; refresh: number; windowLabel: string; flowAt: string | null; stale: boolean
|
||||
activePath: FlowMapServicePath | null; onPath: (path: FlowMapServicePath) => void
|
||||
onClose: () => void; filtered: boolean; onFilter: () => void
|
||||
userId?: string; ix?: boolean; topology?: ReadonlySet<string>
|
||||
}) {
|
||||
const [recent, setRecent] = useState<{ data: FlowAnalyticsDto; at: string } | null>(null)
|
||||
const [volume, setVolume] = useState<{ bytes: number | null; window: string; at: string } | null>(null)
|
||||
const canMatchService = !service.id.endsWith("svc:other") && service.label !== "Прочее"
|
||||
const sources = [...new Set(paths.map(path => path.viaId).filter(id => /^[1-9]\d*$/.test(id)))].sort()
|
||||
const exporter = sources.length === 1 && /^[1-9]\d*$/.test(sources[0]) ? sources[0] : undefined
|
||||
const scopedUser = userId && !userId.startsWith("ix:") ? userId : undefined
|
||||
const scoped = Boolean(userId || topology)
|
||||
useEffect(() => {
|
||||
if (base === null) return
|
||||
const controller = new AbortController()
|
||||
const init = { signal: controller.signal }
|
||||
if (canMatchService && (!scoped || scopedUser || exporter && !userId)) void getFlowAnalytics(base, { range: "5m", userId: scopedUser, serverId: !scopedUser && scoped ? exporter : undefined }, init)
|
||||
.then(data => { if (!controller.signal.aborted) setRecent({data, at: new Date().toISOString()}) })
|
||||
.catch(() => { if (!controller.signal.aborted) setRecent(null) })
|
||||
if (!scoped) void getFlowMapHops(base, { range: "24h" }, init)
|
||||
.then(raw => {
|
||||
if (controller.signal.aborted) return
|
||||
const data = flowMapHopsDtoSchema.parse(raw)
|
||||
const minutes = data.sourceWindow?.effectiveMinutes ?? 1440
|
||||
if (data.rangeMinutes !== minutes || data.windowSec !== minutes * 60 || data.sourceWindow && data.sourceWindow.requestedMinutes !== 1440) throw new Error("Не подтверждено окно объёма")
|
||||
const services = country ? data.countryServiceGroups?.find(g => g.countryId === service.id.split("|")[0])?.services : data.services
|
||||
setVolume({bytes: services?.find(row => row.id === service.id)?.bytes ?? null,
|
||||
window: data.sourceWindow ? minutes + " мин" : "24 ч", at: new Date().toISOString()})
|
||||
})
|
||||
.catch(() => { if (!controller.signal.aborted) setVolume(null) })
|
||||
return () => controller.abort()
|
||||
}, [base, refresh, country, service.id, canMatchService, scoped, scopedUser, exporter, userId])
|
||||
const countryFilter = service.id.startsWith("cc:other|") ? "unknown" : country
|
||||
const flows = recent?.data.conversationsList.filter(row => (!topology || topology.has(row.enId || row.serverId)) && matchesMapService(row, service.label, countryFilter))
|
||||
.sort((a, b) => b.bps - a.bps).slice(0, 5) ?? []
|
||||
const asns = [...new Set(flows.flatMap(flow => flow.dstAsn ? [flow.dstAsn] : []))]
|
||||
const rates = [...exits].sort((a, b) => b.bps - a.bps)
|
||||
const exitIds = [...new Set([...rates.filter(e => !e.observedOnly).map(e => e.fromId), ...paths.map(p => p.enId).filter(Boolean)])]
|
||||
const exporterIds = [...new Set([...rates.filter(e => e.observedOnly).map(e => e.fromId), ...paths.filter(p => !p.enId).map(p => p.viaId)])]
|
||||
const attributedBytes = (country ? paths : exits).reduce((sum, entry) => sum + entry.bytes, 0)
|
||||
const remainder = Math.max(0, service.bytes - attributedBytes)
|
||||
const observed = service.bytes > 0 && !stale
|
||||
const currentVolume = base === null || scoped
|
||||
const trafficQuery = new URLSearchParams({ view: "flows", service: service.label, serviceId: service.id, from: "map" })
|
||||
if (scopedUser) trafficQuery.set("user", scopedUser)
|
||||
else if (exporter) trafficQuery.set("server", exporter)
|
||||
if (userId?.startsWith("ix:")) trafficQuery.set("mapUser", userId)
|
||||
if (ix) trafficQuery.set("mapView", "ix")
|
||||
if (topology) {
|
||||
if (!scopedUser) trafficQuery.set("exporters", sources.join(","))
|
||||
trafficQuery.set("nodes", [...topology].filter(id => /^[1-9]\d*$/.test(id)).join(","))
|
||||
}
|
||||
if (countryFilter) trafficQuery.set("country", countryFilter)
|
||||
return <>
|
||||
<header className="flex items-center gap-2 px-3 py-3">
|
||||
<div className="grid size-8 shrink-0 place-items-center rounded-md bg-muted"><ServiceBrandIcon label={service.label} size={18} /></div>
|
||||
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold" title={service.label}>{service.label}</h2>
|
||||
<p className="truncate text-[11px] text-muted-foreground" title={flowAt ? new Date(flowAt).toLocaleString("ru-RU") : undefined}>{[service.category, asns.length === 1 ? "AS" + asns[0] : null, country, windowLabel].filter(Boolean).join(" · ")}</p></div>
|
||||
<Badge size="sm" variant={observed ? "success-light" : "secondary"} title="Наличие трафика в окне NetFlow"><span aria-hidden>•</span>{stale ? "Архив" : observed ? "Есть трафик" : "Нет трафика"}</Badge>
|
||||
<Button size="icon-xs" variant="ghost" aria-label="Закрыть детали назначения" onClick={onClose}><XIcon /></Button>
|
||||
</header>
|
||||
<div className="mx-0.5 mb-0.5 min-h-0 overflow-y-auto rounded-lg border">
|
||||
<InspectorMetrics rows={[
|
||||
["Скорость", formatNetflowRate({ bps: service.bps }), "Средняя скорость NetFlow за " + windowLabel],
|
||||
[country ? "Доля страны" : "Доля трафика", new Intl.NumberFormat("ru-RU", {style:"percent", maximumFractionDigits:1}).format(service.share)],
|
||||
["Объём · " + (currentVolume ? windowLabel : volume?.window ?? "24 ч"), <>{currentVolume ? formatBytes(service.bytes) : volume?.bytes == null ? "—" : formatBytes(volume.bytes)}{volume && <time dateTime={volume.at} title={new Date(volume.at).toLocaleString("ru-RU")} className="block text-[10px] font-normal text-muted-foreground">ответ {new Date(volume.at).toLocaleTimeString("ru-RU")}</time>}</>],
|
||||
exitIds.length || !exporterIds.length
|
||||
? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined]
|
||||
: ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"],
|
||||
]} />
|
||||
<InspectorUsers users={serviceUsers(service, paths)} windowLabel={windowLabel} />
|
||||
<section className="space-y-2 border-b px-3.5 py-3"><h3 className="text-[11px] text-muted-foreground">Путь трафика</h3>
|
||||
{paths.map(p => {
|
||||
const parts = [p.clientName !== "—" ? p.clientName : "", p.viaId !== p.enId ? p.viaName : "",
|
||||
p.enName, service.label].filter(Boolean)
|
||||
const key = servicePathKey(p)
|
||||
const active = activePath && servicePathKey(activePath) === key
|
||||
return <button type="button" key={key} onClick={() => onPath(p)} aria-pressed={Boolean(active)} title={formatNetflowRate(p)} className={cn("flex w-full flex-wrap items-center gap-1 rounded-sm text-left", active && "ring-1 ring-primary")}>
|
||||
{parts.map((name, i) => <span key={i} className="inline-flex max-w-full items-center gap-1">{i > 0 && <ChevronRightIcon aria-hidden className="size-3 shrink-0 text-muted-foreground" />}<span className={cn("truncate rounded-md bg-muted px-1.5 py-1 font-mono text-[10px] font-semibold", i === parts.length - 1 && "bg-chart-4/20")}>{name}</span></span>)}
|
||||
{!p.enId && <span className="basis-full text-[10px] text-muted-foreground">
|
||||
Наблюдение IPFIX{p.viaIface ? ` · интерфейс ${p.viaIface}` : ""} · выход не подтверждён
|
||||
</span>}
|
||||
</button>
|
||||
})}
|
||||
{rates.filter(e => !paths.some(p => (p.enId || p.viaId) === e.fromId && Boolean(p.enId) !== Boolean(e.observedOnly))).map(e => <div key={e.fromId} className="flex justify-between gap-2 text-xs"><span>{exitName(e.fromId)} → {service.label}{e.observedOnly && " · наблюдение IPFIX"}</span><span className="shrink-0 font-mono">{formatNetflowRate(e)}</span></div>)}
|
||||
{remainder > 0 && <div className="flex justify-between gap-2 text-xs text-muted-foreground"><span>Выход не определён</span><span className="font-mono">{formatNetflowRate({bps:service.bps * remainder / service.bytes})}</span></div>}
|
||||
{!paths.length && !rates.length && !remainder && <p className="text-xs text-muted-foreground">Маршрут не определён</p>}
|
||||
</section>
|
||||
<section className="space-y-3 border-b px-3.5 py-3"><h3 className="flex items-center justify-between font-mono text-[11px] text-muted-foreground"><span>Крупные потоки · {recent?.data.sourceWindow?.effectiveMinutes ?? 5} мин</span><span title="Наблюдения экспортёров">{recent ? flows.length : "—"}</span></h3>
|
||||
{flows.map((f,i) => <div key={i} className="flex items-center gap-2 text-xs"><span aria-hidden className="size-1.5 shrink-0 rounded-full bg-[var(--status-online)]" /><div className="min-w-0 flex-1"><p className="font-medium [overflow-wrap:anywhere]">{f.src} → {f.dst}</p><p className="truncate text-[11px] text-muted-foreground" title={`Экспортёр: ${f.serverName || f.serverId}`}><span>{f.protoName}{f.dstPort ? "/" + f.dstPort : ""}</span> · {f.serverName || f.serverId}</p></div><span className="font-mono text-[11px] text-muted-foreground">{formatNetflowRate({bps:f.bps})}</span></div>)}
|
||||
{!flows.length && <p className="text-xs text-muted-foreground">{recent ? "Сервис отсутствует в выборке крупных потоков" : "Нет подтверждённых записей"}</p>}
|
||||
{recent && <time dateTime={recent.at} title={new Date(recent.at).toLocaleString("ru-RU")} className="block font-mono text-[10px] text-muted-foreground">ответ {new Date(recent.at).toLocaleTimeString("ru-RU")}</time>}
|
||||
</section>
|
||||
<div className="flex flex-wrap gap-1.5 px-3.5 py-3">
|
||||
<Link href={`/traffic?${trafficQuery}`} className={buttonVariants({size:"xs"})}>Открыть в «Трафике»</Link>
|
||||
<Button size="xs" variant="outline" aria-pressed={filtered} onClick={onFilter}>{filtered ? "Снять фильтр" : "Фильтр по сервису"}</Button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { UsersIcon, XIcon } from "lucide-react"
|
||||
import type { IxLinuxBinding, IxSegment } from "@mmapp/contracts/internet-exchange"
|
||||
import type { FlowMapService, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
import { Command, CommandDialog, CommandEmpty, CommandInput, CommandItem, CommandList } from "@/components/ui/command"
|
||||
import { INIT_USERS } from "@/lib/users"
|
||||
import { fmtRate } from "@/lib/fmt-rate"
|
||||
import { formatNetflowRate } from "@/lib/map-netflow-hops"
|
||||
import { projectTrafficObservations } from "@/lib/traffic-observations"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
import { listAppUsers } from "@/shared/api/users"
|
||||
|
||||
type AccessBinding = { id: string; node: string; name: string; kind: string; enabled?: boolean; peerScoped?: boolean; identity?: string }
|
||||
export type MapAccessUser = { id: string; name: string; login?: string; linux?: true; bindings: AccessBinding[] }
|
||||
type AccessRate = { rxNow: number | null; txNow: number | null }
|
||||
|
||||
const mapUsers = (users: typeof INIT_USERS): MapAccessUser[] => users.map(user => ({
|
||||
id: user.id, name: user.name || user.login, login: user.login,
|
||||
bindings: user.bindings.map(binding => ({ id: binding.id, node: binding.serverId, name: binding.interfaceName, kind: binding.interfaceType,
|
||||
peerScoped: Boolean(binding.peerPublicKey), identity: JSON.stringify([binding.serverId, binding.interfaceName, binding.peerPublicKey || null]) })),
|
||||
}))
|
||||
const demoUsers = mapUsers(INIT_USERS)
|
||||
|
||||
export function useMapAccess(base: string | null, hasIx: boolean, refresh: number, userSelected: boolean) {
|
||||
const [directory, setDirectory] = useState<{ base: string; users: MapAccessUser[]; unavailable: boolean }>()
|
||||
const [linux, setLinux] = useState<{ base: string; users: MapAccessUser[]; unavailable: boolean }>()
|
||||
const [traffic, setTraffic] = useState<{ base: string; rates: Map<string, AccessRate> }>()
|
||||
useEffect(() => {
|
||||
if (base === null) return
|
||||
const controller = new AbortController()
|
||||
void listAppUsers(base, { signal: controller.signal }).then(users => {
|
||||
if (!controller.signal.aborted) setDirectory({ base, users: mapUsers(users), unavailable: false })
|
||||
}).catch(() => { if (!controller.signal.aborted) setDirectory({ base, users: [], unavailable: true }) })
|
||||
return () => controller.abort()
|
||||
}, [base, refresh])
|
||||
useEffect(() => {
|
||||
if (base === null || !hasIx) return
|
||||
const controller = new AbortController()
|
||||
const init = { signal: controller.signal }
|
||||
async function load() {
|
||||
const payload = await requestJson<{ items: IxSegment[] }>(base!, "/api/ix/segments?limit=100", init)
|
||||
const clients = new Map<string, MapAccessUser>()
|
||||
function add(segment: IxSegment, node: number, iface: string, kind: string, name: string, enabled?: boolean, clientId?: string) {
|
||||
const id = "ix:" + (clientId ?? `${segment.id}:${node}:${iface}`)
|
||||
const user = clients.get(id) ?? { id, name, linux: true, bindings: [] }
|
||||
if (!user.bindings.some(binding => binding.node === String(node) && binding.name === iface)) {
|
||||
user.bindings.push({ id: `${node}:${iface}`, node: String(node), name: iface, kind, enabled })
|
||||
}
|
||||
clients.set(id, user)
|
||||
}
|
||||
const applied = await Promise.allSettled(payload.items.map(segment => segment.appliedRevision === null
|
||||
? [] : requestJson<{ items: IxLinuxBinding[] }>(base!, `/api/ix/segments/${encodeURIComponent(segment.id)}/linux`, init).then(result => result.items)))
|
||||
payload.items.forEach((segment, index) => {
|
||||
const rows = applied[index]
|
||||
if (rows.status === "fulfilled") for (const row of rows.value) {
|
||||
add(segment, row.serverId, row.interfaceName, row.kind, row.name ?? row.interfaceName, row.enabled, row.policy?.clientId)
|
||||
}
|
||||
})
|
||||
if (!controller.signal.aborted) setLinux({ base: base!, users: [...clients.values()], unavailable: applied.some(result => result.status === "rejected") })
|
||||
}
|
||||
void load().catch(() => { if (!controller.signal.aborted) setLinux({ base, users: [], unavailable: true }) })
|
||||
return () => controller.abort()
|
||||
}, [base, hasIx, refresh])
|
||||
useEffect(() => {
|
||||
if (base === null || !userSelected) return
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
async function load() {
|
||||
const rates = new Map<string, AccessRate>()
|
||||
try {
|
||||
const payload = await requestJson<{ interfaces: Array<{ bindingId: string; status?: string }> }>(base!, "/api/traffic/bound-interfaces?range=5m", { signal: controller.signal })
|
||||
for (const row of payload.interfaces) {
|
||||
if (row.status === "offline") continue
|
||||
try { rates.set(row.bindingId, projectTrafficObservations(row)) } catch { /* Invalid measurements remain unknown. */ }
|
||||
}
|
||||
} finally {
|
||||
if (!controller.signal.aborted) {
|
||||
setTraffic({ base: base!, rates })
|
||||
timer = setTimeout(() => { void load().catch(() => {}) }, 15_000)
|
||||
}
|
||||
}
|
||||
}
|
||||
void load().catch(() => {})
|
||||
return () => { controller.abort(); clearTimeout(timer) }
|
||||
}, [base, refresh, userSelected])
|
||||
|
||||
const users = base === null ? demoUsers : directory?.base === base ? directory.users : []
|
||||
const rates = new Map(base !== null && traffic?.base === base ? traffic.rates : undefined)
|
||||
const bindingsByInterface = new Map<string, { user: string; binding: AccessBinding }[]>()
|
||||
for (const user of users) for (const binding of user.bindings) {
|
||||
const key = JSON.stringify([binding.node, binding.name])
|
||||
const entries = bindingsByInterface.get(key) ?? []
|
||||
entries.push({ user: user.id, binding })
|
||||
bindingsByInterface.set(key, entries)
|
||||
}
|
||||
for (const entries of bindingsByInterface.values()) for (const { user, binding } of entries) {
|
||||
if (entries.some(other => other.user !== user && other.binding.identity === binding.identity) || !binding.peerScoped && entries.some(other => other.binding.peerScoped)) rates.delete(binding.id)
|
||||
}
|
||||
return {
|
||||
users,
|
||||
linux: base !== null && hasIx && linux?.base === base ? linux.users : [],
|
||||
pending: base !== null && directory?.base !== base,
|
||||
unavailable: base !== null && directory?.base === base && directory.unavailable,
|
||||
linuxPending: base !== null && hasIx && linux?.base !== base,
|
||||
linuxUnavailable: base !== null && hasIx && linux?.base === base && linux.unavailable,
|
||||
rates,
|
||||
}
|
||||
}
|
||||
|
||||
export function accessRate(bindings: AccessBinding[], rates?: Map<string, AccessRate>) {
|
||||
let measured = 0, rx = 0, tx = 0
|
||||
const counted = new Set<string>()
|
||||
for (const binding of bindings) {
|
||||
const row = rates?.get(binding.id)
|
||||
const identity = binding.identity ?? binding.id
|
||||
if (row?.rxNow == null || row.txNow == null || counted.has(identity)) continue
|
||||
counted.add(identity)
|
||||
measured++
|
||||
rx += row.rxNow
|
||||
tx += row.txNow
|
||||
}
|
||||
const total = new Set(bindings.map(binding => binding.identity ?? binding.id)).size
|
||||
return { measured, total, rx, tx, label: measured ? `${measured < total ? "≥ " : ""}${fmtRate(rx + tx)}` : "Нет замера" }
|
||||
}
|
||||
|
||||
export function MapUserPicker({ open, onOpenChange, users, pending, unavailable, onPick }: {
|
||||
open: boolean; onOpenChange: (open: boolean) => void; users: MapAccessUser[]; pending: boolean; unavailable: boolean; onPick: (user: MapAccessUser) => void
|
||||
}) {
|
||||
return <CommandDialog open={open} onOpenChange={onOpenChange} title="Выбор пользователя" description="Поиск по имени, логину или интерфейсу">
|
||||
<Command>
|
||||
<CommandInput aria-label="Поиск пользователей" placeholder="Имя, логин или интерфейс…" />
|
||||
<CommandList>
|
||||
<CommandEmpty>{pending ? "Загрузка пользователей…" : unavailable ? "Каталог пользователей недоступен" : "Пользователи не найдены"}</CommandEmpty>
|
||||
{users.map(user => <CommandItem key={user.id} value={user.id} keywords={[user.name, user.login ?? "", ...user.bindings.map(binding => binding.name)]} onSelect={() => onPick(user)}>
|
||||
<UsersIcon aria-hidden /><span className="min-w-0 flex-1 truncate">{user.name}</span>
|
||||
<Badge variant="outline" size="xs">{user.bindings.length}</Badge>
|
||||
</CommandItem>)}
|
||||
</CommandList>
|
||||
</Command>
|
||||
</CommandDialog>
|
||||
}
|
||||
|
||||
export function MapUserDetails({ user, groups, paths, services, rates, windowLabel, onClose, onService, nodeName, trafficHref }: {
|
||||
user: MapAccessUser; groups: Map<string, AccessBinding[]>; paths: FlowMapServicePath[]; services: FlowMapService[]; rates?: Map<string, AccessRate>; windowLabel: string
|
||||
onClose: () => void; onService: (service: FlowMapService) => void; nodeName: (id: string) => string; trafficHref?: string
|
||||
}) {
|
||||
return <>
|
||||
<header className="flex items-center gap-2 border-b p-3">
|
||||
<UsersIcon className="size-4 shrink-0" aria-hidden />
|
||||
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold">{user.name}</h2><p className="text-xs text-muted-foreground">{user.linux ? "Linux-клиент IX" : user.login}</p></div>
|
||||
<Button size="icon-xs" variant="ghost" onClick={onClose} aria-label="Закрыть детали пользователя"><XIcon /></Button>
|
||||
</header>
|
||||
<div className="flex flex-col gap-3 overflow-y-auto p-3">
|
||||
<section className="grid gap-2"><h3 className="text-xs text-muted-foreground">Подключения</h3>
|
||||
{[...groups].map(([node, bindings]) => {
|
||||
const rate = accessRate(bindings, rates)
|
||||
return <div key={node} className="grid gap-1 text-xs">
|
||||
<p className="flex justify-between gap-2 font-medium"><span>{nodeName(node)}</span><span className="shrink-0 font-mono">{rate.label}</span></p>
|
||||
<p className="text-muted-foreground wrap-anywhere">{bindings.map(binding => `${binding.name} · ${binding.kind}${binding.enabled === false ? " · отключён" : ""}`).join(", ")}</p>
|
||||
{rate.measured > 0 && <p className="font-mono text-muted-foreground">RX {fmtRate(rate.rx)} · TX {fmtRate(rate.tx)} · {rate.measured}/{rate.total}</p>}
|
||||
</div>
|
||||
})}
|
||||
{!groups.size && <p className="text-xs text-muted-foreground">Нет привязок к узлам текущего вида.</p>}
|
||||
</section>
|
||||
<section className="grid gap-1 border-t pt-3"><h3 className="text-xs text-muted-foreground">Сервисы · IPFIX · {windowLabel}</h3>
|
||||
{services.filter(service => paths.some(path => path.serviceId === service.id)).map(service => <Button key={service.id} variant="ghost" size="xs" className="w-full justify-between" onClick={() => onService(service)}>{service.label}<span className="font-mono">{formatNetflowRate(service)}</span></Button>)}
|
||||
{!paths.length && <p className="text-xs text-muted-foreground">Нет потоков с подтверждённой привязкой к пользователю.</p>}
|
||||
</section>
|
||||
{trafficHref && <Link href={trafficHref} className={buttonVariants({size:"xs"})}>{user.linux ? "Открыть Linux-клиентов IX" : "Открыть в «Трафике»"}</Link>}
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
@@ -4,13 +4,14 @@ import type { ReactNode } from "react"
|
||||
import { FramePanel } from "@/components/reui/frame"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { SectionFrame, ToneBadge, ToneDot, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
|
||||
import { SectionFrame, ToneBadge, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
export type MapFlowRow = { id: string; client: string; exit: string; dest: string; rate: string; volume: string; hl: boolean }
|
||||
export type MapRttRow = { id: string; name: string; route: string; rtt: string; speed: string; tone: Tone; status: string; hl: boolean }
|
||||
export type MapDestRow = { id: string; label: string; category: string; rate: string; share: number; hl: boolean }
|
||||
export type MapEventRow = { id: string; ts: number; tone: Tone; label: string; title: string; message: string }
|
||||
export type MapEventRow = { id: string; ts: number; tone: Tone; label: string; title: string; message: string; serverId?: string }
|
||||
export type MapBottomTab = "flows" | "rtt" | "dest" | "events"
|
||||
|
||||
function Table({ head, cols, empty, children }: { head: string[]; cols: string; empty: string | null; children: ReactNode }) {
|
||||
@@ -39,13 +40,14 @@ const EVENT_COLS = "grid-cols-[70px_110px_minmax(200px,1.4fr)_minmax(200px,2fr)]
|
||||
* Рабочая панель под картой (макет v3): потоки NetFlow, RTT каналов, назначения и события.
|
||||
* Строки выбранного объекта подсвечены.
|
||||
*/
|
||||
export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, eventsError, stat }: {
|
||||
export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, onEvent, eventsError, stat }: {
|
||||
tab: MapBottomTab
|
||||
onTab: (tab: MapBottomTab) => void
|
||||
flows: MapFlowRow[]
|
||||
rtt: MapRttRow[]
|
||||
destinations: MapDestRow[]
|
||||
events: MapEventRow[]
|
||||
onEvent: (event: MapEventRow) => void
|
||||
eventsError: string | null
|
||||
stat: string
|
||||
}) {
|
||||
@@ -71,7 +73,7 @@ export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, e
|
||||
</div>
|
||||
<FramePanel className="p-0">
|
||||
<TabsContent value="flows">
|
||||
<Table head={["Источник", "Exit", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}>
|
||||
<Table head={["Пользователь", "Выход / экспортёр", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}>
|
||||
{flows.map((r) => (
|
||||
<Row key={r.id} cols={FLOW_COLS} hl={r.hl}>
|
||||
<span className="truncate font-mono">{r.client}</span>
|
||||
@@ -117,7 +119,7 @@ export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, e
|
||||
<Row key={r.id} cols={EVENT_COLS}>
|
||||
<time dateTime={new Date(r.ts).toISOString()} className="text-muted-foreground font-mono text-xs">{new Date(r.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })}</time>
|
||||
<span><ToneBadge tone={r.tone} mark={false}>{r.label}</ToneBadge></span>
|
||||
<span className="truncate font-medium">{r.title}</span>
|
||||
<Button type="button" variant="link" size="xs" className="min-w-0 justify-start" onClick={() => onEvent(r)}><span className="truncate">{r.title}</span></Button>
|
||||
<span className="text-muted-foreground truncate text-xs">{r.message}</span>
|
||||
</Row>
|
||||
))}
|
||||
@@ -136,14 +138,18 @@ export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, e
|
||||
export function MapTimeline({ events, now, onPick }: { events: MapEventRow[]; now: number; onPick: (event: MapEventRow) => void }) {
|
||||
const from = now - 24 * 3_600_000
|
||||
const marks = events.filter((e) => e.ts >= from && e.ts <= now)
|
||||
const pos = (ts: number) => `calc(10px + (100% - 20px) * ${((ts - from) / (now - from)).toFixed(4)})`
|
||||
const at = (t: number) => `calc(10px + (100% - 20px) * ${t.toFixed(4)})`
|
||||
// Шкала макета v3: остановки (кружок и подпись под ним), инциденты — цветные засечки над линией.
|
||||
const stop = "absolute top-[7px] flex -translate-x-1/2 flex-col items-center gap-1 text-[11px] leading-none whitespace-nowrap"
|
||||
return (
|
||||
<div className="flex shrink-0 items-center gap-3 border-t px-3 py-2">
|
||||
<div className="flex shrink-0 items-center gap-3 border-t px-3 pt-1.5 pb-1">
|
||||
<small className="text-muted-foreground text-xs whitespace-nowrap">Момент времени</small>
|
||||
<div role="group" aria-label="Инциденты карты за 24 часа" className="relative h-8 min-w-0 flex-1">
|
||||
<span aria-hidden="true" className="bg-border absolute inset-x-2.5 top-1/2 h-px" />
|
||||
{[0, 0.75, 0.9583].map((t, i) => (
|
||||
<span key={i} aria-hidden="true" className="text-muted-foreground absolute top-0 -translate-x-1/2 text-xs leading-none" style={{ left: `calc(10px + (100% - 20px) * ${t})` }}>{["−24 ч", "−6 ч", "−1 ч"][i]}</span>
|
||||
<div role="group" aria-label="Инциденты карты за 24 часа" className="relative mx-3.5 h-9 min-w-0 flex-1">
|
||||
<span aria-hidden="true" className="bg-border absolute inset-x-2.5 top-[11px] h-0.5 rounded-full" />
|
||||
{[["−24 ч", 0], ["−6 ч", 0.75], ["−1 ч", 0.9583]].map(([label, t]) => (
|
||||
<span key={label} aria-hidden="true" className={cn(stop, "text-muted-foreground")} style={{ left: at(Number(t)) }}>
|
||||
<i className="bg-card border-muted-foreground block size-2.5 rounded-full border-2" />{label}
|
||||
</span>
|
||||
))}
|
||||
{marks.map((e) => (
|
||||
<button
|
||||
@@ -152,12 +158,14 @@ export function MapTimeline({ events, now, onPick }: { events: MapEventRow[]; no
|
||||
onClick={() => onPick(e)}
|
||||
aria-label={`${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}`}
|
||||
title={`${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}`}
|
||||
className="focus-visible:ring-ring absolute top-1/2 size-3 -translate-1/2 rounded-full border-2 border-[var(--card)] outline-none focus-visible:ring-2"
|
||||
style={{ left: pos(e.ts), background: TONE_COLOR[e.tone] }}
|
||||
/>
|
||||
className="focus-visible:ring-ring absolute top-1 flex h-4 w-3 -translate-x-1/2 justify-center rounded-sm outline-none focus-visible:ring-2"
|
||||
style={{ left: at((e.ts - from) / (now - from)) }}
|
||||
>
|
||||
<span aria-hidden="true" className="block h-full w-1.5 rounded-sm" style={{ background: TONE_COLOR[e.tone] }} />
|
||||
</button>
|
||||
))}
|
||||
<span className="text-success absolute top-1/2 right-0 flex translate-x-1/2 -translate-y-1/2 items-center gap-1 text-xs font-medium">
|
||||
<ToneDot tone="ok" />Live
|
||||
<span className={cn(stop, "text-foreground font-semibold")} style={{ left: at(1) }}>
|
||||
<i className="bg-success border-success block size-2.5 rounded-full border-2 shadow-[0_0_0_4px_color-mix(in_oklch,var(--success)_25%,transparent)]" />Live
|
||||
</span>
|
||||
</div>
|
||||
<small className="text-muted-foreground font-mono text-xs">{new Date(now).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })}</small>
|
||||
|
||||
@@ -1,18 +1,27 @@
|
||||
"use client"
|
||||
|
||||
import type { Server } from "@/lib/data"
|
||||
import { fmtRate } from "@/lib/fmt-rate"
|
||||
import { formatMapFlowWindow, formatNetflowRate } from "@/lib/map-netflow-hops"
|
||||
import { TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
type StatusFilter = "online" | "degraded" | "offline"
|
||||
type StatusFilter = "online" | "degraded" | "offline" | "unknown"
|
||||
|
||||
const STATUS: Array<{ key: StatusFilter; label: string; tone: Tone }> = [
|
||||
{ key: "online", label: "Онлайн", tone: "ok" },
|
||||
{ key: "degraded", label: "Внимание", tone: "wn" },
|
||||
{ key: "offline", label: "Оффлайн", tone: "er" },
|
||||
{ key: "unknown", label: "Неизвестно", tone: "mu" },
|
||||
]
|
||||
|
||||
const EXIT_COLORS = ["var(--chart-4)", "var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-5)"]
|
||||
|
||||
/** Русское склонение: 1 узел, 2 узла, 5 узлов. */
|
||||
export function ruPlural(n: number, one: string, few: string, many: string) {
|
||||
const m10 = n % 10, m100 = n % 100
|
||||
return m10 === 1 && m100 !== 11 ? one : m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14) ? few : many
|
||||
}
|
||||
|
||||
function Seg({ parts }: { parts: Array<{ n: number; color: string }> }) {
|
||||
const shown = parts.filter((part) => part.n > 0)
|
||||
return (
|
||||
@@ -39,9 +48,14 @@ function Card({ title, value, unit, children }: { title: string; value: string;
|
||||
* KPI-полоса над картой (макет v3): узлы, GRE-туннели, NetFlow и узлы, требующие внимания.
|
||||
* Счётчики статусов фильтруют карту, строки проблем открывают узел.
|
||||
*/
|
||||
export function MapKpiStrip({ servers, tunnels, netflowBytes, windowSec, filter, onFilter, onSelect, className }: {
|
||||
export function MapKpiStrip({ servers, tunnels, downRoutes = [], exits = [], liveLink, netflowBytes, windowSec, filter, onFilter, onSelect, className }: {
|
||||
servers: Server[]
|
||||
tunnels: Array<{ status: "up" | "down" | "degraded" }>
|
||||
/** «A → B» недоступных GRE на карте — для подвала карточки туннелей. */
|
||||
downRoutes?: string[]
|
||||
/** Скорость NetFlow через Exit-узлы за окно, бит/с. */
|
||||
exits?: Array<{ name: string; bps: number }>
|
||||
liveLink?: { name: string; bps: number; bpsFwd: number; bpsRev: number }
|
||||
/** Байты NetFlow за окно; null — потоки не загружены. */
|
||||
netflowBytes: number | null
|
||||
windowSec: number
|
||||
@@ -53,14 +67,20 @@ export function MapKpiStrip({ servers, tunnels, netflowBytes, windowSec, filter,
|
||||
const count = (status: Server["status"]) => servers.filter((server) => server.status === status).length
|
||||
const up = tunnels.filter((tunnel) => tunnel.status === "up").length
|
||||
const degraded = tunnels.filter((tunnel) => tunnel.status === "degraded").length
|
||||
const down = tunnels.length - up - degraded
|
||||
const problems = servers.filter((server) => server.enabled !== false && server.status !== "online")
|
||||
const minutes = Math.max(1, Math.round(windowSec / 60))
|
||||
const topExits = netflowBytes == null ? [] : [...exits].filter((exit) => exit.bps > 0).sort((a, b) => b.bps - a.bps)
|
||||
const flowRate = netflowBytes == null ? null : formatNetflowRate({ bps: (netflowBytes * 8) / Math.max(1, windowSec) })
|
||||
const flowLabel = `NetFlow · ${formatMapFlowWindow(windowSec)}`
|
||||
const greFoot = !tunnels.length ? "Туннелей на карте нет"
|
||||
: downRoutes.length ? `${downRoutes[0]} — без ответа${downRoutes.length > 1 ? ` · ещё ${downRoutes.length - 1}` : ""}`
|
||||
: degraded ? `С деградацией: ${degraded}` : "Все туннели на карте работают"
|
||||
return (
|
||||
<div className={cn("grid grid-cols-[repeat(auto-fit,minmax(min(240px,100%),1fr))] gap-3", className)}>
|
||||
<Card title="Узлы на карте" value={String(servers.length)} unit="устройств">
|
||||
<Card title="Узлы на карте" value={String(servers.length)} unit={ruPlural(servers.length, "устройство", "устройства", "устройств")}>
|
||||
<Seg parts={STATUS.map((s) => ({ n: count(s.key), color: TONE_COLOR[s.tone] }))} />
|
||||
<div className="-mx-1.5 -mb-1 flex flex-wrap gap-0.5">
|
||||
{STATUS.map((s) => (
|
||||
{STATUS.filter((s) => s.key !== "unknown" || count(s.key) > 0).map((s) => (
|
||||
<button
|
||||
key={s.key}
|
||||
type="button"
|
||||
@@ -76,14 +96,20 @@ export function MapKpiStrip({ servers, tunnels, netflowBytes, windowSec, filter,
|
||||
</div>
|
||||
</Card>
|
||||
<Card title="GRE-туннели на карте" value={tunnels.length ? `${up} из ${tunnels.length}` : "—"} unit="работают">
|
||||
<Seg parts={[{ n: up, color: TONE_COLOR.ok }, { n: degraded, color: TONE_COLOR.wn }, { n: tunnels.length - up - degraded, color: TONE_COLOR.er }]} />
|
||||
<div className="text-muted-foreground text-xs">{tunnels.length ? `Деградация: ${degraded} · недоступны: ${tunnels.length - up - degraded}` : "Туннелей на карте нет"}</div>
|
||||
<Seg parts={[{ n: up, color: TONE_COLOR.ok }, { n: degraded, color: TONE_COLOR.wn }, { n: down, color: TONE_COLOR.er }]} />
|
||||
<div className="text-muted-foreground text-xs [overflow-wrap:anywhere]">{greFoot}</div>
|
||||
</Card>
|
||||
<Card title={`NetFlow · окно ${minutes} мин`} value={netflowBytes == null ? "—" : fmtRate((netflowBytes * 8) / Math.max(1, windowSec))} unit="в среднем за окно">
|
||||
<Seg parts={[{ n: netflowBytes ? 1 : 0, color: "var(--chart-4)" }]} />
|
||||
<div className="text-muted-foreground text-xs">{netflowBytes == null ? "Потоки ещё не загружены" : "Все потоки NetFlow за окно"}</div>
|
||||
<Card title={liveLink ? "Макс. из замеров · Live" : flowLabel} value={liveLink ? formatNetflowRate(liveLink) : flowRate ?? "—"} unit={liveLink ? "RX + TX" : "в среднем"}>
|
||||
<Seg parts={liveLink ? [{ n: liveLink.bpsFwd, color: "var(--chart-4)" }, { n: liveLink.bpsRev, color: "var(--chart-1)" }]
|
||||
: topExits.length ? topExits.map((exit, i) => ({ n: exit.bps, color: EXIT_COLORS[i % EXIT_COLORS.length] })) : [{ n: netflowBytes ? 1 : 0, color: "var(--chart-4)" }]} />
|
||||
<div className="text-muted-foreground text-xs [overflow-wrap:anywhere]">
|
||||
{liveLink && <div title={liveLink.name}>{liveLink.name}</div>}
|
||||
{liveLink
|
||||
? flowRate && `${flowLabel} · среднее ${flowRate}`
|
||||
: netflowBytes == null ? "Потоки ещё не загружены" : topExits.length ? topExits.slice(0, 3).map((exit) => `${exit.name} ${formatNetflowRate({ bps: exit.bps })}`).join(" · ") : "Выборка IPFIX"}
|
||||
</div>
|
||||
</Card>
|
||||
<Card title="Требуют внимания" value={String(problems.length)} unit="узлов">
|
||||
<Card title="Требуют внимания" value={String(problems.length)} unit={ruPlural(problems.length, "узел", "узла", "узлов")}>
|
||||
{problems.length ? (
|
||||
<div className="-mx-1.5 -mb-1 flex flex-col">
|
||||
{problems.slice(0, 3).map((server) => (
|
||||
@@ -94,7 +120,7 @@ export function MapKpiStrip({ servers, tunnels, netflowBytes, windowSec, filter,
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-muted-foreground text-xs">Проблемных узлов нет</div>
|
||||
<div className="text-muted-foreground text-xs">На момент снимка все узлы отвечали.</div>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
"use client"
|
||||
|
||||
import { Fragment, type ReactNode } from "react"
|
||||
import { usePathname } from "next/navigation"
|
||||
import { InfoIcon, SearchIcon } from "lucide-react"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import {
|
||||
Breadcrumb,
|
||||
BreadcrumbItem,
|
||||
@@ -11,8 +16,8 @@ import {
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
} from "@/components/ui/breadcrumb"
|
||||
import { AppsMenu } from "@/components/apps-menu"
|
||||
import { SystemMonitorPopover } from "@/components/system-monitor-popover"
|
||||
import { openCommandPalette } from "@/components/command-palette"
|
||||
|
||||
interface Crumb {
|
||||
label: string
|
||||
@@ -26,21 +31,53 @@ interface PageHeaderProps {
|
||||
status?: ReactNode
|
||||
}
|
||||
|
||||
/** Header chrome — AppsMenu + SystemMonitor; theme in NavUser. @see https://reui.io/preview/base/app-shell-12 */
|
||||
export function PageHeader({ crumbs, actions, status }: PageHeaderProps) {
|
||||
/** Откуда раздел берёт данные — окно «Источники и свежесть данных» (как в шапке EvoBGP и макета v2). */
|
||||
const FRESH: Record<string, { badge: string; text: string }> = {
|
||||
"/dashboard": { badge: "Live", text: "Серверы, туннели, пробы, BGP, трафик, Internet path и события из API · обновление каждые 30 с" },
|
||||
"/traffic": { badge: "Live", text: "Счётчики интерфейсов RouterOS и потоки IPFIX · текущая скорость по live-потоку" },
|
||||
"/statistics": { badge: "Куб", text: "Куб NetFlow: факты IPFIX по суткам и часам · уникальный объём без дублей" },
|
||||
"/network-map": { badge: "Снимок", text: "Снимок карты из API и NetFlow за окно 5 мин · DNS для адресов GRE" },
|
||||
"/uptime": { badge: "Пробы", text: "Пробы ping и скорости по серверам · история RTT за час" },
|
||||
"/servers": { badge: "Каталог", text: "Каталог серверов и последний опрос RouterOS API" },
|
||||
"/ix": { badge: "IX", text: "Сегменты, площадки и Linux-клиенты точек обмена трафиком" },
|
||||
}
|
||||
|
||||
function freshFor(pathname: string) {
|
||||
const key = Object.keys(FRESH).sort((a, b) => b.length - a.length).find((k) => pathname === k || pathname.startsWith(`${k}/`))
|
||||
return key ? FRESH[key] : { badge: "API", text: "Данные раздела из API MikrotikManager" }
|
||||
}
|
||||
|
||||
function FreshnessPopover() {
|
||||
const fresh = freshFor(usePathname())
|
||||
return (
|
||||
<header className="bg-background sticky top-0 z-10 flex min-h-12 shrink-0 flex-wrap items-center gap-2 border-b px-4 py-1.5 md:px-6">
|
||||
<Popover>
|
||||
<PopoverTrigger render={<Button type="button" variant="ghost" size="icon" aria-label="Источники и свежесть данных" title="Источники и свежесть данных" />}>
|
||||
<InfoIcon aria-hidden />
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="end" sideOffset={8} className="flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-2">
|
||||
<Badge variant="success-light" size="sm" className="w-fit">{fresh.badge}</Badge>
|
||||
<p className="text-muted-foreground text-sm">{fresh.text}</p>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
/** Шапка общего макета v2 и EvoBGP: меню, «Главная / раздел / страница», источники данных, поиск, состояние системы. */
|
||||
export function PageHeader({ crumbs, actions, status }: PageHeaderProps) {
|
||||
const trail = crumbs[0]?.label === "Главная" ? crumbs : [{ label: "Главная", href: "/dashboard" }, ...crumbs]
|
||||
return (
|
||||
<header className="bg-background/80 sticky top-0 z-10 flex min-h-12 shrink-0 flex-wrap items-center gap-2 border-b px-4 py-1.5 backdrop-blur md:px-6">
|
||||
<SidebarTrigger className="-ml-1" />
|
||||
<Separator orientation="vertical" className="mr-2 data-[orientation=vertical]:h-4" />
|
||||
<Breadcrumb aria-label="Путь страницы" className="min-w-0 flex-1">
|
||||
<BreadcrumbList className="flex-nowrap">
|
||||
{crumbs.map((crumb, i) => (
|
||||
{trail.map((crumb, i) => (
|
||||
<Fragment key={i}>
|
||||
{i > 0 && <BreadcrumbSeparator className="text-muted-foreground hidden shrink-0 sm:block">/</BreadcrumbSeparator>}
|
||||
<BreadcrumbItem className={i < crumbs.length - 1 ? "hidden shrink-0 sm:inline-flex" : "min-w-0"}>
|
||||
{i < crumbs.length - 1 && crumb.href ? (
|
||||
<BreadcrumbItem className={i < trail.length - 1 ? "hidden shrink-0 sm:inline-flex" : "min-w-0"}>
|
||||
{i < trail.length - 1 && crumb.href ? (
|
||||
<BreadcrumbLink href={crumb.href}>{crumb.label}</BreadcrumbLink>
|
||||
) : i < crumbs.length - 1 ? (
|
||||
) : i < trail.length - 1 ? (
|
||||
<span className="text-muted-foreground text-sm">{crumb.label}</span>
|
||||
) : (
|
||||
<BreadcrumbPage className="wrap-anywhere">{crumb.label}</BreadcrumbPage>
|
||||
@@ -54,7 +91,10 @@ export function PageHeader({ crumbs, actions, status }: PageHeaderProps) {
|
||||
{actions ? <div role="group" aria-label="Действия страницы" className="flex min-w-0 flex-1 flex-wrap items-center gap-2">{actions}</div> : null}
|
||||
<div className="ml-auto flex shrink-0 items-center gap-2">
|
||||
{status}
|
||||
<AppsMenu />
|
||||
<FreshnessPopover />
|
||||
<Button type="button" variant="outline" size="icon" aria-label="Командная палитра (⌘K)" className="md:hidden" onClick={openCommandPalette}>
|
||||
<SearchIcon aria-hidden />
|
||||
</Button>
|
||||
<SystemMonitorPopover />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts"
|
||||
import { useState } from "react"
|
||||
import { CartesianGrid, Line, LineChart, ReferenceLine, XAxis, YAxis } from "recharts"
|
||||
import { Frame, FramePanel } from "@/components/reui/frame"
|
||||
import { ChartContainer, ChartTooltip, type ChartConfig } from "@/components/ui/chart"
|
||||
import { fmtRate, formatRangeAgo, TRAFFIC_RANGE_MINUTES } from "@/lib/fmt-rate"
|
||||
@@ -59,6 +60,7 @@ function toChartData(rx: (number|null)[], tx: (number|null)[], rangeMinutes: num
|
||||
return Array.from({ length: n }, (_, i) => {
|
||||
const minutesAgo = Math.round((1 - i / denom) * rangeMinutes)
|
||||
return {
|
||||
index: i,
|
||||
time: formatRangeAgo(minutesAgo),
|
||||
rx: typeof rx[i] === "number" && Number.isFinite(rx[i]) && rx[i] >= 0 ? rx[i] : null,
|
||||
tx: typeof tx[i] === "number" && Number.isFinite(tx[i]) && tx[i] >= 0 ? tx[i] : null,
|
||||
@@ -72,6 +74,7 @@ export function TrafficRxTxChart({
|
||||
range = "1h",
|
||||
rangeMinutes: actualMinutes,
|
||||
embedded = false,
|
||||
scrub = false,
|
||||
}: {
|
||||
rx: (number|null)[]
|
||||
tx: (number|null)[]
|
||||
@@ -79,9 +82,13 @@ export function TrafficRxTxChart({
|
||||
rangeMinutes?: number
|
||||
/** Skip outer Frame when already inside OpsPanel / Frame. */
|
||||
embedded?: boolean
|
||||
scrub?: boolean
|
||||
}) {
|
||||
const rangeMinutes = actualMinutes ?? TRAFFIC_RANGE_MINUTES[range] ?? 60
|
||||
const data = toChartData(rx, tx, rangeMinutes)
|
||||
const [selected, setSelected] = useState<number>()
|
||||
const index = Math.min(selected ?? data.length - 1, data.length - 1)
|
||||
const point = data[index]
|
||||
const tickEvery = Math.max(1, Math.ceil(data.length / 6))
|
||||
|
||||
const hasRx = data.some(point => point.rx !== null)
|
||||
@@ -105,7 +112,8 @@ export function TrafficRxTxChart({
|
||||
stroke="var(--border)"
|
||||
/>
|
||||
<XAxis
|
||||
dataKey="time"
|
||||
dataKey="index"
|
||||
tickFormatter={(value: number) => data[value]?.time ?? ""}
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
tick={{ fontSize: 11 }}
|
||||
@@ -121,6 +129,7 @@ export function TrafficRxTxChart({
|
||||
width={72}
|
||||
/>
|
||||
<ChartTooltip content={<CustomTooltip />} />
|
||||
{scrub && selected !== undefined && <ReferenceLine x={index} stroke="var(--muted-foreground)" />}
|
||||
{hasRx && <Line
|
||||
dataKey="rx"
|
||||
type="monotone"
|
||||
@@ -141,6 +150,15 @@ export function TrafficRxTxChart({
|
||||
<ChartLegendItem label="RX (входящий)" color="var(--chart-rx)" />
|
||||
<ChartLegendItem label="TX (исходящий)" color="var(--chart-tx)" />
|
||||
</div>
|
||||
{scrub && data.length > 1 && <div className="grid gap-2 border-t pt-2 text-xs">
|
||||
<label className="flex flex-wrap items-center gap-2 text-muted-foreground">
|
||||
Точка на графике
|
||||
<input type="range" className="min-w-24 flex-1 accent-primary" min={0} max={data.length - 1} value={index}
|
||||
aria-valuetext={`${point.time} · RX ${fmtRate(point.rx)} · TX ${fmtRate(point.tx)}`}
|
||||
onChange={event => setSelected(Number(event.target.value))} />
|
||||
</label>
|
||||
<p className="font-mono tabular-nums">{point.time} · RX {fmtRate(point.rx)} · TX {fmtRate(point.tx)}</p>
|
||||
</div>}
|
||||
</div>
|
||||
)
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState, type ReactNode } from "react"
|
||||
import { Activity, Filter, HeartPulse, Server } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import { Activity, ArrowRightIcon, Filter, HeartPulse, Server } from "lucide-react"
|
||||
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
|
||||
@@ -151,7 +152,15 @@ export function SystemMonitorPopover() {
|
||||
[apiOk, filtersCount, healthOk, monitoringCount, serversCount],
|
||||
)
|
||||
|
||||
const spiking = metrics.some((m) => m.alert)
|
||||
// Проблемы для «Состояния системы» — только подтверждённые сигналы: API и сводка.
|
||||
const items: Array<{ id: string; tone: "er" | "wn"; title: string; text: string }> = []
|
||||
if (healthOk === false) items.push({ id: "api", tone: "er", title: "API MikrotikManager не отвечает", text: "GET /health вернул ошибку или не ответил" })
|
||||
if (data?.countsError) items.push({ id: "counts", tone: "wn", title: "Сводка не обновлена", text: data.countsError })
|
||||
const errors = items.filter((i) => i.tone === "er").length
|
||||
const warnings = items.length - errors
|
||||
const okCount = metrics.length - items.length
|
||||
const label = errors ? "Сбой" : warnings ? "Внимание" : healthOk == null ? "Нет данных" : "Норма"
|
||||
const tone = errors ? "destructive" : warnings || healthOk == null ? "warning" : "success"
|
||||
|
||||
return (
|
||||
<Popover>
|
||||
@@ -159,63 +168,73 @@ export function SystemMonitorPopover() {
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Монитор системы"
|
||||
aria-label={`Состояние системы: ${label.toLowerCase()}, сбоев ${errors}, предупреждений ${warnings}`}
|
||||
className={cn(
|
||||
"relative inline-flex h-8 items-center gap-1.5 rounded-md border px-2 transition-colors outline-none",
|
||||
"border-border hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",
|
||||
"relative inline-flex h-8 items-center gap-2 rounded-md border px-2 text-sm font-medium transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring max-[760px]:w-8 max-[760px]:justify-center max-[760px]:border-transparent max-[760px]:bg-transparent max-[760px]:px-0",
|
||||
tone === "destructive" && "border-destructive/40 bg-destructive/10 hover:bg-destructive/20 aria-expanded:bg-destructive/20",
|
||||
tone === "warning" && "border-warning/40 bg-warning/10 hover:bg-warning/20 aria-expanded:bg-warning/20",
|
||||
tone === "success" && "border-border hover:bg-accent aria-expanded:bg-accent",
|
||||
)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="relative flex size-3.5 items-center justify-center">
|
||||
<Activity
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"size-3.5 transition-colors",
|
||||
spiking ? "text-destructive" : "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
{spiking ? (
|
||||
<span className="bg-destructive/25 absolute inset-0 animate-ping rounded-full" aria-hidden />
|
||||
) : null}
|
||||
<Activity aria-hidden className={cn("size-4", tone === "destructive" ? "text-destructive" : tone === "warning" ? "text-warning" : "text-success")} />
|
||||
<span className={cn("hidden min-[1000px]:inline", tone === "destructive" ? "text-destructive-foreground" : tone === "warning" ? "text-warning-foreground" : "text-foreground")}>{label}</span>
|
||||
<span className="hidden items-center gap-1.5 tabular-nums min-[1240px]:inline-flex">
|
||||
<span className="bg-destructive size-1.5 rounded-full" aria-hidden />
|
||||
{errors}
|
||||
<span className="bg-warning size-1.5 rounded-full" aria-hidden />
|
||||
{warnings}
|
||||
</span>
|
||||
<span className="text-foreground hidden text-xs font-medium sm:inline">Система</span>
|
||||
<Badge
|
||||
variant={spiking ? "destructive-light" : apiOk?"success-light":"outline"}
|
||||
size="xs"
|
||||
className={cn("h-4 px-1.5 text-[10px]",apiOk&&"text-emerald-700 dark:text-emerald-400",spiking&&"text-red-700 dark:text-red-400")}
|
||||
>
|
||||
{spiking?"Нет связи":apiOk?"API доступен":"Нет данных"}
|
||||
</Badge>
|
||||
{items.length ? <span className="bg-destructive ring-background absolute top-1 right-1 size-2 rounded-full ring-2 min-[760px]:hidden" aria-hidden /> : null}
|
||||
</PopoverTrigger>
|
||||
|
||||
<PopoverContent align="end" sideOffset={8} className="flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-0! p-0!">
|
||||
<div className="border-border flex items-center justify-between border-b px-3 py-2.5">
|
||||
<span className="text-foreground text-xs font-medium">Монитор MikrotikManager</span>
|
||||
<span className="text-muted-foreground text-[11px] tabular-nums">
|
||||
{mode!=="live"?"Демо":data?.receivedAt?new Date(data.receivedAt).toLocaleTimeString("ru-RU"):"Снимок не получен"}
|
||||
</span>
|
||||
<PopoverContent align="end" sideOffset={8} className="flex w-[24rem] max-w-[calc(100vw-1.5rem)] flex-col gap-2 p-2">
|
||||
<div className="flex items-start justify-between gap-2 px-1.5 pt-1.5">
|
||||
<div className="grid leading-tight">
|
||||
<b className="text-sm font-semibold">Состояние системы</b>
|
||||
<span className="text-muted-foreground text-xs">
|
||||
{mode !== "live" ? "Демо-данные" : data?.receivedAt ? `обновлено ${new Date(data.receivedAt).toLocaleTimeString("ru-RU")}` : "Снимок не получен"}
|
||||
</span>
|
||||
</div>
|
||||
<Badge variant={errors ? "destructive-light" : warnings ? "warning-light" : "success-light"} size="sm" className={cn(!errors && !warnings && "text-emerald-700 dark:text-emerald-400", errors && "text-red-700 dark:text-red-400")}>{label}</Badge>
|
||||
</div>
|
||||
{data?.countsError?<p role="status" className="px-3 py-2 text-xs text-muted-foreground">{data.countsError}</p>:null}
|
||||
<div className="grid grid-cols-2">
|
||||
<div className="grid grid-cols-3 gap-1.5">
|
||||
{[
|
||||
{ n: errors, l: "сбой", c: "text-destructive-foreground" },
|
||||
{ n: warnings, l: "предупреждения", c: "text-warning-foreground" },
|
||||
{ n: Math.max(0, okCount), l: "в норме", c: "text-success-foreground" },
|
||||
].map((x) => (
|
||||
<span key={x.l} className="bg-muted/55 text-muted-foreground flex flex-col rounded-lg px-2.5 py-2 text-xs">
|
||||
<b className={cn("text-lg leading-tight font-semibold tabular-nums", x.c)}>{x.n}</b>
|
||||
{x.l}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{items.length ? (
|
||||
<div role="status"><ul className="flex flex-col gap-0.5">
|
||||
{items.map((m) => (
|
||||
<li key={m.id} className="flex items-center gap-2.5 rounded-md px-1.5 py-2">
|
||||
<span aria-hidden className={cn("size-2 shrink-0 rounded-full", m.tone === "er" ? "bg-destructive" : "bg-warning")} />
|
||||
<span className="grid min-w-0 flex-1 leading-tight">
|
||||
<b className="truncate text-[13px] font-medium">{m.title}</b>
|
||||
<span className="text-muted-foreground truncate text-xs">{m.text}</span>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul></div>
|
||||
) : null}
|
||||
<div className="grid grid-cols-2 overflow-hidden rounded-lg border">
|
||||
{metrics.map((metric, i) => (
|
||||
<div
|
||||
key={metric.id}
|
||||
className={cn(
|
||||
i % 2 === 1 && "border-border border-l",
|
||||
i >= 2 && "border-border border-t",
|
||||
)}
|
||||
>
|
||||
<div key={metric.id} className={cn(i % 2 === 1 && "border-l", i >= 2 && "border-t")}>
|
||||
<MetricCell metric={metric} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="border-border text-muted-foreground border-t px-3 py-2 text-[11px]">
|
||||
Источник:{" "}
|
||||
<span className="text-foreground font-medium">
|
||||
{mode === "live" ? "API" : "мок"}
|
||||
</span>
|
||||
</div>
|
||||
<Link href="/uptime" className="text-muted-foreground hover:text-foreground flex items-center justify-between px-1.5 pt-1 pb-0.5 text-sm">
|
||||
Мониторинг
|
||||
<ArrowRightIcon className="size-3.5" aria-hidden />
|
||||
</Link>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
DATA_GRID_CELL_PAD_LAST,
|
||||
} from "@/components/data-grids/shared/data-grid-layout"
|
||||
import { TrafficFlowsDataGrid } from "@/components/data-grids/traffic-flows-data-grid"
|
||||
import { matchesMapService } from "@/lib/flow-map-service-match"
|
||||
import { FlowTrafficMap } from "@/components/traffic/flow-traffic-map"
|
||||
import { StatusDot } from "@/components/status-dot"
|
||||
import { Flag } from "@/components/flag"
|
||||
@@ -103,13 +104,14 @@ type BreakdownFilter = {
|
||||
label: string
|
||||
serverId?: string
|
||||
}
|
||||
type SessionFilter = BreakdownFilter | { kind: "path"; path: FlowPathRow; label: string }
|
||||
type SessionFilter = BreakdownFilter | { kind: "path"; path: FlowPathRow; label: string } | { kind: "map-service"; label: string; country?: string }
|
||||
|
||||
function talkerMatchesFilter(row: FlowTalkerDto, filter: SessionFilter): boolean {
|
||||
switch (filter.kind) {
|
||||
case "application": return row.application === filter.value
|
||||
case "category": return row.category === filter.value
|
||||
case "service": return row.service === filter.value
|
||||
case "map-service": return matchesMapService(row, filter.label, filter.country)
|
||||
case "asn": return String(row.dstAsn ?? "unknown") === filter.value
|
||||
case "country": return (!filter.serverId || row.serverId === filter.serverId) && (row.dstCountry || "unknown") === filter.value
|
||||
case "protocol": return row.protoName === filter.value
|
||||
@@ -329,6 +331,9 @@ export function FlowAnalyticsDetail({
|
||||
onExcludeOverlay,
|
||||
liveHint,
|
||||
emptyHint,
|
||||
initialService,
|
||||
initialCountry,
|
||||
mapNodes,
|
||||
}: {
|
||||
card: (Pick<FlowEntityCard, "id" | "name" | "country" | "site"> & Partial<FlowEntityCard>) | null
|
||||
analytics: FlowAnalyticsDto | null
|
||||
@@ -349,14 +354,16 @@ export function FlowAnalyticsDetail({
|
||||
onExcludeOverlay: (value: boolean) => void
|
||||
liveHint?: string
|
||||
emptyHint?: string
|
||||
initialService?: string
|
||||
initialCountry?: string
|
||||
mapNodes?: string[]
|
||||
}) {
|
||||
const [slice, setSlice] = useState("applications")
|
||||
const [sessionFilter, setSessionFilter] = useState<SessionFilter | null>(null)
|
||||
const [slice, setSlice] = useState(initialService ? "sessions" : "applications")
|
||||
const [sessionFilter, setSessionFilter] = useState<SessionFilter | null>(initialService ? { kind: "map-service", label: initialService, country: initialCountry } : null)
|
||||
const rxNow = analytics ? analytics.bpsNow / 1_000_000 : (card?.rxNow ?? 0)
|
||||
const bytes = analytics?.bytes ?? card?.bytes ?? 0
|
||||
const sessionRows = (analytics?.conversationsList ?? []).filter((row) =>
|
||||
sessionFilter ? talkerMatchesFilter(row, sessionFilter) : true,
|
||||
)
|
||||
const sessionRows = (analytics?.conversationsList ?? []).filter(row =>
|
||||
(!mapNodes || mapNodes.includes(row.enId || row.serverId)) && (!sessionFilter || talkerMatchesFilter(row, sessionFilter)))
|
||||
|
||||
function pickBreakdown(kind: BreakdownFilter["kind"], row: FlowBreakdownRow) {
|
||||
setSessionFilter({ kind, value: row.id, label: row.label })
|
||||
|
||||
|
Before Width: | Height: | Size: 163 KiB After Width: | Height: | Size: 169 KiB |
|
Before Width: | Height: | Size: 66 KiB After Width: | Height: | Size: 61 KiB |
|
Before Width: | Height: | Size: 62 KiB After Width: | Height: | Size: 60 KiB |
|
Before Width: | Height: | Size: 146 KiB After Width: | Height: | Size: 145 KiB |
|
Before Width: | Height: | Size: 65 KiB After Width: | Height: | Size: 60 KiB |
|
Before Width: | Height: | Size: 63 KiB After Width: | Height: | Size: 54 KiB |
@@ -1,70 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { isTrafficLiveSample } from "@/hooks/use-traffic-live"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
|
||||
export interface GreTrafficTarget {
|
||||
edgeId: string
|
||||
serverId: string
|
||||
iface: string
|
||||
}
|
||||
|
||||
type Rate = { bps: number; bpsFwd: number; bpsRev: number; receivedAt: number }
|
||||
const MAX_CONCURRENT_READS = 4
|
||||
const REFRESH_MS = 8_000
|
||||
const MAX_SAMPLE_AGE_MS = 30_000
|
||||
|
||||
export function useMapGreTraffic(backendUrl: string, targets: GreTrafficTarget[]) {
|
||||
const key = JSON.stringify(targets)
|
||||
const [snapshot, setSnapshot] = useState<{ backendUrl: string; key: string; rates: Map<string, Rate> }>()
|
||||
|
||||
useEffect(() => {
|
||||
const scope: GreTrafficTarget[] = JSON.parse(key)
|
||||
if (!scope.length) return
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
const run = async () => {
|
||||
if (document.hidden) {
|
||||
timer = setTimeout(run, REFRESH_MS)
|
||||
return
|
||||
}
|
||||
for (let offset = 0; offset < scope.length && !controller.signal.aborted; offset += MAX_CONCURRENT_READS) {
|
||||
const batch = await Promise.all(scope.slice(offset, offset + MAX_CONCURRENT_READS).map(async ({ edgeId, serverId, iface }) => {
|
||||
try {
|
||||
const query = new URLSearchParams({ iface, once: "1" })
|
||||
const sample = await requestJson<unknown>(backendUrl, `/api/traffic/servers/${encodeURIComponent(serverId)}/live?${query}`, {
|
||||
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(6_000)]),
|
||||
cache: "no-store",
|
||||
})
|
||||
if (isTrafficLiveSample(sample)) {
|
||||
const bpsFwd = sample.rxMbps * 1_000_000
|
||||
const bpsRev = sample.txMbps * 1_000_000
|
||||
return { edgeId, rate: { bps: bpsFwd + bpsRev, bpsFwd, bpsRev, receivedAt: Date.now() } }
|
||||
}
|
||||
} catch {
|
||||
// One unavailable interface cannot hide readings on other links.
|
||||
}
|
||||
return { edgeId }
|
||||
}))
|
||||
if (controller.signal.aborted) return
|
||||
setSnapshot(previous => {
|
||||
const rates = new Map(previous?.key === key && previous.backendUrl === backendUrl ? previous.rates : [])
|
||||
for (const { edgeId, rate } of batch) {
|
||||
if (rate) rates.set(edgeId, rate)
|
||||
else rates.delete(edgeId)
|
||||
}
|
||||
return { backendUrl, key, rates }
|
||||
})
|
||||
}
|
||||
if (!controller.signal.aborted) timer = setTimeout(run, REFRESH_MS)
|
||||
}
|
||||
void run()
|
||||
return () => { controller.abort(); clearTimeout(timer) }
|
||||
}, [backendUrl, key])
|
||||
|
||||
return (edgeId: string) => {
|
||||
const rate = snapshot?.key === key && snapshot.backendUrl === backendUrl ? snapshot.rates.get(edgeId) : undefined
|
||||
return rate && Date.now() - rate.receivedAt <= MAX_SAMPLE_AGE_MS ? rate : undefined
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { isTrafficLiveSample, type TrafficLiveSample } from "@/hooks/use-traffic-live"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
|
||||
export interface MapTrafficTarget {
|
||||
edgeId: string
|
||||
serverId: string
|
||||
iface: string
|
||||
}
|
||||
|
||||
type Rate = { bps: number; bpsFwd: number; bpsRev: number; at: string; receivedAt: number }
|
||||
const MAX_CONCURRENT_READS = 4
|
||||
const REFRESH_MS = 8_000
|
||||
const MAX_SAMPLE_AGE_MS = 30_000
|
||||
|
||||
export function isFreshMapTrafficSample(sample: unknown, now = Date.now()): sample is TrafficLiveSample {
|
||||
return isTrafficLiveSample(sample) && Math.abs(now - Date.parse(sample.at)) <= MAX_SAMPLE_AGE_MS
|
||||
}
|
||||
|
||||
export function useMapInterfaceTraffic(backendUrl: string, targets: MapTrafficTarget[]) {
|
||||
const key = JSON.stringify(targets)
|
||||
const [snapshot, setSnapshot] = useState<{ backendUrl: string; key: string; rates: Map<string, Rate> }>()
|
||||
|
||||
useEffect(() => {
|
||||
const scope: MapTrafficTarget[] = JSON.parse(key)
|
||||
if (!scope.length) return
|
||||
const servers = new Map<string, Map<string, string[]>>()
|
||||
for (const { edgeId, serverId, iface } of scope) {
|
||||
const interfaces = servers.get(serverId) ?? new Map<string, string[]>()
|
||||
interfaces.set(iface, [...(interfaces.get(iface) ?? []), edgeId])
|
||||
servers.set(serverId, interfaces)
|
||||
}
|
||||
const requests = [...servers].flatMap(([serverId, interfaces]) => {
|
||||
const entries = [...interfaces]
|
||||
return Array.from({ length: Math.ceil(entries.length / 16) }, (_, i) => ({
|
||||
serverId, entries: entries.slice(i * 16, (i + 1) * 16),
|
||||
}))
|
||||
})
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
const run = async () => {
|
||||
if (document.hidden) {
|
||||
timer = setTimeout(run, REFRESH_MS)
|
||||
return
|
||||
}
|
||||
for (let offset = 0; offset < requests.length && !controller.signal.aborted; offset += MAX_CONCURRENT_READS) {
|
||||
const batch = await Promise.all(requests.slice(offset, offset + MAX_CONCURRENT_READS).map(async ({ serverId, entries }) => {
|
||||
const single = entries.length === 1
|
||||
let samples: Record<string, unknown> = {}
|
||||
try {
|
||||
const names = entries.map(([iface]) => iface).join(",")
|
||||
const query = new URLSearchParams({ [single ? "iface" : "ifaces"]: names, once: "1" })
|
||||
const response = await requestJson<{ interfaces?: Record<string, unknown> }>(backendUrl, `/api/traffic/servers/${encodeURIComponent(serverId)}/live?${query}`, {
|
||||
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(9_000)]),
|
||||
cache: "no-store",
|
||||
})
|
||||
samples = single ? { [names]: response } : response?.interfaces ?? {}
|
||||
} catch {
|
||||
// Other routers can still return fresh samples.
|
||||
}
|
||||
return entries.flatMap(([iface, edgeIds]) => {
|
||||
const sample = samples[iface]
|
||||
const receivedAt = Date.now()
|
||||
const rate = isFreshMapTrafficSample(sample, receivedAt) ? {
|
||||
bps: (sample.rxMbps + sample.txMbps) * 1_000_000,
|
||||
bpsFwd: sample.rxMbps * 1_000_000,
|
||||
bpsRev: sample.txMbps * 1_000_000,
|
||||
at: sample.at,
|
||||
receivedAt,
|
||||
} : undefined
|
||||
return edgeIds.map(edgeId => ({ edgeId, rate }))
|
||||
})
|
||||
}))
|
||||
if (controller.signal.aborted) return
|
||||
setSnapshot(previous => {
|
||||
const rates = new Map(previous?.key === key && previous.backendUrl === backendUrl ? previous.rates : [])
|
||||
for (const { edgeId, rate } of batch.flat()) {
|
||||
if (rate) rates.set(edgeId, rate)
|
||||
else rates.delete(edgeId)
|
||||
}
|
||||
return { backendUrl, key, rates }
|
||||
})
|
||||
}
|
||||
if (!controller.signal.aborted) timer = setTimeout(run, REFRESH_MS)
|
||||
}
|
||||
void run()
|
||||
return () => { controller.abort(); clearTimeout(timer) }
|
||||
}, [backendUrl, key])
|
||||
|
||||
return (edgeId: string) => {
|
||||
const rate = snapshot?.key === key && snapshot.backendUrl === backendUrl ? snapshot.rates.get(edgeId) : undefined
|
||||
return rate && Date.now() - Math.min(rate.receivedAt, Date.parse(rate.at)) <= MAX_SAMPLE_AGE_MS ? rate : undefined
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { FlowTalkerDto } from "@mmapp/contracts/traffic-flow"
|
||||
|
||||
export function matchesMapService(row: Pick<FlowTalkerDto, "service" | "category" | "dstCountry">, label: string, country?: string) {
|
||||
const service = row.service === label || row.category === label && (row.service === "Прочее" || ["DNS", "SSH", "BGP"].includes(label))
|
||||
if (!service || !country) return service
|
||||
return country === "unknown" ? !row.dstCountry || row.dstCountry.toLowerCase() === "unknown" : row.dstCountry?.toUpperCase() === country.toUpperCase()
|
||||
}
|
||||
@@ -43,3 +43,7 @@ export function formatServicePathTitle(label: string, serviceLabel: string): str
|
||||
if (label.includes(svc)) return label
|
||||
return `${label} · ${svc}`
|
||||
}
|
||||
|
||||
export function servicePathKey(p: { clientId: string; viaId: string; viaIface?: string; enId: string; serviceId: string }): string {
|
||||
return JSON.stringify([p.clientId, p.viaId, p.viaIface, p.enId, p.serviceId])
|
||||
}
|
||||
@@ -18,6 +18,7 @@ export interface GreSpeedProbeSnapshot {
|
||||
lastRxAvgMbps?: number | null
|
||||
lastPingAt?: string | null
|
||||
lastPingRttMs?: number | null
|
||||
lastPingLossPct?: number | null
|
||||
}
|
||||
|
||||
export type GreTunnelProbeEdge = {
|
||||
|
||||
@@ -51,6 +51,11 @@ export function formatNetflowDir(hop: Pick<MatchedNetflowHop, "bpsFwd" | "bpsRev
|
||||
return `↓${formatNetflowRate({ bps: hop.bpsFwd })} ↑${formatNetflowRate({ bps: hop.bpsRev })}`
|
||||
}
|
||||
|
||||
export function formatMapFlowWindow(windowSec: number): string {
|
||||
const seconds = Math.floor(windowSec % 60)
|
||||
return `${Math.floor(windowSec / 60)} мин${seconds ? ` ${seconds} с` : ""}`
|
||||
}
|
||||
|
||||
/** GRE rates use RX/TX at the tunnel owner, regardless of its position on the map. */
|
||||
function greInterfaceObservation(
|
||||
tunnel: { name: string; serverId: string },
|
||||
|
||||
@@ -2,4 +2,5 @@ import {test} from "node:test"
|
||||
import assert from "node:assert/strict"
|
||||
import {fitNetworkMapCamera} from "./network-map-camera"
|
||||
test("camera fits off-world nodes and labels across aspect ratios",()=>{for(const h of [580,1600]){const points=[{x:-200,y:50},{x:1000,y:700}],c=fitNetworkMapCamera(points,1240,h);for(const p of points){assert.ok(p.x>=c.pan.x+119);assert.ok(p.x<=c.pan.x+1240/c.zoom-119);assert.ok(p.y>=c.pan.y+99);assert.ok(p.y<=c.pan.y+h/c.zoom-99)}}})
|
||||
test("camera keeps objects above the bottom overlay band",()=>{const points=[{x:0,y:0},{x:1000,y:600}],c=fitNetworkMapCamera(points,1240,900,.25);for(const p of points)assert.ok(p.y<=c.pan.y+(900*.75)/c.zoom-99)})
|
||||
test("empty/invalid positions and maximum initial zoom",()=>{assert.deepEqual(fitNetworkMapCamera([],1240,580),{pan:{x:0,y:0},zoom:1});assert.deepEqual(fitNetworkMapCamera([{x:NaN,y:1}],1240,580),{pan:{x:0,y:0},zoom:1});assert.equal(fitNetworkMapCamera([{x:1,y:1}],1240,1600).zoom,3)})
|
||||
@@ -1,8 +1,10 @@
|
||||
export interface MapPoint {x:number;y:number}
|
||||
export function fitNetworkMapCamera(points:readonly MapPoint[],width:number,height:number) {
|
||||
/** bottomReserve — доля высоты снизу под панель масштаба и миникарту: объекты вписываются над ней. */
|
||||
export function fitNetworkMapCamera(points:readonly MapPoint[],width:number,height:number,bottomReserve=0) {
|
||||
const valid=points.filter(p=>Number.isFinite(p.x)&&Number.isFinite(p.y))
|
||||
if(!valid.length||width<=0||height<=0)return {pan:{x:0,y:0},zoom:1}
|
||||
const xs=valid.map(p=>p.x),ys=valid.map(p=>p.y),left=Math.min(...xs)-120,right=Math.max(...xs)+120,top=Math.min(...ys)-100,bottom=Math.max(...ys)+100
|
||||
const zoom=Math.max(.2,Math.min(3,width/(right-left),height/(bottom-top)))
|
||||
return {pan:{x:(left+right)/2-width/(2*zoom),y:(top+bottom)/2-height/(2*zoom)},zoom}
|
||||
const usable=height*(1-Math.min(.6,Math.max(0,bottomReserve)))
|
||||
const zoom=Math.max(.2,Math.min(3,width/(right-left),usable/(bottom-top)))
|
||||
return {pan:{x:(left+right)/2-width/(2*zoom),y:(top+bottom)/2-usable/(2*zoom)},zoom}
|
||||
}
|
||||
@@ -73,14 +73,93 @@ const MAX_NODE_Y = H - 44
|
||||
export function mapLinkPath(
|
||||
a: { x: number; y: number }, aHalfW: number,
|
||||
b: { x: number; y: number }, bHalfW: number,
|
||||
): { d: string; x1: number; y1: number; x2: number; y2: number } {
|
||||
): MapLink {
|
||||
if (Math.abs(b.x - a.x) < aHalfW + bHalfW) {
|
||||
const x1 = a.x + aHalfW, x2 = b.x + bHalfW, bend = Math.max(x1, x2) + 48
|
||||
return { d: `M ${x1} ${a.y} C ${bend} ${a.y} ${bend} ${b.y} ${x2} ${b.y}`, x1, y1: a.y, x2, y2: b.y }
|
||||
return { d: `M ${x1} ${a.y} C ${bend} ${a.y} ${bend} ${b.y} ${x2} ${b.y}`, x1, y1: a.y, x2, y2: b.y, cx: bend }
|
||||
}
|
||||
const dir = b.x > a.x ? 1 : -1
|
||||
const x1 = a.x + dir * aHalfW, x2 = b.x - dir * bHalfW, mx = (x1 + x2) / 2
|
||||
return { d: `M ${x1} ${a.y} C ${mx} ${a.y} ${mx} ${b.y} ${x2} ${b.y}`, x1, y1: a.y, x2, y2: b.y }
|
||||
return { d: `M ${x1} ${a.y} C ${mx} ${a.y} ${mx} ${b.y} ${x2} ${b.y}`, x1, y1: a.y, x2, y2: b.y, cx: mx }
|
||||
}
|
||||
|
||||
/** Связь карты: путь и опорные точки кривой (cx — x обеих управляющих точек). */
|
||||
export interface MapLink { d: string; x1: number; y1: number; x2: number; y2: number; cx: number }
|
||||
|
||||
/** Точка кривой связи при параметре t ∈ [0, 1]. */
|
||||
export function mapLinkPoint(l: MapLink, t: number): { x: number; y: number } {
|
||||
const u = 1 - t, a = u * u * u, b = 3 * u * u * t, c = 3 * u * t * t, d = t * t * t
|
||||
return { x: a * l.x1 + (b + c) * l.cx + d * l.x2, y: (a + b) * l.y1 + (c + d) * l.y2 }
|
||||
}
|
||||
|
||||
/** Прямоугольник на холсте (левый верхний угол и размеры). */
|
||||
export interface MapBox { x: number; y: number; w: number; h: number }
|
||||
|
||||
/** Подпись связи макета v3: «таблетка» 20 px, Geist Mono 11 px. */
|
||||
export const MAP_PILL_H = 20
|
||||
export const mapPillWidth = (text: string) => Math.round(text.length * 6.6 + 16)
|
||||
|
||||
const boxesHit = (a: MapBox, b: MapBox) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
|
||||
/** Сначала середина кривой (как в макете), затем ближе к концам. */
|
||||
const LABEL_T = [0.5, 0.42, 0.58, 0.34, 0.66, 0.27, 0.73]
|
||||
|
||||
/**
|
||||
* Раскладка подписей связей без наложений: каждая подпись ставится на свою кривую в первое свободное место —
|
||||
* не поверх карточек и других подписей. `texts` — варианты от полного к короткому; если не влезает ни один,
|
||||
* подпись не рисуется (значение остаётся в aria-label связи и в панели деталей).
|
||||
*/
|
||||
export function placeMapLinkLabels<T extends { id: string; link: MapLink; texts: string[] }>(
|
||||
labels: T[],
|
||||
obstacles: MapBox[],
|
||||
gap = 4,
|
||||
): Array<T & { x: number; y: number; w: number; text: string }> {
|
||||
const taken = obstacles.map((o) => ({ x: o.x - gap, y: o.y - gap, w: o.w + gap * 2, h: o.h + gap * 2 }))
|
||||
const out: Array<T & { x: number; y: number; w: number; text: string }> = []
|
||||
for (const label of labels) {
|
||||
search: for (const text of label.texts) {
|
||||
const w = mapPillWidth(text)
|
||||
for (const t of LABEL_T) {
|
||||
const p = mapLinkPoint(label.link, t)
|
||||
const box = { x: p.x - w / 2, y: p.y - MAP_PILL_H / 2, w, h: MAP_PILL_H }
|
||||
if (taken.some((o) => boxesHit(box, o))) continue
|
||||
taken.push({ x: box.x - gap, y: box.y - gap, w: w + gap * 2, h: MAP_PILL_H + gap * 2 })
|
||||
out.push({ ...label, x: Math.round(p.x), y: Math.round(p.y), w, text })
|
||||
break search
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Ленты NetFlow (Sankey) макета v3: толщина — скорость, ленты одного узла уложены стопкой у его края,
|
||||
* без подписей. Самая толстая стопка у узла — `maxPx`.
|
||||
*/
|
||||
export function mapRibbons<T extends { from: { x: number; y: number }; fromHalfW: number; to: { x: number; y: number }; toHalfW: number; bps: number }>(
|
||||
flows: T[],
|
||||
maxPx = 36,
|
||||
): Array<T & { d: string; w: number }> {
|
||||
const key = (p: { x: number; y: number }) => `${Math.round(p.x)},${Math.round(p.y)}`
|
||||
const sum = (m: Map<string, number>, k: string, v: number) => m.set(k, (m.get(k) ?? 0) + v)
|
||||
const outs = new Map<string, number>(), ins = new Map<string, number>()
|
||||
for (const f of flows) { sum(outs, key(f.from), Math.max(0, f.bps)); sum(ins, key(f.to), Math.max(0, f.bps)) }
|
||||
const peak = Math.max(0, ...outs.values(), ...ins.values())
|
||||
const rows = flows.map((f) => ({ f, w: Math.max(1.5, peak > 0 ? (Math.max(0, f.bps) / peak) * maxPx : 1.5), sy: 0, ty: 0 }))
|
||||
const stack = (side: "from" | "to", other: "from" | "to", y: "sy" | "ty") => {
|
||||
const groups = new Map<string, typeof rows>()
|
||||
for (const r of rows) groups.set(key(r.f[side]), [...(groups.get(key(r.f[side])) ?? []), r])
|
||||
for (const group of groups.values()) {
|
||||
group.sort((a, b) => a.f[other].y - b.f[other].y)
|
||||
let cum = group[0].f[side].y - group.reduce((s, r) => s + r.w, 0) / 2
|
||||
for (const r of group) { r[y] = cum + r.w / 2; cum += r.w }
|
||||
}
|
||||
}
|
||||
stack("from", "to", "sy")
|
||||
stack("to", "from", "ty")
|
||||
return rows.map(({ f, w, sy, ty }) => {
|
||||
const x1 = f.from.x + f.fromHalfW, x2 = f.to.x - f.toHalfW, cx = Math.round((x1 + x2) / 2)
|
||||
return { ...f, w: Number(w.toFixed(1)), d: `M ${x1} ${sy.toFixed(1)} C ${cx} ${sy.toFixed(1)} ${cx} ${ty.toFixed(1)} ${x2} ${ty.toFixed(1)}` }
|
||||
})
|
||||
}
|
||||
|
||||
/** Одна горизонтальная «полка» на карте: Home → JH → Exit слева направо. */
|
||||
@@ -831,6 +910,7 @@ function greEndpointAnchor(
|
||||
export interface GreMapEdge {
|
||||
tunnel: GreTunnel
|
||||
peerTunnel?: GreTunnel
|
||||
ambiguousPeerKey?: string
|
||||
from: { x: number; y: number }
|
||||
to: { x: number; y: number }
|
||||
fromServer: Server
|
||||
@@ -880,17 +960,16 @@ export function buildGreMapEdges(
|
||||
if (!a || !b) continue
|
||||
if (a.id === b.id) continue
|
||||
|
||||
const la = layerOfServer(a)
|
||||
const lb = layerOfServer(b)
|
||||
if (la == null || lb == null) continue
|
||||
// EN→EN, JH→JH и т.п. на карте не показываем — только межуровневые рёбра.
|
||||
if (la === lb) continue
|
||||
const aIsIx = a.type === "ix-node", bIsIx = b.type === "ix-node"
|
||||
const la = aIsIx ? roleLayer("EN") : layerOfServer(a)
|
||||
const lb = bIsIx ? roleLayer("EN") : layerOfServer(b)
|
||||
if (la == null || lb == null || la === lb && !aIsIx && !bIsIx) continue
|
||||
|
||||
// Строгий поток слева направо: HR → JH → EN.
|
||||
// Если направление туннеля против иерархии — переворачиваем визуальное ребро.
|
||||
let fromServer = a
|
||||
let toServer = b
|
||||
if (la > lb) {
|
||||
if (la > lb || la === lb && a.id > b.id) {
|
||||
fromServer = b
|
||||
toServer = a
|
||||
}
|
||||
@@ -903,8 +982,11 @@ export function buildGreMapEdges(
|
||||
if (group) group.push(edge)
|
||||
else links.set(key, [edge])
|
||||
}
|
||||
return [...links.values()].flatMap(group => {
|
||||
if (group.length !== 2 || group[0].tunnel.serverId === group[1].tunnel.serverId) return group
|
||||
return [...links.entries()].flatMap(([key, group]) => {
|
||||
if (group.length !== 2 || group[0].tunnel.serverId === group[1].tunnel.serverId) {
|
||||
return group.some(edge => edge.tunnel.serverId !== group[0].tunnel.serverId)
|
||||
? group.map(edge => ({ ...edge, ambiguousPeerKey: key })) : group
|
||||
}
|
||||
const [one, two] = group
|
||||
const [edge, peer] = tunnelPriority(two.tunnel) > tunnelPriority(one.tunnel) ? [two, one] : [one, two]
|
||||
return [{ ...edge, peerTunnel: peer.tunnel }]
|
||||
|
||||
@@ -45,6 +45,10 @@ test("map Flow envelope retains zeros and refuses missing metadata and contradic
|
||||
assert.throws(()=>networkMapFlowSchema.parse({...shorter,sourceWindow:{requestedMinutes:15,effectiveMinutes:2}}))
|
||||
assert.throws(()=>networkMapFlowSchema.parse({...shorter,rangeMinutes:1,windowSec:60}))
|
||||
assert.throws(()=>networkMapFlowSchema.parse({...shorter,windowSec:300}))
|
||||
const recent={...empty,rangeMinutes:1,windowSec:90.125,includesCurrentMinute:true}
|
||||
assert.equal(networkMapFlowSchema.parse(recent).windowSec,90.125)
|
||||
assert.throws(()=>networkMapFlowSchema.parse({...recent,windowSec:120}))
|
||||
assert.throws(()=>networkMapFlowSchema.parse({...recent,includesCurrentMinute:undefined}))
|
||||
})
|
||||
test("map DNS matches exactly requested names and accepts explicit unresolved null",()=>{
|
||||
assert.deepEqual(validateNetworkMapDns({results:{"router.example":null}},["router.example"]),{"router.example":null})
|
||||
|
||||
@@ -27,11 +27,12 @@ export function validateNetworkMapSnapshot(servers:unknown,gre:unknown,probes:un
|
||||
|
||||
import {flowMapHopsDtoSchema} from "@mmapp/contracts/traffic-flow"
|
||||
import {isIpv4String} from "./gre-endpoint-resolve"
|
||||
export const networkMapFlowSchema = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true }).refine(data =>
|
||||
(data.sourceWindow
|
||||
? data.sourceWindow.requestedMinutes === 5 && data.sourceWindow.effectiveMinutes === data.rangeMinutes
|
||||
: data.rangeMinutes === 5) &&
|
||||
data.windowSec === data.rangeMinutes * 60 &&
|
||||
export const networkMapFlowSchema = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true, includesCurrentMinute: true, nodeUsers: true }).refine(data =>
|
||||
(data.includesCurrentMinute
|
||||
? !data.sourceWindow && data.rangeMinutes === 1 && data.windowSec >= 60 && data.windowSec < 120
|
||||
: data.windowSec === data.rangeMinutes * 60 && (data.sourceWindow
|
||||
? data.sourceWindow.requestedMinutes === 5 && data.sourceWindow.effectiveMinutes === data.rangeMinutes
|
||||
: data.rangeMinutes === 5)) &&
|
||||
data.namedBytes <= data.totalBytes && data.unclassifiedBytes <= data.totalBytes
|
||||
)
|
||||
export function validateNetworkMapDns(raw:unknown,hosts:string[]){
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import type { Server } from "@/lib/data"
|
||||
|
||||
export function isolatedIxServers(servers: Pick<Server, "id" | "type">[], links: readonly (readonly [string, string])[]) {
|
||||
const neighbors = new Map<string, string[]>()
|
||||
for (const [from, to] of links) {
|
||||
neighbors.set(from, [...(neighbors.get(from) ?? []), to])
|
||||
neighbors.set(to, [...(neighbors.get(to) ?? []), from])
|
||||
}
|
||||
const connected = new Set(servers.filter(server => server.type === "jump-host" || server.type === "exit-node").map(server => server.id))
|
||||
for (const id of connected) for (const neighbor of neighbors.get(id) ?? []) connected.add(neighbor)
|
||||
return new Set(servers.filter(server => server.type === "ix-node" && !connected.has(server.id)).map(server => server.id))
|
||||
}
|
||||
|
||||
export function scopeMapDestinations(
|
||||
services: FlowMapService[], edges: FlowMapServiceEdge[], paths: FlowMapServicePath[],
|
||||
includes: (id: string) => boolean, userId?: string, retainUnassigned = false,
|
||||
) {
|
||||
const visiblePaths = paths.filter(path => includes(path.enId || path.viaId) && (!userId || path.clientId === userId))
|
||||
const visibleEdges = userId ? [] : edges.filter(edge => includes(edge.fromId))
|
||||
if (userId) {
|
||||
const bySource = new Map<string, FlowMapServiceEdge>()
|
||||
for (const path of visiblePaths) {
|
||||
const fromId = path.enId || path.viaId
|
||||
const key = JSON.stringify([fromId, path.serviceId, Boolean(path.enId)])
|
||||
const edge = bySource.get(key) ?? {
|
||||
fromId, toId: path.serviceId, bytes: 0, bps: 0, bpsFwd: 0, bpsRev: 0,
|
||||
...(path.enId ? {} : { observedOnly: true as const }),
|
||||
}
|
||||
edge.bytes += path.bytes
|
||||
edge.bps += path.bps
|
||||
bySource.set(key, edge)
|
||||
}
|
||||
visibleEdges.push(...bySource.values())
|
||||
}
|
||||
const totals = new Map<string, { bytes: number; bps: number }>()
|
||||
const allByService = new Map<string, number>()
|
||||
if (retainUnassigned) for (const edge of edges) allByService.set(edge.toId, (allByService.get(edge.toId) ?? 0) + edge.bytes)
|
||||
let bytes = 0
|
||||
for (const edge of visibleEdges) {
|
||||
const total = totals.get(edge.toId) ?? { bytes: 0, bps: 0 }
|
||||
total.bytes += edge.bytes
|
||||
total.bps += edge.bps
|
||||
bytes += edge.bytes
|
||||
totals.set(edge.toId, total)
|
||||
}
|
||||
if (retainUnassigned) for (const service of services) {
|
||||
const unassigned = service.bytes - (allByService.get(service.id) ?? 0)
|
||||
if (unassigned <= 0) continue
|
||||
const total = totals.get(service.id) ?? { bytes: 0, bps: 0 }
|
||||
total.bytes += unassigned
|
||||
total.bps += service.bps * unassigned / service.bytes
|
||||
bytes += unassigned
|
||||
totals.set(service.id, total)
|
||||
}
|
||||
return {
|
||||
services: services.flatMap(service => {
|
||||
const total = totals.get(service.id)
|
||||
return total ? [{ ...service, ...total, share: bytes ? total.bytes / bytes : 0 }] : []
|
||||
}).sort((a, b) => b.bytes - a.bytes || a.label.localeCompare(b.label)),
|
||||
edges: visibleEdges,
|
||||
paths: visiblePaths,
|
||||
}
|
||||
}
|
||||
@@ -388,6 +388,7 @@ export const flowMapServiceEdgeDtoSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
})).optional(),
|
||||
observedOnly: z.literal(true).optional(),
|
||||
})
|
||||
|
||||
export const flowMapServicePathDtoSchema = z.object({
|
||||
@@ -395,6 +396,8 @@ export const flowMapServicePathDtoSchema = z.object({
|
||||
clientName: z.string(),
|
||||
viaId: z.string(),
|
||||
viaName: z.string(),
|
||||
viaIface: z.string().optional(),
|
||||
/** Empty when IPFIX identified the exporter but the exit could not be inferred. */
|
||||
enId: z.string(),
|
||||
enName: z.string(),
|
||||
serviceId: z.string(),
|
||||
@@ -412,6 +415,13 @@ export const flowMapCountryServiceGroupDtoSchema = z.object({
|
||||
|
||||
export const flowMapHopsDtoSchema = z.object({
|
||||
sourceWindow: flowSourceWindowSchema.optional(),
|
||||
nodeUsers: z.record(z.string(), z.array(z.object({
|
||||
clientId: z.string(),
|
||||
clientName: z.string(),
|
||||
bytes: z.number().nonnegative(),
|
||||
bps: z.number().nonnegative(),
|
||||
}))).optional(),
|
||||
includesCurrentMinute: z.literal(true).optional(),
|
||||
/** Link counters include private routed payload. Mesh visibility applies to the inferred graph. */
|
||||
interfaceTraffic: z.array(z.object({
|
||||
serverId: z.string(), iface: z.string(),
|
||||
@@ -462,3 +472,4 @@ export type FlowMapServicePath = z.infer<typeof flowMapServicePathDtoSchema>
|
||||
export type FlowMapCountryServiceGroup = z.infer<typeof flowMapCountryServiceGroupDtoSchema>
|
||||
export type FlowMapHopsDto = z.infer<typeof flowMapHopsDtoSchema>
|
||||
export type FlowMapInterfaceTraffic = NonNullable<FlowMapHopsDto["interfaceTraffic"]>[number]
|
||||
export type FlowMapUser = NonNullable<FlowMapHopsDto["nodeUsers"]>[string][number]
|
||||
@@ -133,6 +133,7 @@ export async function getFlowMapHops(
|
||||
excludeMesh?: boolean
|
||||
excludeOverlay?: boolean
|
||||
} = {},
|
||||
init?: RequestInit,
|
||||
): Promise<FlowMapHopsDto> {
|
||||
return requestJson<FlowMapHopsDto>(baseUrl, `/api/traffic/flow/map-hops${flowQuery({
|
||||
range: params.range ?? "5m",
|
||||
@@ -142,7 +143,7 @@ export async function getFlowMapHops(
|
||||
dedup: params.dedup,
|
||||
excludeMesh: params.excludeMesh,
|
||||
excludeOverlay: params.excludeOverlay,
|
||||
})}`)
|
||||
})}`, init)
|
||||
}
|
||||
|
||||
export async function getFlowAnalytics(
|
||||
@@ -156,8 +157,9 @@ export async function getFlowAnalytics(
|
||||
excludeMesh?: boolean
|
||||
excludeOverlay?: boolean
|
||||
},
|
||||
init?: RequestInit,
|
||||
): Promise<FlowAnalyticsDto> {
|
||||
return flowConfirmed(flowAnalyticsSchema, await requestJson<unknown>(baseUrl, `/api/traffic/flow/analytics${flowQuery(params)}`))
|
||||
return flowConfirmed(flowAnalyticsSchema, await requestJson<unknown>(baseUrl, `/api/traffic/flow/analytics${flowQuery(params)}`, init))
|
||||
}
|
||||
|
||||
export async function getFlowMonthly(
|
||||
|
||||
@@ -20,14 +20,14 @@ for(const theme of ["dark","light"])for(const width of [320,1440])for(const path
|
||||
})
|
||||
test("Shell keyboard skip link moves focus to main and menus restore focus",async({page})=>{
|
||||
await setup(page,"dark");await page.goto("/releases");await expect(page.getByText("Текущая версия",{exact:true})).toBeVisible();await page.keyboard.press("Tab");const skip=page.getByRole("link",{name:"К содержимому",exact:true});await expect(skip).toBeFocused();await page.keyboard.press("Enter");await expect(page.locator("#main-content")).toBeFocused()
|
||||
const apps=page.getByRole("button",{name:"Приложения",exact:true});await apps.focus();await page.keyboard.press("Enter");await expect(page.getByRole("menu")).toBeVisible();await page.keyboard.press("Escape");await expect(apps).toBeFocused()
|
||||
const monitor=page.getByRole("button",{name:"Монитор системы",exact:true});await monitor.focus();await page.keyboard.press("Enter");await expect(page.locator('[data-slot="popover-content"]')).toBeVisible();await page.keyboard.press("Escape");await expect(monitor).toBeFocused()
|
||||
const apps=page.getByRole("button",{name:/^Переключатель приложений/});await apps.focus();await page.keyboard.press("Enter");await expect(page.getByRole("menu")).toBeVisible();await page.keyboard.press("Escape");await expect(apps).toBeFocused()
|
||||
const monitor=page.getByRole("button",{name:/^Состояние системы/});await monitor.focus();await page.keyboard.press("Enter");await expect(page.locator('[data-slot="popover-content"]')).toBeVisible();await page.keyboard.press("Escape");await expect(monitor).toBeFocused()
|
||||
})
|
||||
test("System monitor recognizes confirmed legacy health consistently",async({page})=>{await setup(page,"dark");await page.route("**/health",r=>r.fulfill({json:{ok:true}}));await page.goto("/releases");await expect(page.getByRole("button",{name:"Монитор системы",exact:true})).toContainText("API доступен")})
|
||||
test("System monitor recognizes confirmed legacy health consistently",async({page})=>{await setup(page,"dark");await page.route("**/health",r=>r.fulfill({json:{ok:true}}));await page.goto("/releases");await expect(page.getByRole("button",{name:/^Состояние системы/})).toContainText("Норма")})
|
||||
|
||||
for(const theme of ["dark","light"])for(const width of [320,1440])test("Open shell layers audit/"+theme+"/"+width,async({page},info)=>{
|
||||
await setup(page,theme);await page.setViewportSize({width,height:900});await page.goto("/releases");await expect(page.getByRole("button",{name:"Монитор системы",exact:true})).toContainText("API доступен");await page.getByRole("button",{name:"Монитор системы",exact:true}).click();await expect(page.locator('[data-slot="popover-content"]')).toBeVisible();await page.addScriptTag({content:axe.source});
|
||||
await setup(page,theme);await page.setViewportSize({width,height:900});await page.goto("/releases");await expect(page.getByRole("button",{name:/^Состояние системы/})).toContainText("Норма");await page.getByRole("button",{name:/^Состояние системы/}).click();await expect(page.locator('[data-slot="popover-content"]')).toBeVisible();await page.addScriptTag({content:axe.source});
|
||||
const result=await page.evaluate(async()=>{const engine=(window as unknown as {axe:typeof axe}).axe;return engine.run('[data-slot="popover-content"]',{runOnly:{type:"tag",values:["wcag2a","wcag2aa","wcag21a","wcag21aa","wcag22aa"]}})});await info.attach("axe-open-monitor",{body:JSON.stringify(result,null,2),contentType:"application/json"});expect(result.violations.map(v=>({id:v.id,nodes:v.nodes.map(n=>({target:n.target,html:n.html,summary:n.failureSummary}))}))).toEqual([]);
|
||||
await page.screenshot({path:"docs/ux-ui/screens/shell-monitor-"+theme+"-"+width+".png",animations:"disabled"});await page.keyboard.press("Escape");await page.getByRole("button",{name:"Приложения",exact:true}).click();await expect(page.getByRole("menu")).toBeVisible();await settleAnimations(page);const menu=await page.evaluate(async()=>{const engine=(window as unknown as {axe:typeof axe}).axe;return engine.run('[role="menu"]',{runOnly:{type:"tag",values:["wcag2a","wcag2aa","wcag21a","wcag21aa","wcag22aa"]}})});expect(menu.violations.map(v=>({id:v.id,nodes:v.nodes.map(n=>({target:n.target,html:n.html,summary:n.failureSummary}))}))).toEqual([]);
|
||||
await page.screenshot({path:"docs/ux-ui/screens/shell-monitor-"+theme+"-"+width+".png",animations:"disabled"});await page.keyboard.press("Escape");if(width<768)await page.getByRole("button",{name:"Боковое меню",exact:true}).click();await page.getByRole("button",{name:/^Переключатель приложений/}).click();await expect(page.getByRole("menu")).toBeVisible();await settleAnimations(page);const menu=await page.evaluate(async()=>{const engine=(window as unknown as {axe:typeof axe}).axe;return engine.run('[role="menu"]',{runOnly:{type:"tag",values:["wcag2a","wcag2aa","wcag21a","wcag21aa","wcag22aa"]}})});expect(menu.violations.map(v=>({id:v.id,nodes:v.nodes.map(n=>({target:n.target,html:n.html,summary:n.failureSummary}))}))).toEqual([]);
|
||||
})
|
||||
for(const theme of ["dark","light"])test("Unconfirmed health remains unavailable/"+theme,async({page})=>{await setup(page,theme);await page.route("**/health",r=>r.fulfill({json:{ok:false,status:"unknown"}}));await page.goto("/releases");await expect(page.getByRole("button",{name:"Монитор системы",exact:true})).toContainText("Нет связи")})
|
||||
for(const theme of ["dark","light"])test("Unconfirmed health remains unavailable/"+theme,async({page})=>{await setup(page,theme);await page.route("**/health",r=>r.fulfill({json:{ok:false,status:"unknown"}}));await page.goto("/releases");await expect(page.getByRole("button",{name:/^Состояние системы/})).toContainText("Сбой")})
|
||||
@@ -31,7 +31,7 @@ test("поиск страниц: одинаковые названия, сино
|
||||
for (const item of navigationItems) {
|
||||
await expect(sidebar.locator(`a[href="${item.url}"]`)).toContainText(item.title)
|
||||
}
|
||||
const opener = page.getByRole("button", { name: "Приложения", exact: true })
|
||||
const opener = page.getByRole("button", { name: "Источники и свежесть данных", exact: true })
|
||||
await opener.focus()
|
||||
await page.keyboard.press("Control+k")
|
||||
const dialog = page.getByRole("dialog", { name: "Поиск страниц", exact: true })
|
||||
|
||||
@@ -9,7 +9,6 @@ test("Карта: PostgreSQL даты не скрывают JumpHost и Exit Nod
|
||||
const map=page.getByRole("group",{name:"Интерактивная карта сети"})
|
||||
await expect(map.getByText("Узел JH",{exact:true})).toBeVisible()
|
||||
await expect(map.getByText("Узел EN",{exact:true})).toBeVisible()
|
||||
await expect(page.getByRole("combobox",{name:"Устройство на карте"})).toBeEnabled()
|
||||
await expect(page.getByRole("alert").filter({hasText:"Первоначальная загрузка карты"})).toHaveCount(0)
|
||||
})
|
||||
for(const part of ["servers","gre","probes"] as const)for(const malformed of [false,true])test("Карта: первоначальный отказ и повтор "+part+"/"+malformed,async({page})=>{
|
||||
@@ -28,10 +27,10 @@ for(const part of ["servers","gre","probes"] as const)test("Карта: част
|
||||
await page.route("**/health",r=>r.fulfill({json:{ok:true}}))
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill(failing&&p===paths[part]?{status:503,json:{error:"Источник недоступен"}}:{json:body(p,failing?"Новый роутер":"Последний роутер")})})
|
||||
await page.goto("/network-map")
|
||||
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Последний роутер",{exact:true})).toBeVisible()
|
||||
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByRole("button",{name:"Устройство Последний роутер",exact:true})).toBeVisible()
|
||||
failing=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
||||
await expect(page.getByRole("alert").filter({hasText:"Последний полный снимок"})).toBeVisible()
|
||||
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Последний роутер",{exact:true})).toBeVisible()
|
||||
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByRole("button",{name:"Устройство Последний роутер",exact:true})).toBeVisible()
|
||||
await expect(page.getByText("Новый роутер",{exact:true})).toHaveCount(0)
|
||||
})
|
||||
|
||||
@@ -39,7 +38,8 @@ test("Карта: неизвестный статус не становится
|
||||
await page.route("**/health",r=>r.fulfill({json:{ok:true}}))
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;const data=body(p);return r.fulfill({json:p===paths.servers?[{...(data as object[])[0],status:null}]:data})})
|
||||
await page.goto("/network-map")
|
||||
await expect(page.getByText("1 неизвестно",{exact:true})).toBeVisible()
|
||||
await page.getByText("Сводка сети", {exact:true}).click()
|
||||
await expect(page.getByRole("button",{name:"Неизвестно 1",exact:true})).toBeVisible()
|
||||
await expect(page.getByRole("button",{name:"Оффлайн 0",exact:true})).toBeVisible()
|
||||
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true}).click()
|
||||
await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible()
|
||||
@@ -52,8 +52,9 @@ for(const polled of [false,true])test("Карта: реальные и неиз
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;const data=body(p);return r.fulfill({json:p===paths.servers?[{...(data as object[])[0],...(polled?{cpuLoad:0,totalMemory:1048576,freeMemory:1048576,uptime:"0s",polledAt:"2020-01-01T00:00:00Z"}:{})}]:data})})
|
||||
await page.goto("/network-map");await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true}).click()
|
||||
const panel=page.getByText("Ресурсы",{exact:true}).locator("..")
|
||||
await panel.locator("summary").click()
|
||||
await expect(panel.getByText("История CPU и диск API не передаются.",{exact:false})).toBeVisible()
|
||||
await expect(panel.locator("svg")).toHaveCount(0)
|
||||
await expect(panel.locator("svg polyline")).toHaveCount(0)
|
||||
await expect(panel.getByText("HDD",{exact:true})).toBeVisible()
|
||||
await expect(panel.getByText("— / —",{exact:true})).toHaveCount(polled?1:2)
|
||||
if(polled){await expect(panel.getByText("0%",{exact:true})).toBeVisible();await expect(panel.getByText("0 МБ / 1 МБ",{exact:true})).toBeVisible();await expect(panel.getByText("0м",{exact:true})).toBeVisible()}
|
||||
|
||||
@@ -9,15 +9,21 @@ test("Карта: открытые детали обновляются вмес
|
||||
let changed=false
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...jh,name:changed?"Новый Jump":"Jump",status:changed?null:"online",cpuLoad:changed?0:20}]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.goto("/network-map");await page.getByRole("button",{name:"Устройство Jump",exact:true}).click()
|
||||
await expect(page.getByText("20%",{exact:true})).toBeVisible()
|
||||
const metrics=page.getByText("CPU · RAM",{exact:true}).locator("..")
|
||||
await expect(metrics).toContainText("20% · —")
|
||||
await page.getByText("Ресурсы",{exact:true}).click()
|
||||
const sessions=page.getByText("Сессий",{exact:true}).locator("..");await expect(sessions).toHaveText("Сессий—")
|
||||
changed=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
||||
await expect(page.getByText("0%",{exact:true})).toBeVisible();await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible()
|
||||
await expect(metrics).toContainText("0% · —");await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible()
|
||||
await expect(page.getByText("Jump",{exact:true})).toHaveCount(0);await expect(page.getByText("Новый Jump",{exact:true}).last()).toBeVisible()
|
||||
})
|
||||
test("Карта: модель WAN не утверждает активный маршрут и RTT линии",async({page})=>{
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.goto("/network-map");await expect(page.getByText("Пунктир WAN→JH — модель связности; маршрут не подтверждён.",{exact:true})).toBeVisible()
|
||||
await page.goto("/network-map")
|
||||
const legend = page.getByRole("button", {name:"Легенда",exact:true})
|
||||
await legend.click()
|
||||
await expect(page.getByText("WAN → JH · модель связности",{exact:true})).toBeVisible()
|
||||
await legend.click()
|
||||
await expect(page.locator("svg text").filter({hasText:/^5 мс$/})).toHaveCount(0)
|
||||
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Домашний",{exact:true}).click()
|
||||
await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:"Интерфейсы"}).click();await expect(page.getByText("Аплинк каталога",{exact:true})).toBeVisible();await expect(page.getByText("Модель связей с JH · Ping модели",{exact:true})).toBeVisible()
|
||||
@@ -31,7 +37,7 @@ test("Карта: выбранный GRE обновляется и неизве
|
||||
await expect(page.getByText("gre-home",{exact:true}).last()).toBeVisible();await expect(page.getByText("Ping неизвестен",{exact:true})).toBeVisible()
|
||||
changed=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
||||
await expect(page.getByText("gre-new",{exact:true}).last()).toBeVisible();await expect(page.getByText("Недоступен",{exact:true})).toBeVisible()
|
||||
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1");await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:/^GRE/}).click();await expect(page.getByText("IPsec неизвестен",{exact:true})).toBeVisible()
|
||||
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click();await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:/^GRE/}).click();await expect(page.getByText("IPsec неизвестен",{exact:true})).toBeVisible()
|
||||
})
|
||||
|
||||
test("Карта: GRE сохраняет частичное измерение, ноль Ping и дату пробы",async({page})=>{
|
||||
@@ -44,3 +50,72 @@ test("Карта: GRE сохраняет частичное измерение,
|
||||
await expect(page.getByText("Проба measured-probe",{exact:false}).last()).toContainText("2020")
|
||||
await expect(page.getByText("Проба measured-probe",{exact:false}).last()).toContainText("время TX/RX неизвестно")
|
||||
})
|
||||
|
||||
test("Карточки Exit, JumpHost и сервиса показывают измерения и обрабатывают действия", async ({ page }, info) => {
|
||||
const exit = { ...jh, id: 3, type: "exit-node", name: "fra-exit02", host: "fra-exit02.rtnt.top", country: "DE", latency: 31, cpuLoad: 18, uptime: "23d9h", totalMemory: 100, freeMemory: 64, os: "7.16.1", polledAt: "2026-11-25T09:02:11Z" }
|
||||
const jump = { ...exit, id: 2, name: "nov-gw01", host: "nov-gw01.rtnt.top", type: "jump-host", status: "degraded", country: "RU" }
|
||||
const service = { id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 0.29 }
|
||||
const edge = { fromId: "3", toId: service.id, bytes: service.bytes, bps: service.bps, bpsFwd: 8000, bpsRev: 16000 }
|
||||
const path = { clientId: "u1", clientName: "msk-hr01", viaId: "2", viaName: jump.name, enId: "3", enName: exit.name, serviceId: service.id, bytes: edge.bytes, bps: edge.bps }
|
||||
const record = {serverId:"3",serverName:exit.name,src:"10.20.4.18",dst:"142.250.74.14",proto:6,protoName:"TCP",srcPort:45000,dstPort:443,bytes:1000,packets:1,bps:8000,inIface:"gre1",service:"YouTube",dstAsn:15169}
|
||||
const country = {...service, id:"cc:other", label:"Прочее", category:"Страна"}
|
||||
const dns = {...service, id:"cc:other|svc:dns", label:"DNS", category:"DNS"}
|
||||
const rows = [13,17,15,27,51,55,48,33,16,12,15,18]
|
||||
const sample = { rxNow: 15, txNow: 12, rxPeak: 55, txPeak: 55, rxTotal: 1, txTotal: 1, rxSeries: rows, txSeries: rows, observations: { rxNow: true, txNow: true, rxSeries: rows.map(() => true), txSeries: rows.map(() => true), sampledAt: "2026-11-25T09:02:11Z" } }
|
||||
await page.route("**/api/**", route => {
|
||||
const url = new URL(route.request().url()), endpoint = url.pathname
|
||||
const daily = url.searchParams.get("range") === "24h"
|
||||
const data = endpoint === "/api/servers" ? [exit, jump]
|
||||
: endpoint === "/api/filters/gre-tunnels" ? { tunnels: [], failures: [] }
|
||||
: endpoint === "/api/uptime/speed-probes" ? {probes: []}
|
||||
: endpoint === "/api/traffic/flow/map-hops" ? {...empty,rangeMinutes:daily?1440:5,windowSec:daily?86400:300,totalBytes:daily?4100000000:3103448,namedBytes:daily?4100000000:service.bytes,services:[{...service,bytes:daily?4100000000:service.bytes}],servicePaths:[path],serviceEdges:[edge],countries:[country],countryServiceGroups:[{countryId:country.id,services:[dns],paths:[{...path,serviceId:dns.id,bytes:100000,bps:100000*8/300}],edges:[]}]}
|
||||
: endpoint === "/api/traffic/flow/analytics" ? {bpsNow:8000,bytes:1000,packets:1,conversations:3,uniqueSrc:1,uniqueDst:3,topProto:"TCP",rxSeries:[],txSeries:[],applications:[],protocols:[],sources:[],destinations:[],interfaces:[],conversationsList:[record,...["unknown","US"].map(dstCountry=>({...record,service:"Прочее",category:"DNS",dstCountry,dst:dstCountry==="US"?"192.0.2.53":"198.51.100.53",dstPort:53}))],ifaces:[],live:true}
|
||||
: endpoint === "/api/traffic/servers/3" ? {server:{...sample,id:"3"}}
|
||||
: endpoint === "/api/traffic/servers/2" ? {server:{...sample,id:"2",observations:{...sample.observations,currentState:"error",error:"RouterOS API 401 на /interface",lastAttemptAt:"2026-11-25T09:31:08Z"}}}
|
||||
: endpoint === "/api/auth/config" ? {required:false} : {}
|
||||
return route.fulfill({json:data})
|
||||
})
|
||||
await page.goto("/network-map?server=3")
|
||||
const card = page.getByRole("complementary",{name:"Детали объекта карты"})
|
||||
await expect(card.getByRole("img",{name:"История измерений"})).toBeVisible()
|
||||
await card.getByRole("button",{name:"Закрепить",exact:true}).click()
|
||||
await expect(card.getByText("Закреплён",{exact:true}).locator("..")).toContainText("да")
|
||||
await card.getByRole("button",{name:"Открепить",exact:true}).click()
|
||||
await card.screenshot({path:info.outputPath("exit.png")})
|
||||
await card.getByRole("button",{name:/YouTube/}).click()
|
||||
await expect(card.getByText("Объём · 24 ч",{exact:true}).locator("..")).toContainText("4.10 ГБ")
|
||||
await expect(card.getByText("10.20.4.18 → 142.250.74.14",{exact:true})).toBeVisible()
|
||||
await expect(card.getByText("TCP/443",{exact:true})).toBeVisible()
|
||||
await card.screenshot({path:info.outputPath("service.png")})
|
||||
await card.getByRole("button",{name:"Фильтр по сервису"}).click()
|
||||
await expect(page.getByText(/фильтр: YouTube/)).toBeVisible()
|
||||
await card.getByRole("button",{name:"Снять фильтр"}).click()
|
||||
await page.goto("/network-map?server=2")
|
||||
await expect(card.getByText(/RouterOS API 401 на \/interface/)).toBeVisible()
|
||||
await card.screenshot({path:info.outputPath("jump.png")})
|
||||
await card.getByRole("button",{name:/fra-exit02/}).click()
|
||||
await expect(card.getByRole("heading",{name:exit.name})).toBeVisible()
|
||||
await page.getByRole("button",{name:"Страны",exact:true}).click()
|
||||
await page.getByRole("button",{name:"Страна Прочее",exact:true}).press("Enter")
|
||||
await card.getByRole("button",{name:/DNS/}).click()
|
||||
await expect(card.getByText("Выход не определён", {exact:true})).toBeVisible()
|
||||
await expect(card.getByText(/198\.51\.100\.53/)).toBeVisible()
|
||||
await expect(card.getByText(/192\.0\.2\.53/)).toHaveCount(0)
|
||||
})
|
||||
|
||||
test("Обновление NetFlow отображается внутри кнопки", async ({page}) => {
|
||||
let release!: () => void
|
||||
const wait = new Promise<void>(resolve => { release = resolve })
|
||||
await page.route("**/api/**", async route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
if (path === "/api/traffic/flow/map-hops") await wait
|
||||
return route.fulfill({json:path === "/api/traffic/flow/map-hops" ? empty : path === "/api/servers" ? [jh] : path === "/api/filters/gre-tunnels" ? {tunnels:[],failures:[]} : path === "/api/uptime/speed-probes" ? {probes:[]} : path === "/api/auth/config" ? {required:false} : {}})
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
const refresh = page.getByRole("button",{name:"Обновить",exact:true})
|
||||
await expect(refresh.locator("[data-slot=spinner]")).toBeVisible()
|
||||
await expect(page.getByText("Обновление NetFlow…",{exact:true})).toHaveCount(0)
|
||||
release()
|
||||
await expect(refresh).toBeEnabled()
|
||||
await expect(refresh.locator("[data-slot=spinner]")).toHaveCount(0)
|
||||
})
|
||||
@@ -1,15 +1,79 @@
|
||||
import {test,expect} from "@playwright/test"
|
||||
import { installOpenLiveStream } from "./live-stream-fixture"
|
||||
import { observedTrafficFixturePayload } from "./traffic-observation-fixture"
|
||||
const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false}
|
||||
const flowPath="/api/traffic/flow/map-hops"
|
||||
test.beforeEach(async({page})=>{await page.route("**/health",r=>r.fulfill({json:{ok:true}}))})
|
||||
const server={id:1,name:"Router",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online"}
|
||||
|
||||
test("Карта и трафик сохраняют пользователя и сервис, IX остаётся отдельным", async ({page}) => {
|
||||
const clientId = "alice"
|
||||
const timestamps = { createdAt: "2026-11-26T12:00:00Z", updatedAt: "2026-11-26T12:00:00Z" }
|
||||
const binding = { ...timestamps, userId: clientId, id: "a1", serverId: 1,
|
||||
serverName: "Вход", serverSite: "MSK", serverCountry: "RU", interfaceName: "gre-alice", interfaceType: "gre", comment: "" }
|
||||
const user = { ...timestamps, id: clientId, name: "Алиса", login: "alice", email: "[email protected]", role: "viewer", active: true,
|
||||
avatar: "A", lastSeen: null, sections: [], servers: [], bindings: [binding, {...binding, id: "a2", interfaceName: "gre-alice-2"}] }
|
||||
const counters = ["a1", "a2"].map(bindingId => ({bindingId, status: "online", rxNow: 4, txNow: 6, rxPeak: 4, txPeak: 6, rxTotal: 0, txTotal: 0, rxSeries: [4], txSeries: [6]}))
|
||||
const dns = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 300000, bps: 8000, share: 1}
|
||||
const path = {clientId, clientName: "Алиса", viaId: "1", viaName: "Вход", enId: "", enName: "", serviceId: dns.id, bytes: dns.bytes, bps: dns.bps}
|
||||
const requests: string[] = []
|
||||
await page.route("**/api/**", route => {
|
||||
const url = new URL(route.request().url())
|
||||
requests.push(url.pathname + url.search)
|
||||
const clientCard = { id: clientId, name: "Алиса", subtitle: "alice", site: "MSK", country: "RU", status: "online", rxNow: 0, txNow: 0, sessions: 1, bytes: dns.bytes, rxSeries: [], txSeries: [] }
|
||||
const replies: Record<string, unknown> = {
|
||||
"/api/auth/config": {required: false},
|
||||
"/api/servers": [{...server, name: "Вход", type: "jump-host"}, {...server, id: 9, name: "Изолированный IX", host: "192.0.2.9", type: "ix-node"}],
|
||||
"/api/filters/gre-tunnels": {tunnels: [], failures: []}, "/api/uptime/speed-probes": {probes: []},
|
||||
"/api/ix/topology": {links: []}, "/api/ix/segments": {items: [{id: "segment", appliedRevision: 1}]},
|
||||
"/api/ix/segments/segment/linux": {items: [{serverId: 9, interfaceName: "wg-linux", kind: "wireguard", name: "Linux VPS", enabled: true}]},
|
||||
"/api/users": {users: [user]}, "/api/traffic/bound-interfaces": observedTrafficFixturePayload({interfaces: counters}),
|
||||
"/api/traffic/flow/exporters": {exporters: []}, "/api/traffic/flow/clients": {clients: [clientCard]},
|
||||
"/api/traffic/flows": {exportersOnline: 0, bytesPerMin: 0, uniqueSrc: 0, uniqueDst: 0, topProto: "TCP", talkers: [], listenerBound: true},
|
||||
[flowPath]: {...empty, totalBytes: dns.bytes, namedBytes: dns.bytes, services: [dns], servicePaths: [path],
|
||||
serviceEdges: [{fromId: "1", toId: dns.id, observedOnly: true, bytes: dns.bytes, bps: dns.bps, bpsFwd: 0, bpsRev: dns.bps}]},
|
||||
}
|
||||
return route.fulfill({json: replies[url.pathname] ?? {}})
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
const map = page.getByRole("group", {name: "Интерактивная карта сети"})
|
||||
const panel = page.getByRole("complementary", {name: "Детали объекта карты"})
|
||||
await expect(page.getByRole("button", {name: "Выбрать пользователя", exact: true})).toBeVisible()
|
||||
await expect(map.getByRole("button", {name: "Устройство Изолированный IX"})).toHaveCount(0)
|
||||
await map.getByRole("button", {name: "Сервис DNS", exact: true}).press("Enter")
|
||||
await panel.getByRole("button", {name: "Фильтр по сервису"}).click()
|
||||
await page.getByRole("button", {name: "Пользователи", exact: true}).click()
|
||||
await page.getByRole("option", {name: /Алиса/}).click()
|
||||
await expect.poll(() => requests.some(request => request === `${flowPath}?range=1m&userId=${clientId}`)).toBe(true)
|
||||
await expect(panel.getByRole("heading", {name: "Алиса", exact: true})).toBeVisible()
|
||||
await expect(panel.getByText(/gre-alice · gre, gre-alice-2/)).toBeVisible()
|
||||
await expect(panel.getByText(/RX 8.*TX 12.*2\/2/)).toBeVisible()
|
||||
await panel.getByRole("button", {name: /DNS/}).click()
|
||||
await panel.getByRole("link", {name: "Открыть в «Трафике»"}).click()
|
||||
await expect(page).toHaveURL(/\/traffic\?.*user=alice/)
|
||||
await expect(page.getByRole("button", {name: "Клиенты", exact: true}).last()).toBeVisible()
|
||||
await page.getByRole("link", {name: "Вернуться на карту"}).click()
|
||||
await expect(panel.getByRole("heading", {name: "DNS", exact: true})).toBeVisible()
|
||||
await page.getByRole("button", {name: "IX и клиенты"}).click()
|
||||
await expect(map.getByRole("button", {name: "Устройство Вход"})).toHaveCount(0)
|
||||
await expect(map.getByRole("button", {name: "Устройство Изолированный IX"})).toBeVisible()
|
||||
await page.getByRole("button", {name: "Linux-клиенты", exact: true}).click()
|
||||
await page.getByRole("option", {name: /Linux VPS/}).click()
|
||||
await expect(panel.getByText("wg-linux · wireguard")).toBeVisible()
|
||||
await expect(panel.getByText("Нет потоков с подтверждённой привязкой к пользователю.")).toBeVisible()
|
||||
})
|
||||
|
||||
test("Карта не приписывает весь YouTube единственному выходу ARN", async ({page}) => {
|
||||
const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1}
|
||||
const edge = {fromId: "1", toId: service.id, bytes: 300000, bps: 8000, bpsFwd: 2000, bpsRev: 6000}
|
||||
let known = false
|
||||
await page.route("**/api/**", route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
const url = new URL(route.request().url())
|
||||
const path = url.pathname
|
||||
if (path === flowPath && url.searchParams.get("range") === "24h") {
|
||||
return route.fulfill({ json: { ...empty, rangeMinutes: 1440, windowSec: 86400, totalBytes: service.bytes, namedBytes: service.bytes, services: [service] } })
|
||||
}
|
||||
if (path === flowPath) expect(url.searchParams.get("range")).toBe("1m")
|
||||
const responses: Record<string, unknown> = {
|
||||
"/api/auth/config": {required: false}, "/api/servers": [{...server, type: "exit-node", name: "ARN"}],
|
||||
"/api/filters/gre-tunnels": {tunnels: [], failures: []}, "/api/uptime/speed-probes": {probes: []},
|
||||
@@ -20,7 +84,7 @@ test("Карта не приписывает весь YouTube единствен
|
||||
await page.goto("/network-map")
|
||||
await page.getByRole("button", {name: "Сервис YouTube", exact: true}).press("Enter")
|
||||
const unknown = page.getByText("Выход не определён", {exact: true}).locator("..")
|
||||
const badges = page.getByRole("button", {name: "Поток NetFlow между узлами"})
|
||||
const badges = page.locator("[data-map-ribbon] > title")
|
||||
await expect(unknown).toContainText("24 Кбит/с")
|
||||
await expect(badges).toHaveCount(0)
|
||||
known = true
|
||||
@@ -31,6 +95,41 @@ test("Карта не приписывает весь YouTube единствен
|
||||
await expect(badges).toContainText("↓6 Кбит/с ↑2 Кбит/с")
|
||||
})
|
||||
|
||||
test("Карта: DNS виден от экспортёра, пользователи разбиты в обеих карточках", async ({page}) => {
|
||||
const router = {...server, name: "MSK", type: "jump-host"}
|
||||
const dns = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 300000, bps: 8000, share: 1}
|
||||
const users = [
|
||||
{clientId: "u1", clientName: "Алиса", bytes: 225000, bps: 6000},
|
||||
{clientId: "—", clientName: "—", bytes: 75000, bps: 2000},
|
||||
]
|
||||
const servicePaths = users.map(u => ({...u, viaId: "1", viaName: "MSK", viaIface: "ether1", enId: "", enName: "", serviceId: dns.id}))
|
||||
await page.route("**/api/**", route => {
|
||||
const url = new URL(route.request().url())
|
||||
const path = url.pathname
|
||||
return route.fulfill({json: path === "/api/auth/config" ? {required: false}
|
||||
: path === "/api/servers" ? [router] : path === "/api/filters/gre-tunnels" ? {tunnels: [], failures: []}
|
||||
: path === "/api/uptime/speed-probes" ? {probes: []} : path === flowPath ? {
|
||||
...empty,
|
||||
...(url.searchParams.get("range") === "24h" ? {rangeMinutes: 1440, windowSec: 86400} : {}),
|
||||
totalBytes: dns.bytes, services: [dns], servicePaths, nodeUsers: {"1": users},
|
||||
serviceEdges: [{fromId: "1", toId: dns.id, observedOnly: true, bytes: dns.bytes, bps: dns.bps, bpsFwd: 0, bpsRev: dns.bps}],
|
||||
} : {}})
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
await expect(page.locator("[data-map-ribbon][data-observation] > title")).toContainText("MSK → DNS")
|
||||
await page.getByRole("button", {name: "Сервис DNS", exact: true}).press("Enter")
|
||||
const panel = page.getByRole("complementary", {name: "Детали объекта карты"})
|
||||
const breakdown = panel.getByRole("region", {name: "Трафик по пользователям"})
|
||||
await expect(breakdown.getByText("Алиса", {exact: true}).locator("..")).toContainText("6 Кбит/с")
|
||||
await expect(breakdown.getByText("Без привязки к пользователю")).toBeVisible()
|
||||
await expect(panel.getByText("Экспортёр", {exact: true})).toBeVisible()
|
||||
await expect(panel.getByText(/интерфейс ether1 · выход не подтверждён/i).first()).toBeVisible()
|
||||
await panel.getByRole("button").filter({hasText: /Алиса.*Наблюдение IPFIX/}).click()
|
||||
await expect(panel.getByRole("button", {pressed: true}).filter({hasText: "Наблюдение IPFIX"})).toHaveCount(1)
|
||||
await page.getByRole("button", {name: "Устройство MSK", exact: true}).press("Enter")
|
||||
await expect(breakdown.getByText("Алиса", {exact: true}).locator("..")).toContainText("75%")
|
||||
})
|
||||
|
||||
for (const reverse of [false, true]) test(`Карта: малый NetFlow и текущие RX/TX GRE показаны отдельно, reverse=${reverse}`, async ({ page }) => {
|
||||
const exit = { ...server, name: "ARN", type: "exit-node" }
|
||||
const jump = { ...server, id: 2, name: "MSK-02", host: "192.0.2.2", type: "jump-host" }
|
||||
@@ -48,15 +147,20 @@ for (const reverse of [false, true]) test(`Карта: малый NetFlow и т
|
||||
const exact = { fromId: String(owner.id), fromLabel: owner.name, toId: "", toLabel: "", kind: "iface", iface: tunnel.name,
|
||||
bytes: 3_750_000, bps: 100_000, bpsFwd: 100_000, bpsRev: 0 }
|
||||
let exactNetflow = false
|
||||
let nativeAvailable = false
|
||||
let liveReads = 0
|
||||
await page.route("**/api/**", route => {
|
||||
const url = new URL(route.request().url())
|
||||
if (/\/traffic\/servers\/\d+\/live$/.test(url.pathname)) {
|
||||
if (url.pathname === `/api/traffic/servers/${peer.id}/live`) {
|
||||
return route.fulfill({ status: 503, json: { error: "Нет замера" } })
|
||||
}
|
||||
if (url.pathname === `/api/traffic/servers/${owner.id}/live`) {
|
||||
expect(url.pathname).toBe(`/api/traffic/servers/${owner.id}/live`)
|
||||
expect(url.searchParams.get("iface")).toBe(tunnel.name)
|
||||
expect(url.searchParams.get("once")).toBe("1")
|
||||
liveReads++
|
||||
return route.fulfill({ json: { rxMbps: 0.16168, txMbps: 0.119224, at: "2026-11-23T07:20:36Z", timestampKind: "backend-receipt" } })
|
||||
return nativeAvailable ? route.fulfill({ json: { rxMbps: 80, txMbps: 1, at: new Date().toISOString(), timestampKind: "backend-receipt" } })
|
||||
: route.fulfill({ status: 503, json: { error: "Нет замера" } })
|
||||
}
|
||||
const json = {
|
||||
"/api/auth/config": { required: false },
|
||||
@@ -71,43 +175,86 @@ for (const reverse of [false, true]) test(`Карта: малый NetFlow и т
|
||||
return route.fulfill({ json })
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
const badge = page.getByRole("button", { name: "Поток NetFlow между узлами" })
|
||||
await expect(badge).toContainText("Нет записей")
|
||||
expect(liveReads).toBe(0)
|
||||
const badge = page.getByRole("button", { name: /^Связь / })
|
||||
await expect(badge.locator("text")).toHaveText("—")
|
||||
await expect.poll(() => liveReads).toBeGreaterThan(0)
|
||||
await badge.click()
|
||||
const panel = page.getByRole("complementary", { name: "Детали объекта карты" })
|
||||
await expect(panel.getByText("Нет записей", { exact: true })).toBeVisible()
|
||||
const live = page.getByText("Live GRE · RX/TX сейчас", {exact: true}).locator("..")
|
||||
await expect(live).toContainText("↓162 Кбит/с ↑119 Кбит/с")
|
||||
await expect(live).toContainText("Нет замера")
|
||||
await expect(page.getByText(/Последняя минута с данными/)).toBeVisible()
|
||||
exactNetflow = true
|
||||
await expect(badge).toContainText("14 бит/с", {timeout: 12000})
|
||||
await expect(live).toContainText("↓162 Кбит/с ↑119 Кбит/с")
|
||||
await expect(badge).toContainText("↓14 бит/с ↑0 Кбит/с")
|
||||
await expect(badge).toHaveAccessibleName(/14 бит\/с/, {timeout: 12000})
|
||||
await expect(panel.getByText("↓14 бит/с ↑0 Кбит/с", { exact: true })).toBeVisible()
|
||||
await expect(page.getByText("За интервал · 525 Б · 3 пак.")).toBeVisible()
|
||||
await expect(badge).not.toContainText("Live GRE")
|
||||
|
||||
nativeAvailable = true
|
||||
await expect(badge).toHaveAccessibleName(/81[.,]0 Мбит\/с/, {timeout: 18000})
|
||||
await expect(page.getByText("Макс. из замеров · Live", {exact: true}).locator("..")).toContainText("81")
|
||||
await expect(live).toContainText("↓80")
|
||||
await expect(panel.getByText("↓14 бит/с ↑0 Кбит/с", { exact: true })).toBeVisible()
|
||||
})
|
||||
|
||||
test("Карта: два GRE одного роутера к одному узлу сохраняют отдельные счётчики", async ({ page }) => {
|
||||
test("Карта: параллельные GRE с разными владельцами суммируются один раз", async ({ page }) => {
|
||||
const peer = { ...server, id: 2, name: "Exit", host: "192.0.2.2", type: "exit-node" }
|
||||
const tunnels = ["gre-low", "gre-other"].map(name => ({
|
||||
const forward = ["gre-low", "gre-other"].map((name, i) => ({
|
||||
name, id: name, serverId: "1", enabled: true, status: "up", localAddress: server.host, remoteAddress: peer.host,
|
||||
localInnerIp: "", remoteInnerIp: "", poolId: "", ipsec: null, mtu: 1400, keepaliveInterval: 10, keepaliveRetries: 3,
|
||||
localInnerIp: `10.0.${i}.1`, remoteInnerIp: `10.0.${i}.2`, poolId: "", ipsec: null, mtu: 1400, keepaliveInterval: 10, keepaliveRetries: 3,
|
||||
dscp: "inherit", clampTcpMss: true, allowFastPath: false, comment: "",
|
||||
}))
|
||||
const interfaceTraffic = tunnels.map(({name}, i) => ({ serverId: "1", iface: name, rxBytes: 600 * (i + 1), txBytes: 0,
|
||||
const reverse = forward.map(t => ({ ...t, name: t.name + "-peer", id: t.id + "-peer", serverId: "2",
|
||||
localAddress: peer.host, remoteAddress: server.host, localInnerIp: t.remoteInnerIp, remoteInnerIp: t.localInnerIp }))
|
||||
const tunnels = [forward[0], reverse[0], reverse[1], forward[1]]
|
||||
const interfaceTraffic = forward.map(({name}, i) => ({ serverId: "1", iface: name, rxBytes: 600 * (i + 1), txBytes: 0,
|
||||
rxPackets: i + 1, txPackets: 0, inWindow: true, lastBucketAt: "2026-11-23T07:00:00Z" }))
|
||||
const sample = (rxMbps: number) => ({ rxMbps, txMbps: 0, at: new Date().toISOString(), timestampKind: "backend-receipt" })
|
||||
let liveReads = 0
|
||||
await page.route("**/api/**", route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
const url = new URL(route.request().url())
|
||||
const path = url.pathname
|
||||
if (path === "/api/traffic/servers/1/live" && url.searchParams.get("once") === "1") {
|
||||
expect(url.searchParams.get("ifaces")?.split(",").sort()).toEqual(["gre-low", "gre-other"])
|
||||
liveReads++
|
||||
return route.fulfill({ json: { interfaces: {
|
||||
"gre-low": { ...sample(180), at: "2026-11-23T07:20:36Z" }, "gre-other": sample(10),
|
||||
} } })
|
||||
}
|
||||
if (path === "/api/traffic/servers/2/live" && url.searchParams.get("once") === "1") {
|
||||
expect(url.searchParams.get("ifaces")?.split(",").sort()).toEqual(["gre-low-peer", "gre-other-peer"])
|
||||
return route.fulfill({ json: { interfaces: { "gre-low-peer": sample(80), "gre-other-peer": sample(10) } } })
|
||||
}
|
||||
return route.fulfill({ json: path === "/api/servers" ? [{ ...server, type: "jump-host" }, peer]
|
||||
: path === "/api/filters/gre-tunnels" ? { tunnels, failures: [] }
|
||||
: path === flowPath ? { ...empty, live: true, interfaceTraffic }
|
||||
: path === "/api/uptime/speed-probes" ? { probes: [] } : path === "/api/auth/config" ? { required: false } : {} })
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
const badges = page.getByRole("button", { name: "Поток NetFlow между узлами" })
|
||||
await expect(badges).toHaveCount(2)
|
||||
await expect(badges.filter({hasText: "↓16 бит/с"})).toHaveCount(1)
|
||||
await expect(badges.filter({hasText: "↓32 бит/с"})).toHaveCount(1)
|
||||
await expect(page.getByRole("button", { name: /^Связь Router → Exit: 90.*GRE ×2$/ })).toHaveCount(1)
|
||||
expect(liveReads).toBeGreaterThan(0)
|
||||
await page.getByRole("button", { name: "Устройство Router", exact: true }).click()
|
||||
const panel = page.getByRole("complementary", { name: "Детали объекта карты" })
|
||||
await panel.getByRole("tab", { name: "Интерфейсы" }).click()
|
||||
await expect(panel.getByText("gre-low", { exact: true }).locator("..")).toContainText("↓ 16 бит/с")
|
||||
await expect(panel.getByText("gre-other", { exact: true }).locator("..")).toContainText("↓ 32 бит/с")
|
||||
})
|
||||
|
||||
test("Карта: карточка узла показывает отдельно фактические RX/TX RouterOS", async ({ page }) => {
|
||||
await page.route("**/api/**", route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
return route.fulfill({ json: path === "/api/servers" ? [server] : path === flowPath ? empty
|
||||
: path === "/api/filters/gre-tunnels" ? { tunnels: [], failures: [] }
|
||||
: path === "/api/uptime/speed-probes" ? { probes: [] } : path === "/api/auth/config" ? { required: false } : {} })
|
||||
})
|
||||
await installOpenLiveStream(page, "/api/traffic/servers/1/live", { rxMbps: 80, txMbps: 1, at: new Date().toISOString(), timestampKind: "backend-receipt" })
|
||||
await page.goto("/network-map")
|
||||
await page.getByRole("button", { name: "Устройство Router", exact: true }).click()
|
||||
const panel = page.getByRole("complementary", { name: "Детали объекта карты" })
|
||||
await expect(panel.getByText("Входящий · Live")).toBeVisible()
|
||||
await expect(panel.getByText("80.0 Мбит/с")).toBeVisible()
|
||||
await expect(panel.getByText("Исходящий · Live")).toBeVisible()
|
||||
await expect(panel.getByText("1.00 Мбит/с")).toBeVisible()
|
||||
await page.clock.fastForward(15_001)
|
||||
await expect(panel.getByText("Входящий · Live")).toHaveCount(0)
|
||||
})
|
||||
|
||||
for(const malformed of [false,true])test("Карта: NetFlow отказ и повтор "+malformed,async({page})=>{
|
||||
|
||||
@@ -8,20 +8,20 @@ test.beforeEach(async({page})=>{
|
||||
await page.route("**/health",r=>r.fulfill({json:{ok:true}}))
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...home,name:"Домашний роутер с очень длинным названием и описанием устройства"},{...jh,name:"Промежуточный узел с длинной подписью"}]:p==="/api/filters/gre-tunnels"?{tunnels:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
|
||||
})
|
||||
for(const width of [1440,390,320])test("Карта: доступные детали и адаптивная оболочка "+width,async({page})=>{
|
||||
for(const width of [1440,390,320])test("Карта: доступные детали и адаптивная оболочка "+width,async({page},testInfo)=>{
|
||||
await page.setViewportSize({width,height:900});await page.goto("/network-map")
|
||||
await expect(page.getByRole("combobox",{name:"Устройство на карте"})).toBeEnabled()
|
||||
await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
||||
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true)
|
||||
await page.screenshot({path:"docs/ux-ui/screens/network-map-overview-"+(width===1440?"desktop":width===390?"mobile":"narrow")+".png"})
|
||||
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1")
|
||||
await page.screenshot({path:testInfo.outputPath("network-map-overview.png")})
|
||||
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click()
|
||||
const panel=page.getByRole("complementary",{name:"Детали объекта карты"})
|
||||
await expect(panel).toBeVisible();await expect(panel.getByText("Ресурсы",{exact:true})).toBeVisible()
|
||||
const bounds=await panel.boundingBox(),map=width>=1024?await page.getByRole("group",{name:"Интерактивная карта сети"}).boundingBox():null
|
||||
const bounds=await panel.boundingBox(),map=await page.getByRole("group",{name:"Интерактивная карта сети"}).boundingBox()
|
||||
expect(bounds!.width).toBeGreaterThan(250);expect(bounds!.height).toBeGreaterThan(350)
|
||||
if(width<1024)await expect(page.getByRole("group",{name:"Интерактивная карта сети"})).toBeHidden()
|
||||
else expect(map!.height).toBeGreaterThan(0)
|
||||
expect(map!.height).toBeGreaterThanOrEqual(390)
|
||||
if(width>=1024)expect(bounds!.x).toBeGreaterThan(map!.x+map!.width/2)
|
||||
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true)
|
||||
await page.screenshot({path:"docs/ux-ui/screens/network-map-detail-"+(width===1440?"desktop":width===390?"mobile":"narrow")+".png"})
|
||||
await page.screenshot({path:testInfo.outputPath("network-map-detail.png")})
|
||||
await panel.getByRole("button",{name:"Закрыть детали устройства"}).click()
|
||||
await expect(panel).toHaveCount(0)
|
||||
const node=page.getByRole("button",{name:/^Устройство Домашний/});await node.focus();await node.press("Enter");await expect(panel).toBeVisible()
|
||||
@@ -58,7 +58,7 @@ test("Карта: пропорции камеры, ручной масштаб
|
||||
await expect(page.getByRole("button",{name:"Обновить",exact:true})).toBeEnabled();await expect(map).toHaveAttribute("viewBox",manual!)
|
||||
await page.getByRole("button",{name:"Вписать карту",exact:true}).click()
|
||||
expect(await map.getAttribute("viewBox")).not.toBe(manual)
|
||||
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1")
|
||||
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click()
|
||||
await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:"Интерфейсы"}).click()
|
||||
const wan=page.getByRole("button",{name:"WAN WAN",exact:true});await wan.focus();await wan.press("Enter")
|
||||
await expect(page).toHaveURL(/wan=0/);await expect(wan).toHaveAttribute("aria-pressed","true")
|
||||
@@ -67,11 +67,11 @@ test("Карта: пропорции камеры, ручной масштаб
|
||||
test("Карта: pointer capture, клавиатурный pan и возврат фокуса",async({page})=>{
|
||||
await page.goto("/network-map");const map=page.getByRole("group",{name:"Интерактивная карта сети"}),node=page.getByRole("button",{name:/^Устройство Домашний/})
|
||||
await expect(node).toBeVisible();await map.focus();const before=await map.getAttribute("viewBox");await map.press("ArrowDown");expect(await map.getAttribute("viewBox")).not.toBe(before)
|
||||
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1")
|
||||
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click()
|
||||
const transform=await node.getAttribute("transform"),point=await node.evaluate((g:SVGGElement)=>{const matrix=g.getScreenCTM()!;return {x:matrix.e,y:matrix.f}})
|
||||
await page.mouse.move(point.x,point.y);await page.mouse.down();await page.mouse.move(point.x+80,point.y+25,{steps:5});await page.mouse.up()
|
||||
expect(await node.getAttribute("transform")).not.toBe(transform);await expect(page).toHaveURL(/server=1/)
|
||||
await page.getByRole("button",{name:"Закрыть детали устройства"}).click();await expect(page.getByRole("combobox",{name:"Устройство на карте"})).toBeFocused()
|
||||
await page.getByRole("button",{name:"Закрыть детали устройства"}).click();await expect(page.getByRole("textbox",{name:"Поиск узла или назначения"})).toBeFocused()
|
||||
const box=(await map.boundingBox())!,pan=await map.getAttribute("viewBox")
|
||||
await page.mouse.move(box.x+15,box.y+box.height-50);await page.mouse.down();await page.mouse.move(box.x-30,box.y+box.height-80,{steps:5});await page.mouse.up()
|
||||
expect(await map.getAttribute("viewBox")).not.toBe(pan)
|
||||
@@ -79,7 +79,7 @@ test("Карта: pointer capture, клавиатурный pan и возвра
|
||||
})
|
||||
test("Карта: touch pan и отмена жеста без залипания",async({page})=>{
|
||||
await page.setViewportSize({width:390,height:900});await page.goto("/network-map")
|
||||
const map=page.getByRole("group",{name:"Интерактивная карта сети"});await expect(page.getByRole("combobox",{name:"Устройство на карте"})).toBeEnabled()
|
||||
const map=page.getByRole("group",{name:"Интерактивная карта сети"});await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
||||
expect(await map.evaluate(e=>getComputedStyle(e).touchAction)).toBe("none")
|
||||
const box=(await map.boundingBox())!,before=await map.getAttribute("viewBox"),session=await page.context().newCDPSession(page)
|
||||
await session.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{x:box.x+20,y:box.y+box.height-70,id:1}]})
|
||||
@@ -90,9 +90,9 @@ test("Карта: touch pan и отмена жеста без залипания
|
||||
await page.getByRole("button",{name:/^Устройство Домашний/}).click();await expect(page.getByRole("complementary",{name:"Детали объекта карты"})).toBeVisible()
|
||||
})
|
||||
test("Карта: пустой источник отличается от пустого среза",async({page})=>{
|
||||
await page.goto("/network-map");await expect(page.getByRole("combobox",{name:"Устройство на карте"})).toBeEnabled()
|
||||
await page.getByRole("textbox",{name:"Поиск узла"}).fill("нет такого узла");await expect(page.getByRole("status").filter({hasText:"Узлы по заданным условиям"})).toBeVisible()
|
||||
await page.getByRole("button",{name:"Сбросить срез карты"}).click();await expect(page.getByRole("textbox",{name:"Поиск узла"})).toHaveValue("")
|
||||
await page.goto("/network-map");await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
||||
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("нет такого узла");await expect(page.getByRole("status").filter({hasText:"Узлы по заданным условиям"})).toBeVisible()
|
||||
await page.getByRole("button",{name:"Сбросить срез карты"}).click();await expect(page.getByRole("textbox",{name:"Поиск узла или назначения"})).toHaveValue("")
|
||||
await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
||||
await page.route("**/api/servers",r=>r.fulfill({json:[]}));await page.route("**/api/filters/gre-tunnels",r=>r.fulfill({json:{tunnels:[],failures:[]}}))
|
||||
await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
||||
|
||||
@@ -17,19 +17,30 @@ test.beforeEach(async ({ page }) => {
|
||||
|
||||
test("Карта: раскрытая легенда объясняет статусы, типы, линии и неизвестные измерения", async ({ page }) => {
|
||||
await page.goto("/network-map")
|
||||
const trigger = page.getByRole("button", { name: "Легенда", exact: true })
|
||||
const legend = page.getByRole("region", { name: "Легенда карты" })
|
||||
await expect(legend).not.toBeVisible()
|
||||
await page.locator("[data-map-legend] summary").click()
|
||||
await trigger.click()
|
||||
await expect(legend).toBeVisible()
|
||||
for (const text of ["Онлайн", "Внимание", "Оффлайн", "Неизвестно", "JumpHost", "Exit Node", "Home Router", "GRE + IPsec", "Поток NetFlow"]) await expect(legend.getByText(text, { exact: true })).toBeVisible()
|
||||
const firstStatus = legend.getByText("Онлайн", { exact: true })
|
||||
await expect.poll(() => firstStatus.evaluate(element => {
|
||||
const { x, y, width, height } = element.getBoundingClientRect()
|
||||
const hit = document.elementFromPoint(x + width / 2, y + height / 2)
|
||||
return hit !== null && element.contains(hit)
|
||||
})).toBe(true)
|
||||
for (const text of ["Онлайн", "Внимание", "Оффлайн", "Неизвестно", "JumpHost", "Exit Node", "Home Router", "GRE + IPsec", "Связь с сервисом"]) await expect(legend.getByText(text, { exact: true })).toBeVisible()
|
||||
await expect(legend).toContainText("нет измерения")
|
||||
await expect(legend).toContainText("не пропускная способность канала")
|
||||
await page.locator("[data-map-legend] summary").click()
|
||||
await expect(legend).toContainText("последний замер RX/TX интерфейса RouterOS")
|
||||
await expect(legend).toContainText("среднюю скорость по принятым записям IPFIX")
|
||||
await trigger.click()
|
||||
await expect(legend).not.toBeVisible()
|
||||
await page.locator("[data-map-legend] summary").press("Enter")
|
||||
await trigger.press("Enter")
|
||||
await expect(legend).toBeVisible()
|
||||
await legend.getByText("Онлайн", { exact: true }).click()
|
||||
await page.screenshot({ path: "tmp/map270-desktop.png" })
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(legend).not.toBeVisible()
|
||||
await expect(trigger).toBeFocused()
|
||||
})
|
||||
|
||||
test("Карта: мышь не рисует прямоугольную рамку, клавиатурный фокус остаётся видимым", async ({ page }) => {
|
||||
@@ -51,15 +62,16 @@ test("Карта: мышь не рисует прямоугольную рамк
|
||||
test("Карта: легенда помещается на телефоне и сворачивается", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.goto("/network-map")
|
||||
const trigger = page.getByRole("button", { name: "Легенда", exact: true })
|
||||
const legend = page.getByRole("region", { name: "Легенда карты" })
|
||||
await expect(page.locator("[data-map-legend]")).not.toHaveAttribute("open", "")
|
||||
await expect(trigger).toHaveAttribute("aria-expanded", "false")
|
||||
await page.screenshot({ path: "tmp/map270-mobile.png" })
|
||||
await page.locator("[data-map-legend] summary").click()
|
||||
await trigger.click()
|
||||
await expect(legend).toBeVisible()
|
||||
const bounds = await legend.boundingBox()
|
||||
expect(bounds!.x).toBeGreaterThanOrEqual(0)
|
||||
expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(390)
|
||||
await page.locator("[data-map-legend] summary").click()
|
||||
await trigger.click()
|
||||
await expect(legend).not.toBeVisible()
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { test, expect, type Page } from "@playwright/test"
|
||||
|
||||
// Подписи и карточки холста не наезжают друг на друга: проверяем видимые тела (data-map-box), а не фоновые полосы.
|
||||
const empty = { hops: [], live: true, rangeMinutes: 5, windowSec: 300, totalBytes: 0, namedBytes: 0, unclassifiedBytes: 0, asnLoaded: false, countryLoaded: false, services: [], serviceEdges: [], servicePaths: [], countries: [], countryEdges: [], countryPaths: [], countryServiceGroups: [], mapServiceMinSharePct: 0, dedupApplied: false, excludeMeshApplied: false, excludeOverlayApplied: false }
|
||||
const srv = (id: number, name: string, type: string, country = "RU", status = "online") =>
|
||||
({ id, name, host: `192.0.2.${id}`, type, country, enabled: true, status, latency: 10 + id })
|
||||
const gre = (id: string, owner: number, peer: number, status = "up") => ({
|
||||
id, serverId: String(owner), name: id, localAddress: `192.0.2.${owner}`, remoteAddress: `192.0.2.${peer}`, localInnerIp: "", remoteInnerIp: "",
|
||||
poolId: "", ipsec: null, mtu: 1400, keepaliveInterval: 10, keepaliveRetries: 3, dscp: "inherit", clampTcpMss: true, allowFastPath: false, comment: "", enabled: true, status,
|
||||
})
|
||||
|
||||
async function serve(page: Page, servers: unknown[], tunnels: ReturnType<typeof gre>[], flow: Record<string, unknown>) {
|
||||
await page.route("**/health", (r) => r.fulfill({ json: { ok: true } }))
|
||||
await page.route("**/api/**", (r) => {
|
||||
const p = new URL(r.request().url()).pathname
|
||||
const json = p === "/api/servers" ? servers : p === "/api/filters/gre-tunnels" ? { tunnels, failures: [] }
|
||||
: p === "/api/uptime/speed-probes" ? { probes: [] } : p === "/api/traffic/flow/map-hops" ? { ...empty, ...flow }
|
||||
: p === "/api/ix/topology" ? { links: [] } : p === "/api/auth/config" ? { required: false } : {}
|
||||
return r.fulfill({ json })
|
||||
})
|
||||
}
|
||||
|
||||
async function overlaps(page: Page) {
|
||||
return page.getByRole("group", { name: "Интерактивная карта сети" }).evaluate((svg) => {
|
||||
const boxes = [...svg.querySelectorAll("[data-map-box]")].map((el) => ({ kind: el.getAttribute("data-map-box")!, label: el.closest("[aria-label]")?.getAttribute("aria-label") ?? el.parentElement?.textContent ?? "", text: el.parentElement?.querySelector(":scope > text")?.textContent ?? "", r: el.getBoundingClientRect() }))
|
||||
// Панель масштаба и миникарта лежат поверх холста — они тоже не должны закрывать карточки и подписи.
|
||||
const overlays = [...document.querySelectorAll("[data-map-overlay]")].map((el) => ({ kind: el.getAttribute("data-map-overlay")!, label: "", r: el.getBoundingClientRect() }))
|
||||
const hits: string[] = []
|
||||
const pairs = [...boxes.flatMap((a, i) => boxes.slice(i + 1).map((b) => [a, b] as const)), ...overlays.flatMap((o) => boxes.map((b) => [o, b] as const))]
|
||||
for (const [a, b] of pairs) {
|
||||
const ix = Math.min(a.r.right, b.r.right) - Math.max(a.r.left, b.r.left), iy = Math.min(a.r.bottom, b.r.bottom) - Math.max(a.r.top, b.r.top)
|
||||
if (ix > 1 && iy > 1) hits.push(`${a.kind} «${a.label}» × ${b.kind} «${b.label}»`)
|
||||
}
|
||||
return { overlays: overlays.length, rates: boxes.filter((b) => b.kind === "pill" && /бит\/с/.test(b.text)).length, pills: boxes.filter((b) => b.kind === "pill").length, cards: boxes.filter((b) => b.kind === "card").length, hits }
|
||||
})
|
||||
}
|
||||
|
||||
test("Карта: 3 JH → Exit + IX, параллельные GRE и 8 сервисов без наложений", async ({ page }) => {
|
||||
const servers = [
|
||||
srv(1, "msk-gw01.example.net", "jump-host"), srv(2, "msk-gw02.example.net", "jump-host"), srv(3, "nov-gw01.example.net", "jump-host"),
|
||||
srv(4, "arn-gw01.example.net", "exit-node", "SE"), srv(5, "chr-ix.example.net", "ix-node", "PL"),
|
||||
]
|
||||
// У каждого JH два туннеля до выхода и запись встречного конца на выходе; один JH ещё и до IX.
|
||||
const tunnels = [1, 2, 3].flatMap((jh) => [gre(`gre-${jh}a`, jh, 4), gre(`gre-${jh}b`, jh, 4, jh === 3 ? "down" : "up"), gre(`gre-4-${jh}`, 4, jh)])
|
||||
tunnels.push(gre("gre-ix", 1, 5))
|
||||
const names = ["Прочее", "YouTube", "Cloudflare", "main", "AWS", "Akamai", "Google", "Telegram"]
|
||||
const services = names.map((label, i) => ({ id: "svc:" + i, label, category: "Веб", bytes: 9e6 - i * 1e6, bps: 6e6 - i * 7e5, share: 0.2 - i * 0.02 }))
|
||||
const serviceEdges = services.map((s) => ({ fromId: "4", toId: s.id, bytes: s.bytes, bps: s.bps, bpsFwd: s.bps / 4, bpsRev: (s.bps * 3) / 4 }))
|
||||
const interfaceTraffic = tunnels.map((t, i) => ({ serverId: t.serverId, iface: t.name, rxBytes: 4e6 + i * 1e5, txBytes: 1e6, rxPackets: 10, txPackets: 5, inWindow: true, lastBucketAt: "2026-11-23T07:00:00Z" }))
|
||||
await serve(page, servers, tunnels, { services, serviceEdges, interfaceTraffic, totalBytes: 5e7, namedBytes: 5e7 })
|
||||
await page.goto("/network-map")
|
||||
await page.getByRole("button", { name: /^Остальные сервисы \(/ }).first().click()
|
||||
await expect(page.getByRole("button", { name: "Сервис Telegram", exact: true })).toBeVisible()
|
||||
await expect.poll(async () => (await overlaps(page)).cards).toBe(5)
|
||||
const result = await overlaps(page)
|
||||
expect(result.cards).toBe(5)
|
||||
expect(result.overlays).toBe(2)
|
||||
expect(result.hits).toEqual([])
|
||||
// Скорость NetFlow пары не теряется: она на подписи или, если не влезла между карточками, — в title линии.
|
||||
expect(result.rates + await page.locator("path > title", { hasText: /^Связь .*бит\/с/ }).count()).toBeGreaterThan(0)
|
||||
// Имя хоста без домена, параллельные туннели — одной подписью.
|
||||
await expect(page.getByRole("group", { name: "Интерактивная карта сети" }).getByText("msk-gw01", { exact: true })).toBeVisible()
|
||||
const pair = /^Связь msk-gw01\.example\.net → arn-gw01\.example\.net: .*GRE ×2/
|
||||
expect(await page.getByRole("button", { name: pair }).count()).toBeLessThanOrEqual(1)
|
||||
expect(await page.locator("path > title", { hasText: pair }).count()).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
test("Карта: сетка JH × Exit и аплинки WAN без наложений подписей", async ({ page }) => {
|
||||
const wan = (i: number) => ({ id: "w" + i, name: "WAN" + i, iface: "ether" + i, isp: "ISP-" + i, ip: `198.51.100.${i}`, maxDl: 100, maxUl: 50 })
|
||||
const servers = [
|
||||
{ ...srv(1, "home-msk", "home-router"), wanUplinks: [wan(1), wan(2)] }, { ...srv(2, "home-spb", "home-router"), wanUplinks: [wan(3), wan(4)] },
|
||||
srv(3, "mt-msk-core-01", "jump-host"), srv(4, "mt-msk-lab-01", "jump-host"), srv(5, "mt-ams-test-01", "jump-host", "NL"),
|
||||
srv(6, "mt-fra-edge-01", "exit-node", "DE"), srv(7, "mt-sgp-edge-01", "exit-node", "SG", "offline"), srv(8, "mt-spb-edge-01", "exit-node"), srv(9, "mt-ams-edge-01", "exit-node", "NL", "degraded"),
|
||||
]
|
||||
const tunnels = [3, 4, 5].flatMap((jh) => [6, 7, 8, 9].map((en) => gre(`gre-${jh}-${en}`, jh, en, en === 7 ? "down" : "up")))
|
||||
await serve(page, servers, tunnels, {})
|
||||
await page.goto("/network-map")
|
||||
await expect(page.getByRole("button", { name: /^Устройство mt-ams-edge-01/ })).toBeVisible()
|
||||
await expect.poll(async () => (await overlaps(page)).pills).toBeGreaterThan(2)
|
||||
expect((await overlaps(page)).hits).toEqual([])
|
||||
})
|
||||
@@ -8,12 +8,12 @@ test.beforeEach(async({page})=>{
|
||||
test("Карта URL: устройство/WAN, фильтр, поиск, назначения, reload и история",async({page})=>{
|
||||
await page.goto("/network-map?server=1&wan=0&filter=unknown&q=Router&dest=countries&tag=keep#anchor")
|
||||
await expect(page.getByText("Ресурсы",{exact:true})).toBeVisible()
|
||||
await expect(page.getByRole("textbox",{name:"Поиск узла",exact:true})).toHaveValue("Router")
|
||||
await expect(page.getByRole("textbox",{name:"Поиск узла или назначения",exact:true})).toHaveValue("Router")
|
||||
await page.reload();await expect(page.getByText("Ресурсы",{exact:true})).toBeVisible()
|
||||
await page.getByRole("button",{name:/^Фильтр/}).click();await page.getByRole("button",{name:"Онлайн",exact:true}).click()
|
||||
await expect(page).toHaveURL(/filter=online/);await page.goBack();await expect(page).toHaveURL(/filter=unknown/)
|
||||
await page.getByRole("button",{name:"Сервисы",exact:true}).click();await expect(page).not.toHaveURL(/dest=countries/);await page.goBack();await expect(page).toHaveURL(/dest=countries/)
|
||||
await page.getByRole("textbox",{name:"Поиск узла",exact:true}).fill("Router URL");await expect.poll(()=>new URL(page.url()).searchParams.get("q")).toBe("Router URL")
|
||||
await page.getByRole("textbox",{name:"Поиск узла или назначения",exact:true}).fill("Router URL");await expect.poll(()=>new URL(page.url()).searchParams.get("q")).toBe("Router URL")
|
||||
await expect(page).toHaveURL(/tag=keep/);await expect(page).toHaveURL(/#anchor$/)
|
||||
await page.getByRole("button",{name:"Устройство Router URL",exact:true}).focus();await page.keyboard.press("Escape");await expect(page).not.toHaveURL(/server=/);await expect(page).not.toHaveURL(/wan=/)
|
||||
await page.getByRole("button",{name:"Устройство Router URL",exact:true}).click();await expect(page).toHaveURL(/server=1/)
|
||||
|
||||
@@ -32,10 +32,10 @@ for (const width of [320, 390, 1024, 1440]) {
|
||||
})
|
||||
expect(visibleBounds.filter(control => !control.inside)).toEqual([])
|
||||
expect(await header.locator("ol").evaluate(list => [...list.children].every(child => child.tagName === "LI"))).toBe(true)
|
||||
const apps = header.getByRole("button", { name: "Приложения", exact: true })
|
||||
const apps = header.getByRole("button", { name: /^Состояние системы/ })
|
||||
await apps.focus()
|
||||
await page.keyboard.press("Enter")
|
||||
await expect(page.getByRole("menu")).toBeVisible()
|
||||
await expect(page.locator('[data-slot="popover-content"]')).toBeVisible()
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(apps).toBeFocused()
|
||||
if (width < 768) {
|
||||
|
||||
@@ -9,7 +9,8 @@ for(const width of [1440,320])test(`Меню приложений использ
|
||||
path==='/api/servers'?[]:path==='/api/evobgp/settings'?{enabled:false,baseUrl:'',secretConfigured:false}:{}})
|
||||
})
|
||||
await page.goto('/servers')
|
||||
await page.getByRole('button',{name:'Приложения',exact:true}).click()
|
||||
if(width<768)await page.getByRole('button',{name:'Боковое меню',exact:true}).click()
|
||||
await page.getByRole('button',{name:/^Переключатель приложений/}).click()
|
||||
await expect(page.getByRole('menuitem',{name:'Настроить на портале',exact:true})).toHaveAttribute('href','https://runtime.example.test/admin/apps')
|
||||
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1)).toBe(true)
|
||||
})
|
||||
@@ -2,11 +2,5 @@ import {test,expect,type Page} from "@playwright/test"
|
||||
import {emptyAlerts,emptyOutbox} from "./fixtures/alerts"
|
||||
const counts={servers:4,filterRules:0,uptimeProbes:0,uptimeSpeedProbes:0,monitoringItems:0,recursiveRoutes:0}
|
||||
async function setup(page:Page,reply:(path:string)=>{status?:number;json:unknown}){await page.route("**/health",r=>r.fulfill({json:{status:"ok"}}));await page.route("**/api/**",r=>{const path=new URL(r.request().url()).pathname;return r.fulfill(path==="/api/auth/config"?{json:{required:false}}:path==="/api/alerts"?{json:emptyAlerts}:path==="/api/alerts/outbox"?{json:emptyOutbox}:reply(path))});await page.goto("/alerts")}
|
||||
const badge=(page:Page,name:string)=>page.getByRole("navigation",{name:"Основная навигация"}).getByRole("link",{name:new RegExp(name)}).locator("span").last()
|
||||
test("Sidebar missing optional counts remain unknown; confirmed zero is displayed",async({page})=>{await setup(page,path=>({json:path==="/api/sidebar-counts"?counts:path==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:[]}));await expect(badge(page,"Серверы")).toHaveText("4");await expect(badge(page,"GRE-туннели")).toHaveText("0");await expect(badge(page,"Пользователи")).toHaveText("Пользователи")})
|
||||
test("Sidebar partial GRE refresh retains last complete count, other counts update independently",async({page})=>{await page.clock.install();let partial=false;await setup(page,path=>({json:path==="/api/sidebar-counts"?{...counts,servers:partial?5:4}:path==="/api/filters/gre-tunnels"?{tunnels:partial?[]:[{name:"g",serverId:"1"}],failures:partial?[{error:"offline"}]:[]}:[]}));await expect(badge(page,"GRE-туннели")).toHaveText("1");partial=true;await page.clock.fastForward(120001);await expect(badge(page,"Серверы")).toHaveText("5");await expect(badge(page,"GRE-туннели")).toHaveText("1")})
|
||||
test("Sidebar GRE does not wait for unavailable summary reader",async({page})=>{await setup(page,path=>path==="/api/sidebar-counts"?{status:503,json:{error:"counts unavailable"}}:{json:path==="/api/filters/gre-tunnels"?{tunnels:[{name:"g",serverId:"1"}],failures:[]}:[]});await expect(badge(page,"GRE-туннели")).toHaveText("1");await expect(badge(page,"Серверы")).toHaveText("Серверы")})
|
||||
|
||||
test("Sidebar GRE arrives while summary request is pending",async({page})=>{let started=false,release!:()=>void;const gate=new Promise<void>(resolve=>release=resolve);await page.route("**/health",r=>r.fulfill({json:{status:"ok"}}));await page.route("**/api/**",async r=>{const path=new URL(r.request().url()).pathname;if(path==="/api/sidebar-counts"){started=true;await gate;try{await r.fulfill({json:counts})}catch{};return}return r.fulfill({json:path==="/api/auth/config"?{required:false}:path==="/api/alerts"?emptyAlerts:path==="/api/alerts/outbox"?emptyOutbox:path==="/api/filters/gre-tunnels"?{tunnels:[{name:"g",serverId:"1"}],failures:[]}:[]})});try{await page.goto("/alerts");await expect.poll(()=>started).toBe(true);await expect(badge(page,"GRE-туннели")).toHaveText("1");await expect(badge(page,"Серверы")).toHaveText("Серверы");release();await expect(badge(page,"Серверы")).toHaveText("4")}finally{release()}})
|
||||
|
||||
test("System monitor summary failure preserves API health and last confirmed counts",async({page})=>{await page.clock.install();let fail=false;await setup(page,path=>path==="/api/sidebar-counts"&&fail?{status:503,json:{error:"summary unavailable"}}:{json:path==="/api/sidebar-counts"?counts:path==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:[]});const button=page.getByRole("button",{name:"Монитор системы"});await expect(button).toContainText("API доступен");await button.click();const popover=page.locator('[data-slot="popover-content"]');await expect(popover.getByText("4шт.",{exact:true})).toBeVisible();fail=true;await page.clock.fastForward(30001);await expect(popover.getByRole("status")).toContainText("Сводка не обновлена");await expect(popover.getByText("4шт.",{exact:true})).toBeVisible();await expect(button).toContainText("API доступен")})
|
||||
test("System monitor summary failure preserves API health and last confirmed counts",async({page})=>{await page.clock.install();let fail=false;await setup(page,path=>path==="/api/sidebar-counts"&&fail?{status:503,json:{error:"summary unavailable"}}:{json:path==="/api/sidebar-counts"?counts:path==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:[]});const button=page.getByRole("button",{name:/^Состояние системы/});await expect(button).toContainText("Норма");await button.click();const popover=page.locator('[data-slot="popover-content"]');await expect(popover.getByText("4шт.",{exact:true})).toBeVisible();fail=true;await page.clock.fastForward(30001);await expect(popover.getByRole("status")).toContainText("Сводка не обновлена");await expect(popover.getByText("4шт.",{exact:true})).toBeVisible();await expect(button).toContainText("Внимание");await expect(popover.getByText("OK",{exact:true})).toBeVisible()})
|
||||
@@ -30,6 +30,10 @@ async function setup(page: Page) {
|
||||
|
||||
test('Детали трафика: поздний период не заменяет текущий', async ({ page }) => {
|
||||
const control = await setup(page)
|
||||
const reading = page.getByRole('slider', {name: 'Точка на графике'})
|
||||
await expect(reading).toHaveAttribute('aria-valuetext', /сейчас · RX 2.* · TX 3/)
|
||||
await reading.press('Home')
|
||||
await expect(reading).toHaveAttribute('aria-valuetext', /RX 1.* · TX 2/)
|
||||
control.holdRange = '24h'
|
||||
const started = page.waitForRequest(r => new URL(r.url()).pathname === '/api/traffic/servers/1' && r.url().includes('range=24h'))
|
||||
await page.getByRole('button', { name: '24ч', exact: true }).click()
|
||||
|
||||
@@ -2,6 +2,26 @@ import { observedTrafficFixturePayload } from "./traffic-observation-fixture"
|
||||
import { installOpenLiveStream, resumeLiveStream, sendLiveHeartbeat } from "./live-stream-fixture"
|
||||
import { test, expect } from '@playwright/test'
|
||||
|
||||
test("Трафик открывает сервер из ссылки карты", async ({ page }) => {
|
||||
const second = { id: "2", name: "Выбранный Exit", site: "TEST", country: "RU", status: "online", rxNow: 2, txNow: 3,
|
||||
rxPeak: 5, txPeak: 6, rxTotal: 100, txTotal: 200, sessions: 1, rxSeries: [1, 2], txSeries: [2, 3] }
|
||||
const first = { ...second, id: "1", name: "Первый роутер" }
|
||||
const requested: string[] = []
|
||||
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
|
||||
await page.route("**/api/**", route => {
|
||||
const { pathname } = new URL(route.request().url())
|
||||
if (/\/traffic\/servers\/\d+\/live$/.test(pathname)) requested.push(pathname)
|
||||
const data = pathname === "/api/auth/config" ? { required: false }
|
||||
: pathname === "/api/traffic/servers" ? { servers: [first, second] }
|
||||
: pathname === "/api/traffic/servers/2" ? { server: second }
|
||||
: pathname === "/api/traffic/users" ? { users: [] } : { interfaces: [] }
|
||||
return route.fulfill({ json: observedTrafficFixturePayload(data) })
|
||||
})
|
||||
await page.goto("/traffic?server=2")
|
||||
await expect(page.getByLabel("Скорость выбранного сервера")).toBeVisible()
|
||||
await expect.poll(() => requested).toEqual(["/api/traffic/servers/2/live"])
|
||||
})
|
||||
|
||||
for (const variant of ['closed', 'invalid', 'http-error', 'silent', 'awaiting'] as const) {
|
||||
test(`Трафик: SSE ${variant} не выдаёт старое измерение за live`, async ({ page }) => {
|
||||
const server = { id: '1', name: 'Тестовый сервер', site: 'TEST', country: 'RU', status: 'online', rxNow: 2, txNow: 3, rxPeak: 5, txPeak: 6, rxTotal: 100, txTotal: 200, sessions: 1, rxSeries: [1, 2], txSeries: [2, 3] }
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { test } from "node:test"
|
||||
import assert from "node:assert/strict"
|
||||
import { MAP_CARD_H, MAP_CARD_W, MAP_PILL_H, mapLinkPath, mapLinkPoint, mapRibbons, placeMapLinkLabels, type MapBox } from "../../lib/network-map-layout"
|
||||
|
||||
const card = (x: number, y: number): MapBox => ({ x: x - MAP_CARD_W / 2, y: y - MAP_CARD_H / 2, w: MAP_CARD_W, h: MAP_CARD_H })
|
||||
const hit = (a: MapBox, b: MapBox) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
|
||||
const pill = (p: { x: number; y: number; w: number }): MapBox => ({ x: p.x - p.w / 2, y: p.y - MAP_PILL_H / 2, w: p.w, h: MAP_PILL_H })
|
||||
|
||||
test("кривая связи проходит через концы и середину", () => {
|
||||
const l = mapLinkPath({ x: 0, y: 0 }, 10, { x: 200, y: 100 }, 10)
|
||||
assert.deepEqual(mapLinkPoint(l, 0), { x: 10, y: 0 })
|
||||
assert.deepEqual(mapLinkPoint(l, 1), { x: 190, y: 100 })
|
||||
assert.deepEqual(mapLinkPoint(l, 0.5), { x: 100, y: 50 })
|
||||
})
|
||||
|
||||
test("подписи не наезжают на карточки и друг на друга, длинная — укорачивается или пропадает", () => {
|
||||
// Три JH слева сходятся в один EN справа; у каждой пары — длинный и короткий вариант подписи.
|
||||
const jh = [100, 180, 260].map((y) => ({ x: 542, y }))
|
||||
const en = { x: 780, y: 180 }
|
||||
const obstacles = [...jh.map((p) => card(p.x, p.y)), card(en.x, en.y)]
|
||||
const labels = jh.map((p, i) => ({
|
||||
id: "jh" + i,
|
||||
link: mapLinkPath(p, MAP_CARD_W / 2, en, MAP_CARD_W / 2),
|
||||
texts: ["24 мс · 86 Мбит/с", "24 мс"],
|
||||
}))
|
||||
// Горизонтальная связь в узком зазоре: длинной подписи места нет нигде.
|
||||
labels.push({ id: "flat", link: mapLinkPath({ x: 542, y: 400 }, MAP_CARD_W / 2, { x: 780, y: 400 }, MAP_CARD_W / 2), texts: ["очень длинная подпись связи"] })
|
||||
obstacles.push(card(542, 400), card(780, 400))
|
||||
const placed = placeMapLinkLabels(labels, obstacles)
|
||||
assert.ok(placed.length >= 3, "подписи трёх сходящихся связей размещены")
|
||||
assert.equal(placed.find((p) => p.id === "flat"), undefined, "не влезающая подпись не рисуется")
|
||||
for (const [i, a] of placed.entries()) {
|
||||
for (const o of obstacles) assert.equal(hit(pill(a), o), false, a.id + " поверх карточки")
|
||||
for (const b of placed.slice(i + 1)) assert.equal(hit(pill(a), pill(b)), false, a.id + " поверх " + b.id)
|
||||
}
|
||||
})
|
||||
|
||||
test("ленты NetFlow уложены стопкой у узла и толще у большей скорости", () => {
|
||||
const exit = { x: 780, y: 300 }
|
||||
const flows = [
|
||||
{ id: "a", from: exit, fromHalfW: 80, to: { x: 1080, y: 200 }, toHalfW: 140, bps: 300 },
|
||||
{ id: "b", from: exit, fromHalfW: 80, to: { x: 1080, y: 400 }, toHalfW: 140, bps: 100 },
|
||||
]
|
||||
const [a, b] = mapRibbons(flows, 40)
|
||||
assert.equal(a.w, 30)
|
||||
assert.equal(b.w, 10)
|
||||
// У выхода ленты лежат вплотную по центру карточки (стопка 40 px при пике 400 — сумма у выхода).
|
||||
assert.match(a.d, /^M 860 295\.0 /)
|
||||
assert.match(b.d, /^M 860 315\.0 /)
|
||||
assert.match(a.d, / 940 200\.0$/)
|
||||
})
|
||||
|
||||
test("совпадающие середины двух связей разводятся по своим кривым", () => {
|
||||
const a = mapLinkPath({ x: 0, y: 0 }, 0, { x: 300, y: 200 }, 0)
|
||||
const b = mapLinkPath({ x: 0, y: 200 }, 0, { x: 300, y: 0 }, 0)
|
||||
const placed = placeMapLinkLabels([{ id: "a", link: a, texts: ["12 мс"] }, { id: "b", link: b, texts: ["14 мс"] }], [])
|
||||
assert.equal(placed.length, 2)
|
||||
assert.equal(hit(pill(placed[0]), pill(placed[1])), false)
|
||||
})
|
||||