Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ca40fbb4d | ||
|
|
589fc782f9 |
No files matched your search
+250
-248
@@ -73,6 +73,7 @@ import {
|
||||
type GreSpeedProbeSnapshot,
|
||||
} from "@/lib/map-gre-speed-probe"
|
||||
import {
|
||||
formatMapFlowWindow,
|
||||
formatNetflowDir,
|
||||
formatNetflowRate,
|
||||
hopHasRate,
|
||||
@@ -81,10 +82,13 @@ import {
|
||||
type GreNetflowHop,
|
||||
type MatchedNetflowHop,
|
||||
} from "@/lib/map-netflow-hops"
|
||||
import { useMapGreTraffic } from "@/hooks/use-map-gre-traffic"
|
||||
import { isFreshMapTrafficSample, useMapInterfaceTraffic } from "@/hooks/use-map-interface-traffic"
|
||||
import { useTrafficLive } from "@/hooks/use-traffic-live"
|
||||
import { formatBytes } from "@/lib/fmt-rate"
|
||||
import type { FlowMapCountryServiceGroup, FlowMapInterfaceTraffic, FlowMapHop, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import type { FlowMapCountryServiceGroup, FlowMapHopsDto, FlowMapInterfaceTraffic, FlowMapHop, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
|
||||
import { InspectorMetrics, InspectorUsers, NodeHistory, ServiceInspector, serviceUsers } from "@/components/network-map/inspector-traffic"
|
||||
import { Spinner } from "@/components/ui/spinner"
|
||||
import { CountryFlagSvg } from "@/components/network-map/country-flag-svg"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { StatusBadge } from "@/components/status-badge"
|
||||
@@ -96,7 +100,7 @@ import {
|
||||
CableIcon, ActivityIcon,
|
||||
} from "lucide-react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { formatServicePathLabel, formatServicePathTitle } from "@/lib/format-service-path-label"
|
||||
import { formatServicePathLabel, formatServicePathTitle, servicePathKey } from "@/lib/format-service-path-label"
|
||||
import Link from "next/link"
|
||||
import { MapBottomPanel, MapTimeline, type MapBottomTab, type MapEventRow } from "@/components/network-map/map-bottom-panel"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
@@ -360,11 +364,8 @@ function destDisplayLabel(node: FlowMapService | undefined, mode: DestMode, fall
|
||||
return countryName(node.label)
|
||||
}
|
||||
|
||||
function servicePathKey(p: Pick<FlowMapServicePath, "clientId" | "viaId" | "enId" | "serviceId">): string {
|
||||
return `${p.clientId}|${p.viaId}|${p.enId}|${p.serviceId}`
|
||||
}
|
||||
|
||||
function greMatchesPath(e: GreMapEdge, h: { viaId: string; enId: string }): boolean {
|
||||
if (!h.enId || h.viaId === h.enId) return false
|
||||
const ids = new Set([e.fromServer.id, e.toServer.id])
|
||||
return ids.has(h.viaId) && ids.has(h.enId)
|
||||
}
|
||||
@@ -426,6 +427,10 @@ function greEdgeKey(e: GreMapEdge): string {
|
||||
|
||||
const PILL_TONE = { fg: "var(--foreground)", mu: "var(--muted-foreground)", wn: "var(--warning)", er: "var(--destructive)" }
|
||||
|
||||
function compactMapRate(rate: string): string {
|
||||
return rate.replace(/\.0+(?= [ГМК]?бит\/с)/, "").replace(/ ([ГМК])бит\/с/, "$1").replace(" бит/с", "б/с")
|
||||
}
|
||||
|
||||
/** Подпись связи макета v3: «таблетка» с RTT / скоростью; подробности — в title и панели справа. */
|
||||
function MapLinkPill({ x, y, w, text, tone, opacity, label, hint, onOpen }: {
|
||||
x: number; y: number; w: number; text: string
|
||||
@@ -628,7 +633,7 @@ function ServicePathList({
|
||||
paths: FlowMapServicePath[]
|
||||
servers: Server[]
|
||||
services: FlowMapService[]
|
||||
highlight: { viaId: string; enId: string; serviceId: string } | null
|
||||
highlight: FlowMapServicePath | null
|
||||
viaMode: "via" | "service"
|
||||
destMode: DestMode
|
||||
onToggle: (p: FlowMapServicePath) => void
|
||||
@@ -644,18 +649,15 @@ function ServicePathList({
|
||||
const en = servers.find((s) => s.id === p.enId)
|
||||
const svc = services.find((s) => s.id === p.serviceId)
|
||||
const destLabel = destDisplayLabel(svc, destMode, p.serviceId)
|
||||
const label = formatServicePathLabel(p, viaMode, {
|
||||
const label = p.enId ? formatServicePathLabel(p, viaMode, {
|
||||
viaName: via?.name,
|
||||
viaSite: via?.site,
|
||||
enName: en?.name,
|
||||
serviceLabel: destLabel,
|
||||
})
|
||||
}) : [p.viaName || p.viaId, p.viaIface, "наблюдение IPFIX"].filter(Boolean).join(" · ")
|
||||
const title = formatServicePathTitle(label, destLabel)
|
||||
const active = Boolean(
|
||||
highlight
|
||||
&& highlight.viaId === p.viaId
|
||||
&& highlight.enId === p.enId
|
||||
&& highlight.serviceId === p.serviceId,
|
||||
highlight && servicePathKey(highlight) === rowKey,
|
||||
)
|
||||
return (
|
||||
<button type="button"
|
||||
@@ -678,10 +680,11 @@ function ServicePathList({
|
||||
)
|
||||
}
|
||||
|
||||
function WanSatNode({ x, y, wan, color, active, isSel, isDragged, onSelect, onPointerDown }: {
|
||||
function WanSatNode({ x, y, wan, color, active, isSel, isDragged, traffic, onSelect, onPointerDown }: {
|
||||
x: number; y: number
|
||||
wan: { name: string; isp: string; maxDl: number; maxUl: number }
|
||||
color: string; active: boolean; isSel: boolean; isDragged: boolean
|
||||
traffic?: string
|
||||
onSelect: () => void
|
||||
onPointerDown: (e: React.PointerEvent<SVGGElement>) => void
|
||||
}) {
|
||||
@@ -693,6 +696,7 @@ function WanSatNode({ x, y, wan, color, active, isSel, isDragged, onSelect, onPo
|
||||
style={{ cursor: isDragged ? "grabbing" : "grab" }}
|
||||
onPointerDown={e => { e.stopPropagation(); onPointerDown(e) }}
|
||||
onClick={e => { e.stopPropagation(); onSelect() }}>
|
||||
{traffic && <title>{traffic}</title>}
|
||||
<rect className="network-map-focus-ring" x={-hw - 4} y="-26" width={MAP_WAN_W + 8} height="52" rx="26" fill="none" stroke="var(--ring)" strokeWidth="2" />
|
||||
{isSel && <rect x={-hw - 5} y="-27" width={MAP_WAN_W + 10} height="54" rx="27" fill="none" stroke={color} strokeWidth="1.2" strokeDasharray="3 2" opacity="0.7" />}
|
||||
<rect data-map-box="wan" x={-hw} y="-22" width={MAP_WAN_W} height="44" rx="22" fill="var(--card)" stroke={isSel ? color : "var(--border)"} strokeWidth="1.5" opacity={active ? 1 : 0.8} />
|
||||
@@ -702,7 +706,7 @@ function WanSatNode({ x, y, wan, color, active, isSel, isDragged, onSelect, onPo
|
||||
</g>
|
||||
<circle cx={-hw + 32} cy="-10" r="4.5" fill={active ? "var(--success)" : "var(--muted-foreground)"} stroke="var(--card)" strokeWidth="2" />
|
||||
<text x={-hw + 42} y="-3" fill="var(--foreground)" fontSize="13" fontWeight="600" fontFamily="Geist,sans-serif">{shortName(wan.isp || wan.name, 12)}</text>
|
||||
<text x={-hw + 42} y="12" fill="var(--muted-foreground)" fontSize="11" fontFamily="Geist Mono,monospace">{shortName(wan.name, 8)} · ↓{wan.maxDl}</text>
|
||||
<text x={-hw + 42} y="12" fill="var(--muted-foreground)" fontSize="11" fontFamily="Geist Mono,monospace">{traffic ? compactMapRate(traffic) : `${shortName(wan.name, 8)} · ↓${wan.maxDl}`}</text>
|
||||
</g>
|
||||
)
|
||||
}
|
||||
@@ -716,7 +720,7 @@ function ContextMenu({ menu, onClose }: { menu: CtxMenu; onClose: () => void })
|
||||
{
|
||||
icon: <TerminalIcon aria-hidden="true" className="size-3" />,
|
||||
label: "Открыть терминал",
|
||||
href: `/terminal?host=${encodeURIComponent(menu.server.host)}`,
|
||||
href: `/terminal?server=${encodeURIComponent(menu.server.id)}`,
|
||||
},
|
||||
{
|
||||
icon: <ShieldIcon aria-hidden="true" className="size-3" />,
|
||||
@@ -896,6 +900,7 @@ function NetworkMapContent() {
|
||||
}, [apiFetch, useLiveData, hasIxNodes])
|
||||
const [speedProbes, setSpeedProbes] = useState<GreSpeedProbeSnapshot[]>([])
|
||||
const [mapHops, setMapHops] = useState<FlowMapHop[]>([])
|
||||
const [mapNodeUsers, setMapNodeUsers] = useState<FlowMapHopsDto["nodeUsers"]>()
|
||||
const [interfaceTraffic, setInterfaceTraffic] = useState<FlowMapInterfaceTraffic[]>()
|
||||
const [mapServices, setMapServices] = useState<FlowMapService[]>([])
|
||||
const [mapServiceEdges, setMapServiceEdges] = useState<FlowMapServiceEdge[]>([])
|
||||
@@ -908,6 +913,7 @@ function NetworkMapContent() {
|
||||
const [mapNamedBytes, setMapNamedBytes] = useState(0)
|
||||
const [mapTotalBytes, setMapTotalBytes] = useState(0)
|
||||
const [mapWindowSec, setMapWindowSec] = useState(300)
|
||||
const mapWindow = formatMapFlowWindow(mapWindowSec)
|
||||
const [mapAsnLoaded, setMapAsnLoaded] = useState(true)
|
||||
const [mapCountryLoaded, setMapCountryLoaded] = useState(true)
|
||||
/** FQDN из GRE outer → IPv4 (ответ POST /api/network/resolve-hosts), для матчинга с WAN. */
|
||||
@@ -918,6 +924,7 @@ function NetworkMapContent() {
|
||||
const [flowLoading,setFlowLoading]=useState(false)
|
||||
const [flowRefresh,setFlowRefresh]=useState(0)
|
||||
const [bottomTab, setBottomTab] = useState<MapBottomTab>("flows")
|
||||
const [filteredServiceId, setFilteredServiceId] = useState<string | null>(null)
|
||||
const [mapEvents, setMapEvents] = useState<EventItem[] | null>(null)
|
||||
const [eventsError, setEventsError] = useState<string | null>(null)
|
||||
const [eventsAt, setEventsAt] = useState(() => Date.now())
|
||||
@@ -1063,6 +1070,10 @@ function NetworkMapContent() {
|
||||
|
||||
// ── Interaction ─────────────────────────────────────────────────────────────
|
||||
const selected=urlState.server?mapServers.find(server=>server.id===urlState.server)??null:null
|
||||
const selectedNodeTraffic = useTrafficLive({
|
||||
enabled: useLiveData && Boolean(selected && selected.enabled !== false && selected.status !== "offline"),
|
||||
backendUrl, serverId: selected?.id ?? "", iface: "__all__", reloadKey: flowRefresh,
|
||||
})
|
||||
const setSelected=useCallback((value:React.SetStateAction<Server|null>)=>{
|
||||
const next=typeof value==="function"?value(selected):value
|
||||
updateUrl({server:next?.id??null,wan:null})
|
||||
@@ -1100,7 +1111,7 @@ function NetworkMapContent() {
|
||||
const expandedCountry = expandedCountryId
|
||||
? mapCountries.find((c) => c.id === expandedCountryId) ?? null
|
||||
: null
|
||||
const [highlightedPath, setHighlightedPath] = useState<{ viaId: string; enId: string; serviceId: string } | null>(null)
|
||||
const [highlightedPath, setHighlightedPath] = useState<FlowMapServicePath | null>(null)
|
||||
const selWanIdx=urlState.wan
|
||||
function setSelWanIdx(value:React.SetStateAction<number|null>){const next=typeof value==="function"?value(selWanIdx):value;updateUrl({wan:next==null?null:String(next)})}
|
||||
const [hoveredId, setHoveredId] = useState<string | null>(null)
|
||||
@@ -1152,6 +1163,7 @@ function NetworkMapContent() {
|
||||
if (!useLiveData) {
|
||||
queueMicrotask(() => {
|
||||
setMapHops([])
|
||||
setMapNodeUsers(undefined)
|
||||
setInterfaceTraffic(undefined)
|
||||
setMapServices(MOCK_MAP_SERVICES)
|
||||
setMapServiceEdges(MOCK_MAP_SERVICE_EDGES)
|
||||
@@ -1177,11 +1189,12 @@ function NetworkMapContent() {
|
||||
setFlowLoading(true)
|
||||
ac?.abort()
|
||||
ac = new AbortController()
|
||||
apiFetch<unknown>("/api/traffic/flow/map-hops?range=5m", { signal: ac.signal })
|
||||
apiFetch<unknown>("/api/traffic/flow/map-hops?range=1m", { signal: ac.signal })
|
||||
.then((raw) => {
|
||||
if (cancelled||request!==epoch) return
|
||||
const res=networkMapFlowSchema.parse(raw)
|
||||
setMapHops(res.hops)
|
||||
setMapNodeUsers(res.nodeUsers)
|
||||
setInterfaceTraffic(res.interfaceTraffic)
|
||||
setMapServices(res.services)
|
||||
setMapServiceEdges(res.serviceEdges)
|
||||
@@ -1374,14 +1387,31 @@ function NetworkMapContent() {
|
||||
return m
|
||||
}, [greEdges, mapHops, interfaceTraffic, mapWindowSec, showNetflow])
|
||||
|
||||
const greTrafficTargets = useMemo(() => {
|
||||
if (!useLiveData || !selectedGreEdge) return []
|
||||
const { tunnel, fromServer, toServer } = selectedGreEdge
|
||||
const owner = tunnel.serverId === fromServer.id ? fromServer : toServer
|
||||
return tunnel.enabled && tunnel.status !== "down" && owner.status !== "offline" && tunnel.name
|
||||
? [{ edgeId: greEdgeKey(selectedGreEdge), serverId: owner.id, iface: tunnel.name }] : []
|
||||
}, [useLiveData, selectedGreEdge])
|
||||
const getGreLiveRate = useMapGreTraffic(backendUrl, greTrafficTargets)
|
||||
const liveTrafficTargets = useMemo(() => {
|
||||
if (!useLiveData || !showNetflow && !selectedGreEdge) return []
|
||||
const gre = (showNetflow ? greEdges : [selectedGreEdge]).flatMap(edge => {
|
||||
if (!edge) return []
|
||||
const { tunnel, peerTunnel, fromServer, toServer } = edge
|
||||
const id = greEdgeKey(edge)
|
||||
return [tunnel, peerTunnel].flatMap((end, i) => {
|
||||
if (!end) return []
|
||||
const owner = end.serverId === fromServer.id ? fromServer : toServer
|
||||
return end.enabled && end.status !== "down" && owner.status !== "offline" && end.name
|
||||
? [{ edgeId: i === 0 ? id : id + ":peer", serverId: owner.id, iface: end.name }] : []
|
||||
})
|
||||
})
|
||||
const wan = showNetflow ? homeRouters.flatMap(home => home.status === "offline" ? [] :
|
||||
(home.wanUplinks ?? []).flatMap((uplink, i) => uplink.iface
|
||||
? [{ edgeId: `wan:${home.id}:${i}`, serverId: home.id, iface: uplink.iface }] : [])) : []
|
||||
return [...gre, ...wan]
|
||||
}, [useLiveData, showNetflow, selectedGreEdge, greEdges, homeRouters])
|
||||
const getInterfaceLiveRate = useMapInterfaceTraffic(backendUrl, liveTrafficTargets)
|
||||
const getGreLiveRate = (id: string) => {
|
||||
const local = getInterfaceLiveRate(id)
|
||||
if (local) return { ...local, peerObservation: false }
|
||||
const peer = getInterfaceLiveRate(id + ":peer")
|
||||
return peer && { ...peer, bpsFwd: peer.bpsRev, bpsRev: peer.bpsFwd, peerObservation: true }
|
||||
}
|
||||
|
||||
const netflowByWanKey = useMemo(() => {
|
||||
const m = new Map<string, MatchedNetflowHop>()
|
||||
@@ -1391,13 +1421,10 @@ function NetworkMapContent() {
|
||||
const hop = matchNetflowForWan(home.id, wan.iface, mapHops)
|
||||
if (!hopHasRate(hop)) continue
|
||||
m.set(`${home.id}\t${wIdx}`, hop)
|
||||
for (const e of wanJhEdges) {
|
||||
if (e.homeId === home.id && e.wanIdx === wIdx) m.set(wanJhEdgeMapKey(e), hop)
|
||||
}
|
||||
}
|
||||
}
|
||||
return m
|
||||
}, [homeRouters, wanJhEdges, mapHops, showNetflow])
|
||||
}, [homeRouters, mapHops, showNetflow])
|
||||
|
||||
const destNodes = destMode === "countries" ? mapCountries : mapServices
|
||||
const destEdges = destMode === "countries" ? mapCountryEdges : mapServiceEdges
|
||||
@@ -1408,9 +1435,11 @@ function NetworkMapContent() {
|
||||
? destEdges.filter(edge => nodePosById[edge.fromId] && visibleMapServices.some(service => service.id === edge.toId))
|
||||
: []
|
||||
|
||||
const selectedExitEdges = destEdges.filter(edge => edge.toId === liveSelectedService?.id)
|
||||
const selectedDestEdges = destEdges.filter(edge => edge.toId === liveSelectedService?.id)
|
||||
const selectedDestPaths = (selectedNestedService ? expandedCountryGroup?.paths ?? [] : destPaths)
|
||||
.filter(p => p.serviceId === liveSelectedService?.id).sort((a, b) => b.bps - a.bps)
|
||||
const unassignedBytes = liveSelectedService
|
||||
? liveSelectedService.bytes - selectedExitEdges.reduce((sum, edge) => sum + edge.bytes, 0)
|
||||
? liveSelectedService.bytes - selectedDestEdges.reduce((sum, edge) => sum + edge.bytes, 0)
|
||||
: 0
|
||||
|
||||
const nodes = mapServers
|
||||
@@ -1756,14 +1785,7 @@ function NetworkMapContent() {
|
||||
}
|
||||
|
||||
function togglePathHighlight(p: FlowMapServicePath) {
|
||||
setHighlightedPath((prev) => (
|
||||
prev
|
||||
&& prev.viaId === p.viaId
|
||||
&& prev.enId === p.enId
|
||||
&& prev.serviceId === p.serviceId
|
||||
? null
|
||||
: { viaId: p.viaId, enId: p.enId, serviceId: p.serviceId }
|
||||
))
|
||||
setHighlightedPath(prev => prev && servicePathKey(prev) === servicePathKey(p) ? null : p)
|
||||
}
|
||||
|
||||
function openWanJhSpeedDetail(ev: React.SyntheticEvent<SVGElement>, edge: WanJhEdge) {
|
||||
@@ -1859,10 +1881,17 @@ function NetworkMapContent() {
|
||||
e, i, id, sp, open,
|
||||
merged: mergeGreMetricsWithSpeedProbe(sp, greTunnelProbe(e.tunnel, !useLiveData)),
|
||||
flowHop: netflowByGreKey.get(id),
|
||||
liveRate: getGreLiveRate(id),
|
||||
opacity: dimmed ? 0.05 : highlightedPath && !greMatchesPath(e, highlightedPath) ? 0.14 : 1,
|
||||
link: mapLinkPath(e.from, greHalfW(e.from, e.fromServer), e.to, greHalfW(e.to, e.toServer)),
|
||||
}
|
||||
})
|
||||
const busiestLiveLink = showNetflow ? liveTrafficTargets.reduce<{ name: string; bps: number; bpsFwd: number; bpsRev: number } | undefined>((best, target) => {
|
||||
const rate = getInterfaceLiveRate(target.edgeId)
|
||||
if (!rate || best && best.bps >= rate.bps) return best
|
||||
const server = mapServers.find(node => node.id === target.serverId)
|
||||
return { ...rate, name: `${server ? mapCardName(server.name, 40).text + " · " : ""}${target.iface}` }
|
||||
}, undefined) : undefined
|
||||
// Параллельные туннели одной пары (и записи обоих концов одного туннеля) — одна связь и одна подпись.
|
||||
const greGroups = [...greLinks.reduce((m, g) => {
|
||||
const a = `${Math.round(g.link.x1)},${Math.round(g.link.y1)}`, b = `${Math.round(g.link.x2)},${Math.round(g.link.y2)}`
|
||||
@@ -1871,20 +1900,41 @@ function NetworkMapContent() {
|
||||
}, new Map<string, typeof greLinks>()).values()]
|
||||
// Полная подпись связи — в title линии: короткая «таблетка» может не влезть между карточками.
|
||||
const greLinkTitle = new Map<string, string>()
|
||||
const maxPerGreOwner = (edges: typeof greLinks, getValue: (edge: typeof greLinks[number]) => number | undefined) => {
|
||||
const totals = new Map<string, number>()
|
||||
for (const edge of edges) {
|
||||
const value = getValue(edge)
|
||||
if (value !== undefined) {
|
||||
const owner = edge.e.tunnel.serverId
|
||||
totals.set(owner, (totals.get(owner) ?? 0) + value)
|
||||
}
|
||||
}
|
||||
return totals.size ? Math.max(...totals.values()) : null
|
||||
}
|
||||
const greLabels = greGroups.flatMap((group) => {
|
||||
const lead = group.find((g) => greTunnelIdsWithMapBadge.has(g.id)) ?? group[0]
|
||||
// Записи обоих концов туннеля лежат на разных роутерах: число туннелей — максимум записей у одного роутера.
|
||||
const count = Math.max(...[...group.reduce((m, g) => m.set(g.e.tunnel.serverId, (m.get(g.e.tunnel.serverId) ?? 0) + 1), new Map<string, number>()).values()])
|
||||
// Distinct tunnel pairs can have a different reporting owner even when they share one line.
|
||||
const links = [...group.reduce((m, g) => {
|
||||
const key = g.e.ambiguousPeerKey ?? g.id
|
||||
return m.set(key, [...(m.get(key) ?? []), g])
|
||||
}, new Map<string, typeof greLinks>()).values()]
|
||||
const count = links.reduce((n, edges) => n + (maxPerGreOwner(edges, () => 1) ?? 0), 0)
|
||||
const down = group.every((g) => g.e.tunnel.status === "down")
|
||||
// Скорость пары: записи одного роутера — разные туннели (сумма), записи двух концов — один туннель (максимум по роутерам).
|
||||
const perServer = group.reduce((m, g) => g.flowHop?.inWindow ? m.set(g.e.tunnel.serverId, (m.get(g.e.tunnel.serverId) ?? 0) + g.flowHop.bps) : m, new Map<string, number>())
|
||||
const flowBps = perServer.size ? Math.max(...perServer.values()) : null
|
||||
const flows = links.map(edges => maxPerGreOwner(edges, g => g.flowHop?.inWindow ? g.flowHop.bps : undefined))
|
||||
const flowBps = flows.some(bps => bps !== null) ? flows.reduce<number>((n, bps) => n + (bps ?? 0), 0) : null
|
||||
const flow = count === 1 ? group.map((g) => g.flowHop).filter((h) => h?.inWindow).sort((x, y) => y!.bps - x!.bps)[0] : undefined
|
||||
const rate = showNetflow && flowBps != null ? formatNetflowRate({ bps: flowBps }) : ""
|
||||
const active = group.filter(g => g.e.tunnel.enabled && g.e.tunnel.status !== "down")
|
||||
const liveBps = active.length && active.every(g => g.liveRate)
|
||||
? links.reduce((n, edges) => n + (maxPerGreOwner(edges, g => g.liveRate?.bps) ?? 0), 0) : null
|
||||
const rate = !showNetflow ? "" : liveBps != null ? `Live ${formatNetflowRate({ bps: liveBps })}`
|
||||
: flowBps != null ? `≈${formatNetflowRate({ bps: flowBps })}` : ""
|
||||
const rtt = showPingBadges && lead.merged.pingMs != null ? rttLabel(lead.merged.pingMs) : ""
|
||||
const many = count > 1 ? `GRE ×${count}` : ""
|
||||
// «—» — только когда не известно ничего: известное, но не влезающее значение не подменяем прочерком.
|
||||
const texts = down ? ["нет связи"] : rtt || rate || many ? [...new Set([[rtt, rate, many].filter(Boolean).join(" · "), [rtt, rate].filter(Boolean).join(" · "), rate || rtt || many].filter(Boolean))] : ["—"]
|
||||
const texts = down ? ["нет связи"] : rtt || rate || many ? [...new Set([
|
||||
[rtt, rate, many].filter(Boolean).join(" · "), [rtt, rate].filter(Boolean).join(" · "), rate || rtt || many,
|
||||
compactMapRate(rate), many,
|
||||
].filter(Boolean))] : ["—"]
|
||||
for (const g of group) greLinkTitle.set(g.id, `Связь ${lead.e.fromServer.name} → ${lead.e.toServer.name}: ${texts[0]}`)
|
||||
if (!showPingBadges && !showNetflow) return []
|
||||
const outer = greOuterSummaryLine(lead.e.tunnel, nodeById[lead.e.fromServer.id], nodeById[lead.e.toServer.id], greResolvedMap)
|
||||
@@ -1893,7 +1943,8 @@ function NetworkMapContent() {
|
||||
(lead.sp?.lastPingRttMs != null ? "RTT — ping/BT из «Мониторинг → скорость». " : lead.merged.pingMs == null ? "RTT неизвестен. " : "RTT — демонстрационная модель. ") +
|
||||
(lead.sp?.lastTxAvgMbps != null || lead.sp?.lastRxAvgMbps != null ? "TX/RX — с пробы. " : "") +
|
||||
(lead.sp ? "Проба " + lead.sp.id + "; время Ping: " + (lead.sp.lastPingAt ? new Date(lead.sp.lastPingAt).toLocaleString("ru-RU") : "неизвестно") + "; время TX/RX неизвестно. " : "") +
|
||||
(flow ? `NetFlow · ${mapWindowSec / 60} мин: ${formatNetflowRate(flow)} (${formatNetflowDir(flow)}). ` : flowBps != null ? `NetFlow · ${mapWindowSec / 60} мин: ${formatNetflowRate({ bps: flowBps })} по ${count} туннелям. ` : "") +
|
||||
(showNetflow && liveBps != null ? `RouterOS Live · ${formatNetflowRate({ bps: liveBps })}. ` : "") +
|
||||
(flow ? `NetFlow · ${mapWindow}: ${formatNetflowRate(flow)} (${formatNetflowDir(flow)}). ` : flowBps != null ? `NetFlow · ${mapWindow}: ${formatNetflowRate({ bps: flowBps })} по ${count} туннелям. ` : "") +
|
||||
"Клик — панель справа."
|
||||
return [{
|
||||
id: "gre:" + lead.id, link: lead.link, texts, hint, open: lead.open,
|
||||
@@ -1908,23 +1959,20 @@ function NetworkMapContent() {
|
||||
const key = wanJhEdgeMapKey(edge)
|
||||
const sp = speedProbeByWanJhKey.get(key)
|
||||
const merged = mergeGreMetricsWithSpeedProbe(sp, { pingMs: useLiveData ? null : edge.pingMs, dlMbps: null, ulMbps: null })
|
||||
return [{ edge, key, sp, merged, jh, flow: netflowByWanKey.get(key), link: mapLinkPath(sat, MAP_WAN_W / 2, jh, MAP_CARD_W / 2) }]
|
||||
return [{ edge, key, sp, merged, jh, link: mapLinkPath(sat, MAP_WAN_W / 2, jh, MAP_CARD_W / 2) }]
|
||||
})
|
||||
const wanLabels = wanLinks.flatMap(({ edge, key, sp, merged, jh, flow, link }) => {
|
||||
const wanLabels = wanLinks.flatMap(({ edge, key, sp, merged, jh, link }) => {
|
||||
const vis = filter === "all" || filter === "home-router" || filter === "jump-host" || filter === "online"
|
||||
const hl = selected?.id === edge.homeId && (selWanIdx === null || selWanIdx === edge.wanIdx)
|
||||
const suppressed = merged.hasSpeedMonitor ? suppressWanJhSpeedBadgeDuplicate.has(key) : suppressWanJhPingBadge.has(key)
|
||||
const rtt = showPingBadges && !suppressed ? rttLabel(merged.pingMs) : ""
|
||||
const rate = showNetflow && hopHasRate(flow) ? formatNetflowRate(flow!) : ""
|
||||
const texts = [...new Set([[rtt, rate].filter(Boolean).join(" · "), rtt || rate].filter(Boolean))]
|
||||
if (!texts.length) return []
|
||||
const hasDetail = merged.hasSpeedMonitor || hopHasRate(flow)
|
||||
if (!rtt) return []
|
||||
return [{
|
||||
id: "wan:" + key, link, texts, opacity: vis ? (hl ? 1 : 0.6) : 0.05,
|
||||
tone: merged.pingMs == null && !rate ? "mu" as const : "fg" as const,
|
||||
id: "wan:" + key, link, texts: [rtt], opacity: vis ? (hl ? 1 : 0.6) : 0.05,
|
||||
tone: "fg" as const,
|
||||
name: `${homeRouters.find((r) => r.id === edge.homeId)?.wanUplinks?.[edge.wanIdx]?.name ?? "WAN"} → ${jh.name}`,
|
||||
hint: sp ? "Проба " + sp.id + ". Клик — панель справа." : "WAN → JumpHost: latency из каталога (дом + JH), не RTT по GRE.",
|
||||
open: hasDetail ? (ev: React.SyntheticEvent<SVGElement>) => openWanJhSpeedDetail(ev, edge) : undefined,
|
||||
hint: sp ? "Проба " + sp.id + ". Клик — панель справа." : "WAN → JumpHost: задержка из каталога.",
|
||||
open: merged.hasSpeedMonitor ? (ev: React.SyntheticEvent<SVGElement>) => openWanJhSpeedDetail(ev, edge) : undefined,
|
||||
}]
|
||||
})
|
||||
const destHalfW = (expandedCountryGroup ? MAP_SERVICE_COMPACT_W : MAP_SERVICE_NODE_W) / 2
|
||||
@@ -1957,11 +2005,13 @@ function NetworkMapContent() {
|
||||
return { id: e.id, ts: eventsAt - (m ? Number(m[1]) * unitMs[m[2]] : 0), ...eventTone(e.sev === "destructive" ? "critical" : e.sev), title: e.title, message: e.message }
|
||||
})
|
||||
).filter(e => Number.isFinite(e.ts)).sort((a, b) => b.ts - a.ts)
|
||||
const flowRows = [...destPaths].sort((a, b) => b.bps - a.bps).slice(0, 100).map(p => ({
|
||||
const filterService = liveSelectedService?.id === filteredServiceId ? liveSelectedService : null
|
||||
const tablePaths = filterService ? (selectedNestedService ? expandedCountryGroup?.paths ?? [] : destPaths).filter(p => p.serviceId === filterService.id) : destPaths
|
||||
const flowRows = [...tablePaths].sort((a, b) => b.bps - a.bps).slice(0, 100).map(p => ({
|
||||
id: servicePathKey(p),
|
||||
client: p.clientName || p.viaName || p.viaId,
|
||||
exit: p.enName || p.enId,
|
||||
dest: destDisplayLabel(destNodes.find(svc => svc.id === p.serviceId), destMode, p.serviceId),
|
||||
client: p.clientId === "—" ? "Без привязки" : p.clientName,
|
||||
exit: p.enName || p.enId || `IPFIX · ${p.viaName || p.viaId}`,
|
||||
dest: filterService?.label ?? destDisplayLabel(destNodes.find(svc => svc.id === p.serviceId), destMode, p.serviceId),
|
||||
rate: rateOf(p.bytes, p.bps),
|
||||
volume: formatBytes(p.bytes),
|
||||
hl: Boolean(selected && (p.viaId === selected.id || p.enId === selected.id)) || selectedService?.id === p.serviceId,
|
||||
@@ -1992,7 +2042,7 @@ function NetworkMapContent() {
|
||||
const mapHeadSub = (
|
||||
<>
|
||||
<span>{useLiveData ? (readAt ? `Live · снимок API ${new Date(readAt).toLocaleTimeString("ru-RU")}` : "Данные карты неизвестны") : "Демо · mock"}</span>
|
||||
{useLiveData ? <>{" · "}<span>{showNetflow || showServices ? (flowReadAt ? `NetFlow · ${mapWindowSec / 60} мин${mapWindowSec < 300 ? " из 5 запрошенных" : ""} · ответ ${new Date(flowReadAt).toLocaleTimeString("ru-RU")} · ${flowListener ? "приёмник включён" : "приёмник выключен"}` : "Данные NetFlow неизвестны") : "NetFlow: отображение и обновление выключены"}</span></> : null}
|
||||
{useLiveData ? <>{" · "}<span>{showNetflow || showServices ? (flowReadAt ? `NetFlow · ${mapWindow}${mapWindowSec >= 120 && mapWindowSec < 300 ? " из 5 запрошенных" : ""} · ответ ${new Date(flowReadAt).toLocaleTimeString("ru-RU")} · ${flowListener ? "приёмник включён" : "приёмник выключен"}` : "Данные NetFlow неизвестны") : "NetFlow: отображение и обновление выключены"}</span></> : null}
|
||||
{" · "}
|
||||
<span>{`${mapServers.length} ${ruPlural(mapServers.length, "узел", "узла", "узлов")}, ${mapLinkCount} ${ruPlural(mapLinkCount, "связь", "связи", "связей")}, ${visibleMapServices.length} ${ruPlural(visibleMapServices.length, "назначение", "назначения", "назначений")}`}</span>
|
||||
</>
|
||||
@@ -2003,7 +2053,8 @@ function NetworkMapContent() {
|
||||
...visibleMapServices.filter((d) => !sq || destDisplayLabel(d, destMode).toLowerCase().includes(sq)).map((d) => ({ key: "d:" + d.id, label: destDisplayLabel(d, destMode), sub: `${destMode === "countries" ? "Страна" : d.category || "Сервис"} · ${formatNetflowRate({ bps: d.bps })}`, dot: "var(--chart-4)", pick: () => selectService(d) })),
|
||||
].slice(0, 8) : []
|
||||
const statusFilterLabel = ({ online: "Онлайн", degraded: "Внимание", offline: "Оффлайн", unknown: "Неизвестно", "jump-host": "JumpHost", "exit-node": "Exit Node", "home-router": "Home Router" } as Record<string, string>)[filter]
|
||||
const bottomStat = `Окно ${Math.round(mapWindowSec / 60)} мин${flowReadAt ? " · " + new Date(flowReadAt).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }) : ""}${selected || selectedService || selectedGreEdge ? " · строки выбранного объекта подсвечены" : ""}`
|
||||
const bottomStat = `Окно ${mapWindow}${flowReadAt ? " · " + new Date(flowReadAt).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }) : ""}${filterService && bottomTab === "flows" ? " · фильтр: " + filterService.label : selected || selectedService || selectedGreEdge ? " · строки выбранного объекта подсвечены" : ""}`
|
||||
const refreshBusy = dataLoading || flowLoading && (showNetflow || showServices)
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full min-h-0 min-w-0 [&_button]:focus-visible:outline-2 [&_button]:focus-visible:outline-ring [&_button]:focus-visible:outline-offset-2">
|
||||
@@ -2017,8 +2068,8 @@ function NetworkMapContent() {
|
||||
actions={
|
||||
<>
|
||||
{useLiveData && (
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => {void loadLive();setFlowRefresh(value=>value+1)}} disabled={dataLoading}>
|
||||
<RefreshCwIcon aria-hidden="true" className={cn("size-4", dataLoading && "animate-spin")} />
|
||||
<Button type="button" variant="outline" size="sm" aria-busy={refreshBusy} title={refreshBusy ? "Данные карты обновляются" : "Обновить данные карты"} onClick={() => {void loadLive();setFlowRefresh(value=>value+1)}} disabled={refreshBusy}>
|
||||
{refreshBusy ? <Spinner aria-hidden="true" className="size-4 motion-reduce:animate-none" /> : <RefreshCwIcon aria-hidden="true" className="size-4" />}
|
||||
Обновить
|
||||
</Button>
|
||||
)}
|
||||
@@ -2033,7 +2084,8 @@ function NetworkMapContent() {
|
||||
servers={mapServers}
|
||||
tunnels={mapGreTunnels}
|
||||
downRoutes={[...new Set(greEdges.filter((e) => e.tunnel.status === "down").map((e) => `${mapCardName(e.fromServer.name, 999).text} → ${mapCardName(e.toServer.name, 999).text}`))]}
|
||||
exits={[...destEdges.reduce((m, e) => m.set(e.fromId, (m.get(e.fromId) ?? 0) + e.bps), new Map<string, number>())].map(([id, bps]) => ({ name: mapCardName(mapServers.find((s) => s.id === id)?.name ?? id, 999).text, bps }))}
|
||||
exits={[...destEdges.filter(e => !e.observedOnly).reduce((m, e) => m.set(e.fromId, (m.get(e.fromId) ?? 0) + e.bps), new Map<string, number>())].map(([id, bps]) => ({ name: mapCardName(mapServers.find((s) => s.id === id)?.name ?? id, 999).text, bps }))}
|
||||
liveLink={busiestLiveLink}
|
||||
netflowBytes={mapTotalBytes > 0 ? mapTotalBytes : useLiveData && flowReadAt ? 0 : null}
|
||||
windowSec={mapWindowSec}
|
||||
filter={filter}
|
||||
@@ -2177,10 +2229,8 @@ function NetworkMapContent() {
|
||||
</FramePanel>
|
||||
|
||||
{/* Состояние данных: загрузка и ошибки снимка, NetFlow и DNS */}
|
||||
{(dataLoading || dataError || (useLiveData && ((showNetflow || showServices) && (flowLoading || flowError) || dnsError))) ? (
|
||||
{(dataError || (useLiveData && ((showNetflow || showServices) && flowError || dnsError))) ? (
|
||||
<div className="flex shrink-0 flex-col gap-1 px-1.5 text-xs">
|
||||
{dataLoading && <span role="status" className="text-muted-foreground">Обновление снимка карты…</span>}
|
||||
{useLiveData&&flowLoading&&(showNetflow||showServices)&&<span role="status" className="text-muted-foreground">Обновление NetFlow…</span>}
|
||||
{dataError && <p role="alert" className="border-destructive/40 bg-destructive/10 text-destructive rounded-md border px-3 py-1.5 [overflow-wrap:anywhere]">{dataError}. {hasSnapshot ? "Последний полный снимок; актуальность не подтверждена." : "Первоначальная загрузка карты не подтверждена."}</p>}
|
||||
{useLiveData&&flowError&&(showNetflow||showServices)&&<p role="alert" className="border-destructive/40 bg-destructive/10 text-destructive rounded-md border px-3 py-1.5 [overflow-wrap:anywhere]">NetFlow: {flowError}. {flowReadAt?"Сохранён предыдущий снимок NetFlow; актуальность не подтверждена.":"Первоначальная загрузка NetFlow не подтверждена."}</p>}
|
||||
{useLiveData&&dnsError&&<p role="alert" className="border-destructive/40 bg-destructive/10 text-destructive rounded-md border px-3 py-1.5 [overflow-wrap:anywhere]">DNS: {dnsError}. Связи по неизвестному адресу не подтверждены.</p>}
|
||||
@@ -2228,10 +2278,11 @@ function NetworkMapContent() {
|
||||
</g>
|
||||
))}
|
||||
|
||||
{/* ── Ленты NetFlow: Exit → назначения (толщина — скорость) ── */}
|
||||
{/* Ленты NetFlow от выходов и экспортёров к назначениям. */}
|
||||
{destRibbons.map(({ edge, d, w }) => {
|
||||
const hop = destinationRate(edge)
|
||||
const pathHit = Boolean(highlightedPath && highlightedPath.enId === edge.fromId && highlightedPath.serviceId === edge.toId)
|
||||
const selectedDestinationId = highlightedPath?.serviceId.split("|")[0]
|
||||
const pathHit = Boolean(highlightedPath && (highlightedPath.enId || highlightedPath.viaId) === edge.fromId && selectedDestinationId === edge.toId)
|
||||
const hl = pathHit || (!highlightedPath && (selectedService?.id === edge.toId || selected?.id === edge.fromId || expandedCountryId === edge.toId))
|
||||
const countryDim = !hl && Boolean(expandedCountryGroup) && edge.toId !== expandedCountryId
|
||||
const svc = visibleMapServices.find((s) => s.id === edge.toId)
|
||||
@@ -2239,12 +2290,14 @@ function NetworkMapContent() {
|
||||
const clientLabel = edge.clients?.map((c) => c.name).filter(Boolean).join(", ") || edge.clientName || "—"
|
||||
const rate = hopHasRate(hop) ? ` · ${formatNetflowRate(hop)} (${formatNetflowDir(hop)})` : ""
|
||||
return (
|
||||
<g key={`${edge.fromId}|${edge.toId}`} data-map-ribbon opacity={highlightedPath && !pathHit ? 0.08 : hl ? 0.75 : countryDim ? 0.12 : 0.42}
|
||||
<g key={`${edge.fromId}|${edge.toId}`} data-map-ribbon data-observation={edge.observedOnly || undefined} opacity={highlightedPath && !pathHit ? 0.08 : hl ? 0.75 : countryDim ? 0.12 : 0.42}
|
||||
style={{ transition: "opacity 0.3s", cursor: "pointer" }}
|
||||
onPointerDown={(ev) => { ev.stopPropagation() }}
|
||||
onClick={(ev) => { ev.stopPropagation(); if (svc) selectService(svc) }}>
|
||||
<title>{`${clientLabel} → ${enName} → ${destDisplayLabel(svc, destMode, edge.toId)}${rate}`}</title>
|
||||
<path d={d} fill="none" stroke="var(--chart-4)" strokeWidth={w} />
|
||||
<title>{edge.observedOnly
|
||||
? `Наблюдение IPFIX · ${enName} → ${destDisplayLabel(svc, destMode, edge.toId)}${rate} · выход не подтверждён`
|
||||
: `${clientLabel} → ${enName} → ${destDisplayLabel(svc, destMode, edge.toId)}${rate}`}</title>
|
||||
<path d={d} fill="none" stroke="var(--chart-4)" strokeWidth={w} strokeDasharray={edge.observedOnly ? "7 4" : undefined} />
|
||||
<path d={d} fill="none" stroke="transparent" strokeWidth={Math.max(12, w)} />
|
||||
{showAnimDots && !reducedMotion && hopHasRate(hop) && (
|
||||
<circle r="2.5" fill="var(--foreground)" opacity="0.7" pointerEvents="none">
|
||||
@@ -2367,11 +2420,14 @@ function NetworkMapContent() {
|
||||
const isActive = wanJhEdges.filter(e => e.homeId === router.id && e.wanIdx === wIdx).some(e => e.active)
|
||||
const isSatSel = selected?.id === router.id && selWanIdx === wIdx
|
||||
const satKey = `${router.id}-${wIdx}`
|
||||
const live = showNetflow ? getInterfaceLiveRate(`wan:${router.id}:${wIdx}`) : undefined
|
||||
const flow = netflowByWanKey.get(`${router.id}\t${wIdx}`)
|
||||
return (
|
||||
<g key={`${router.id}-wan-${wIdx}`} opacity={vis ? 1 : 0.06} style={{ transition: "opacity 0.3s" }}>
|
||||
<WanSatNode
|
||||
x={sat.x} y={sat.y} wan={wan} color={color}
|
||||
active={isActive} isSel={isSatSel}
|
||||
traffic={live ? `Live ${formatNetflowRate(live)}` : flow ? `≈${formatNetflowRate(flow)}` : undefined}
|
||||
isDragged={draggedSatKey === satKey}
|
||||
onSelect={() => {
|
||||
if (suppressClickRef.current) { suppressClickRef.current = false; return }
|
||||
@@ -2529,7 +2585,7 @@ function NetworkMapContent() {
|
||||
</Frame>
|
||||
|
||||
{/* ── Инспектор: узел, связь или назначение ── */}
|
||||
<Frame spacing="sm" className={cn("min-w-0 shrink-0 lg:sticky lg:top-3 lg:max-h-[calc(100svh-5rem)] lg:w-80 lg:self-start", !(selectedGreEdge || selected || selectedService) && "max-lg:hidden")}>
|
||||
<Frame spacing="sm" className={cn("min-w-0 shrink-0 lg:sticky lg:top-3 lg:max-h-[calc(100svh-5rem)] lg:self-start", selected || selectedService ? "lg:w-72" : "lg:w-80", !(selectedGreEdge || selected || selectedService) && "max-lg:hidden")}>
|
||||
<FramePanel className="flex min-h-0 flex-1 flex-col overflow-hidden p-0">
|
||||
{!(selectedGreEdge || selected || selectedService) && (
|
||||
<div className="text-muted-foreground flex flex-1 flex-col items-center justify-center gap-2 px-5 py-8 text-center text-[13px]">
|
||||
@@ -2639,7 +2695,7 @@ function NetworkMapContent() {
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">NetFlow · {mapWindowSec / 60} мин{greFlow?.source === "retained" ? " · выборка" : ""}</span>
|
||||
<span className="text-xs text-muted-foreground">NetFlow · {mapWindow}{greFlow?.source === "retained" ? " · выборка" : ""}</span>
|
||||
<span className="text-xs font-mono">{greFlow?.inWindow ? formatNetflowDir(greFlow) : missingNetflow}</span>
|
||||
</div>
|
||||
{greFlow?.inWindow && greFlow.packets !== undefined && <p className="text-xs text-muted-foreground">
|
||||
@@ -2648,14 +2704,14 @@ function NetworkMapContent() {
|
||||
{greFlow?.lastBucketAt && <p className="text-xs text-muted-foreground">Последняя минута с данными · {new Date(greFlow.lastBucketAt).toLocaleString("ru-RU")}</p>}
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">Live GRE · RX/TX сейчас</span>
|
||||
<span className="text-xs font-mono">{liveRate ? formatNetflowDir(liveRate) : "Нет замера"}</span>
|
||||
<span className="text-xs font-mono" title={liveRate ? `Ответ RouterOS · ${new Date(liveRate.at).toLocaleTimeString("ru-RU")}` : undefined}>{liveRate ? formatNetflowDir(liveRate) : "Нет замера"}</span>
|
||||
</div>
|
||||
<p className="text-[10px] text-muted-foreground pt-2 leading-snug">
|
||||
{merged.hasSpeedMonitor
|
||||
? "Ping и/или TX/RX — с последнего прогона speed-пробы; проба сопоставляется с этим GRE по WAN и интерфейсам. "
|
||||
: useLiveData?"Измерения GRE неизвестны: нет подходящей пробы. ":"Измерения демонстрационные. "}
|
||||
{spGr?"Проба "+spGr.id+" · время Ping: "+(spGr.lastPingAt?new Date(spGr.lastPingAt).toLocaleString("ru-RU"):"неизвестно")+" · время TX/RX неизвестно. ":""}
|
||||
Скорости RX/TX указаны со стороны {tunnelOwner.name}.{greFlow?.peerObservation ? " NetFlow получен с противоположного конца туннеля." : ""}
|
||||
Скорости RX/TX указаны со стороны {tunnelOwner.name}.{greFlow?.peerObservation ? " NetFlow получен с противоположного конца туннеля." : ""}{liveRate?.peerObservation ? " Live получен с противоположного конца туннеля." : ""}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -2746,70 +2802,20 @@ function NetworkMapContent() {
|
||||
})()}
|
||||
</div>
|
||||
</>
|
||||
) : selectedNestedService ? (
|
||||
<>
|
||||
<div className="flex items-start gap-2 px-4 py-3 border-b">
|
||||
<div className="mt-0.5">
|
||||
<ServiceBrandIcon aria-hidden="true" label={selectedNestedService.label} size={22} />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-mono font-semibold text-sm [overflow-wrap:anywhere]">
|
||||
{selectedNestedService.label}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{`Сервис в ${destDisplayLabel(expandedCountry ?? undefined, "countries")} · ${selectedNestedService.category}`}
|
||||
</p>
|
||||
</div>
|
||||
<button type="button"
|
||||
aria-label="Закрыть детали назначения" onClick={() => {setSelectedService(null);returnToMapControl()}}
|
||||
className="text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<XIcon aria-hidden="true" className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex-1 min-h-0 overflow-y-auto px-4 py-4 flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-0">
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">Доля страны</span>
|
||||
<span className="text-xs font-mono font-medium text-cyan-400">{serviceSharePct(selectedNestedService.share)}</span>
|
||||
</div>
|
||||
{mapTotalBytes > 0 && (
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">Доля окна</span>
|
||||
<span className="text-xs font-mono font-medium text-cyan-400">
|
||||
{serviceSharePct(selectedNestedService.bytes / mapTotalBytes)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">Скорость</span>
|
||||
<span className="text-xs font-mono font-medium [overflow-wrap:anywhere] text-right">
|
||||
{formatNetflowRate({
|
||||
bytes: selectedNestedService.bytes,
|
||||
bps: selectedNestedService.bps,
|
||||
bpsFwd: selectedNestedService.bps,
|
||||
bpsRev: 0,
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground mb-2">Выход</p>
|
||||
<ServicePathList
|
||||
paths={(expandedCountryGroup?.paths ?? [])
|
||||
.filter((p) => p.serviceId === selectedNestedService.id)
|
||||
.slice()
|
||||
.sort((a, b) => b.bps - a.bps)}
|
||||
servers={mapServers}
|
||||
services={nestedServices}
|
||||
highlight={highlightedPath}
|
||||
viaMode="via"
|
||||
destMode="services"
|
||||
onToggle={togglePathHighlight}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : liveSelectedService && (destMode === "services" || selectedNestedService) ? (
|
||||
<ServiceInspector key={liveSelectedService.id} service={liveSelectedService}
|
||||
paths={selectedDestPaths}
|
||||
exits={selectedNestedService ? [] : selectedDestEdges}
|
||||
exitName={id => mapServers.find(s => s.id === id)?.name ?? id}
|
||||
country={selectedNestedService ? expandedCountry?.label : undefined}
|
||||
base={useLiveData ? backendUrl : null} refresh={flowRefresh} windowLabel={mapWindow} flowAt={flowReadAt} stale={Boolean(flowError)}
|
||||
activePath={highlightedPath} onPath={togglePathHighlight}
|
||||
onClose={() => { setSelectedService(null); returnToMapControl() }}
|
||||
filtered={Boolean(filterService)} onFilter={() => {
|
||||
setFilteredServiceId(filterService ? null : liveSelectedService.id)
|
||||
setBottomTab("flows")
|
||||
}}
|
||||
/>
|
||||
) : liveSelectedService ? (
|
||||
<>
|
||||
<div className="flex items-start gap-2 px-4 py-3 border-b">
|
||||
@@ -2843,7 +2849,7 @@ function NetworkMapContent() {
|
||||
</div>
|
||||
{mapTotalBytes > 0 && (
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">Классифицировано</span>
|
||||
<span className="text-xs text-muted-foreground">Распознаны сервисы</span>
|
||||
<span className="text-xs font-mono font-medium text-cyan-400">
|
||||
{formatNetflowRate({
|
||||
bytes: mapNamedBytes,
|
||||
@@ -2874,7 +2880,7 @@ function NetworkMapContent() {
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">Скорость по сохранённым потокам</span>
|
||||
<span className="text-xs text-muted-foreground">Средняя скорость NetFlow</span>
|
||||
<span className="text-xs font-mono font-medium [overflow-wrap:anywhere] text-right">
|
||||
{formatNetflowRate({
|
||||
bytes: liveSelectedService.bytes,
|
||||
@@ -2885,6 +2891,7 @@ function NetworkMapContent() {
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<InspectorUsers users={serviceUsers(liveSelectedService, selectedDestPaths)} windowLabel={mapWindow} />
|
||||
{expandedCountryGroup && liveSelectedService.id === expandedCountryGroup.countryId && (
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground mb-2">Сервисы в стране</p>
|
||||
@@ -2909,7 +2916,7 @@ function NetworkMapContent() {
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground mb-2">Выход</p>
|
||||
<p className="text-xs font-semibold text-muted-foreground mb-2">Выходы и наблюдения</p>
|
||||
<div className="flex flex-col gap-3">
|
||||
{unassignedBytes > 0 && (
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
@@ -2917,16 +2924,13 @@ function NetworkMapContent() {
|
||||
<span className="font-mono">{formatNetflowRate({ bps: liveSelectedService.bps * unassignedBytes / liveSelectedService.bytes })}</span>
|
||||
</div>
|
||||
)}
|
||||
{selectedExitEdges.map((e) => {
|
||||
{selectedDestEdges.map((e) => {
|
||||
const src = mapServers.find((s) => s.id === e.fromId)
|
||||
const enPaths = destPaths
|
||||
.filter((p) => p.serviceId === liveSelectedService.id && p.enId === e.fromId)
|
||||
.slice()
|
||||
.sort((a, b) => b.bps - a.bps)
|
||||
const enPaths = selectedDestPaths.filter(p => (p.enId || p.viaId) === e.fromId)
|
||||
return (
|
||||
<div key={`${e.fromId}|${e.toId}`} className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
<span className="font-mono truncate">{src?.name ?? e.fromId}</span>
|
||||
<span className="font-mono truncate">{src?.name ?? e.fromId}{e.observedOnly && " · IPFIX"}</span>
|
||||
<span className="font-mono text-emerald-400 tabular-nums">
|
||||
{formatNetflowRate({ bytes: e.bytes, bps: e.bps, bpsFwd: e.bpsFwd, bpsRev: e.bpsRev })}
|
||||
</span>
|
||||
@@ -2949,96 +2953,92 @@ function NetworkMapContent() {
|
||||
</>
|
||||
) : selected ? (
|
||||
<>
|
||||
<div className="flex items-center gap-2.5 border-b py-2.5 pr-1.5 pl-3">
|
||||
<span aria-hidden="true" className="inline-flex size-9 shrink-0 items-center justify-center rounded-md font-mono text-xs font-semibold" style={{ color: TYPE_STYLE[selected.type].fill, background: `color-mix(in oklch, ${TYPE_STYLE[selected.type].fill} 18%, transparent)` }}>{TYPE_STYLE[selected.type].label}</span>
|
||||
<header className="flex items-center gap-2 py-3 pr-1.5 pl-3">
|
||||
<span aria-hidden className="inline-flex size-8 shrink-0 items-center justify-center rounded-md font-mono text-[11px] font-semibold" style={{ color: TYPE_STYLE[selected.type].fill, background: `color-mix(in oklch, ${TYPE_STYLE[selected.type].fill} 18%, transparent)` }}>{TYPE_STYLE[selected.type].label}</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-[15px] leading-tight font-semibold" title={selected.name}>{selected.name}</p>
|
||||
<p className="text-muted-foreground mt-0.5 truncate text-xs" title={selected.host}>{TYPE_LABELS[selected.type]} · {selected.site || "—"} · {selected.host}</p>
|
||||
<h2 className="truncate text-sm font-semibold" title={selected.name}>{selected.name}</h2>
|
||||
<p className="truncate text-[11px] text-muted-foreground" title={selected.host}>{TYPE_LABELS[selected.type]} · {selected.country?.toUpperCase() || selected.site} · {selected.host}</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
<StatusBadge status={selected.status} />
|
||||
<button type="button" aria-label="Закрыть детали устройства" onClick={() => { setSelected(null); setSelWanIdx(null); returnToMapControl() }}
|
||||
className="text-muted-foreground hover:text-foreground transition-colors">
|
||||
<XIcon aria-hidden="true" className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<StatusBadge status={selected.status} />
|
||||
<Button size="icon-xs" variant="ghost" aria-label="Закрыть детали устройства" onClick={() => { setSelected(null); setSelWanIdx(null); returnToMapControl() }}><XIcon /></Button>
|
||||
</header>
|
||||
|
||||
<Tabs key={selected.id} defaultValue="over" className="flex min-h-0 flex-1 flex-col gap-0">
|
||||
<TabsList aria-label="Разделы панели" className="mx-3 mt-2.5 self-start">
|
||||
<TabsList aria-label="Разделы панели" className="mx-1 mb-1.5 self-start">
|
||||
<TabsTrigger value="over" className="px-2.5">Обзор</TabsTrigger>
|
||||
<TabsTrigger value="ifaces" className="px-2.5">Интерфейсы</TabsTrigger>
|
||||
<TabsTrigger value="gre" className="px-2.5">GRE<Badge variant="secondary" size="sm" className="font-mono">{connectedTunnels.length}</Badge></TabsTrigger>
|
||||
<TabsTrigger value="gre" className="px-2.5">GRE</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="over" className="flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto px-4 py-4">
|
||||
<TabsContent value="over" className="mx-0.5 mb-0.5 min-h-0 flex-1 overflow-y-auto rounded-lg border">
|
||||
{(() => {
|
||||
const ifs = (interfaceTraffic ?? []).filter(t => t.serverId === selected.id && t.inWindow)
|
||||
const rate = (bytes: number) => ifs.length ? rateOf(bytes, (bytes * 8) / mapWindowSec) : "—"
|
||||
const sessions = useLiveData ? (sessionCounts[selected.id] == null ? "—" : String(sessionCounts[selected.id])) : String(selected.sessions)
|
||||
return (
|
||||
<div className="bg-border -mx-4 -mt-4 grid grid-cols-2 gap-px border-b">
|
||||
{[
|
||||
["RTT", selected.latency == null ? "—" : `${selected.latency} мс`],
|
||||
["Сессии", sessions],
|
||||
["Входящий", rate(ifs.reduce((sum, t) => sum + t.rxBytes, 0))],
|
||||
["Исходящий", rate(ifs.reduce((sum, t) => sum + t.txBytes, 0))],
|
||||
].map(([k, v]) => (
|
||||
<div key={k} className="bg-card flex min-w-0 flex-col gap-0.5 px-3.5 py-2.5">
|
||||
<small className="text-muted-foreground text-xs">{k}</small>
|
||||
<b className="truncate font-mono text-[15px] font-medium">{v}</b>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
const lossProbe = speedProbes.filter(p => p.enabled && p.dstServerId === selected.id && p.lastPingAt && p.lastPingLossPct != null)
|
||||
.sort((a,b) => Date.parse(b.lastPingAt!) - Date.parse(a.lastPingAt!))[0]
|
||||
const live = !selectedNodeTraffic.error && isFreshMapTrafficSample(selectedNodeTraffic.sample) ? selectedNodeTraffic.sample : null
|
||||
const rateLabel = live ? " · Live" : ifs.length ? " · NetFlow" : ""
|
||||
const rateSource = live ? `RouterOS · ответ ${new Date(live.at).toLocaleString("ru-RU")}`
|
||||
: `Средняя по NetFlow · ${mapWindow}${flowReadAt ? " · ответ " + new Date(flowReadAt).toLocaleString("ru-RU") : ""}`
|
||||
return <InspectorMetrics rows={[
|
||||
["RTT", selected.latency == null ? "—" : selected.latency + " мс", "Последний опрос устройства"],
|
||||
["Потери", lossProbe ? lossProbe.lastPingLossPct + "%" : "—", lossProbe ? `Ping-проба ${lossProbe.id} → ${selected.name} · ${new Date(lossProbe.lastPingAt!).toLocaleString("ru-RU")}` : "Нет измерения потерь до устройства"],
|
||||
["Входящий" + rateLabel, live ? formatNetflowRate({ bps: live.rxMbps * 1_000_000 }) : rate(ifs.reduce((sum, t) => sum + t.rxBytes, 0)), rateSource],
|
||||
["Исходящий" + rateLabel, live ? formatNetflowRate({ bps: live.txMbps * 1_000_000 }) : rate(ifs.reduce((sum, t) => sum + t.txBytes, 0)), rateSource],
|
||||
]} />
|
||||
})()}
|
||||
<NodeHistory key={selected.id} id={selected.id} base={useLiveData ? backendUrl : null} refresh={flowRefresh} degraded={selected.status === "degraded"} />
|
||||
<InspectorUsers users={mapNodeUsers && (mapNodeUsers[selected.id] ?? [])} windowLabel={mapWindow} />
|
||||
{(() => {
|
||||
const res = srvResMap[selected.id]
|
||||
const ram = res?.ramUsed != null && res.ramTotal ? Math.round(res.ramUsed / res.ramTotal * 100) : null
|
||||
return <section className="border-b px-3.5 py-3">
|
||||
<h3 className="mb-2 text-right font-mono text-[11px] text-muted-foreground">Устройство</h3>
|
||||
<dl className="grid grid-cols-2 gap-x-3.5 gap-y-2.5">
|
||||
{([
|
||||
["Адрес",selected.host], ["Аптайм",fmtUptime(res?.uptimeSeconds ?? null)],
|
||||
["CPU · RAM",<><span>{res?.cpu != null ? res.cpu + "%" : "—"}</span> · <span>{ram != null ? ram + "%" : "—"}</span></>], ["RouterOS",selected.os],
|
||||
["Последний опрос", selected.polledAt ? <time dateTime={selected.polledAt} title={new Date(selected.polledAt).toLocaleString("ru-RU")}>{new Date(selected.polledAt).toLocaleTimeString("ru-RU")}</time> : "—"],
|
||||
["Закреплён",nodePositions[selected.id] ? "да" : "нет"],
|
||||
] as const).map(([k,v]) => <div key={k} className="min-w-0"><dt className="text-[11px] text-muted-foreground">{k}</dt><dd className="mt-0.5 font-mono text-xs font-semibold [overflow-wrap:anywhere]">{v || "—"}</dd></div>)}
|
||||
</dl>
|
||||
</section>
|
||||
})()}
|
||||
{selected.type === "jump-host" && (() => {
|
||||
const exitIds = new Set(destPaths.filter(p => p.viaId === selected.id).map(p => p.enId))
|
||||
for (const e of greEdges) {
|
||||
if (e.fromServer.id === selected.id) exitIds.add(e.toServer.id)
|
||||
if (e.toServer.id === selected.id) exitIds.add(e.fromServer.id)
|
||||
}
|
||||
const exits = mapServers.filter(s => s.type === "exit-node" && exitIds.has(s.id))
|
||||
return <section className="border-b px-3.5 py-3"><h3 className="mb-2 flex justify-between font-mono text-[11px] text-muted-foreground"><span>Exit-узлы за JumpHost</span><span>{exits.length}</span></h3>
|
||||
{exits.map(s => <button type="button" key={s.id} onClick={() => selectServer(s)} className="flex w-full items-center gap-2 rounded py-1.5 text-left hover:bg-muted"><StatusDot status={s.status} />
|
||||
<span className="min-w-0 flex-1"><b className="block truncate text-xs font-medium">{s.name}</b><span className="block text-[11px] text-muted-foreground">Exit Node · {s.country}</span></span>
|
||||
<span title="Статус и задержка устройства по последнему опросу" className="shrink-0 font-mono text-[11px] text-muted-foreground">{s.status === "offline" ? "нет связи" : s.latency == null ? "—" : s.latency + " мс"}</span>
|
||||
</button>)}
|
||||
{!exits.length && <p className="text-xs text-muted-foreground">Связи с Exit-узлами не найдены</p>}
|
||||
</section>
|
||||
})()}
|
||||
{selected.type === "exit-node" && (() => {
|
||||
const destinations = destEdges.filter(e => e.fromId === selected.id).sort((a,b) => b.bps - a.bps)
|
||||
const sum = destinations.reduce((n, e) => n + e.bytes, 0)
|
||||
return <section className="border-b px-3.5 py-3"><h3 className="mb-2 flex justify-between font-mono text-[11px] text-muted-foreground"><span>Назначения через узел</span><span>{destinations.length}</span></h3>
|
||||
{destinations.map(e => {
|
||||
const svc = destNodes.find(s => s.id === e.toId)
|
||||
return <button type="button" key={e.toId} disabled={!svc} onClick={() => svc && selectService(svc)} className="flex w-full items-center gap-2 rounded py-1.5 text-left hover:bg-muted">
|
||||
<span aria-hidden className="size-1.5 shrink-0 rounded-full bg-chart-4" /><span className="min-w-0 flex-1"><b className="block truncate text-xs font-medium">{destDisplayLabel(svc, destMode, e.toId)}</b><span className="block text-[11px] text-muted-foreground">{destMode === "countries" ? "Страна" : svc?.category}</span><span className="mt-1 block h-1 overflow-hidden rounded-full bg-muted"><span className="block h-full rounded-full bg-chart-4" style={{width:(sum ? e.bytes / sum * 100 : 0) + "%"}} /></span></span>
|
||||
<span className="shrink-0 font-mono text-[11px] text-muted-foreground">{formatNetflowRate(e)}</span>
|
||||
</button>
|
||||
})}
|
||||
{!destinations.length && <p className="text-xs text-muted-foreground">Нет назначений с подтверждённым выходом через узел</p>}
|
||||
</section>
|
||||
})()}
|
||||
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground mb-2">Устройство</p>
|
||||
<dl className="grid grid-cols-2 gap-x-3.5 gap-y-2.5">
|
||||
{[
|
||||
["Адрес", selected.host],
|
||||
["Площадка", selected.site],
|
||||
["Модель", selected.model],
|
||||
["RouterOS", selected.os],
|
||||
...(selected.type !== "home-router"
|
||||
? [["ASN", selected.asn], ["Сессий", useLiveData?(sessionCounts[selected.id]==null?"—":String(sessionCounts[selected.id])):String(selected.sessions)]]
|
||||
: [["LAN", selected.lanSubnet ?? "—"]]),
|
||||
].map(([k, v]) => (
|
||||
<div key={k} className="min-w-0">
|
||||
<dt className="text-xs text-muted-foreground">{k}</dt>
|
||||
<dd className="mt-0.5 font-mono text-[13px] [overflow-wrap:anywhere]">{v || "—"}</dd>
|
||||
</div>
|
||||
))}
|
||||
<div className="min-w-0">
|
||||
<dt className="text-xs text-muted-foreground">Задержка</dt>
|
||||
<dd className="mt-0.5 font-mono text-[13px]" style={{ color: latencyColor(selected.latency) }}>{selected.latency == null ? "—" : `${selected.latency} мс`}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
</div>
|
||||
|
||||
{(selected.type === "jump-host" || selected.type === "exit-node") && (
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground mb-2">Назначения через узел</p>
|
||||
<ServicePathList
|
||||
paths={destPaths
|
||||
.filter((p) => (
|
||||
selected.type === "exit-node"
|
||||
? p.enId === selected.id
|
||||
: p.viaId === selected.id
|
||||
))
|
||||
.slice()
|
||||
.sort((a, b) => b.bps - a.bps)}
|
||||
servers={mapServers}
|
||||
services={destNodes}
|
||||
highlight={highlightedPath}
|
||||
viaMode="service"
|
||||
destMode={destMode}
|
||||
onToggle={togglePathHighlight}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<details className="border-b px-3.5 py-2">
|
||||
<summary className="cursor-pointer text-[11px] text-muted-foreground">Ресурсы</summary>
|
||||
<dl className="mt-2 grid grid-cols-2 gap-2 text-xs">
|
||||
{Object.entries({"Площадка":selected.site, "Модель":selected.model, "Сессий":useLiveData ? sessionCounts[selected.id] : selected.sessions, ...(selected.type === "home-router" ? {LAN:selected.lanSubnet} : {ASN:selected.asn})}).map(([k,v]) => <div key={k}><dt className="text-muted-foreground">{k}</dt><dd className="font-mono [overflow-wrap:anywhere]">{v ?? "—"}</dd></div>)}
|
||||
</dl>
|
||||
|
||||
|
||||
{/* Resources */}
|
||||
@@ -3050,9 +3050,6 @@ function NetworkMapContent() {
|
||||
const hddPct = res.hddUsed==null||res.hddTotal==null||res.hddTotal===0?null:Math.round(res.hddUsed/res.hddTotal*100)
|
||||
return (
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground mb-1">
|
||||
Ресурсы
|
||||
</p>
|
||||
{!res.fromPoll && (
|
||||
<p className="text-[9px] text-muted-foreground mb-3 leading-snug">
|
||||
Нет снапшота опроса — показаны демо-значения. Включите опрос серверов или откройте «Серверы».
|
||||
@@ -3132,20 +3129,26 @@ function NetworkMapContent() {
|
||||
})()}
|
||||
|
||||
|
||||
{/* Действия узла — рядом кнопок, как в макете; «Действия устройства» — ещё и копирование адреса. */}
|
||||
<div role="group" aria-label="Переходы по устройству" className="-mx-4 -mb-4 flex flex-wrap gap-1.5 border-t px-3.5 py-3">
|
||||
<Button type="button" variant="ghost" size="xs" onClick={() => { const n = nodeById[selected.id]; if (n) focusNode(n.x, n.y) }}><HomeIcon />Навести на узел</Button>
|
||||
</details>
|
||||
<div role="group" aria-label="Переходы по устройству" className="flex flex-wrap gap-1.5 px-3.5 py-3">
|
||||
<Button type="button" variant="outline" size="xs" aria-pressed={Boolean(nodePositions[selected.id])} title="Закрепить координаты узла при автоматической раскладке" onClick={() => {
|
||||
setNodePositions(prev => {
|
||||
const next = { ...prev }
|
||||
if (next[selected.id]) delete next[selected.id]
|
||||
else next[selected.id] = nodePosById[selected.id]
|
||||
return next
|
||||
})
|
||||
}}>{nodePositions[selected.id] ? "Открепить" : "Закрепить"}</Button>
|
||||
{([
|
||||
["Терминал", `/terminal?host=${encodeURIComponent(selected.host)}`],
|
||||
["Терминал", `/terminal?server=${encodeURIComponent(selected.id)}`],
|
||||
["Firewall", `/firewall?server=${selected.id}`],
|
||||
["GRE-туннели", `/gre?server=${selected.id}`],
|
||||
["Трафик", `/traffic?server=${selected.id}`],
|
||||
] as const).map(([label, href]) => (
|
||||
<Button key={label} variant="outline" size="sm" nativeButton={false} render={<Link href={href} />}>{label}</Button>
|
||||
<Button key={label} variant="outline" size="xs" nativeButton={false} render={<Link href={href} />}>{label}</Button>
|
||||
))}
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => { const n = nodes.find(x => x.id === selected.id); if (n) focusNode(n.x, n.y) }}>
|
||||
<HomeIcon aria-hidden="true" />Навести на узел
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="sm" data-map-device-actions onClick={()=>setCtxMenu({x:0,y:0,server:selected})}>Действия устройства</Button>
|
||||
<Button type="button" variant="ghost" size="icon-xs" data-map-device-actions aria-label="Действия устройства" title="Действия устройства" onClick={()=>setCtxMenu({x:0,y:0,server:selected})}>•••</Button>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
@@ -3191,14 +3194,13 @@ function NetworkMapContent() {
|
||||
))}
|
||||
{(() => {
|
||||
const hop = netflowByWanKey.get(`${selected.id}\t${wIdx}`)
|
||||
if (!hopHasRate(hop)) return null
|
||||
const liveRate = showNetflow ? getInterfaceLiveRate(`wan:${selected.id}:${wIdx}`) : undefined
|
||||
if (!liveRate && !hopHasRate(hop)) return null
|
||||
return (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-[10px] text-muted-foreground">Поток</span>
|
||||
<span className="text-[10px] text-muted-foreground">{liveRate ? "RouterOS Live" : `NetFlow · ${mapWindow}`}</span>
|
||||
<span className="text-[10px] font-mono text-emerald-400">
|
||||
{hop.bpsFwd > 0 && hop.bpsRev > 0
|
||||
? formatNetflowDir(hop)
|
||||
: formatNetflowRate(hop)}
|
||||
{liveRate ? formatNetflowDir(liveRate) : formatNetflowRate(hop!)}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
@@ -3240,7 +3242,7 @@ function NetworkMapContent() {
|
||||
const rate = (bytes: number) => rateOf(bytes, (bytes * 8) / mapWindowSec)
|
||||
return (
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground mb-1">Трафик интерфейсов · окно {Math.round(mapWindowSec / 60)} мин</p>
|
||||
<p className="text-xs font-semibold text-muted-foreground mb-1">NetFlow по интерфейсам · {mapWindow}</p>
|
||||
{ifs.map(t => (
|
||||
<div key={t.iface} className="flex items-center justify-between gap-2 border-b py-2 text-xs last:border-b-0">
|
||||
<span className="font-mono font-medium">{t.iface}</span>
|
||||
@@ -3325,7 +3327,7 @@ function NetworkMapContent() {
|
||||
)}
|
||||
{greFlow && (
|
||||
<span className="text-[9px] ml-1.5 text-emerald-400">
|
||||
NetFlow · {mapWindowSec / 60} мин · {greFlow.inWindow ? formatNetflowRate(greFlow) : "Нет записей"}{greFlow.source === "retained" ? " · выборка" : ""}
|
||||
NetFlow · {mapWindow} · {greFlow.inWindow ? formatNetflowRate(greFlow) : "Нет записей"}{greFlow.source === "retained" ? " · выборка" : ""}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useMemo, useEffect, type ReactNode } from "react"
|
||||
import { useState, useMemo, useEffect, useRef, type ReactNode } from "react"
|
||||
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"
|
||||
@@ -832,6 +832,7 @@ export default function TrafficPage() {
|
||||
const [sortField, setSortField] = useState<SortField>("rx")
|
||||
const [sortDir, setSortDir] = useState<SortDir>("desc")
|
||||
const [selectedId, setSelectedId] = useState("srv1")
|
||||
const initialServerApplied = useRef(false)
|
||||
const [range, setRange] = useState<Range>("1h")
|
||||
const [search, setSearch] = useState("")
|
||||
const [trafficRetry, setTrafficRetry] = useState(0)
|
||||
@@ -938,9 +939,13 @@ export default function TrafficPage() {
|
||||
setLiveUsers(mappedUsers)
|
||||
setLiveBoundIfaces(liveIfaces)
|
||||
setTrafficState({ key, status: "ready", receivedAt: Date.now(), peaks: srvRes.peaks })
|
||||
const requestedServer = groupMode === "servers" && mapped.length && !initialServerApplied.current
|
||||
? new URLSearchParams(window.location.search).get("server") : null
|
||||
if (groupMode === "servers" && mapped.length) initialServerApplied.current = true
|
||||
setSelectedId((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 ?? "")
|
||||
if (requestedServer && mapped.some((x) => x.id === requestedServer)) return requestedServer
|
||||
return mapped.some((x) => x.id === prev) ? prev : (mapped[0]?.id ?? "")
|
||||
})
|
||||
} catch (e) {
|
||||
|
||||
@@ -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,24 +1,21 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useRef } from "react"
|
||||
import { InfoIcon } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
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 bg-background hover:bg-muted/60 text-foreground flex h-8 cursor-pointer list-none items-center gap-1.5 rounded-lg border px-2.5 text-[13px] font-medium transition-colors focus-visible:outline-2 focus-visible:outline-ring [&::-webkit-details-marker]:hidden [[open]>&]:bg-muted">
|
||||
<Popover key={compact ? "compact" : "overview"}>
|
||||
<PopoverTrigger render={<Button type="button" variant="outline" className="text-[13px]" />}>
|
||||
<InfoIcon aria-hidden="true" className="size-4" />Легенда
|
||||
</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-[310px] max-w-[calc(100vw-2rem)] flex-col gap-2 overflow-y-auto rounded-lg border p-3 text-xs shadow-lg">
|
||||
</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]) => (
|
||||
@@ -43,9 +40,10 @@ export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
|
||||
<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)" strokeWidth="2" strokeDasharray="2 6" strokeLinecap="round" /></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)" strokeOpacity="0.55" strokeWidth="6" /></svg>Лента NetFlow · толщина = скорость</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="3" strokeDasharray="5 3" /></svg>Наблюдение IPFIX · выход не подтверждён</span>
|
||||
</div>
|
||||
<p className="text-muted-foreground leading-snug">RTT — задержка пробы (ping/BT из «Мониторинг → скорость»), «—» — нет измерения. NetFlow — трафик за 5 минут, не пропускная способность канала. Live GRE — текущие RX/TX в деталях туннеля.</p>
|
||||
</div>
|
||||
</details>
|
||||
<p className="text-muted-foreground leading-snug">Live — последний замер RX/TX интерфейса RouterOS. «≈» и ленты NetFlow показывают среднюю скорость по принятым записям IPFIX. RTT — задержка пробы, «—» означает, что нет измерения.</p>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
"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 } 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"
|
||||
|
||||
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 }: {
|
||||
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
|
||||
}) {
|
||||
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 !== "Прочее"
|
||||
useEffect(() => {
|
||||
if (base === null) return
|
||||
const controller = new AbortController()
|
||||
const init = { signal: controller.signal }
|
||||
if (canMatchService) void getFlowAnalytics(base, { range: "5m" }, init)
|
||||
.then(data => { if (!controller.signal.aborted) setRecent({data, at: new Date().toISOString()}) })
|
||||
.catch(() => { if (!controller.signal.aborted) setRecent(null) })
|
||||
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])
|
||||
const flows = recent?.data.conversationsList.filter(row => {
|
||||
const categoryFallback = row.category === service.label && (row.service === "Прочее" || ["DNS", "SSH", "BGP"].includes(row.category))
|
||||
if (row.service !== service.label && !categoryFallback) return false
|
||||
if (!country) return true
|
||||
if (service.id.startsWith("cc:other|")) return !row.dstCountry || row.dstCountry.toLowerCase() === "unknown"
|
||||
return row.dstCountry?.toUpperCase() === country.toUpperCase()
|
||||
})
|
||||
.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
|
||||
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">
|
||||
<Button size="xs" nativeButton={false} render={<Link href="/traffic" />}>Открыть в «Трафике»</Button>
|
||||
<Button size="xs" variant="outline" aria-pressed={filtered} onClick={onFilter}>{filtered ? "Снять фильтр" : "Фильтр по сервису"}</Button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
@@ -71,7 +71,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>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import type { Server } from "@/lib/data"
|
||||
import { formatNetflowRate } from "@/lib/map-netflow-hops"
|
||||
import { formatMapFlowWindow, formatNetflowRate } from "@/lib/map-netflow-hops"
|
||||
import { TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
@@ -48,13 +48,14 @@ function Card({ title, value, unit, children }: { title: string; value: string;
|
||||
* KPI-полоса над картой (макет v3): узлы, GRE-туннели, NetFlow и узлы, требующие внимания.
|
||||
* Счётчики статусов фильтруют карту, строки проблем открывают узел.
|
||||
*/
|
||||
export function MapKpiStrip({ servers, tunnels, downRoutes = [], exits = [], 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
|
||||
@@ -68,8 +69,9 @@ export function MapKpiStrip({ servers, tunnels, downRoutes = [], exits = [], net
|
||||
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}` : "Все туннели на карте работают"
|
||||
@@ -97,10 +99,14 @@ export function MapKpiStrip({ servers, tunnels, downRoutes = [], exits = [], net
|
||||
<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 ? "—" : formatNetflowRate({ bps: (netflowBytes * 8) / Math.max(1, windowSec) })} unit={topExits.length ? "через Exit-узлы" : "в среднем за окно"}>
|
||||
<Seg parts={topExits.length ? topExits.map((exit, i) => ({ n: exit.bps, color: EXIT_COLORS[i % EXIT_COLORS.length] })) : [{ n: netflowBytes ? 1 : 0, color: "var(--chart-4)" }]} />
|
||||
<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]">
|
||||
{netflowBytes == null ? "Потоки ещё не загружены" : topExits.length ? topExits.slice(0, 3).map((exit) => `${exit.name} ${formatNetflowRate({ bps: exit.bps })}`).join(" · ") : "Все потоки NetFlow за окно"}
|
||||
{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={ruPlural(problems.length, "узел", "узла", "узлов")}>
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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 },
|
||||
|
||||
@@ -910,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
|
||||
@@ -982,8 +983,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[]){
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -51,8 +51,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 page.locator("[data-map-legend] summary").click();await expect(page.getByText("Пунктир WAN→JH — модель связности; маршрут не подтверждён.",{exact:true})).toBeVisible();await page.locator("[data-map-legend] summary").click()
|
||||
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()
|
||||
@@ -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,4 +1,5 @@
|
||||
import {test,expect} from "@playwright/test"
|
||||
import { installOpenLiveStream } from "./live-stream-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}}))})
|
||||
@@ -9,7 +10,12 @@ test("Карта не приписывает весь YouTube единствен
|
||||
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: []},
|
||||
@@ -31,6 +37,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 +89,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 },
|
||||
@@ -73,40 +119,60 @@ for (const reverse of [false, true]) test(`Карта: малый NetFlow и т
|
||||
await page.goto("/network-map")
|
||||
const badge = page.getByRole("button", { name: /^Связь / })
|
||||
await expect(badge.locator("text")).toHaveText("—")
|
||||
expect(liveReads).toBe(0)
|
||||
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).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).toContainText("Live 81", {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")
|
||||
await expect(page.getByRole("button", { name: /^Связь Router → Exit: .*GRE ×2$/ })).toHaveCount(1)
|
||||
await expect(page.getByRole("button", { name: /^Связь Router → Exit: Live 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()
|
||||
@@ -114,6 +180,25 @@ test("Карта: два GRE одного роутера к одному узл
|
||||
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})=>{
|
||||
let failing=true
|
||||
const recovered=malformed?{...empty,rangeMinutes:2,windowSec:120,sourceWindow:{requestedMinutes:5,effectiveMinutes:2}}:empty
|
||||
|
||||
@@ -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()
|
||||
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", "Лента NetFlow · толщина = скорость"]) 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()
|
||||
})
|
||||
|
||||
|
||||
@@ -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] }
|
||||
|
||||
Reference in new issue
Block a user