Compare commits

...
1 Commits
Author SHA1 Message Date
Denozordec 589fc782f9 fix(map): исправить трафик и карточки карты сети
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m29s
Docker images / frontend-image (push) Successful in 2m13s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 1m59s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-26 10:34:20 +07:00
33 changed files with 872 additions and 424 deletions

No files matched your search

+217 -209
View File
@@ -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 { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
import { InspectorMetrics, NodeHistory, ServiceInspector } 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"
@@ -426,6 +430,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
@@ -678,10 +686,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 +702,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 +712,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 +726,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" />,
@@ -908,6 +918,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 +929,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 +1075,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})
@@ -1177,7 +1193,7 @@ 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)
@@ -1374,14 +1390,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 +1424,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
@@ -1859,10 +1889,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 +1908,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 +1951,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 +1967,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 +2013,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),
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 +2050,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 +2061,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 +2076,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>
)}
@@ -2034,6 +2093,7 @@ function NetworkMapContent() {
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 }))}
liveLink={busiestLiveLink}
netflowBytes={mapTotalBytes > 0 ? mapTotalBytes : useLiveData && flowReadAt ? 0 : null}
windowSec={mapWindowSec}
filter={filter}
@@ -2177,10 +2237,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>}
@@ -2367,11 +2425,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 +2590,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 +2700,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 +2709,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 +2807,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={(selectedNestedService ? expandedCountryGroup?.paths ?? [] : destPaths).filter(p => p.serviceId === liveSelectedService.id).sort((a, b) => b.bps - a.bps)}
exits={selectedNestedService ? [] : selectedExitEdges}
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 +2854,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 +2885,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,
@@ -2949,96 +2960,91 @@ 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"} />
{(() => {
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 +3056,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 +3135,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 +3200,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 +3248,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 +3333,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>
+6 -1
View File
@@ -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) {
+3 -1
View File
@@ -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) => {
+16 -7
View File
@@ -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",
+1 -1
View File
@@ -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: {
@@ -768,7 +768,7 @@ ingestClosed(9, [{
proto: 6,
srcPort: 51234,
dstPort: 443,
bytes: 12_000,
bytes: 120_000,
packets: 10,
inIface: "1",
outIface: "1",
@@ -786,7 +786,8 @@ 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(googleEdge.bps, googlePaths[0]?.bps)
} finally {
seedFlowTopologyForTests(null)
@@ -1031,12 +1032,19 @@ 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]), [["10", 2000], ["9", 1000]])
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 3000)
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()
+24 -15
View File
@@ -33,6 +33,7 @@ const HOPS_CACHE_TTL_MS = 2000
export interface FlowMapHopsQuery {
minutes: number
includeCurrentMinute?: boolean
serverId?: number
userId?: string
iface?: string
@@ -329,6 +330,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,
@@ -409,21 +411,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 +481,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()
@@ -662,22 +665,27 @@ 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 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))
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 bytes = payloadBytes.get(r) ?? r.bytes
totalBytes += bytes
const { endpoints: ep, exitId, reverse } = observed.get(r)!
const dst = ep.internetPeer
const dstPort = ep.peerPort || r.dstPort
@@ -685,8 +693,8 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
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
if (exitId !== undefined) bumpFrom(acc, String(r.serverId), String(exitId), bytes, reverse, client)
dstAcc.set(destKey, acc)
}
@@ -755,7 +763,7 @@ 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 } : {}),
@@ -764,6 +772,7 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
.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,
@@ -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++
+15 -1
View File
@@ -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")
+77 -48
View File
@@ -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" }
})
}
+30 -21
View File
@@ -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 -1
View File
@@ -44,7 +44,7 @@ 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" 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>
</div>
<p className="text-muted-foreground leading-snug">RTT — задержка пробы (ping/BT из «Мониторинг → скорость»), «—» — нет измерения. NetFlow — трафик за 5 минут, не пропускная способность канала. Live GRE — текущие RX/TX в деталях туннеля.</p>
<p className="text-muted-foreground leading-snug">Live — последний замер RX/TX интерфейса RouterOS. «≈» и ленты NetFlow показывают среднюю скорость по принятым записям IPFIX. RTT — задержка пробы, «—» означает, что нет измерения.</p>
</div>
</details>
)
@@ -0,0 +1,146 @@
"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 } 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 { 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 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: { viaId: string; enId: string; serviceId: string } | 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.map(e => e.fromId), ...paths.map(p => p.enId)])]
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>}</>],
["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder ? "Часть трафика без подтверждённого выхода" : undefined],
]} />
<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 active = activePath?.viaId === p.viaId && activePath.enId === p.enId && activePath.serviceId === p.serviceId
return <button type="button" key={JSON.stringify([p.clientId,p.viaId,p.enId])} onClick={() => onPath(p)} aria-pressed={active} title={formatNetflowRate({bps:p.bps})} 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>)}
</button>
})}
{rates.filter(e => !paths.some(p => p.enId === e.fromId)).map(e => <div key={e.fromId} className="flex justify-between gap-2 text-xs"><span>{exitName(e.fromId)} → {service.label}</span><span className="shrink-0 font-mono">{formatNetflowRate({bps:e.bps})}</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>
</>
}
+12 -6
View File
@@ -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, "узел", "узла", "узлов")}>
-70
View File
@@ -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
}
}
+96
View File
@@ -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
}
}
+1
View File
@@ -18,6 +18,7 @@ export interface GreSpeedProbeSnapshot {
lastRxAvgMbps?: number | null
lastPingAt?: string | null
lastPingRttMs?: number | null
lastPingLossPct?: number | null
}
export type GreTunnelProbeEdge = {
+5
View File
@@ -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 },
+6 -2
View File
@@ -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 }]
+4
View File
@@ -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})
+6 -5
View File
@@ -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 }).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[]){
+1
View File
@@ -412,6 +412,7 @@ export const flowMapCountryServiceGroupDtoSchema = z.object({
export const flowMapHopsDtoSchema = z.object({
sourceWindow: flowSourceWindowSchema.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(),
+4 -2
View File
@@ -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(
+2 -1
View File
@@ -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()}
+73 -2
View File
@@ -9,10 +9,12 @@ 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})=>{
@@ -44,3 +46,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)
})
+65 -15
View File
@@ -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: []},
@@ -48,15 +54,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 +84,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 +145,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
+2 -1
View File
@@ -23,7 +23,8 @@ test("Карта: раскрытая легенда объясняет стат
await expect(legend).toBeVisible()
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 expect(legend).toContainText("последний замер RX/TX интерфейса RouterOS")
await expect(legend).toContainText("среднюю скорость по принятым записям IPFIX")
await page.locator("[data-map-legend] summary").click()
await expect(legend).not.toBeVisible()
await page.locator("[data-map-legend] summary").press("Enter")
+20
View File
@@ -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] }