Compare commits

..
3 Commits
Author SHA1 Message Date
Denozordec 4097e1a6fc fix(traffic): восстановить распознавание видеосервисов на карте
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m55s
Docker images / backend-image (push) Successful in 1m58s
Docker images / frontend-image (push) Successful in 2m17s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
Показать среднюю скорость и время последней минуты с потоками.
2026-11-27 01:40:50 +07:00
Denozordec 7cf17c7283 fix(traffic): согласовать трафик пользователей и уточнить данные карты
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m46s
Docker images / backend-image (push) Successful in 1m59s
Docker images / frontend-image (push) Successful in 2m16s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 31s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
2026-11-27 00:59:36 +07:00
Denozordec 4eafc78c8e fix(map): улучшить навигацию и разбор инцидентов на карте
Docker images / prepare-release (push) Successful in 15s
Docker images / backend-test (push) Successful in 4s
Docker images / frontend-image (push) Successful in 2m22s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / backend-image (push) Successful in 16s
Docker images / publish-release (push) Successful in 10s
Docker images / notify-webhook (push) Successful in 2s
2026-11-27 00:13:40 +07:00
36 changed files with 850 additions and 385 deletions

No files matched your search

+192 -111
View File
@@ -2,6 +2,7 @@
import { useState, useRef, useEffect, useMemo, useCallback, Suspense } from "react"
import {fitNetworkMapCamera} from "@/lib/network-map-camera"
import { mapObservationRoute } from "@/lib/network-map-observation-route"
import { useSearchParams } from "next/navigation"
import {readNetworkMapUrl,patchNetworkMapUrl,type NetworkMapFilter} from "@/lib/network-map-url-state"
import {Alert,AlertTitle,AlertDescription} from "@/components/ui/alert"
@@ -101,7 +102,7 @@ import {
DownloadIcon, XIcon, LockIcon, LockOpenIcon, WifiIcon, RefreshCwIcon,
SearchIcon,
LayersIcon, FilterIcon, MapIcon, HomeIcon, TerminalIcon, ShieldIcon,
CableIcon, ActivityIcon, ArrowDownLeftIcon, ArrowUpRightIcon, UsersIcon,
CableIcon, ActivityIcon, ArrowDownLeftIcon, ArrowUpRightIcon, UsersIcon, ChevronDownIcon, ChevronUpIcon, CircleHelpIcon,
} from "lucide-react"
import { cn } from "@/lib/utils"
import { formatServicePathLabel, formatServicePathTitle, servicePathKey } from "@/lib/format-service-path-label"
@@ -558,6 +559,12 @@ function ServerNode({ n, isSel, isVis, isDragged, hideCatalogLatency, rates, onC
)
}
function serviceMapSubtitle(service: FlowMapService): string {
const top = service.trafficTypes?.[0]
if (service.category !== "Прочее" || !top || top.bytes * 2 <= service.bytes) return service.category
return top.application ? shortName(`≈ ${top.application} · ${top.transport}`, 25) : top.transport
}
function ServiceNode({
label,
share,
@@ -573,6 +580,7 @@ function ServiceNode({
category,
rate,
compact,
expanded,
onClick,
onPointerDown,
}: {
@@ -584,6 +592,7 @@ function ServiceNode({
rate?: string
/** Узкая строка: раскрытая страна показывает две колонки назначений. */
compact?: boolean
expanded?: boolean
x: number
y: number
isSel: boolean
@@ -604,10 +613,10 @@ function ServiceNode({
const barW = bw - 72
const flagIso = destMode === "countries" && iso && iso !== "Прочее" ? iso : ""
return (
<g role="button" aria-label={(destMode==="countries"?"Страна ":"Сервис ")+label} aria-pressed={isSel} tabIndex={isVis?0:-1} className="network-map-focusable"
<g role="button" aria-label={expanded === undefined ? (destMode==="countries"?"Страна ":"Сервис ")+label : label} aria-pressed={expanded === undefined ? isSel : undefined} aria-expanded={expanded} tabIndex={isVis?0:-1} className="network-map-focusable"
onKeyDown={e=>{if(e.key==="Enter"||e.key===" "){e.preventDefault();e.stopPropagation();onClick()}}}
transform={`translate(${x},${y})`}
style={{ cursor: isDragged ? "grabbing" : "grab", transition: isDragged ? "none" : "opacity 0.25s" }}
style={{ cursor: expanded !== undefined ? "pointer" : isDragged ? "grabbing" : "grab" }}
opacity={isVis ? (dim ? 0.35 : 1) : 0.08}
onPointerDown={(e) => { e.stopPropagation(); onPointerDown(e) }}
onClick={(e) => { e.stopPropagation(); onClick() }}
@@ -620,9 +629,10 @@ function ServiceNode({
<g transform={`translate(${-hw + 13},${flagIso ? -8 : -11})`} pointerEvents="none">
{flagIso
? <CountryFlagSvg iso={flagIso} size={22} />
: <ServiceBrandIcon aria-hidden="true" label={destMode === "countries" ? "Прочее" : label} size={22} />}
: expanded !== undefined ? expanded ? <ChevronUpIcon width={22} height={22} color="var(--muted-foreground)" /> : <ChevronDownIcon width={22} height={22} color="var(--muted-foreground)" />
: <ServiceBrandIcon aria-hidden="true" label={destMode === "countries" ? "Прочее" : label} size={22} />}
</g>
<text x={-hw + 48} y="-3" fill="var(--foreground)" fontSize="13" fontWeight="600" fontFamily="Geist,sans-serif">{shortName(label, compact ? 8 : 18)}</text>
<text x={-hw + 48} y="-3" fill="var(--foreground)" fontSize="13" fontWeight="600" fontFamily="Geist,sans-serif">{shortName(label, expanded === undefined ? compact ? 8 : 18 : 28)}</text>
<text x={-hw + 48} y="12" fill="var(--muted-foreground)" fontSize="11" fontFamily="Geist,sans-serif">{compact ? serviceSharePct(share) : category || (destMode === "countries" ? "Страна" : "Сервис")}</text>
{!compact && rate ? <text x={hw - 12} y="-3" textAnchor="end" fill="var(--foreground)" fontSize="12" fontFamily="Geist Mono,monospace">{rate}</text> : null}
{!compact ? <text x={hw - 12} y="12" textAnchor="end" fill="var(--muted-foreground)" fontSize="11" fontFamily="Geist Mono,monospace">{serviceSharePct(share)}</text> : null}
@@ -909,7 +919,7 @@ function NetworkMapContent() {
const [showSmallServices, setShowSmallServices] = useState(false)
const [inspectedEvent, setInspectedEvent] = useState<MapEventRow | null>(null)
const [flowRefresh,setFlowRefresh]=useState(0)
const access = useMapAccess(useLiveData ? backendUrl : null, hasIxNodes, flowRefresh, Boolean(pickedUserId))
const access = useMapAccess(useLiveData ? backendUrl : null, hasIxNodes, flowRefresh, pickedUserId)
useEffect(() => {
if (!useLiveData || !hasIxNodes) return
const controller = new AbortController()
@@ -942,8 +952,10 @@ function NetworkMapContent() {
const [flowReadAt,setFlowReadAt]=useState<string|null>(null)
const [flowListener,setFlowListener]=useState(false)
const [flowLoading,setFlowLoading]=useState(false)
const [userFlow, setUserFlow] = useState<{ key: string; data?: ReturnType<typeof networkMapFlowSchema.parse>; error?: string }>()
const [userFlow, setUserFlow] = useState<{ key: string; data?: ReturnType<typeof networkMapFlowSchema.parse>; at?: string; error?: string }>()
const [bottomTab, setBottomTab] = useState<MapBottomTab>("flows")
const [analysisOpen, setAnalysisOpen] = useState(false)
const [summaryOpen, setSummaryOpen] = useState(false)
const [filteredServiceId, setFilteredServiceId] = useState<string | null>(null)
const [mapEvents, setMapEvents] = useState<EventItem[] | null>(null)
const [eventsError, setEventsError] = useState<string | null>(null)
@@ -953,9 +965,21 @@ function NetworkMapContent() {
useEffect(() => {
if (!useLiveData) return
let cancelled = false
listEvents(backendUrl, { limit: 50 })
.then(rows => { if (!cancelled) { setMapEvents(rows); setEventsError(null); setEventsAt(Date.now()) } })
.catch(error => { if (!cancelled) setEventsError(error instanceof Error ? error.message : "не удалось загрузить") })
const now = Date.now()
const from = new Date(now - 86_400_000).toISOString()
void Promise.allSettled([
listEvents(backendUrl, { limit: 50 }),
listEvents(backendUrl, { limit: 100, level: "critical", from }),
listEvents(backendUrl, { limit: 100, level: "warning", from }),
]).then(results => {
if (cancelled) return
const rows = new Map<string, EventItem>()
for (const result of results) if (result.status === "fulfilled") for (const event of result.value) rows.set(event.id, event)
if (results.some(result => result.status === "fulfilled")) {
setMapEvents([...rows.values()]); setEventsAt(now)
}
setEventsError(results.every(result => result.status === "fulfilled") ? null : "Журнал загружен не полностью")
})
return () => { cancelled = true }
}, [useLiveData, backendUrl, flowRefresh])
const [dnsError,setDnsError]=useState<string|null>(null)
@@ -1184,6 +1208,7 @@ function NetworkMapContent() {
const [showAnimDots, setShowAnimDots] = useState(true)
const [showMinimap, setShowMinimap] = useState(true)
const [showHints, setShowHints] = useState(false)
const [showAuxLinks, setShowAuxLinks] = useState(true)
const [showLayers, setShowLayers] = useState(false)
const [showUsers, setShowUsers] = useState(true)
@@ -1271,18 +1296,17 @@ function NetworkMapContent() {
return out
}, [mapServers, autoLayout.wanSatPos, satPositions])
const compactLanes = homeRouters.length === 0 ? 180 : 0
const nodePosById = useMemo(
() =>
Object.fromEntries(
mapServers.map((s) => {
const pos =
nodePositions[s.id] ??
autoLayout.nodePos[s.id] ??
{ x: W / 2, y: NETWORK_MAP_PIPELINE_Y }
const auto = autoLayout.nodePos[s.id] ?? { x: W / 2, y: NETWORK_MAP_PIPELINE_Y }
const pos = nodePositions[s.id] ?? { x: auto.x - compactLanes, y: auto.y }
return [s.id, pos] as const
}),
),
[mapServers, nodePositions, autoLayout.nodePos],
[mapServers, nodePositions, autoLayout.nodePos, compactLanes],
)
const greEdges = useMemo(
@@ -1305,6 +1329,11 @@ function NetworkMapContent() {
const scopeUser = pickedUser && !pickedUser.linux ? pickedUser.id : undefined
const scopeKey = JSON.stringify([backendUrl, scopeUser, flowRefresh])
const userSnapshot = useLiveData && scopeUser && userFlow?.key === scopeKey ? userFlow : undefined
const destinationWindowSec = userSnapshot?.data?.windowSec ?? mapWindowSec
const destinationWindow = formatMapFlowWindow(destinationWindowSec)
const destinationReadAt = pickedUserId ? userSnapshot?.at ?? null : flowReadAt
const destinationTotalBytes = pickedUserId ? userSnapshot?.data?.totalBytes : mapTotalBytes
const destinationNamedBytes = pickedUserId ? userSnapshot?.data?.namedBytes : mapNamedBytes
useEffect(() => {
if (!useLiveData || !scopeUser || !showServices) return
const controller = new AbortController()
@@ -1313,9 +1342,9 @@ function NetworkMapContent() {
try {
const raw = await apiFetch<unknown>(`/api/traffic/flow/map-hops?${new URLSearchParams({range:"1m",userId:scopeUser!})}`, {signal:controller.signal})
const data = networkMapFlowSchema.parse(raw)
if (!controller.signal.aborted) setUserFlow({ key: scopeKey, data })
if (!controller.signal.aborted) setUserFlow({ key: scopeKey, data, at: new Date().toISOString() })
} catch {
if (!controller.signal.aborted) setUserFlow(last => ({ key: scopeKey, data: last?.key === scopeKey ? last.data : undefined, error: "Снимок потоков пользователя недоступен" }))
if (!controller.signal.aborted) setUserFlow(last => ({ ...(last?.key === scopeKey ? last : undefined), key: scopeKey, error: "Снимок потоков пользователя недоступен" }))
} finally {
if (!controller.signal.aborted) timer = setTimeout(() => { void refresh() }, 15_000)
}
@@ -1350,6 +1379,10 @@ function NetworkMapContent() {
setInspectUser(true); setUserPicker(false)
updateUrl({ user: user.id, server: null, wan: null, service: null, q: null, filter: ixOnly ? "ix-node" : null })
}
function returnToNetwork() {
updateUrl({user:null, server:null, wan:null, service:null})
setSelectedService(null); setSelectedGreEdge(null); setHighlightedPath(null); setUserPicker(false)
}
/** Speed-пробы на сегментах WAN→JH (тот же формат бейджа, что на GRE JH↔EN). */
const speedProbeByWanJhKey = useMemo(
@@ -1535,9 +1568,11 @@ function NetworkMapContent() {
const activeService = destNodes.find(service => service.id === activeServiceId) ?? selectedNestedService ?? null
const liveSelectedService = activeService
const expandedCountry = destNodes.find(service => service.id === expandedCountryId)
const minorServices = destMode === "services" ? destNodes.filter(service => service.share <= 0.1 && service.id !== activeService?.id && service.id !== filteredServiceId) : []
const hasMinorServices = minorServices.length > 0
const visibleMapServices = !showServices ? [] : showSmallServices ? destNodes : destNodes.filter(service => !minorServices.includes(service))
const minorServices = destMode === "services" ? destNodes.filter(service => service.share <= 0.1) : []
const groupedServices = minorServices.filter(service => service.id !== activeService?.id && service.id !== filteredServiceId)
const mainServices = showServices ? destNodes.filter(service => !groupedServices.includes(service)) : []
const hasMinorServices = showServices && (groupedServices.length > 0 || showSmallServices && minorServices.length > 0)
const visibleMapServices = showServices && showSmallServices ? [...mainServices, ...groupedServices] : mainServices
const visibleServiceEdges = showServices
? destEdges.filter(edge => nodePosById[edge.fromId] && visibleMapServices.some(service => service.id === edge.toId))
: []
@@ -1562,30 +1597,34 @@ function NetworkMapContent() {
const nodeById = Object.fromEntries(nodes.map((n) => [n.id, n]))
const autoServicePos = placeServiceNodes(
[...visibleMapServices.map((s) => s.id), ...(showServices && hasMinorServices && !showSmallServices ? ["minor-services"] : [])],
mapServers
[...mainServices.map((s) => s.id), ...(hasMinorServices ? ["minor-services"] : [])],
nodes
.filter((s) => s.type === "exit-node")
.map((s) => nodePosById[s.id])
.filter((p): p is { x: number; y: number } => Boolean(p)),
)
// Раскрытая страна: колонка стран уходит влево, правый x занимает столбец её сервисов.
const countryColShift = expandedCountryGroup ? SERVICE_COL_W : 0
const autoDestPos = countryColShift
? Object.fromEntries(
Object.entries(autoServicePos).map(([id, p]) => [id, { x: p.x - countryColShift, y: p.y }]),
)
: autoServicePos
const emptyExitShift = destMode === "services" && nodes.some(node => node.type === "jump-host")
&& !nodes.some(node => node.type === "exit-node" || node.type === "ix-node") ? 100 : 0
const autoDestPos = Object.fromEntries(Object.entries(autoServicePos).map(([id, p]) => [id, { x: p.x - countryColShift - compactLanes - emptyExitShift, y: p.y }]))
const minorPosition = autoDestPos["minor-services"]
if (minorPosition && showSmallServices) for (const [index, service] of groupedServices.entries()) {
autoDestPos[service.id] = { x: minorPosition.x, y: minorPosition.y + (index + 1) * (MAP_SERVICE_NODE_H + 10) }
}
const servicePosById = Object.fromEntries(
visibleMapServices.map((s) => [s.id, servicePositions[s.id] ?? autoDestPos[s.id]!]),
)
const minorPosition = autoDestPos["minor-services"]
const autoNestedPos = placeCountryServiceNodes(
nestedServices.map((s) => s.id),
expandedCountryId ? servicePosById[expandedCountryId] ?? autoDestPos[expandedCountryId] : undefined,
)
const nestedPosById = Object.fromEntries(
nestedServices
.map((s) => [s.id, servicePositions[s.id] ?? autoNestedPos[s.id]] as const)
.map((s) => {
const position = autoNestedPos[s.id]
return [s.id, servicePositions[s.id] ?? (position && { x: position.x - compactLanes, y: position.y })] as const
})
.filter((entry): entry is readonly [string, { x: number; y: number }] => Boolean(entry[1])),
)
@@ -1621,20 +1660,25 @@ function NetworkMapContent() {
function exportSvg() {
const svg = svgRef.current
if (!svg) return
// Clone with full viewBox (reset pan/zoom)
const clone = svg.cloneNode(true) as SVGSVGElement
const x = Math.min(0, ...mapObstacles.map(box => box.x - 20))
const y = Math.min(0, lanesTop - 16, ...observationTracks.map(track => track - 20))
const width = Math.ceil(Math.max(W, ...mapObstacles.map(box => box.x + box.w + 20)) - x)
const height = Math.ceil(Math.max(H, lanesBottom + 16, ...observationTracks.map(track => track + 20)) - y)
clone.querySelectorAll(".network-map-focus-ring").forEach(ring => ring.remove())
clone.setAttribute("viewBox", `0 0 ${W} ${H}`)
clone.setAttribute("width", String(W))
clone.setAttribute("height", String(H))
clone.setAttribute("viewBox", `${x} ${y} ${width} ${height}`)
clone.setAttribute("width", String(width))
clone.setAttribute("height", String(height))
clone.setAttribute("xmlns","http://www.w3.org/2000/svg")
const computed=getComputedStyle(svg)
const variables=new Set([...clone.outerHTML.matchAll(/var\((--[a-zA-Z0-9_-]+)/g)].map(match=>match[1]))
variables.add("--background")
for(const name of variables){const value=computed.getPropertyValue(name).trim();if(!value)continue;clone.style.setProperty(name,value);for(const match of value.matchAll(/var\((--[a-zA-Z0-9_-]+)/g))variables.add(match[1])}
clone.style.width=W+"px";clone.style.height=H+"px"
clone.style.width=width+"px";clone.style.height=height+"px"
const background=document.createElementNS("http://www.w3.org/2000/svg","rect")
background.setAttribute("width",String(W));background.setAttribute("height",String(H));background.setAttribute("fill","var(--background)");clone.prepend(background)
background.setAttribute("x",String(x));background.setAttribute("y",String(y));background.setAttribute("width",String(width));background.setAttribute("height",String(height));background.setAttribute("fill","var(--background)");clone.prepend(background)
const grid = clone.querySelector("[data-map-background]")
for (const key of ["x", "y", "width", "height"]) grid?.setAttribute(key, background.getAttribute(key)!)
const blob = new Blob(
[`<?xml version="1.0" encoding="UTF-8"?>\n`, new XMLSerializer().serializeToString(clone)],
{ type: "image/svg+xml;charset=utf-8" },
@@ -1685,16 +1729,17 @@ function NetworkMapContent() {
},[zoom,viewportHeight])
// Миникарта — только на широком холсте; снизу резервируем полосу под неё и панель масштаба.
const minimapVisible = showMinimap && canvasPx.w >= 640
const overlayReserve = canvasPx.h ? ((minimapVisible ? 112 : 36) + 20) / canvasPx.h : 0
const accessPosition = { x: homeRouters.some(router => onMap(router.id)) ? -105 : MAP_LANES.home.cx,
y: Math.max(80, [...accessGroups.keys()].reduce((sum, id) => sum + (nodePosById[id]?.y ?? 0), 0) / (accessGroups.size || 1)) }
const detailsOpen = Boolean(selected || activeService || selectedGreEdge || userDetailsOpen)
const fitWidth = canvasPx.w >= 760 && detailsOpen ? W * (1 - 330 / canvasPx.w) : W
const sideInspector = canvasPx.w >= 620 && detailsOpen
const minimapVisible = showMinimap && canvasPx.w >= 640 && !detailsOpen
const overlayReserve = canvasPx.h ? ((minimapVisible ? 112 : 36) + 20) / canvasPx.h + (detailsOpen && !sideInspector ? 0.35 : 0) : 0
const fitWidth = sideInspector ? W * (1 - 302 / canvasPx.w) : W
const {pan:{x:fitX,y:fitY},zoom:fitZoom}=fitNetworkMapCamera([...nodes,...homeRouters.filter(router => onMap(router.id)).flatMap(router => effectiveSatPos[router.id] ?? []),...(showUsers && usersInTopology.length ? [accessPosition] : []),...(minorPosition ? [minorPosition] : []),...Object.values(servicePosById).map(p=>({x:p.x+(expandedCountryGroup?MAP_SERVICE_COMPACT_W:MAP_SERVICE_NODE_W)/2-100,y:p.y})),...Object.values(nestedPosById).map(p=>({x:p.x+MAP_SERVICE_COMPACT_W/2-100,y:p.y}))],fitWidth,viewportHeight,overlayReserve)
function fitView(){setPan({x:fitX,y:fitY});setZoom(fitZoom)}
useEffect(()=>{if(initialFit.current||!canvasMeasured||!mapServers.length)return;initialFit.current=true;queueMicrotask(()=>{setPan({x:fitX,y:fitY});setZoom(fitZoom)})},[canvasMeasured,mapServers.length,fitX,fitY,fitZoom])
const viewKey = `${ixOnly}:${pickedUser?.id ?? ""}:${filteredServiceId ?? ""}:${showSmallServices}:${splitIx}:${fitWidth !== W}:${Boolean(userSnapshot?.data)}:${showUsers && usersInTopology.length > 0}`
const viewKey = `${ixOnly}:${pickedUser?.id ?? ""}:${filteredServiceId ?? ""}:${showSmallServices}:${splitIx}:${fitWidth !== W}:${Boolean(userSnapshot?.data)}:${showUsers && usersInTopology.length > 0}:${Math.round(canvasPx.w)}x${Math.round(canvasPx.h)}`
const lastViewKey = useRef(viewKey)
const lastUserView = useRef(pickedUser?.id)
useEffect(() => {
@@ -1716,11 +1761,11 @@ function NetworkMapContent() {
// ── Keyboard shortcuts ────────────────────────────────────────────────────
useEffect(() => {
function onKey(e: KeyboardEvent) {
if (ctxMenu||showLayers) return
if (ctxMenu || showLayers || userPicker || summaryOpen) return
if (e.key!=="Escape"&&(e.ctrlKey||e.metaKey||e.altKey||e.target instanceof HTMLInputElement||e.target instanceof HTMLTextAreaElement||e.target instanceof HTMLSelectElement))return
if (e.key === "Escape") {
setSelected(null)
updateUrl({wan:null})
updateUrl({wan:null,service:null})
setSelectedGreEdge(null)
setSelectedService(null)
setHighlightedPath(null)
@@ -1735,7 +1780,7 @@ function NetworkMapContent() {
}
window.addEventListener("keydown", onKey)
return () => window.removeEventListener("keydown", onKey)
}, [applyZoomCenter,fitX,fitY,fitZoom,setSelected,updateUrl,ctxMenu,showLayers,returnToMapControl])
}, [applyZoomCenter,fitX,fitY,fitZoom,setSelected,updateUrl,ctxMenu,showLayers,userPicker,summaryOpen,returnToMapControl])
// ── Drag ─────────────────────────────────────────────────────────────────
function onSvgPointerDown(e: React.PointerEvent<SVGSVGElement>) {
@@ -2008,7 +2053,9 @@ function NetworkMapContent() {
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,
opacity: dimmed ? 0.05 : highlightedPath ? greMatchesPath(e, highlightedPath) ? 1 : 0.16
: activeService ? selectedDestPaths.some(path => greMatchesPath(e, path)) ? 1 : 0.2
: selected && selected.id !== e.fromServer.id && selected.id !== e.toServer.id ? 0.3 : 1,
link: mapLinkPath(e.from, greHalfW(e.from, e.fromServer), e.to, greHalfW(e.to, e.toServer)),
}
})
@@ -2080,7 +2127,7 @@ function NetworkMapContent() {
name: `${lead.e.fromServer.name} → ${lead.e.toServer.name}`,
}]
})
const wanLinks = visibleWanJhEdges.flatMap((edge) => {
const wanLinks = (showAuxLinks ? visibleWanJhEdges : []).flatMap((edge) => {
const jh = nodeById[edge.jhId], sat = effectiveSatPos[edge.homeId]?.[edge.wanIdx]
if (!jh || !sat || !onMap(edge.homeId)) return []
const key = wanJhEdgeMapKey(edge)
@@ -2108,10 +2155,10 @@ function NetworkMapContent() {
if (!target || !isVisible(target)) return []
const bindings = pickedUser?.bindings.filter(binding => binding.node === id) ?? []
const rate = accessRate(bindings, access.rates)
const text = pickedUser ? showNetflow ? rate.label : "" : `${users.length} чел.`
const text = pickedUser ? showNetflow && rate.measured ? rate.label : "" : `${users.length} чел.`
const link = mapLinkPath(accessPosition, MAP_CARD_W / 2, target, MAP_CARD_W / 2)
return [{ id: `access:${id}`, link, texts: [text], name: `${pickedUser?.name ?? "Пользователи"} → ${target.name}`, opacity: bindings.length && bindings.every(binding => binding.enabled === false) ? 0.48 : 1,
tone: "fg" as const, hint: pickedUser ? `${rate.measured}/${rate.total} замеров · ${bindings.map(binding => binding.kind).join(", ")}` : "Привязки из каталога пользователей",
tone: "fg" as const, hint: pickedUser ? `RouterOS · RX ${fmtRate(rate.measured ? rate.rx : null)} · TX ${fmtRate(rate.measured ? rate.tx : null)} · ${rate.measured}/${rate.total} замеров` : "Привязки из каталога пользователей",
open: () => { if (pickedUser) { setSelected(null); setSelectedGreEdge(null); setSelectedService(null); setInspectUser(true) } else setUserPicker(true) },
}]
})
@@ -2124,11 +2171,20 @@ function NetworkMapContent() {
...visibleMapServices.flatMap((s) => servicePosById[s.id] ? [{ x: servicePosById[s.id].x - destHalfW, y: servicePosById[s.id].y - MAP_SERVICE_NODE_H / 2, w: destHalfW * 2, h: MAP_SERVICE_NODE_H }] : []),
...(expandedCountryGroup ? nestedServices : []).flatMap((s) => nestedPosById[s.id] ? [{ x: nestedPosById[s.id].x - MAP_SERVICE_COMPACT_W / 2, y: nestedPosById[s.id].y - MAP_SERVICE_NODE_H / 2, w: MAP_SERVICE_COMPACT_W, h: MAP_SERVICE_NODE_H }] : []),
]
const linkLabels = placeMapLinkLabels([...accessLinks.filter(link => link.texts[0]), ...greLabels, ...wanLabels], mapObstacles)
const destRibbons = visibleServiceEdges.flatMap(edge => {
const observationTracks: number[] = []
const destRibbons = [...visibleServiceEdges].sort((a, b) =>
Number(b.toId === activeService?.id) - Number(a.toId === activeService?.id) || b.bps - a.bps || a.fromId.localeCompare(b.fromId) || a.toId.localeCompare(b.toId),
).flatMap(edge => {
const from = nodeById[edge.fromId], to = servicePosById[edge.toId]
return from && to ? [{ edge, link: mapLinkPath(from, MAP_CARD_W / 2, to, destHalfW) }] : []
if (!from || !to) return []
const direct = edge.observedOnly || from.type === "jump-host" || from.type === "home-router"
if (direct && !showAuxLinks) return []
const detour = direct ? mapObservationRoute({ x: from.x + MAP_CARD_W / 2, y: from.y }, { x: to.x - destHalfW, y: to.y }, mapObstacles, observationTracks) : null
if (detour) observationTracks.push(detour.track)
return [{ edge, direct, detour, link: mapLinkPath(from, MAP_CARD_W / 2, to, destHalfW) }]
})
const observationMarkers = destRibbons.flatMap(({ edge, detour }) => edge.observedOnly && detour ? [{ x: detour.marker.x - 17, y: detour.marker.y - 7, w: 34, h: 14 }] : [])
const linkLabels = placeMapLinkLabels([...accessLinks.filter(link => link.texts[0]), ...greLabels, ...wanLabels], [...mapObstacles, ...observationMarkers])
const nestedRibbons = mapRibbons((expandedCountryGroup?.edges ?? []).flatMap((edge) => {
const from = servicePosById[edge.fromId], to = nestedPosById[edge.toId]
return from && to ? [{ edge, from, fromHalfW: MAP_SERVICE_COMPACT_W / 2, to, toHalfW: MAP_SERVICE_COMPACT_W / 2, bps: destinationRate(edge).bps }] : []
@@ -2179,12 +2235,15 @@ function NetworkMapContent() {
hl: selectedService?.id === svc.id || Boolean(selected && destEdges.some(edge => edge.fromId === selected.id && edge.toId === svc.id)),
}))
const mapLinkCount = greGroups.length + wanLinks.length
const activeMapPoints = [...nodes, ...Object.values(servicePosById), ...Object.values(nestedPosById), ...(minorPosition ? [minorPosition] : [])]
const lanesTop = Math.min(...activeMapPoints.map(point => point.y), NETWORK_MAP_PIPELINE_Y) - 66
const lanesBottom = Math.max(...activeMapPoints.map(point => point.y), NETWORK_MAP_PIPELINE_Y) + 52
const recentIncidents = eventRows.filter(event => (event.tone === "er" || event.tone === "wn") && event.ts >= eventsAt - 86_400_000)
const mapHeadSub = (
<>
<span>{useLiveData ? (readAt ? `Live · снимок API ${new Date(readAt).toLocaleTimeString("ru-RU")}` : "Данные карты неизвестны") : "Демо · mock"}</span>
{useLiveData ? <>{" · "}<span>{showNetflow || showServices ? (flowReadAt ? `NetFlow · ${mapWindow}${mapWindowSec >= 120 && mapWindowSec < 300 ? " из 5 запрошенных" : ""} · ответ ${new Date(flowReadAt).toLocaleTimeString("ru-RU")} · ${flowListener ? "приёмник включён" : "приёмник выключен"}` : "Данные NetFlow неизвестны") : "NetFlow: отображение и обновление выключены"}</span></> : null}
{" · "}
<span>{`${nodes.length} ${ruPlural(nodes.length, "узел", "узла", "узлов")}, ${mapLinkCount} ${ruPlural(mapLinkCount, "связь", "связи", "связей")}, ${visibleMapServices.length} ${ruPlural(visibleMapServices.length, "назначение", "назначения", "назначений")}`}</span>
<span title={readAt ? `Снимок API ${new Date(readAt).toLocaleTimeString("ru-RU")}` : undefined}>{useLiveData ? (readAt ? "Снимок сети" : "Данные карты неизвестны") : "Демонстрационные данные"}</span>
{" · "}<span>{nodes.length} {ruPlural(nodes.length, "узел", "узла", "узлов")} · {mapLinkCount} {ruPlural(mapLinkCount, "связь", "связи", "связей")}</span>
{useLiveData && (showNetflow || showServices) && <>{" · "}{flowReadAt ? <span title={`NetFlow · ${destinationWindow}${destinationWindowSec >= 120 && destinationWindowSec < 300 ? " из 5 запрошенных" : ""} · ответ ${new Date(destinationReadAt ?? flowReadAt).toLocaleTimeString("ru-RU")} · ${flowListener ? "приёмник включён" : "приёмник выключен"} · средняя скорость по сохранённым потокам`}>IPFIX · среднее за {destinationWindow}{!flowListener ? " · приёмник выключен" : ""}</span> : <span>Данные NetFlow неизвестны</span>}</>}
</>
)
// Подсказки поиска макета: узлы и назначения текущего снимка.
@@ -2200,9 +2259,17 @@ function NetworkMapContent() {
function inspectEvent(event: MapEventRow) {
setInspectedEvent(event)
setBottomTab("events")
setAnalysisOpen(true)
const node = event.serverId ? nodeById[event.serverId] : undefined
if (node && selected?.id !== node.id) selectServer(node)
}
function inspectFlow(id: string) {
const path = tablePaths.find(row => servicePathKey(row) === id)
const service = path && [...destNodes, ...nestedServices].find(item => item.id === path.serviceId)
if (!path || !service) return
if (activeService?.id !== service.id) selectService(service)
setHighlightedPath(path)
}
const pickedBindings = new Map([...accessGroups.keys()].map(id => [id, pickedUser?.bindings.filter(binding => binding.node === id) ?? []]))
const selectedNodeRate = !selectedNodeTraffic.error && isFreshMapTrafficSample(selectedNodeTraffic.sample) ? selectedNodeTraffic.sample : undefined
function nodeTrafficHref(server: string) {
@@ -2216,11 +2283,11 @@ function NetworkMapContent() {
<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">
<PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Карта сети" }]} />
<div className="flex min-h-0 min-w-0 flex-1 flex-col gap-5 overflow-y-auto px-4 pt-5 pb-6 md:px-7 md:pt-6">
<div className="flex min-h-0 min-w-0 flex-1 flex-col gap-3 overflow-y-auto px-3 py-3 md:overflow-hidden lg:px-5">
<PageTitle
icon={<MapIcon />}
title="Карта сети"
description={mapHeadSub}
description={<span className="line-clamp-2">{mapHeadSub}</span>}
actions={
<>
{useLiveData && (
@@ -2235,8 +2302,9 @@ function NetworkMapContent() {
</>
}
/>
<details className="order-last min-w-0">
<summary className="mb-2 cursor-pointer text-sm font-medium">Сводка сети</summary>
<Dialog open={summaryOpen} onOpenChange={setSummaryOpen}>
<DialogContent className="max-h-[85svh] overflow-y-auto sm:max-w-4xl">
<DialogHeader><DialogTitle>Сводка сети</DialogTitle><DialogDescription>Состояние устройств, туннелей и потоки за текущее окно.</DialogDescription></DialogHeader>
<MapKpiStrip
className="max-lg:order-last"
servers={mapServers}
@@ -2247,21 +2315,17 @@ function NetworkMapContent() {
netflowBytes={mapTotalBytes > 0 ? mapTotalBytes : useLiveData && flowReadAt ? 0 : null}
windowSec={mapWindowSec}
filter={filter}
onFilter={(key) => setFilter(key)}
onSelect={(server) => { setSelectedGreEdge(null); setSelectedService(null); setSelected(server) }}
onFilter={(key) => { setFilter(key); setSummaryOpen(false) }}
onSelect={(server) => { setSelectedGreEdge(null); setSelectedService(null); setSelected(server); setSummaryOpen(false) }}
/>
</details>
<details className="text-sm text-muted-foreground">
<summary className="cursor-pointer font-medium text-foreground">Как читать карту</summary>
<p className="mt-2">Связи GRE и привязки пользователей показывают конфигурацию. IPFIX показывает среднюю скорость за окно. Метка IPFIX на линии означает, что известен экспортёр, а выход не подтверждён.</p>
</details>
</DialogContent>
</Dialog>
{urlState.server&&((hasSnapshot||!useLiveData)&&!selected||selected&&selWanIdx!==null&&!selected.wanUplinks?.[selWanIdx])&&<Alert variant="destructive"><AlertTitle>Объект карты недоступен</AlertTitle><AlertDescription>{!selected?"Устройство "+urlState.server+" отсутствует в текущем снимке.":"Запрошенный WAN отсутствует у выбранного устройства."}<Button type="button" variant="outline" onClick={()=>updateUrl({server:null,wan:null})}>Сбросить выбранный объект</Button></AlertDescription></Alert>}
{pickedUserId && !pickedUser && (ixOnly ? access.linuxPending : access.pending) && <p role="status" className="text-sm text-muted-foreground">Загрузка пользователя карты…</p>}
{pickedUserId && !pickedUser && !(ixOnly ? access.linuxPending : access.pending) && <Alert><AlertTitle>Пользователь карты недоступен</AlertTitle><AlertDescription><Button type="button" size="sm" variant="outline" onClick={() => updateUrl({user:null,service:null})}>Вернуться к схеме</Button></AlertDescription></Alert>}
<div className="relative flex min-w-0 shrink-0 flex-col gap-3">
<Frame spacing="sm" className="min-w-0 flex-1">
<div className="relative flex min-w-0 shrink-0 flex-col md:min-h-0 md:flex-1">
<Frame spacing="sm" className="min-h-0 min-w-0 flex-1">
<FramePanel className="flex items-center gap-1.5 p-1.5 grow-0 shrink-0 flex-wrap">
{/* Поиск узла или назначения с подсказками */}
<div className="relative min-w-[140px] flex-[1_1_150px] md:max-w-[280px]" onBlur={e => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setSearchOpen(false) }}>
@@ -2360,9 +2424,21 @@ function NetworkMapContent() {
{showUsers && <Button type="button" variant="outline" size="sm" onClick={() => setUserPicker(true)}>
<UsersIcon aria-hidden />{pickedUser?.name ?? (ixOnly ? "Linux-клиенты" : "Пользователи")}
</Button>}
{pickedUser && <Button type="button" variant="ghost" size="icon-sm" aria-label="Вся схема пользователей" onClick={() => { updateUrl({user:null, server:null, wan:null, service:null}); setSelectedService(null); setSelectedGreEdge(null); setHighlightedPath(null) }}><XIcon /></Button>}
{pickedUser && <Button type="button" variant="ghost" size="icon-sm" aria-label="Вся схема пользователей" onClick={returnToNetwork}><XIcon /></Button>}
{filterService && <Button type="button" variant="outline" size="sm" aria-label={`Сбросить фильтр сервиса ${filterService.label}`} onClick={() => setFilteredServiceId(null)}>{filterService.label}<XIcon aria-hidden /></Button>}
{showServices && hasMinorServices && <Button type="button" variant="outline" size="sm" aria-expanded={showSmallServices} onClick={() => setShowSmallServices(value => !value)}>{showSmallServices ? "Свернуть остальные" : `Остальные сервисы (${minorServices.length})`}</Button>}
<Button type="button" variant="ghost" size="sm" onClick={() => setSummaryOpen(true)}>Сводка сети</Button>
<Popover>
<PopoverTrigger render={<Button type="button" variant="ghost" size="icon-sm" aria-label="Как читать карту" />}><CircleHelpIcon aria-hidden /></PopoverTrigger>
<PopoverContent align="end" aria-label="Как читать карту" className="max-w-[calc(100vw-2rem)]">
<p className="text-sm font-semibold">Как читать карту</p>
<ol className="grid list-decimal gap-2 pl-4 text-xs text-muted-foreground">
<li>Слева выберите пользователя. Карта покажет правее его узлы подключения, выход в интернет и сервисы.</li>
<li>Откройте узел или линию. Справа появятся источник данных, состояние связи и доступные измерения.</li>
<li>Метка IPFIX показывает, где замечен трафик. Дальнейший маршрут для такой линии требует подтверждения.</li>
<li>На сервисах показана средняя скорость по сохранённым потокам IPFIX. RX/TX на узлах берутся из счётчиков RouterOS.</li>
</ol>
</PopoverContent>
</Popover>
{/* Слои */}
<Popover modal open={showLayers} onOpenChange={setShowLayers}>
@@ -2373,6 +2449,7 @@ function NetworkMapContent() {
{([
{ key: "showPingBadges", label: "RTT на связях", val: showPingBadges, set: setShowPingBadges, hint: "P" },
{ key: "showNetflow", label: "Трафик на линиях", val: showNetflow, set: setShowNetflow, hint: "" },
{ key: "showAuxLinks", label: "Вспомогательные серые линии", val: showAuxLinks, set: setShowAuxLinks, hint: "" },
{ key: "showServices", label: "Назначения", val: showServices, set: setShowServices, hint: "" },
{ key: "showUsers", label: ixOnly ? "Linux-клиенты" : "Пользователи", val: showUsers, set: setShowUsers, hint: "" },
{ key: "showAnimDots", label: "Анимация трафика", val: showAnimDots, set: setShowAnimDots, hint: "" },
@@ -2423,7 +2500,7 @@ function NetworkMapContent() {
{/* ── Canvas ── */}
<div className="flex min-h-0 min-w-0 flex-1 flex-col">
<div ref={canvasRef} className="relative h-[390px] w-full min-w-0 overflow-hidden bg-card select-none md:h-[max(540px,calc(100svh-14rem))]">
<div ref={canvasRef} className="relative h-[390px] w-full min-w-0 overflow-hidden bg-card select-none md:h-auto md:min-h-0 md:flex-1">
<p id="network-map-help" className="sr-only">Стрелки перемещают карту, плюс и минус меняют масштаб, F вписывает объекты. Tab выбирает объект, Enter открывает детали.</p>
<svg
ref={svgRef} role="group" aria-label="Интерактивная карта сети" tabIndex={0} aria-describedby="network-map-help"
@@ -2447,49 +2524,52 @@ function NetworkMapContent() {
{/* Background grid */}
<rect data-map-background x={pan.x} y={pan.y} width={W/zoom} height={viewportHeight/zoom} fill="url(#map-dots)" />
{([
...(showUsers && usersInTopology.length ? [{ lane: { x0: accessPosition.x - 96 + compactLanes, x1: accessPosition.x + 96 + compactLanes }, label: "ПОДКЛЮЧЕНИЯ", tint: false }] : []),
...(nodes.some(node => node.type === "home-router") ? [
{ lane: MAP_LANES.home, label: `HOME ROUTER · ${nodes.filter(node => node.type === "home-router").length}` },
{ lane: MAP_LANES.wan, label: `АПЛИНКИ WAN · ${nodes.reduce((sum, router) => sum + (router.wanUplinks?.length ?? 0), 0)}` },
{ lane: MAP_LANES.home, label: `ДОМАШНИЕ РОУТЕРЫ · ${nodes.filter(node => node.type === "home-router").length}`, tint: true },
{ lane: MAP_LANES.wan, label: `АПЛИНКИ WAN · ${nodes.reduce((sum, router) => sum + (router.wanUplinks?.length ?? 0), 0)}`, tint: false },
] : []),
...(!ixOnly ? [{ lane: MAP_LANES.jh, label: `JUMPHOST · ${nodes.filter(server => server.type === "jump-host").length}` }] : []),
{ lane: MAP_LANES.en, label: ixOnly ? `IX · ${nodes.length}` : `EXIT NODES · ${nodes.filter(server => server.type === "exit-node").length}${nodes.some(server => server.type === "ix-node") ? ` · IX · ${nodes.filter(server => server.type === "ix-node").length}` : ""}` },
...(visibleMapServices.length ? [{ lane: MAP_LANES.dest, label: `${destMode === "countries" ? "СТРАНЫ" : "СЕРВИСЫ"} · ${visibleMapServices.length}` }] : []),
]).map(({ lane, label }, i) => (
<g key={label} aria-hidden="true" pointerEvents="none">
<rect x={lane.x0} y={0} width={lane.x1 - lane.x0} height={H} fill="var(--foreground)" fillOpacity={i % 2 ? 0.035 : 0} />
<text x={(lane.x0 + lane.x1) / 2} y="32" textAnchor="middle" fill="var(--muted-foreground)" fontSize="11" fontWeight="600" letterSpacing="0.08em" fontFamily="Geist,sans-serif">{label}</text>
...(!ixOnly && nodes.some(node => node.type === "jump-host") ? [{ lane: MAP_LANES.jh, label: `УЗЛЫ ДОСТУПА · ${nodes.filter(server => server.type === "jump-host").length}`, tint: true }] : []),
...(nodes.some(node => node.type === "exit-node" || node.type === "ix-node") ? [{ lane: MAP_LANES.en, label: ixOnly ? `IX · ${nodes.length}` : `ИНТЕРНЕТ-ВЫХОДЫ · ${nodes.filter(server => server.type === "exit-node").length}${nodes.some(server => server.type === "ix-node") ? ` · IX · ${nodes.filter(server => server.type === "ix-node").length}` : ""}`, tint: false }] : []),
...(visibleMapServices.length ? [{ lane: MAP_LANES.dest, label: `${destMode === "countries" ? "СТРАНЫ" : "СЕРВИСЫ"} · ${visibleMapServices.length}`, tint: true, shift: emptyExitShift }] : []),
]).map(({ lane, label, tint, shift }) => (
<g key={label} aria-hidden="true" pointerEvents="none" transform={`translate(${-compactLanes - (shift ?? 0)},0)`}>
<rect x={lane.x0} y={lanesTop} width={lane.x1 - lane.x0} height={lanesBottom - lanesTop} fill="var(--foreground)" fillOpacity={tint ? 0.035 : 0} />
<text x={(lane.x0 + lane.x1) / 2} y={lanesTop + 18} textAnchor="middle" fill="var(--muted-foreground)" fontSize="12" fontWeight="600" fontFamily="Geist,sans-serif">{label}</text>
</g>
))}
{accessLinks.map(({ id, link, name, open, opacity }) => <path key={id} d={link.d} fill="none" stroke="var(--chart-2)" strokeWidth={pickedUser ? 2.5 : 1.5} opacity={opacity * (pickedUser ? 0.9 : 0.6)} pointerEvents="stroke" onPointerDown={e => e.stopPropagation()} onClick={open}><title>{name}</title></path>)}
{accessLinks.map(({ id, link, name, open, opacity }) => <path key={id} d={link.d} fill="none" stroke="var(--chart-2)" strokeWidth="1.5" opacity={opacity * 0.75} pointerEvents="stroke" onPointerDown={e => e.stopPropagation()} onClick={open}><title>{name}</title></path>)}
{/* Наблюдаемые пути от выходов и экспортёров к сервисам. */}
{destRibbons.map(({ edge, link }) => {
{destRibbons.map(({ edge, direct, detour, link }) => {
const hop = destinationRate(edge)
const selectedDestinationId = highlightedPath?.serviceId.split("|")[0]
const pathHit = Boolean(highlightedPath && (highlightedPath.enId || highlightedPath.viaId) === edge.fromId && selectedDestinationId === edge.toId)
const hl = pathHit || (!highlightedPath && (activeService?.id === edge.toId || selected?.id === edge.fromId || expandedCountryId === edge.toId || filteredServiceId === edge.toId))
const countryDim = !hl && Boolean(expandedCountryGroup) && edge.toId !== expandedCountryId
const d = direct ? detour?.d : link.d
const svc = visibleMapServices.find((s) => s.id === edge.toId)
const enName = mapServers.find((s) => s.id === edge.fromId)?.name ?? edge.fromId
const clientLabel = edge.clients?.map((c) => c.name).filter(Boolean).join(", ") || edge.clientName || "—"
const rate = hopHasRate(hop) ? ` · ${formatNetflowRate(hop)}${edge.bpsFwd + edge.bpsRev > 0 ? ` (${formatNetflowDir(hop)})` : ""}` : ""
return (
<g key={`${edge.fromId}|${edge.toId}|${Boolean(edge.observedOnly)}`} data-map-ribbon data-observation={edge.observedOnly || undefined} opacity={highlightedPath && !pathHit || filteredServiceId && !hl ? 0.12 : hl ? 1 : countryDim ? 0.12 : 0.52}
<g key={`${edge.fromId}|${edge.toId}|${Boolean(edge.observedOnly)}`} data-map-ribbon data-observation={edge.observedOnly || undefined} opacity={(activeService || selected || highlightedPath || filteredServiceId) && !hl ? 0.13 : hl ? 1 : countryDim ? 0.12 : direct ? 0.47 : 0.72}
style={{ transition: "opacity 0.3s", cursor: "pointer" }}
onPointerDown={(ev) => { ev.stopPropagation() }}
onClick={(ev) => { ev.stopPropagation(); if (svc) selectService(svc) }}>
<title>{edge.observedOnly
? `Наблюдение IPFIX · ${enName} → ${destDisplayLabel(svc, destMode, edge.toId)}${rate} · выход не подтверждён`
: `${clientLabel} → ${enName} → ${destDisplayLabel(svc, destMode, edge.toId)}${rate}`}</title>
<path d={link.d} fill="none" stroke="var(--chart-4)" strokeWidth={hl ? 2.5 : 1.5} />
<path d={link.d} fill="none" stroke="transparent" strokeWidth="14" />
{edge.observedOnly && (() => { const p = mapLinkPoint(link, 0.5); return <g transform={`translate(${p.x},${p.y})`}>
<rect x="-17" y="-8" width="34" height="16" rx="8" fill="var(--card)" stroke="var(--chart-4)" />
{d && <path data-map-route={direct ? "observation" : "service"} d={d} fill="none" stroke={direct ? "var(--muted-foreground)" : "var(--chart-4)"} strokeLinejoin="round" strokeWidth={hl ? 2.5 : 1.5} />}
{d && <path d={d} fill="none" stroke="transparent" strokeWidth="12" />}
{edge.observedOnly && detour && <g transform={`translate(${detour.marker.x},${detour.marker.y})`}>
<rect x="-17" y="-7" width="34" height="14" rx="7" fill="var(--card)" stroke="var(--muted-foreground)" />
<text textAnchor="middle" y="3.5" fill="var(--foreground)" fontSize="9">IPFIX</text>
</g> })()}
{showAnimDots && !reducedMotion && hl && hopHasRate(hop) && (
</g>}
{!d && <circle cx={link.x2 - 5} cy={link.y2} r="4" fill="var(--muted-foreground)" />}
{d && !direct && showAnimDots && !reducedMotion && hl && hopHasRate(hop) && (
<circle r="2.5" fill="var(--foreground)" opacity="0.7" pointerEvents="none">
<animateMotion dur="2.6s" repeatCount="indefinite" path={link.d} />
<animateMotion dur="2.6s" repeatCount="indefinite" path={d} />
</circle>
)}
</g>
@@ -2549,7 +2629,7 @@ function NetworkMapContent() {
</path>
})}
{/* ── Home Router → WAN satellite connectors ── */}
{homeRouters.flatMap(router => {
{showAuxLinks && homeRouters.flatMap(router => {
const rNode = nodes.find(n => n.id === router.id)
if (!rNode) return []
return (router.wanUplinks ?? []).map((wan, wIdx) => {
@@ -2590,7 +2670,7 @@ function NetworkMapContent() {
onClick={() => setUserPicker(true)}
onKeyDown={e => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); e.stopPropagation(); setUserPicker(true) } }}>
<rect className="network-map-focus-ring" x={-MAP_CARD_W / 2 - 4} y={-MAP_CARD_H / 2 - 4} width={MAP_CARD_W + 8} height={MAP_CARD_H + 8} rx="14" fill="none" stroke="var(--ring)" strokeWidth="2" />
<rect x={-MAP_CARD_W / 2} y={-MAP_CARD_H / 2} width={MAP_CARD_W} height={MAP_CARD_H} rx="12" fill="var(--card)" stroke={pickedUser ? "var(--chart-2)" : "var(--border)"} strokeWidth="1.5" />
<rect x={-MAP_CARD_W / 2} y={-MAP_CARD_H / 2} width={MAP_CARD_W} height={MAP_CARD_H} rx="12" fill="var(--card)" stroke="var(--border)" strokeWidth="1.5" />
<rect x="-70" y="-18" width="36" height="36" rx="8" fill="var(--chart-2)" fillOpacity=".18" />
<UsersIcon x="-61" y="-9" width="18" height="18" color="var(--chart-2)" />
<text x="-24" y="-3" fill="var(--foreground)" fontSize="12" fontWeight="600">{mapCardName(pickedUser?.name ?? (ixOnly ? "Linux-клиенты" : "Пользователи"), 92).text}</text>
@@ -2646,8 +2726,8 @@ function NetworkMapContent() {
}).filter(Boolean)
})}
{minorPosition && <ServiceNode label={`Остальные сервисы (${minorServices.length})`} share={minorServices.reduce((sum, service) => sum + service.share, 0)} category="Доля каждого ≤ 10%"
x={minorPosition.x} y={minorPosition.y} destMode="services" isSel={false} isVis isDragged={false} onPointerDown={() => {}} onClick={() => setShowSmallServices(true)} />}
{minorPosition && <ServiceNode label={showSmallServices ? "Свернуть остальные" : `Остальные сервисы (${groupedServices.length})`} share={groupedServices.reduce((sum, service) => sum + service.share, 0)} category={showSmallServices ? `${groupedServices.length} в группе` : "Доля каждого ≤ 10%"}
x={minorPosition.x} y={minorPosition.y} destMode="services" expanded={showSmallServices} isSel={false} isVis isDragged={false} onPointerDown={() => {}} onClick={() => setShowSmallServices(value => !value)} />}
{visibleMapServices.map((svc) => {
const pos = servicePosById[svc.id]
if (!pos) return null
@@ -2656,7 +2736,7 @@ function NetworkMapContent() {
key={svc.id}
label={destDisplayLabel(svc, destMode)}
share={svc.share}
category={destMode === "countries" ? "Страна" : svc.category}
category={destMode === "countries" ? "Страна" : serviceMapSubtitle(svc)}
rate={formatNetflowRate({ bytes: svc.bytes, bps: svc.bps, bpsFwd: svc.bps, bpsRev: 0 })}
compact={Boolean(expandedCountryGroup)}
x={pos.x}
@@ -2786,18 +2866,12 @@ function NetworkMapContent() {
: `Найдено: ${nodes.filter(isVisible).length} узл${nodes.filter(isVisible).length === 1 ? "" : nodes.filter(isVisible).length < 5 ? "а" : "ов"}`}
</div>
)}
</div>
<MapTimeline events={eventRows} now={eventsAt} onPick={inspectEvent} />
</div>
</FramePanel>
</Frame>
{/* ── Инспектор: узел, связь или назначение ── */}
{inspectorOpen && <Frame spacing="sm" className="fixed inset-x-3 bottom-3 z-30 max-h-[52svh] min-w-0 overflow-hidden shadow-lg md:absolute md:inset-x-auto md:top-14 md:right-3 md:bottom-auto md:max-h-[calc(100svh-10rem)] md:w-80">
{inspectorOpen && <Frame spacing="sm" className={cn("fixed inset-x-3 bottom-3 z-30 max-h-[52svh] min-w-0 overflow-hidden md:absolute md:bottom-2", sideInspector ? "md:inset-x-auto md:top-2 md:right-2 md:max-h-none md:w-72" : "md:inset-x-2 md:max-h-[50%]")}>
<FramePanel className="flex min-h-0 flex-1 flex-col overflow-hidden p-0">
{inspectorOpen && (
<div role="complementary" aria-label="Детали объекта карты" className="flex flex-1 flex-col overflow-hidden bg-card w-full min-h-0 min-w-0">
{userDetailsOpen && pickedUser ? <MapUserDetails user={pickedUser} groups={pickedBindings} paths={destPaths} services={destNodes} rates={access.rates} windowLabel={mapWindow}
{userDetailsOpen && pickedUser ? <MapUserDetails user={pickedUser} groups={pickedBindings} paths={destPaths} services={destNodes} rates={access.rates} userRate={access.userRate} windowLabel={destinationWindow}
onClose={() => { setInspectUser(false); returnToMapControl() }} onService={selectService} nodeName={id => nodeById[id]?.name ?? id}
trafficHref={pickedUser.linux ? "/ix" : `/traffic?${new URLSearchParams({user:pickedUser.id,from:"map"})}`} /> : selectedGreEdge ? (
<>
@@ -3011,13 +3085,14 @@ function NetworkMapContent() {
exits={selectedNestedService ? [] : selectedDestEdges}
exitName={id => mapServers.find(s => s.id === id)?.name ?? id}
country={selectedNestedService ? expandedCountry?.label : undefined}
base={useLiveData ? backendUrl : null} refresh={flowRefresh} windowLabel={mapWindow} flowAt={flowReadAt} stale={Boolean(flowError)}
base={useLiveData ? backendUrl : null} refresh={flowRefresh} windowLabel={destinationWindow} flowAt={destinationReadAt} stale={Boolean(pickedUserId ? userSnapshot?.error : flowError)}
activePath={highlightedPath} onPath={togglePathHighlight}
onClose={() => { setSelectedService(null); updateUrl({service:null}); returnToMapControl() }}
userId={pickedUser?.id} ix={ixOnly} topology={ixOnly || splitIx && isolatedIx.size > 0 ? topologyIds : undefined}
filtered={filterService?.id === activeService.id} onFilter={() => {
setFilteredServiceId(filterService?.id === activeService.id ? null : activeService.id)
setBottomTab("flows")
setAnalysisOpen(true)
}}
/>
) : liveSelectedService ? (
@@ -3051,20 +3126,20 @@ function NetworkMapContent() {
<span className="text-xs text-muted-foreground">Доля окна</span>
<span className="text-xs font-mono font-medium text-cyan-400">{serviceSharePct(liveSelectedService.share)}</span>
</div>
{mapTotalBytes > 0 && (
{destinationTotalBytes !== undefined && destinationTotalBytes > 0 && destinationNamedBytes !== undefined && (
<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">
{formatNetflowRate({
bytes: mapNamedBytes,
bps: (mapNamedBytes * 8) / Math.max(1, mapWindowSec),
bytes: destinationNamedBytes,
bps: (destinationNamedBytes * 8) / destinationWindowSec,
bpsFwd: 0,
bpsRev: 0,
})}
{" из "}
{formatNetflowRate({
bytes: mapTotalBytes,
bps: (mapTotalBytes * 8) / Math.max(1, mapWindowSec),
bytes: destinationTotalBytes,
bps: (destinationTotalBytes * 8) / destinationWindowSec,
bpsFwd: 0,
bpsRev: 0,
})}
@@ -3095,7 +3170,7 @@ function NetworkMapContent() {
</span>
</div>
</div>
<InspectorUsers users={serviceUsers(liveSelectedService, selectedDestPaths)} windowLabel={mapWindow} />
<InspectorUsers users={serviceUsers(liveSelectedService, selectedDestPaths)} windowLabel={destinationWindow} />
{expandedCountryGroup && liveSelectedService.id === expandedCountryGroup.countryId && (
<div>
<p className="text-xs font-semibold text-muted-foreground mb-2">Сервисы в стране</p>
@@ -3554,10 +3629,16 @@ function NetworkMapContent() {
)}
</FramePanel>
</Frame>}
</div>
<MapTimeline events={recentIncidents} now={eventsAt} state={useLiveData ? eventsError ?? (mapEvents === null ? "Загрузка журнала" : undefined) : undefined} onPick={inspectEvent} />
</div>
</FramePanel>
</Frame>
</div>
<MapUserPicker open={userPicker} onOpenChange={setUserPicker} users={pickerUsers} pending={ixOnly ? access.linuxPending : access.pending}
unavailable={ixOnly ? access.linuxUnavailable : access.unavailable} onPick={pickMapUser} />
<MapBottomPanel tab={bottomTab} onTab={setBottomTab} flows={flowRows} rtt={rttRows} destinations={destRows} events={eventRows} onEvent={inspectEvent} eventsError={useLiveData ? eventsError : null} stat={bottomStat} />
unavailable={ixOnly ? access.linuxUnavailable : access.unavailable} selectedUser={pickedUser} nodeName={id => mapServers.find(server => server.id === id)?.name ?? id} onPick={pickMapUser} onClear={returnToNetwork} />
<MapBottomPanel tab={bottomTab} onTab={setBottomTab} open={analysisOpen} onOpenChange={setAnalysisOpen} flows={flowRows} rtt={rttRows} destinations={destRows} events={eventRows} onEvent={inspectEvent} onFlow={inspectFlow}
onDestination={id => { const service = destNodes.find(row => row.id === id); if (service && activeService?.id !== id) selectService(service) }} eventsError={useLiveData ? eventsError : null} stat={bottomStat} />
</div>
{/* ── Context menu ── */}
{ctxMenu&&currentCtxServer&&<ContextMenu menu={{...ctxMenu,server:currentCtxServer}} trafficHref={nodeTrafficHref(currentCtxServer.id)} onClose={()=>setCtxMenu(null)} />}
+29 -13
View File
@@ -955,17 +955,32 @@ function TrafficContent({ view, user, server, service, country, exporters: mapEx
useEffect(() => {
if (!isLive || groupMode === "flows") return
let cancelled = false
const loadLiveTraffic = async (targetRange: Range) => {
const key = JSON.stringify([isLive, backendUrl, targetRange, groupMode, trafficRetry])
const controller = new AbortController()
const init = { signal: controller.signal }
let timer: ReturnType<typeof setTimeout>
const q = encodeURIComponent(range === "30d" ? "24h" : range)
async function refreshUsers() {
try {
const { users } = await apiFetch<{ users: UserTraffic[] }>(`/api/traffic/users?range=${q}`, init)
if (!controller.signal.aborted) {
setLiveUsers(users.map(toLiveUser))
const receivedAt = Date.now()
setTrafficState(state => state?.key === trafficKey ? {...state, receivedAt} : state)
}
} catch {
// Keep the last valid observation until its own expiry.
} finally {
if (!controller.signal.aborted) timer = setTimeout(() => { void refreshUsers() }, 15_000)
}
}
const loadLiveTraffic = async () => {
try {
const q = encodeURIComponent(targetRange === "30d" ? "24h" : targetRange)
const [srvRes, usersRes, ifacesRes] = await Promise.all([
apiFetch<{ servers: LiveTrafficServer[]; peaks?: { rx: number | null; tx: number | null } }>(`/api/traffic/servers?range=${q}`),
apiFetch<{ users: UserTraffic[] }>(`/api/traffic/users?range=${q}`),
apiFetch<{ interfaces: BoundIfaceTraffic[] }>(`/api/traffic/bound-interfaces?range=${q}`),
apiFetch<{ servers: LiveTrafficServer[]; peaks?: { rx: number | null; tx: number | null } }>(`/api/traffic/servers?range=${q}`, init),
apiFetch<{ users: UserTraffic[] }>(`/api/traffic/users?range=${q}`, init),
apiFetch<{ interfaces: BoundIfaceTraffic[] }>(`/api/traffic/bound-interfaces?range=${q}`, init),
])
if (cancelled) return
if (controller.signal.aborted) return
const liveIfaces = ifacesRes.interfaces.map(toLiveBound)
const mapped: ServerTraffic[] = srvRes.servers.map((s) => {
const base = toLiveServer(s)
@@ -976,7 +991,8 @@ function TrafficContent({ view, user, server, service, country, exporters: mapEx
setLiveServerOwner(JSON.stringify([isLive, backendUrl]))
setLiveUsers(mappedUsers)
setLiveBoundIfaces(liveIfaces)
setTrafficState({ key, status: "ready", receivedAt: Date.now(), peaks: srvRes.peaks })
setTrafficState({ key: trafficKey, status: "ready", receivedAt: Date.now(), peaks: srvRes.peaks })
if (groupMode === "users") timer = setTimeout(() => { void refreshUsers() }, 15_000)
setSelectedId((prev) => {
if (groupMode === view && prev === linkedId) return prev
if (groupMode === "users") return mappedUsers.some((x) => x.id === prev) ? prev : (mappedUsers[0]?.id ?? "")
@@ -984,12 +1000,12 @@ function TrafficContent({ view, user, server, service, country, exporters: mapEx
return mapped.some((x) => x.id === prev) ? prev : (mapped[0]?.id ?? "")
})
} catch (e) {
if (!cancelled) setTrafficState({ key, status: "error", error: e instanceof Error ? e.message : "Не удалось загрузить трафик" })
if (!controller.signal.aborted) setTrafficState({ key: trafficKey, status: "error", error: e instanceof Error ? e.message : "Не удалось загрузить трафик" })
}
}
void loadLiveTraffic(range)
return () => { cancelled = true }
}, [apiFetch, isLive, groupMode, backendUrl, trafficRetry, range, view, linkedId])
void loadLiveTraffic()
return () => { controller.abort(); clearTimeout(timer) }
}, [apiFetch, isLive, groupMode, backendUrl, trafficKey, range, view, linkedId])
useEffect(() => {
if (!isLive || groupMode !== "flows" || range === "30d") return
@@ -81,7 +81,7 @@ export function registerFlowAnalyticsActions(register: typeof add) {
source: "retained flow_buckets plus pending; same REST analytics engine with scoped topology",
rowLimit: 20000, topRowsPerBucketLimit: Math.max(20, limits.topN), engineTopListLimit: Math.min(50, Math.max(10, limits.topN)),
incomplete: true, coverageVerified: false, rowSumIsNetworkTotal: false, forwardingVerified: false,
inferredPathsVerified: false, historicalOwnershipVerified: false, attribution: "current named whole-interface bindings; users with hidden bindings excluded",
inferredPathsVerified: false, historicalOwnershipVerified: false, attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
backgroundEnrichmentStarted: false, collectorStarted: false }
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ аналитики превышает 1 МиБ; уменьшите страницу", 409)
return withCurrentFlowReadQuality(output,context)
@@ -72,7 +72,7 @@ export function registerFlowCatalogActions(register: typeof add) {
for (const server of selected) await assertTrafficHistorySource(context, server)
return withCurrentFlowReadQuality({ ...page, clients, total: data.total, nextOffset: offset + clients.length < data.total ? offset + clients.length : null,
incomplete: !!data.sourceWindow || page.incomplete || clients.length < data.total || clients.some(row => !row.completeSourceSet || !row.completeAttribution),
source: "retained ingress rows and current named whole-interface bindings", topRowsPerBucketLimit: data.window.topRowsPerBucketLimit,
source: "retained ingress rows and current exclusive interface bindings, including confirmed single-peer WireGuard", topRowsPerBucketLimit: data.window.topRowsPerBucketLimit,
from: data.window.since, to: data.window.until, sourceWindow: data.sourceWindow, ...sourceSemantics },context)
},
})
+1 -1
View File
@@ -59,7 +59,7 @@ export function registerFlowLiveActions(register: typeof add) {
historicalOwnershipVerified: false, currentTrafficVerified: false,
rateSemantics: "REST live rates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback",
liveMeaning: "events[].data.live means listener bound; it does not prove exporter freshness or forwarding",
attribution: "current named whole-interface bindings; users with hidden bindings excluded",
attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
collectorStarted: false, backgroundEnrichmentStarted: false }
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ live превышает 1 МиБ; уменьшите страницу или число samples", 409)
await authorize()
+1 -1
View File
@@ -53,7 +53,7 @@ export function registerFlowMapActions(register: typeof add) {
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,
referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false,
rowSumIsNetworkTotal: false, historicalOwnershipVerified: false,
attribution: "current named whole-interface bindings; users with hidden bindings excluded",
attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
collectorStarted: false, backgroundEnrichmentStarted: false, tracerouteExecuted: false }
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ карты превышает 1 МиБ; уменьшите страницы", 409)
return withCurrentFlowReadQuality(output,context)
+4 -3
View File
@@ -19,6 +19,7 @@ import { getEnabledServerById } from "../services/wireguard-live.js"
import { readTrafficCollectionContext } from "../services/traffic-collection-state.js"
import { readServerTrafficHistory, readServerTrafficHistoryWithSeries, readServerTrafficInterfaces } from "../services/traffic-history-read.js"
import { mergeBuiltTraffic } from "../services/traffic-rate.js"
import { getUserById } from "../modules/users/service/users-service.js"
import {
buildBoundInterfaceTraffic,
buildUserTrafficList,
@@ -236,9 +237,9 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
const minutes = rangeToMinutes(q.range)
const rangeEndMs = Date.now()
const rangeStartMs = rangeEndMs - minutes * 60_000
const users = await buildUserTrafficList(rangeStartMs, rangeEndMs)
const user = users.find((u) => u.id === id)
if (!user) return reply.status(404).send({ error: "Пользователь не найден" })
const source = await getUserById(id)
if (!source) return reply.status(404).send({ error: "Пользователь не найден" })
const [user] = await buildUserTrafficList(rangeStartMs, rangeEndMs, { users: [source] })
return reply.send({ user })
})
+29 -45
View File
@@ -37,7 +37,8 @@ import {
getServerCatalog,
latestWireBps,
loadFlowTopology,
resolveClient,
flowClientInterfaces,
resolveFlowClient,
resolveEn,
} from "./traffic-flow-topology.js"
@@ -95,18 +96,6 @@ function bump(
map.set(id, prev)
}
async function userIfaceAllow(userId: string): Promise<Map<number, Set<string>> | null> {
if (!userId) return null
const binds = await flowReadDbAll<{serverId:number;interfaceName:string}>('SELECT server_id AS "serverId",interface_name AS "interfaceName" FROM user_interface_bindings WHERE user_id=?',[userId])
const allow = new Map<number, Set<string>>()
for (const b of binds) {
const set = allow.get(b.serverId) ?? new Set<string>()
set.add(b.interfaceName)
allow.set(b.serverId, set)
}
return allow
}
function seriesFromRows(rows: PendingFlowRow[], minutes: number, direction: (row: PendingFlowRow) => "rx" | "tx" | "both" | null, now = Date.now()) {
const slots = Math.min(60, Math.max(5, minutes))
const slotMs = (minutes * 60_000) / slots
@@ -241,7 +230,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
const excludeOverlay = q.excludeOverlay !== false
await authorize()
const topo = await loadFlowTopology(scope?.serverIds, authorize)
const allow = q.userId ? scope ? new Map([...topo.clientByIface.values()].filter(b => b.userId === q.userId).map(b => [b.serverId, new Set([...topo.clientByIface.values()].filter(other => other.userId === q.userId && other.serverId === b.serverId).map(other => other.interfaceName))])) : await userIfaceAllow(q.userId) : null
const allow = q.userId ? flowClientInterfaces(topo, q.userId) : null
if (scope && q.userId && !allow?.size) throw new Error("Пользователь не найден в разрешённой топологии")
if (!scope) refreshFlowCatalogInBackground()
@@ -253,7 +242,8 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
const ingress = matchesIngress(row), egress = matchesEgress(row)
return ingress === egress ? null : ingress ? "rx" : "tx"
}
const selected = ifaceFilter || allow ? raw.filter(row => matchesIngress(row) || matchesEgress(row)) : raw
const selected = ifaceFilter || allow ? raw.filter(row => (matchesIngress(row) || matchesEgress(row)) &&
(!q.userId || resolveFlowClient(topo, row.serverId, resolveIfaceName(row.serverId, row.inIface).name, resolveIfaceName(row.serverId, row.outIface).name)?.userId === q.userId)) : raw
const { rows, espDirections } = collapseGreEspRows(selected, ifaceFilter ? interfaceDirection : serverDirection)
const previousMinute = new Date(Math.floor(now / 60_000) * 60_000 - 60_000).toISOString()
const ifacesForWire = new Set<string>()
@@ -370,7 +360,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
inIface: resolved.name,
outIface: outResolved.name,
}, topo.plane)
const client = resolveClient(topo, r.serverId, resolved.name) ?? resolveClient(topo, r.serverId, outResolved.name)
const client = resolveFlowClient(topo, r.serverId, resolved.name, outResolved.name)
const en = resolveEn(topo, r.nextHop, outResolved.name)
const outIface = outResolved.name === "—" ? "" : outResolved.name
const pathKey = JSON.stringify([client?.userId ?? "unknown", r.serverId, en?.id ?? "", dst, resolved.name, outIface,
@@ -546,7 +536,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
const bpsNow = ring
? (!fromBuckets.undirectedBytes && (ring.rxNow + ring.txNow) * 1_000_000) || (totalBytes * 8) / windowSec
: (recentBytes * 8) / 60 || (totalBytes * 8) / windowSec
const greNames = ringServer ? enGreIfaceNames(topo, ringServer, [...ifacesForWire]) : []
const greNames = ringServer && !q.userId ? enGreIfaceNames(topo, ringServer, [...ifacesForWire]) : []
await authorize()
const wire = ringServer ? await latestWireBps(ringServer, greNames, Boolean(scope)) : { bps: 0, bytes: 0 }
await authorize()
@@ -660,32 +650,26 @@ export async function listFlowExporters(minutes: number): Promise<FlowExportersD
}
}
export async function listFlowClients(minutes: number): Promise<{ clients: { id: string; name: string; subtitle: string; site: string; country: string; status: "online" | "offline" | "degraded"; rxNow: number; txNow: number; sessions: number; rxSeries: number[]; txSeries: number[]; bytes: number; }[]; }> {
const inputs = await readFlowClientInputs(minutes)
const users = inputs.users
const binds = users.flatMap(user => user.bindings.map(binding => ({ ...binding, userId: user.id })))
const byUser = new Map<string, typeof binds>()
for (const b of binds) {
const list = byUser.get(b.userId) ?? []
list.push(b)
byUser.set(b.userId, list)
export async function listFlowClients(minutes: number): Promise<{ clients: FlowEntityCard[] }> {
const [inputs, topo] = await Promise.all([readFlowClientInputs(minutes), loadFlowTopology()])
const byUser = new Map<string, PendingFlowRow[]>()
for (const row of inputs.window.rows) {
const inIface = resolveIfaceName(row.serverId, row.inIface).name
const outIface = resolveIfaceName(row.serverId, row.outIface).name
const client = resolveFlowClient(topo, row.serverId, inIface, outIface)
if (!client || classifyFlowPlane({ ...row, inIface, outIface }, topo.plane) !== "payload") continue
const rows = byUser.get(client.userId) ?? []
rows.push(row)
byUser.set(client.userId, rows)
}
const rows = inputs.window.rows
const clients: FlowEntityCard[] = []
for (const u of users) {
const userBinds = byUser.get(u.id) ?? []
if (userBinds.length === 0) continue
const allow = new Map<number, Set<string>>()
for (const b of userBinds) {
const set = allow.get(b.serverId) ?? new Set<string>()
set.add(b.interfaceName)
allow.set(b.serverId, set)
}
for (const u of inputs.users) {
const allow = flowClientInterfaces(topo, u.id)
const namedBindings = u.bindings.filter(binding => allow.get(binding.serverId)?.has(binding.interfaceName)).length
const bound = (id: number, iface: string) => {
const names = allow.get(id)
return names?.has(iface) || names?.has(resolveIfaceName(id, iface).name)
return allow.get(id)?.has(resolveIfaceName(id, iface).name)
}
const matched = rows.filter(r => bound(r.serverId, r.inIface) || bound(r.serverId, r.outIface))
const matched = dedupFlowRowsMaxBytes(byUser.get(u.id) ?? [])
const rates = seriesFromRows(matched, minutes, r => {
if (!bound(r.serverId, r.inIface)) return "rx"
return bound(r.serverId, r.outIface) ? "both" : "tx"
@@ -694,18 +678,18 @@ export async function listFlowClients(minutes: number): Promise<{ clients: { id:
id: u.id,
name: u.login,
subtitle: u.name || u.login,
site: `${userBinds.length} ifaces`,
site: namedBindings < u.bindings.length ? `IPFIX: ${namedBindings}/${u.bindings.length} привязок` : `${namedBindings} инт.`,
country: "UN",
status: u.active ? "online" : "offline",
rxNow: rates.rxNow,
txNow: rates.txNow,
rxNow: matched.length ? rates.rxNow : null,
txNow: matched.length ? rates.txNow : null,
sessions: matched.length,
rxSeries: rates.rx,
txSeries: rates.tx,
rxSeries: matched.length ? rates.rx : [],
txSeries: matched.length ? rates.tx : [],
bytes: matched.reduce((sum, row) => sum + row.bytes, 0),
})
}
clients.sort((a, b) => b.rxNow - a.rxNow)
clients.sort((a, b) => (b.rxNow ?? -1) - (a.rxNow ?? -1))
return { clients }
}
@@ -36,6 +36,7 @@ const WELL_KNOWN: Record<string, string> = {
"17:853": "DNS",
"6:853": "DNS",
"17:51820": "WireGuard",
"17:13231": "WireGuard",
"17:13232": "WireGuard",
"17:51821": "WireGuard",
"17:4789": "VXLAN",
@@ -63,6 +64,13 @@ export function applicationName(proto: number, dstPort: number, srcPort = 0): st
return WELL_KNOWN[dstKey] ?? WELL_KNOWN[srcKey] ?? `${protoName(proto)}/${dstPort || srcPort || "—"}`
}
/** Port hints keep a conventional service port separate from the observed transport. */
export function flowPortApplication(proto: number, port: number): string | null {
if (proto === 6 && port === 853) return "DNS over TLS"
if (proto === 17 && port === 853) return "Защищённый DNS"
return port > 0 ? WELL_KNOWN[`${proto}:${port}`] ?? null : null
}
export interface FlowMatchQuery {
serverId?: number
userId?: string
@@ -89,7 +89,12 @@ assert.equal(resolveFlowBrand("173.194.160.163", 15169, "GOOGLE", 6, 443, 51234)
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 17, 443, 50000)?.service, "YouTube")
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 6, 80, 50000)?.service, "Google")
assert.equal(resolveFlowBrand("2001:4860:4860::8888", 15169, "GOOGLE", 17, 53, 53000)?.service, "Google")
assert.equal(resolveFlowBrand("2001:4860:4860::8888", 15169, "GOOGLE", 17, 443, 50000)?.service, "YouTube")
assert.equal(resolveFlowBrand("2001:4860:4860::8888", 15169, "GOOGLE", 17, 443, 50000)?.service, "Google")
assert.equal(resolveFlowBrand("2001:4860:4860:0:0:0:0:8844/128", 15169, "GOOGLE", 6, 443)?.service, "Google")
assert.equal(resolveFlowBrand("::ffff:8.8.4.4", 15169, "", 17, 443)?.service, "Google")
assert.equal(resolveFlowBrand("2607:f8b0::123", 15169, "", 17, 443)?.service, "YouTube")
assert.equal(resolveFlowBrand("64.233.161.1", 396982, "", 6, 443)?.service, "Google")
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 6, 50000, 443)?.service, "Google", "443 на стороне клиента")
assert.equal(brandByAsn(32934)?.service, "Meta")
assert.equal(lookupBrand("157.240.12.52", 0)?.service, "Meta")
@@ -100,12 +105,12 @@ assert.equal(isNamedInternetService("Instagram", "Видео / стриминг"
assert.equal(
resolveFlowBrand("157.240.12.52", 32934, "FACEBOOK", 6, 443, 51234)?.service,
"Instagram",
"HTTPS на Meta front → Instagram, как YouTube на Google",
"HTTPS в сети Meta",
)
assert.equal(
resolveFlowBrand("57.144.22.192", 0, "", 17, 443, 50000)?.service,
"Instagram",
"cdninstagram CIDR :443 без ASN → Instagram",
"QUIC в префиксе Meta без ASN",
)
assert.equal(
resolveFlowBrand("157.240.12.52", 32934, "FACEBOOK", 6, 80, 50000)?.service,
+20 -30
View File
@@ -1,10 +1,12 @@
import { ipInCidrV4, parseCidrV4 } from "./traffic-flow-ip.js"
import { canonicalIp, ipInCidrV4, ipv6ToInt, parseCidrV4 } from "./traffic-flow-ip.js"
export const OTHER_SERVICE = "Прочее"
export interface BrandHit {
service: string
category: string
operator?: string
heuristic?: true
}
const CDN = { category: "CDN" } as const
@@ -12,6 +14,7 @@ const WEB = { category: "Веб" } as const
const VIDEO = { category: "Видео / стриминг" } as const
const GAMES = { category: "Игры" } as const
const VOICE = { category: "Голос" } as const
const MESSAGING = { category: "Мессенджеры" } as const
const AI = { category: "ИИ" } as const
const DNS = { category: "DNS" } as const
@@ -39,7 +42,7 @@ const TIMEWEB: BrandHit = { service: "Timeweb", ...CDN }
const BEGET: BrandHit = { service: "Beget", ...CDN }
const DDOS_GUARD: BrandHit = { service: "DDoS-Guard", ...CDN }
const META: BrandHit = { service: "Meta", ...CDN }
const INSTAGRAM: BrandHit = { service: "Instagram", ...VIDEO }
const INSTAGRAM: BrandHit = { service: "Instagram", operator: META.service, ...VIDEO }
const GOOGLE: BrandHit = { service: "Google", ...WEB }
const GITHUB: BrandHit = { service: "GitHub", ...WEB }
@@ -54,7 +57,9 @@ const WIKIPEDIA: BrandHit = { service: "Wikipedia", ...WEB }
const PAYPAL: BrandHit = { service: "PayPal", ...WEB }
const SALESFORCE: BrandHit = { service: "Salesforce", ...WEB }
const YOUTUBE: BrandHit = { service: "YouTube", ...VIDEO }
const YOUTUBE: BrandHit = { service: "YouTube", operator: GOOGLE.service, ...VIDEO }
const LIKELY_YOUTUBE: BrandHit = { ...YOUTUBE, heuristic: true }
const LIKELY_INSTAGRAM: BrandHit = { ...INSTAGRAM, heuristic: true }
const NETFLIX: BrandHit = { service: "Netflix", ...VIDEO }
const TWITCH: BrandHit = { service: "Twitch", ...VIDEO }
const TIKTOK: BrandHit = { service: "TikTok", ...VIDEO }
@@ -69,7 +74,7 @@ const ROBLOX: BrandHit = { service: "Roblox", ...GAMES }
const UBISOFT: BrandHit = { service: "Ubisoft", ...GAMES }
const DISCORD: BrandHit = { service: "Discord", ...VOICE }
const TELEGRAM: BrandHit = { service: "Telegram", ...VOICE }
const TELEGRAM: BrandHit = { service: "Telegram", ...MESSAGING }
const ZOOM: BrandHit = { service: "Zoom", ...VOICE }
const CHATGPT: BrandHit = { service: "ChatGPT", ...AI }
@@ -222,18 +227,13 @@ const HOLDER_BRANDS: Array<{ re: RegExp; hit: BrandHit }> = [
const NON_ISO = new Set(["EU", "AP", "ZZ", "XX", "A1", "A2", "O1"])
const STEAM_ASN = 32590
const GOOGLE_FRONT_ASN = new Set([15169, 396982])
/** AS32934 / AS63293 — Meta front (Facebook + Instagram CDN). AS54115 — WhatsApp, не Instagram. */
const META_FRONT_ASN = new Set([32934, 63293])
const WHATSAPP_ASN = 54115
const GOOGLE_DNS_V6 = new Set([ipv6ToInt("2001:4860:4860::8888")!, ipv6ToInt("2001:4860:4860::8844")!])
function isGooglePublicDns(ip: string): boolean {
return ipInCidrV4(ip, "8.8.8.0/24") || ipInCidrV4(ip, "8.8.4.0/24")
}
function isHttpsOrQuic(proto: number, dstPort: number, srcPort: number): boolean {
if (proto !== 6 && proto !== 17) return false
return dstPort === 443 || srcPort === 443
const host = canonicalIp(ip)
if (host === "8.8.8.8" || host === "8.8.4.4") return true
const ipv6 = host.includes(":") ? ipv6ToInt(host) : null
return ipv6 !== null && GOOGLE_DNS_V6.has(ipv6)
}
export function isIsoCountry(code: string): boolean {
@@ -295,19 +295,10 @@ export function lookupBrand(ip: string, asn: number): BrandHit | null {
return brandByCidr(ip) || brandByAsn(asn)
}
function isGoogleFront(asn: number, cidrBrand: BrandHit | null, asnBrand: BrandHit | null): boolean {
return GOOGLE_FRONT_ASN.has(asn) || cidrBrand?.service === "Google" || asnBrand?.service === "Google"
}
function isInstagramFront(asn: number, cidrBrand: BrandHit | null, asnBrand: BrandHit | null): boolean {
if (asn === WHATSAPP_ASN) return false
return META_FRONT_ASN.has(asn) || cidrBrand?.service === "Meta" || asnBrand?.service === "Meta"
}
/**
* Cloudflare CIDR бьёт holder (витрина на CF не становится Steam).
* Holder (YouTube / Instagram и др.) бьёт остальные CIDR/ASN.
* HTTPS/QUIC на Google front → YouTube (кроме 8.8.8.8); на Meta front → Instagram (кроме WhatsApp ASN).
* На порту 443 интернет-узла общие сети Google и Meta дают вероятную атрибуцию.
* Порты Steam — только AS32590 и не выше Cloudflare CIDR.
*/
export function resolveFlowBrand(
@@ -323,13 +314,12 @@ export function resolveFlowBrand(
const holderBrand = brandByHolder(holder)
if (holderBrand) return holderBrand
const asnBrand = brandByAsn(asn)
if (!isGooglePublicDns(ip) && isHttpsOrQuic(proto, dstPort, srcPort) && isGoogleFront(asn, cidrBrand, asnBrand)) {
return YOUTUBE
}
if (isHttpsOrQuic(proto, dstPort, srcPort) && isInstagramFront(asn, cidrBrand, asnBrand)) {
return INSTAGRAM
}
const fromLookup = cidrBrand || asnBrand
if (asnBrand === YOUTUBE && cidrBrand === GOOGLE) return YOUTUBE
if ((proto === 6 || proto === 17) && dstPort === 443) {
if (fromLookup === GOOGLE && (!asn || asn === 15169) && !isGooglePublicDns(ip)) return LIKELY_YOUTUBE
if (fromLookup === META && (!asn || asn === 32934 || asn === 63293)) return LIKELY_INSTAGRAM
}
if (fromLookup) return fromLookup
if (asn === STEAM_ASN && isSteamGamePort(proto, dstPort, srcPort)) return STEAM
return null
@@ -8,14 +8,18 @@ for (const value of [-1, NaN, Infinity, "bad", "1.5", "9007199254740992", null,
assert.equal(flowCounter("0"), 0); assert.equal(flowCounterSum([0, 5, 10]), 15)
assert.throws(() => flowCounterSum([Number.MAX_SAFE_INTEGER, 1]))
const row = { serverId: 1, bytes: 1000, packets: 10, inIface: "client-vlan", bucketAt: "2026-10-19T00:00:00Z" } as PendingFlowRow
const user: FlowClientInput = { id: "u", login: "user", name: "Name", active: true, bindingCount: 2, selectedBindingCount: 1, bindings: [{ serverId: 1, interfaceName: "client-vlan", peerSpecific: false }] }
const user: FlowClientInput = { id: "u", login: "user", name: "Name", active: true, bindingCount: 2, selectedBindingCount: 1, bindings: [{ serverId: 1, interfaceName: "client-vlan", peerSpecific: false, attributable: true }] }
const observed = observeFlowClient(user, [row, { ...row, inIface: "2", bytes: 9999 }, { ...row, serverId: 2, bytes: 8888 }], 5)
assert.equal(observed.ingressNamedRowsBytes, 1000); assert.equal(observed.ingressNamedRowCount, 1)
assert.equal(observed.ifIndexRowsNotAttributed, 1); assert.equal(observed.completeSourceSet, false); assert.equal(observed.completeAttribution, false)
assert.equal(observed.availability, "unknown"); assert.equal(observed.rxMbps, null); assert.equal(observed.txMbps, null); assert.equal(observed.historicalOwnershipVerified, false)
assert.equal(observeFlowClient(user, [row], 5).completeAttribution, false)
const peer = observeFlowClient({ ...user, bindings: [{ ...user.bindings[0], peerSpecific: true }] }, [row], 5)
const peer = observeFlowClient({ ...user, bindings: [{ ...user.bindings[0], peerSpecific: true, attributable: false }] }, [row], 5)
assert.equal(peer.ingressNamedRowsBytes, null); assert.equal(peer.peerBindingsNotAttributed, 1)
const exclusivePeer = observeFlowClient({ ...user, bindingCount: 1, bindings: [{ ...user.bindings[0], peerSpecific: true }] }, [row], 5)
assert.equal(exclusivePeer.ingressNamedRowsBytes, 1000)
assert.equal(exclusivePeer.peerBindingsNotAttributed, 0)
assert.equal(exclusivePeer.completeAttribution, true)
assert.equal(observeFlowClient({ ...user, active: false }, [], 5).availability, "unknown")
const source = { id: 1, name: "R", site: "site", country: "RU", host: "192.0.2.1", type: "home-router", enabled: false }
const exporter = observeFlowExporter({ catalog: { list: [source], byId: new Map([[1, source]]) }, configuredIds: new Set([1]), configurationMembershipVerified: true, window: { rows: [row], since: "", until: "", topRowsPerBucketLimit: 20 } }, 1, 5)
@@ -3,7 +3,7 @@ import { flowCounter, flowCounterSum } from "./traffic-flow-observed-values.js"
export { flowCounter, flowCounterSum } from "./traffic-flow-observed-values.js"
import { listStoredFlowRows, type PendingFlowRow } from "./traffic-flow-ingest.js"
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
import { getServerCatalog } from "./traffic-flow-topology.js"
import { flowBindingAttributionSql, getServerCatalog } from "./traffic-flow-topology.js"
import { observeFlowRing } from "./traffic-flow-engine.js"
const fail = (message: string) => Object.assign(new Error(message), { statusCode: 502 })
@@ -39,7 +39,7 @@ export async function readFlowExporterInputs(minutes: number, serverIds?: readon
}
export interface FlowClientInput {
id: string; login: string; name: string; active: boolean; bindingCount: number; selectedBindingCount: number;
bindings: { serverId: number; interfaceName: string; peerSpecific: boolean }[];
bindings: { serverId: number; interfaceName: string; peerSpecific: boolean; attributable: boolean }[];
}
/** Eligibility, hidden-binding exclusion, paging and selected bindings use one
* SQL statement/snapshot. No hidden user or binding is deserialized in Node. */
@@ -57,7 +57,8 @@ export async function readFlowClientInputs(minutes: number, options?: { serverId
SELECT p.*,
(SELECT count(*) FROM user_interface_bindings b WHERE b.user_id=p.id) AS "bindingCount",
(SELECT count(*) FROM user_interface_bindings b WHERE b.user_id=p.id AND ($1::bigint[] IS NULL OR b.server_id=ANY($1))) AS "selectedBindingCount",
COALESCE((SELECT jsonb_agg(jsonb_build_object('serverId',b.server_id,'interfaceName',b.interface_name,'peerSpecific',b.peer_public_key<>''))
COALESCE((SELECT jsonb_agg(jsonb_build_object('serverId',b.server_id,'interfaceName',b.interface_name,
'peerSpecific',b.peer_public_key<>'','attributable',(${flowBindingAttributionSql})))
FROM (SELECT b.* FROM user_interface_bindings b WHERE b.user_id=p.id AND ($1::bigint[] IS NULL OR b.server_id=ANY($1)) ORDER BY b.id LIMIT $5) b),'[]'::jsonb) AS bindings
FROM page p
) SELECT (SELECT count(*) FROM eligible) AS total,COALESCE(jsonb_agg(to_jsonb(projected)),'[]'::jsonb) AS users FROM projected
@@ -68,7 +69,7 @@ export async function readFlowClientInputs(minutes: number, options?: { serverId
if (!user || typeof user.id !== "string" || typeof user.login !== "string" || typeof user.name !== "string" || typeof user.active !== "boolean" || !Array.isArray(user.bindings)) throw fail("Некорректный клиент NetFlow")
const bindingCount = flowCounter(user.bindingCount), selectedBindingCount = flowCounter(user.selectedBindingCount)
if (options && user.bindings.length > 1000 || user.bindings.length !== selectedBindingCount) throw fail("Превышен предел привязок клиента NetFlow")
if (user.bindings.some((binding: FlowClientInput["bindings"][number]) => !Number.isSafeInteger(binding.serverId) || typeof binding.interfaceName !== "string" || typeof binding.peerSpecific !== "boolean" || selected && !selected.includes(binding.serverId))) throw fail("Некорректная привязка клиента NetFlow")
if (user.bindings.some((binding: FlowClientInput["bindings"][number]) => !Number.isSafeInteger(binding.serverId) || typeof binding.interfaceName !== "string" || typeof binding.peerSpecific !== "boolean" || typeof binding.attributable !== "boolean" || selected && !selected.includes(binding.serverId))) throw fail("Некорректная привязка клиента NetFlow")
return { id: user.id, login: user.login, name: user.name, active: user.active, bindingCount, selectedBindingCount, bindings: user.bindings }
})
return { users, total, window: await readFlowCatalogWindow(minutes, selected) }
@@ -84,16 +85,16 @@ export function observeFlowExporter(input: Awaited<ReturnType<typeof readFlowExp
}
export function observeFlowClient(user: FlowClientInput, rows: PendingFlowRow[], minutes: number) {
const interfaces = new Map<number, Set<string>>()
for (const binding of user.bindings) if (!binding.peerSpecific) {
for (const binding of user.bindings) if (binding.attributable) {
const names = interfaces.get(binding.serverId) ?? new Set<string>(); names.add(binding.interfaceName); interfaces.set(binding.serverId, names)
}
const ifIndexRowsNotAttributed = rows.filter(row => interfaces.has(row.serverId) && /^#?\d+$/.test(row.inIface)).length
const matched = rows.filter(row => !/^#?\d+$/.test(row.inIface) && interfaces.get(row.serverId)?.has(row.inIface))
const attributable = user.bindings.some(binding => !binding.peerSpecific), bytes = attributable ? flowCounterSum(matched.map(row => row.bytes)) : null
const attributable = interfaces.size > 0, bytes = attributable ? flowCounterSum(matched.map(row => row.bytes)) : null
return { id: user.id, name: user.login, displayName: user.name, accountEnabled: user.active, availability: "unknown",
scopedBindingCount: user.bindingCount, selectedBindingCount: user.selectedBindingCount, peerBindingsNotAttributed: user.bindings.filter(binding => binding.peerSpecific).length,
completeSourceSet: user.bindingCount === user.selectedBindingCount, completeAttribution: user.bindingCount === user.selectedBindingCount && user.bindings.every(binding => !binding.peerSpecific) && ifIndexRowsNotAttributed === 0,
ifIndexRowsNotAttributed, historicalOwnershipVerified: false, attribution: "current-named-whole-interface-bindings",
scopedBindingCount: user.bindingCount, selectedBindingCount: user.selectedBindingCount, peerBindingsNotAttributed: user.bindings.filter(binding => binding.peerSpecific && !binding.attributable).length,
completeSourceSet: user.bindingCount === user.selectedBindingCount, completeAttribution: user.bindingCount === user.selectedBindingCount && user.bindings.every(binding => binding.attributable) && ifIndexRowsNotAttributed === 0,
ifIndexRowsNotAttributed, historicalOwnershipVerified: false, attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard",
ingressNamedRowsBytes: bytes, ingressNamedRowCount: attributable ? matched.length : null,
ingressNamedRowsMeanMbps: bytes === null ? null : bytes * 8 / (minutes * 60) / 1000000,
serverContextFlowRing: user.bindings.length ? { serverId: user.bindings[0].serverId, scope: "server-payload; not per-client", ...observeFlowRing(user.bindings[0].serverId) } : null,
@@ -1,5 +1,5 @@
import assert from "node:assert/strict"
import { applicationName } from "./traffic-flow-apps.js"
import { applicationName, flowPortApplication } from "./traffic-flow-apps.js"
import { classifyFlowDst, disableCatalogFetchForTests, resetFlowCatalogForTests, seedFlowCatalogForTests } from "./traffic-flow-classify.js"
disableCatalogFetchForTests()
@@ -7,12 +7,17 @@ resetFlowCatalogForTests()
seedFlowCatalogForTests({
cidrs: [{ cidr: "192.0.2.0/24", purpose: "steam-gaming" },
{ cidr: "198.51.100.0/25", purpose: "Игры" },
{ cidr: "198.51.100.128/25", purpose: "Видео / стриминг" }],
{ cidr: "198.51.100.128/25", purpose: "Видео / стриминг" },
{ cidr: "173.194.0.0/16", purpose: "GOOGLE" },
{ cidr: "173.194.1.0/24", purpose: "Work" },
{ cidr: "57.144.0.0/16", purpose: "Meta" },
{ cidr: "203.0.113.128/25", purpose: "main" }],
})
const hit = classifyFlowDst("192.0.2.10", 6, 443, 50000, null)
assert.equal(hit.category, "Игры")
assert.equal(hit.service, "steam-gaming")
assert.equal(hit.basis, "catalog")
assert.equal(classifyFlowDst("198.51.100.10", 6, 443, 50000, null).category, "Игры")
assert.equal(classifyFlowDst("198.51.100.150", 6, 443, 50000, null).category, "Видео / стриминг")
@@ -37,11 +42,11 @@ const google = classifyFlowDst("173.194.160.163", 6, 443, 1, {
ok: true,
fetchedAt: Date.now(),
})
assert.equal(google.service, "YouTube")
assert.equal(google.category, "Видео / стриминг")
assert.deepEqual(google, { service: "YouTube", category: "Видео / стриминг", basis: "heuristic" })
assert.equal(classifyFlowDst("173.194.1.1", 17, 443, 50000, null).service, "Work")
const googleCidr = classifyFlowDst("173.194.151.65", 6, 80, 50000, null)
assert.equal(googleCidr.service, "Google")
assert.equal(googleCidr.service, "GOOGLE")
assert.equal(googleCidr.category, "Веб")
const youtube = classifyFlowDst("173.194.160.163", 6, 443, 1, {
@@ -56,6 +61,8 @@ const youtube = classifyFlowDst("173.194.160.163", 6, 443, 1, {
})
assert.equal(youtube.service, "YouTube")
assert.equal(youtube.category, "Видео / стриминг")
assert.equal(youtube.basis, "network")
assert.equal(classifyFlowDst("208.65.153.1", 17, 443, 50000, null).basis, "network")
const valve = classifyFlowDst("203.0.113.40", 17, 27015, 50000, {
prefix: "203.0.113.0/24",
@@ -119,8 +126,8 @@ const googleCloud = classifyFlowDst("203.0.113.43", 6, 443, 1, {
ok: true,
fetchedAt: Date.now(),
})
assert.equal(googleCloud.service, "YouTube")
assert.equal(googleCloud.category, "Видео / стриминг")
assert.equal(googleCloud.service, "Google")
assert.equal(googleCloud.category, "Веб")
const gre = classifyFlowDst("198.51.100.1", 47, 0, 0, null)
assert.equal(gre.service, "GRE")
@@ -146,8 +153,10 @@ const dnsGoogle = classifyFlowDst("8.8.8.8", 17, 53, 53000, {
ok: true,
fetchedAt: Date.now(),
})
assert.equal(dnsGoogle.service, "Google")
assert.notEqual(dnsGoogle.service, "Прочее")
assert.equal(dnsGoogle.service, "DNS")
assert.deepEqual(classifyFlowDst("104.18.35.51", 6, 853, 53000, null), {service: "DNS", category: "DNS", basis: "port"})
assert.deepEqual(classifyFlowDst("203.0.113.10", 17, 13231, 53000, null), {service: "WireGuard", category: "Туннель", basis: "port"})
assert.deepEqual(classifyFlowDst("203.0.113.132", 6, 443, 53000, null), {service: "Прочее", category: "Прочее", basis: "unknown"})
const ipv6Yt = classifyFlowDst("2001:4860:4860::8888", 17, 443, 50000, {
prefix: "2001:4860:4860::8888/128",
asn: 15169,
@@ -158,7 +167,7 @@ const ipv6Yt = classifyFlowDst("2001:4860:4860::8888", 17, 443, 50000, {
ok: true,
fetchedAt: Date.now(),
})
assert.equal(ipv6Yt.service, "YouTube")
assert.equal(ipv6Yt.service, "Google")
const instagram = classifyFlowDst("157.240.12.52", 6, 443, 62598, {
prefix: "157.240.0.0/16",
@@ -170,9 +179,7 @@ const instagram = classifyFlowDst("157.240.12.52", 6, 443, 62598, {
ok: true,
fetchedAt: Date.now(),
})
assert.equal(instagram.service, "Instagram")
assert.equal(instagram.category, "Видео / стриминг")
assert.notEqual(instagram.service, "Meta")
assert.deepEqual(instagram, { service: "Instagram", category: "Видео / стриминг", basis: "heuristic" })
const metaHttp = classifyFlowDst("157.240.12.52", 6, 80, 50000, {
prefix: "157.240.0.0/16",
@@ -198,14 +205,17 @@ const igHolder = classifyFlowDst("203.0.113.80", 6, 443, 1, {
fetchedAt: Date.now(),
})
assert.equal(igHolder.service, "Instagram")
assert.equal(igHolder.basis, "network")
const igCidr = classifyFlowDst("57.144.22.192", 17, 443, 50000, null)
assert.equal(igCidr.service, "Instagram")
assert.equal(igCidr.category, "Видео / стриминг")
assert.deepEqual(igCidr, { service: "Instagram", category: "Видео / стриминг", basis: "heuristic" })
const esp = classifyFlowDst("198.51.100.1", 50, 0, 0, null)
assert.equal(esp.category, "Туннель")
assert.equal(applicationName(17, 443, 50000), "QUIC")
assert.equal(applicationName(17, 853, 50000), "DNS")
assert.equal(flowPortApplication(6, 853), "DNS over TLS")
assert.equal(flowPortApplication(17, 853), "Защищённый DNS")
assert.equal(flowPortApplication(17, 50505), null)
console.log("traffic-flow-classify.test.ts: ok")
+21 -10
View File
@@ -6,10 +6,12 @@ import { withActiveDatabaseRequest } from "../modules/mcp/database-request-lease
import { ipInCidrV4, parseCidrV4 } from "./traffic-flow-ip.js"
import type { FlowIpMeta } from "./traffic-flow-ripe.js"
import { applicationName } from "./traffic-flow-apps.js"
import type { FlowServiceBasis } from "@mmapp/contracts/traffic-flow"
export interface FlowClassification {
service: string
category: string
basis: FlowServiceBasis
}
interface CatalogCidr {
@@ -54,6 +56,7 @@ export function categoryFromPurpose(purpose: string, proto: number, dstPort: num
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 (/мессенджер|telegram/.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"
@@ -71,6 +74,11 @@ function matchCidr(ip: string,rows=cidrs): CatalogCidr | null {
return null
}
function servicePurpose(value: string | undefined): string | undefined {
const purpose = value?.trim()
return purpose && !/^(main|default|other|прочее)$/i.test(purpose) ? purpose : undefined
}
export function classifyFlowDst(
dst: string,
proto: number,
@@ -80,20 +88,23 @@ export function classifyFlowDst(
opts?: { ignoreTunnelProto?: boolean;catalog?:{cidrs:CatalogCidr[];asnPurpose:Map<number,string>} },
): FlowClassification {
if (!opts?.ignoreTunnelProto) {
if (proto === 47) return { service: "GRE", category: "Туннель" }
if (proto === 50) return { service: "ESP", category: "Туннель" }
if (proto === 47) return { service: "GRE", category: "Туннель", basis: "port" }
if (proto === 50) return { service: "ESP", category: "Туннель", basis: "port" }
}
const app = applicationName(proto, dstPort, srcPort)
if (app === "WireGuard") return { service: "WireGuard", category: "Туннель" }
const hit = matchCidr(dst,opts?.catalog?.cidrs)
if ((proto === 6 || proto === 17) && (dstPort === 53 || dstPort === 853)) return { service: "DNS", category: "DNS", basis: "port" }
if (app === "WireGuard") return { service: "WireGuard", category: "Туннель", basis: "port" }
const prefixPurpose = servicePurpose(matchCidr(dst,opts?.catalog?.cidrs)?.purpose)
const holder = ripe?.holder ?? ""
const brand = resolveFlowBrand(dst, ripe?.asn ?? 0, holder, proto, dstPort, srcPort)
const asnName = ripe?.asn ? (opts?.catalog?.asnPurpose??asnPurpose).get(ripe.asn) : undefined
const service = (hit?.purpose || brand?.service || asnName || OTHER_SERVICE).trim() || OTHER_SERVICE
const category = hit
? categoryFromPurpose(hit.purpose, proto, dstPort, srcPort)
: (brand?.category || categoryFromPurpose(asnName || "", proto, dstPort, srcPort))
return { service, category }
if (prefixPurpose && prefixPurpose.toLowerCase() !== brand?.operator?.toLowerCase()) {
return { service: prefixPurpose, category: categoryFromPurpose(prefixPurpose, proto, dstPort, srcPort), basis: "catalog" }
}
if (brand) return { service: brand.service, category: brand.category, basis: brand.heuristic ? "heuristic" : "network" }
const asnName = ripe?.asn ? servicePurpose((opts?.catalog?.asnPurpose??asnPurpose).get(ripe.asn)) : undefined
const category = categoryFromPurpose(asnName || "", proto, dstPort, srcPort)
const basis = asnName ? "catalog" : category !== OTHER_SERVICE ? "port" : "unknown"
return { service: asnName || OTHER_SERVICE, category, basis }
}
/** Copies already-observed data only; never fetches the EvoBGP catalog. */
@@ -142,7 +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.deepEqual(mapInternetBrand("185.246.117.91", 17, 53, 53000, null), { service: "DNS", category: "DNS", basis: "port" })
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",
@@ -174,7 +174,7 @@ assert.equal(mapInternetBrand("8.8.8.8", 17, 53, 53000, {
holder: "GOOGLE",
ok: true,
fetchedAt: Date.now(),
}).service, "Google")
}).service, "DNS")
assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, {
prefix: "2001:4860:4860::8888/128",
asn: 15169,
@@ -184,7 +184,7 @@ assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, {
holder: "GOOGLE",
ok: true,
fetchedAt: Date.now(),
}).service, "YouTube")
}).service, "Google")
assert.equal(mapInternetBrand("64.233.161.1", 17, 443, 50000, null).service, "YouTube")
assert.equal(mapInternetBrand("142.250.1.10", 6, 443, 1, null).service, "YouTube")
+3 -3
View File
@@ -71,7 +71,7 @@ export function destCtxForIface(
}
}
const OTHER_BRAND: FlowClassification = { service: OTHER_SERVICE, category: OTHER_SERVICE }
export const OTHER_BRAND: FlowClassification = { service: OTHER_SERVICE, category: OTHER_SERVICE, basis: "unknown" }
function isTunnelProto(proto: number, dstPort: number, srcPort: number): boolean {
if (proto === 47 || proto === 50) return true
@@ -85,7 +85,7 @@ export function classifyInternetBrand(
dstPort: number,
srcPort: number,
ripe: FlowIpMeta | null,
): FlowClassification | null {
): Pick<FlowClassification, "service" | "category"> | null {
if (isTunnelProto(proto, dstPort, srcPort)) return null
const brand = resolveFlowBrand(dst, ripe?.asn ?? 0, ripe?.holder ?? "", proto, dstPort, srcPort)
if (brand && isNamedInternetService(brand.service, brand.category)) return brand
@@ -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 { service: classified.category, category: classified.category }
return { ...classified, service: classified.category }
}
export function resolveInternetDest(opts: {
@@ -114,7 +114,7 @@ setGeoipReadersForTests({
})
const v6meta = resolveFlowIp("2001:4860:4860::8888")
assert.equal(v6meta?.asn, 15169)
assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, v6meta).service, "YouTube")
assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, v6meta).service, "Google")
assert.notEqual(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, v6meta).service, "Прочее")
const cidrYt = mapInternetBrand("64.233.161.1", 17, 443, 50000, resolveFlowIp("64.233.161.1"))
assert.equal(cidrYt.service, "YouTube")
@@ -3,6 +3,8 @@ import { mock } from "node:test"
import { dbQuery } from "../db/index.js"
import { configureEngine, flushEngineNow } from "./traffic-flow-engine.js"
import { parseFlowPacket } from "./traffic-flow-parse.js"
import { buildFlowAnalytics } from "./traffic-flow-analytics.js"
import { readFlowClientInputs } from "./traffic-flow-catalog-read.js"
import { rememberServerIfaces, resetIfaceCacheForTests } from "./traffic-flow-ifindex.js"
import {
ingestParsedFlowsForServerForTests,
@@ -460,13 +462,13 @@ try {
assert.equal(leak.totalBytes, 30_000)
assert.equal(leak.namedBytes, 10_000)
assert.equal(leak.unclassifiedBytes, 20_000)
const yt = leak.services?.find((s) => s.id === "svc:youtube")
const youtube = leak.services?.find((s) => s.id === "svc:youtube")
const other = leak.services?.find((s) => s.id === "svc:other")
assert.ok(yt, "64.233:443 без RIPE → YouTube")
assert.ok(youtube, "YouTube по общему диапазону Google без RIPE")
assert.ok(other, "dest без бренда → Прочее")
assert.equal(yt.bytes, 10_000)
assert.equal(youtube.bytes, 10_000)
assert.equal(other.bytes, 20_000)
assert.ok(Math.abs(yt.share - 10 / 30) < 0.01)
assert.ok(Math.abs(youtube.share - 10 / 30) < 0.01)
assert.ok(Math.abs(other.share - 20 / 30) < 0.01)
assert.equal((leak.serviceEdges ?? []).reduce((n, e) => n + e.bytes, 0), hop.bytes)
} finally {
@@ -656,7 +658,7 @@ ingestClosed(7, [
try {
resetFlowMapHopsCacheForTests()
const rev = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
assert.ok(rev.services?.some((s) => s.id === "svc:youtube"), "реверс googlevideo:443 → YouTube")
assert.ok(rev.services?.some((s) => s.id === "svc:youtube"), "Ответный поток с порта 443 сети Google учитывается как YouTube")
assert.ok(rev.services?.some((s) => s.id === "svc:cloudflare"), "реверс Cloudflare:443 → 10.x")
assert.ok(rev.serviceEdges?.some((e) => e.toId === "svc:youtube" && e.fromId === "9"))
} finally {
@@ -735,7 +737,13 @@ ingestClosed(7, [
try {
resetFlowMapHopsCacheForTests()
const wanOnly = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
assert.equal(wanOnly.services?.find(s => s.id === "svc:youtube")?.bytes, 9000)
const youtube = wanOnly.services?.find(s => s.id === "svc:youtube")
assert.equal(youtube?.bytes, 9000)
assert.deepEqual(youtube.serviceEvidence, [{basis: "heuristic", bytes: 9000}])
assert.deepEqual(youtube.trafficTypes, [{transport: "TCP", application: "HTTPS", bytes: 9000}])
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.trafficTypes,
[{transport: "UDP", application: "DNS", bytes: 6000}])
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.serviceEvidence, [{basis: "port", bytes: 6000}])
const dns = wanOnly.serviceEdges?.find(e => e.toId === "svc:dns")
assert.deepEqual(dns && [dns.fromId, dns.observedOnly, dns.bytes], ["7", true, 6000])
const dnsPath = wanOnly.servicePaths?.find(p => p.serviceId === "svc:dns")
@@ -1044,6 +1052,7 @@ try {
try {
const map = await buildFlowMapHops({ serverId: 7, minutes: 5, minSharePct: 0 })
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.bytes, 12000)
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, new Date(bucket).toISOString())
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes, Boolean(e.observedOnly)]), [["7", 9000, true], ["10", 2000, false], ["9", 1000, false]])
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 12000)
assert.equal(map.nodeUsers?.["7"]?.find(u => u.clientName === "Alice")?.bytes, 12000)
@@ -1051,8 +1060,16 @@ try {
const recent = await buildFlowMapHops({ serverId: 7, minutes: 1, includeCurrentMinute: true, minSharePct: 0 })
assert.equal(recent.windowSec, 90)
const lastMinute = new Date(bucket + 60_000).toISOString()
assert.equal(recent.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, lastMinute)
assert.equal(recent.countryServiceGroups?.flatMap(g => g.services).find(s => s.label === "YouTube")?.lastBucketAt, lastMinute)
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)
const later = bucket + 150_000
clock.mock.mockImplementation(() => later)
ingestParsedFlowsForServerForTests(7, [{ ...flow, bytes: 0, packets: 1, outIface: "ether1" }])
const idle = await buildFlowMapHops({ serverId: 7, minutes: 3, includeCurrentMinute: true, minSharePct: 0 })
assert.equal(idle.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, lastMinute)
} finally { clock.mock.restore() }
} finally {
await dbQuery("DELETE FROM internet_path_snapshots WHERE id=?", [snapshot.id])
@@ -1132,6 +1149,36 @@ try {
assert.equal(resolveClient(topology, sid, "wg-shared"), null, "общий WG не присваивается одному пользователю")
assert.equal(resolveClient(topology, sid, "gre-owner")?.userId, alice)
}
const flow = { ...payloadFlow("8.8.8.8", 1000), inIface: "gre-owner", outIface: "uplink-a" }
ingestClosed(sid, [flow, { ...flow, inIface: "wg-shared", srcPort: 49151 }], bucket - 60_000)
const aliceMap = await buildFlowMapHops({serverId: sid, minutes: 5, userId: alice})
const aliceTraffic = await buildFlowAnalytics({serverId: sid, minutes: 5, userId: alice})
const bobTraffic = await buildFlowAnalytics({serverId: sid, minutes: 5, userId: bob})
assert.equal(aliceMap.totalBytes, 1000)
assert.equal(aliceTraffic.bytes, aliceMap.totalBytes)
assert.equal(bobTraffic.bytes, 0)
await dbQuery(`INSERT INTO user_interface_bindings(id,user_id,server_id,interface_name,interface_type,peer_public_key)
VALUES (?, ?, ?, 'wg-exclusive', 'wg', 'alice-exclusive')`, [alice + "-exclusive", alice, sid])
assert.equal(resolveClient(await loadFlowTopology([sid]), sid, "wg-exclusive"), null)
await dbQuery("UPDATE servers SET enabled=true WHERE id=?", [sid])
const sampledAt = new Date().toISOString()
await dbQuery(`INSERT INTO traffic_samples(server_id,interface_name,peer_public_key,sampled_at)
VALUES (?, 'wg-exclusive', 'alice-exclusive', ?)`, [sid, sampledAt])
await dbQuery(`INSERT INTO traffic_collection_state(server_id,server_updated_at,last_attempt_at,last_succeeded_at,status)
SELECT id,updated_at,?,?,'ok' FROM servers WHERE id=?`, [sampledAt, sampledAt, sid])
seedFlowTopologyForTests(null)
assert.equal(resolveClient(await loadFlowTopology([sid]), sid, "wg-exclusive")?.userId, alice)
const {users} = await readFlowClientInputs(5, {serverIds: [sid], allowedServerIds: [sid], offset: 0, limit: 10})
assert.equal(users.find(u => u.id === alice)?.bindings.find(b => b.interfaceName === "wg-exclusive")?.attributable, true)
ingestClosed(sid, [{ ...flow, inIface: "wg-exclusive", bytes: 2000, srcPort: 49155 }], bucket - 60_000)
resetFlowMapHopsCacheForTests()
assert.equal((await buildFlowMapHops({serverId: sid, minutes: 5, userId: alice})).totalBytes, 3000)
assert.equal((await buildFlowAnalytics({serverId: sid, minutes: 5, userId: alice})).bytes, 3000)
await dbQuery(`INSERT INTO traffic_samples(server_id,interface_name,peer_public_key,sampled_at)
VALUES (?, 'wg-exclusive', 'unbound-peer', ?)`, [sid, sampledAt])
seedFlowTopologyForTests(null)
assert.equal(resolveClient(await loadFlowTopology([sid]), sid, "wg-exclusive"), null, "второй peer виден даже без привязки в приложении")
} finally {
await dbQuery("DELETE FROM app_users WHERE id IN (?,?)", [alice, bob])
}
+42 -40
View File
@@ -2,10 +2,10 @@ import { flowReadDbAll } from "./traffic-flow-read-policy.js"
import { isDeepStrictEqual } from "node:util"
import { readFlowMapSourceLimits } from "./traffic-flow-source-limits.js"
import { flowCounter, flowCounterSum } from "./traffic-flow-observed-values.js"
import type { FlowMapInterfaceTraffic } from "@mmapp/contracts/traffic-flow"
import type { FlowMapInterfaceTraffic, FlowServiceBasis } from "@mmapp/contracts/traffic-flow"
import type { ScopedFlowAnalyticsRead } from "./traffic-flow-analytics.js"
import type { FlowMapCountryServiceGroup, FlowMapHop, FlowMapHopsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
import { flowRowMatchesFilter } from "./traffic-flow-apps.js"
import { flowPortApplication, flowRowMatchesFilter } from "./traffic-flow-apps.js"
import { OTHER_SERVICE, isNamedInternetService, mapCountryNodeId, mapCountryServiceNodeId, mapServiceNodeId, resolveRipeCountry } from "./traffic-flow-brands.js"
import type { FlowIpMeta } from "./traffic-flow-ripe.js"
import { refreshFlowCatalogInBackground } from "./traffic-flow-classify.js"
@@ -13,12 +13,13 @@ import { collapseGreEspRows, dedupFlowRowsAcrossExporters, dedupFlowRowsMaxBytes
import { getFlowListenerState, listStoredFlowRows } from "./traffic-flow-ingest.js"
import { resolveIfaceName } from "./traffic-flow-ifaces.js"
import { classifyFlowPlane, shouldKeepPlane } from "./traffic-flow-planes.js"
import { destCtxForIface, flowRateDirection, mapInternetBrand } from "./traffic-flow-dest.js"
import { destCtxForIface, flowRateDirection, mapInternetBrand, OTHER_BRAND } from "./traffic-flow-dest.js"
import { protoName } from "./traffic-flow-parse.js"
import { resolveFlowEndpoints } from "./traffic-flow-ip.js"
import { geoipReadersStatus, resolveFlowIp } from "./traffic-flow-geoip.js"
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
import { loadFlowTopology, resolveClient, getServerCatalog, type FlowClientBinding, type FlowTopology } from "./traffic-flow-topology.js"
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM } from "./traffic-flow-engine.js"
import { loadFlowTopology, resolveFlowClient, flowClientInterfaces, getServerCatalog, type FlowClientBinding } from "./traffic-flow-topology.js"
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM, minuteBucketIso } from "./traffic-flow-engine.js"
export const DEFAULT_MAP_SERVICE_MIN_SHARE_PCT = 5
export const MAP_SERVICE_NODE_CAP = 20
@@ -73,9 +74,11 @@ interface FromAcc {
interface DstAcc {
dst: string
bytes: number
lastBucketAt: string
proto: number
dstPort: number
srcPort: number
application: string | null
fromBytes: Map<string, FromAcc>
}
@@ -83,6 +86,9 @@ interface DestTotal {
label: string
category: string
bytes: number
lastBucketAt: string
trafficTypes?: Map<string, NonNullable<FlowMapService["trafficTypes"]>[number]>
serviceEvidence?: Map<FlowServiceBasis, number>
}
interface DestEdgeAcc {
@@ -155,13 +161,22 @@ export function pickMapServices(
.slice(0, cap)
}
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number): void {
const prev = totals.get(id)
if (prev) {
prev.bytes += bytes
return
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number, lastBucketAt: string,
detail?: { transport: string; application: string | null; basis: FlowServiceBasis }): void {
const total = totals.get(id) ?? { label, category, bytes: 0, lastBucketAt }
total.bytes += bytes
if (lastBucketAt > total.lastBucketAt) total.lastBucketAt = lastBucketAt
if (detail && bytes > 0) {
const { transport, application, basis } = detail
const types = total.trafficTypes ??= new Map()
const key = JSON.stringify([transport, application])
const type = types.get(key) ?? { transport, application, bytes: 0 }
type.bytes += bytes
types.set(key, type)
const evidence = total.serviceEvidence ??= new Map()
evidence.set(basis, (evidence.get(basis) ?? 0) + bytes)
}
totals.set(id, { label, category, bytes })
totals.set(id, total)
}
function bumpDestFrom(
@@ -237,8 +252,11 @@ function finalizeDestLayer(
label: s.label,
category: s.category,
bytes: s.bytes,
...(s.lastBucketAt ? { lastBucketAt: minuteBucketIso(Date.parse(s.lastBucketAt)) } : {}),
bps: (s.bytes * 8) / windowSec,
share: shareBase > 0 ? s.bytes / shareBase : 0,
...(s.trafficTypes ? { trafficTypes: [...s.trafficTypes.values()].sort((a, b) => b.bytes - a.bytes).slice(0, 5) } : {}),
...(s.serviceEvidence ? { serviceEvidence: [...s.serviceEvidence].map(([basis, bytes]) => ({ basis, bytes })).sort((a, b) => b.bytes - a.bytes) } : {}),
}))
.sort((a, b) => b.bytes - a.bytes),
minSharePct,
@@ -352,18 +370,6 @@ function ifaceUsable(name: string): boolean {
return Boolean(name) && name !== "—"
}
function resolveMapClient(
topo: FlowTopology,
serverId: number,
inName: string,
outName: string,
): FlowClientBinding | null | undefined {
const ingress = resolveClient(topo, serverId, inName)
const egress = resolveClient(topo, serverId, outName)
if (ingress && egress && ingress.userId !== egress.userId) return null
return ingress ?? egress ?? undefined
}
function bump(acc: Map<string, HopAcc>, key: string, seed: Omit<HopAcc, "bytes" | "bytesFwd" | "bytesRev">, bytes: number, dir: "fwd" | "rev" | "both"): void {
const prev = acc.get(key)
const addFwd = dir === "fwd" || dir === "both" ? bytes : 0
@@ -496,18 +502,11 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
const excludeOverlay = q.excludeOverlay !== false
await authorize()
const topo = await loadFlowTopology(scope?.serverIds, authorize)
const allow = q.userId ? new Map<number, Set<string>>() : null
if (allow) {
for (const binding of topo.clientByIface.values()) if (binding.userId === q.userId) {
const names = allow.get(binding.serverId) ?? new Set<string>()
names.add(binding.interfaceName)
allow.set(binding.serverId, names)
}
if (scope && !allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
}
const allow = q.userId ? flowClientInterfaces(topo, q.userId) : null
if (scope && allow && !allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
function rowClient(r: (typeof raw)[number]) {
return resolveMapClient(topo, r.serverId, resolveIfaceName(r.serverId, r.inIface).name, resolveIfaceName(r.serverId, r.outIface).name)
return resolveFlowClient(topo, r.serverId, resolveIfaceName(r.serverId, r.inIface).name, resolveIfaceName(r.serverId, r.outIface).name)
}
const matches = (serverId: number, iface: string) =>
@@ -631,7 +630,7 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
: undefined
const nodeBytes = new Map([[r.serverId, r.bytes]])
if (exitId !== undefined) nodeBytes.set(exitId, r.bytes)
observed.set(r, { endpoints, exitId, viaIface, reverse, client: resolveMapClient(topo, r.serverId, inName, outName), nodeBytes })
observed.set(r, { endpoints, exitId, viaIface, reverse, client: resolveFlowClient(topo, r.serverId, inName, outName), nodeBytes })
if (peerId && peerId !== r.serverId) {
const toId = String(peerId)
const dir = outId === peerId ? "fwd" : "rev"
@@ -707,9 +706,11 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
const dst = ep.internetPeer
const dstPort = ep.peerPort || r.dstPort
const srcPort = ep.otherPort || r.srcPort
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : ""
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, proto: r.proto, dstPort, srcPort, fromBytes: new Map<string, FromAcc>() }
const application = flowPortApplication(r.proto, dstPort) ?? flowPortApplication(r.proto, srcPort)
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : JSON.stringify([r.proto, application])
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, lastBucketAt: "", proto: r.proto, dstPort, srcPort, application, fromBytes: new Map<string, FromAcc>() }
acc.bytes += bytes
if (bytes > 0 && r.bucketAt > acc.lastBucketAt) acc.lastBucketAt = r.bucketAt
bumpFrom(acc, String(r.serverId), exitId === undefined ? "" : String(exitId), viaIface, bytes, reverse, client)
dstAcc.set(destKey, acc)
}
@@ -740,13 +741,14 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
const ripe = dst ? resolveFlowIp(dst) : null
const classified = dst
? mapInternetBrand(dst, acc.proto, acc.dstPort, acc.srcPort, ripe)
: { service: OTHER_SERVICE, category: OTHER_SERVICE }
: OTHER_BRAND
const svcId = mapServiceNodeId(classified.service)
bumpDestTotal(svcTotals, svcId, classified.service, classified.category, acc.bytes)
const detail = { transport: protoName(acc.proto), application: acc.application, basis: classified.basis }
bumpDestTotal(svcTotals, svcId, classified.service, classified.category, acc.bytes, acc.lastBucketAt, detail)
const country = countryDestFromRipe(ripe, dst)
bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes)
bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes, acc.lastBucketAt)
const nestedId = mapCountryServiceNodeId(country.id, svcId)
bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes)
bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes, acc.lastBucketAt, detail)
for (const from of acc.fromBytes.values()) {
const { exporterId, enId: fromId } = from
const enName = nodeName(fromId)
+1 -1
View File
@@ -7,7 +7,7 @@ export const PLANE_LABEL: Record<FlowPlane, string> = {
mgmt: "mgmt",
}
const WG_PORTS = new Set([51820, 13232, 51821])
const WG_PORTS = new Set([51820, 13231, 13232, 51821])
const FLOW_PORTS = new Set([4739, 2055])
export function isRfc1918(ip: string): boolean {
+51 -19
View File
@@ -42,6 +42,27 @@ export interface ServerCatalogEntry {
const CATALOG_TTL_MS = 5_000
// The latest completed RouterOS wave records all observed peers, including disabled peers.
export const flowBindingAttributionSql = `
NOT EXISTS (
SELECT 1 FROM user_interface_bindings conflict
WHERE conflict.server_id=b.server_id AND conflict.interface_name=b.interface_name AND conflict.id<>b.id
) AND (b.peer_public_key='' OR (b.interface_type='wg' AND EXISTS (
SELECT 1 FROM traffic_collection_state state
JOIN servers source ON source.id=state.server_id AND source.enabled AND source.updated_at=state.server_updated_at
JOIN traffic_samples peer ON peer.server_id=state.server_id AND peer.sampled_at=state.last_succeeded_at
AND peer.interface_name=b.interface_name AND peer.peer_public_key=b.peer_public_key
WHERE state.server_id=b.server_id AND state.status IN ('ok','pending')
AND state.last_succeeded_at >= now() - make_interval(secs => 5 * greatest(5, COALESCE(
(SELECT interval_sec FROM traffic_settings WHERE id=1), 30)))
AND NOT EXISTS (
SELECT 1 FROM traffic_samples sibling
WHERE sibling.server_id=peer.server_id AND sibling.sampled_at=peer.sampled_at
AND sibling.interface_name=peer.interface_name AND sibling.peer_public_key NOT IN ('',peer.peer_public_key)
)
)))
`
let seeded: FlowTopology | null = null
let topologyCache: { at: number; topo: FlowTopology } | null = null
let serverCatalogCache: { at: number; list: ServerCatalogEntry[]; byId: Map<number, ServerCatalogEntry> } | null = null
@@ -124,37 +145,30 @@ export async function loadFlowTopology(serverIds?: readonly number[], authorize:
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=u.id AND NOT(hidden.server_id=ANY(?::bigint[]))) LIMIT 1001
`, [serverIds, serverIds])
await authorize()
const binds = serverIds === undefined ? await flowReadDbAll<{userId:string;serverId:number;interfaceName:string;peerPublicKey?:string}>(
'SELECT user_id AS "userId",server_id AS "serverId",interface_name AS "interfaceName",peer_public_key AS "peerPublicKey" FROM user_interface_bindings',
) : await flowReadDbAll<{ userId: string; serverId: number; interfaceName: string; peerPublicKey?: string }>(`
SELECT b.user_id AS "userId",b.server_id AS "serverId",b.interface_name AS "interfaceName" FROM user_interface_bindings b
WHERE b.server_id=ANY(?::bigint[]) AND b.peer_public_key=''
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=b.user_id AND NOT(hidden.server_id=ANY(?::bigint[])))
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings conflict WHERE conflict.server_id=b.server_id
AND conflict.interface_name=b.interface_name AND (conflict.peer_public_key<>'' OR conflict.user_id<>b.user_id))
const binds = await flowReadDbAll<{ userId: string; serverId: number; interfaceName: string; attributable: boolean }>(`
SELECT b.user_id AS "userId",b.server_id AS "serverId",b.interface_name AS "interfaceName",
(${flowBindingAttributionSql}) AS attributable
FROM user_interface_bindings b
WHERE (?::bigint[] IS NULL OR (
b.server_id=ANY(?::bigint[]) AND ${flowBindingAttributionSql}
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=b.user_id AND NOT(hidden.server_id=ANY(?::bigint[])))
))
ORDER BY b.id
LIMIT 1001
`, [serverIds, serverIds])
LIMIT ?
`, [serverIds ?? null, serverIds ?? null, serverIds ?? null, serverIds === undefined ? null : 1001])
if (serverIds !== undefined && (binds.length > 1000 || users.length > 1000)) throw new Error("Превышен предел топологии NetFlow")
const loginById = new Map(users.map((u) => [u.id, u]))
const clientIfaces = new Map<number, Set<string>>()
const clientByIface = new Map<string, FlowClientBinding>()
const ambiguousIfaces = new Set<string>()
const allClientNames = new Set<string>()
for (const b of binds) {
const set = clientIfaces.get(b.serverId) ?? new Set<string>()
set.add(b.interfaceName)
clientIfaces.set(b.serverId, set)
allClientNames.add(b.interfaceName)
const key = ifaceKey(b.serverId, b.interfaceName)
const previous = clientByIface.get(key)
if (b.peerPublicKey || previous && previous.userId !== b.userId) {
ambiguousIfaces.add(key)
clientByIface.delete(key)
}
if (ambiguousIfaces.has(key)) continue
if (!b.attributable) continue
const user = loginById.get(b.userId)
clientByIface.set(key, {
clientByIface.set(ifaceKey(b.serverId, b.interfaceName), {
userId: b.userId,
login: user?.login || b.userId,
name: user?.name || user?.login || b.userId,
@@ -227,6 +241,24 @@ export function resolveClient(
return topo.clientByIface.get(ifaceKey(serverId, inIfaceName)) ?? null
}
/** null represents conflicting ownership; undefined means no attributable interface. */
export function resolveFlowClient(topo: FlowTopology, serverId: number, inIface: string, outIface: string) {
const ingress = resolveClient(topo, serverId, inIface)
const egress = resolveClient(topo, serverId, outIface)
if (ingress && egress && ingress.userId !== egress.userId) return null
return ingress ?? egress ?? undefined
}
export function flowClientInterfaces(topo: FlowTopology, userId: string) {
const interfaces = new Map<number, Set<string>>()
for (const binding of topo.clientByIface.values()) if (binding.userId === userId) {
const names = interfaces.get(binding.serverId) ?? new Set<string>()
names.add(binding.interfaceName)
interfaces.set(binding.serverId, names)
}
return interfaces
}
export function resolveEn(
topo: FlowTopology,
nextHop: string,
+50 -4
View File
@@ -3,7 +3,7 @@
import { useEffect, useState, type ReactNode } from "react"
import Link from "next/link"
import { ChevronRightIcon, XIcon } from "lucide-react"
import type { FlowAnalyticsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath, FlowMapUser } from "@mmapp/contracts/traffic-flow"
import type { FlowAnalyticsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath, FlowMapUser, FlowServiceBasis } from "@mmapp/contracts/traffic-flow"
import { flowMapHopsDtoSchema } from "@mmapp/contracts/traffic-flow"
import { Badge } from "@/components/reui/badge"
import { Sparkline } from "@/components/sparkline"
@@ -18,6 +18,15 @@ import { getFlowAnalytics, getFlowMapHops } from "@/shared/api/traffic-flow"
import { requestJson } from "@/shared/api/http-client"
import { matchesMapService } from "@/lib/flow-map-service-match"
const evidenceLabel: Record<FlowServiceBasis, string> = {
catalog: "По каталогу",
network: "По IP / ASN",
port: "По протоколу / порту",
heuristic: "Оценка по сети и порту",
unknown: "Сервис не определён",
}
const percent = new Intl.NumberFormat("ru-RU", {style: "percent", maximumFractionDigits: 1})
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">
@@ -148,6 +157,10 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
const remainder = Math.max(0, service.bytes - attributedBytes)
const observed = service.bytes > 0 && !stale
const currentVolume = base === null || scoped
const trafficTypes = service.trafficTypes ?? []
const serviceEvidence = service.serviceEvidence ?? []
const otherTypeBytes = Math.max(0, service.bytes - trafficTypes.reduce((sum, row) => sum + row.bytes, 0))
const typeShare = (bytes: number) => percent.format(Math.min(1, bytes / service.bytes))
const trafficQuery = new URLSearchParams({ view: "flows", service: service.label, serviceId: service.id, from: "map" })
if (scopedUser) trafficQuery.set("user", scopedUser)
else if (exporter) trafficQuery.set("server", exporter)
@@ -168,13 +181,33 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
</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)],
["Средняя скорость IPFIX", formatNetflowRate({ bps: service.bps }), "Сохранённые потоки за " + windowLabel],
[country ? "Доля страны" : "Доля трафика", percent.format(service.share)],
["Объём · " + (currentVolume ? windowLabel : volume?.window ?? "24 ч"), <>{currentVolume ? formatBytes(service.bytes) : volume?.bytes == null ? "—" : formatBytes(volume.bytes)}{volume && <time dateTime={volume.at} title={new Date(volume.at).toLocaleString("ru-RU")} className="block text-[10px] font-normal text-muted-foreground">ответ {new Date(volume.at).toLocaleTimeString("ru-RU")}</time>}</>],
exitIds.length || !exporterIds.length
? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined]
: ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"],
]} />
{trafficTypes.length > 0 && service.bytes > 0 && <section className="space-y-2 border-b px-3.5 py-3 text-xs" aria-label="Состав трафика IPFIX">
<h3 className="flex justify-between gap-2 font-medium"><span>Состав трафика</span><span className="font-normal text-muted-foreground">IPFIX · {windowLabel}</span></h3>
<dl className="space-y-1">
{trafficTypes.map(({transport, application, bytes}) => <div key={JSON.stringify([transport, application])} className="flex justify-between gap-2">
<dt>{application ? `${application} · ${transport}` : transport}</dt>
<dd className="shrink-0 font-mono tabular-nums">{typeShare(bytes)}</dd>
</div>)}
{otherTypeBytes > 0 && <div className="flex justify-between gap-2"><dt>Остальные типы</dt><dd className="font-mono tabular-nums">{typeShare(otherTypeBytes)}</dd></div>}
</dl>
{trafficTypes.some(row => row.application) && <p className="text-muted-foreground">Приложения определены по портам.</p>}
{service.lastBucketAt && <p className="text-muted-foreground">Последняя минута с потоками <time dateTime={service.lastBucketAt} className="font-mono">{new Date(service.lastBucketAt).toLocaleTimeString("ru-RU", {hour: "2-digit", minute: "2-digit"})}</time></p>}
{serviceEvidence.length ? <ul aria-label="Основание классификации" className="flex flex-wrap gap-1">
{serviceEvidence.map(row => <li key={row.basis}>
<Badge size="sm" variant={row.basis === "heuristic" ? "info-light" : "secondary"}
title={row.basis === "heuristic" ? "Сервис предполагается по сети назначения и порту 443" : undefined}>
{evidenceLabel[row.basis]}{serviceEvidence.length > 1 && ` · ${typeShare(row.bytes)}`}
</Badge>
</li>)}
</ul> : null}
</section>}
<InspectorUsers users={serviceUsers(service, paths)} windowLabel={windowLabel} />
<section className="space-y-2 border-b px-3.5 py-3"><h3 className="text-[11px] text-muted-foreground">Путь трафика</h3>
{paths.map(p => {
@@ -194,7 +227,20 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
{!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.map((f,i) => {
const port = f.internetPeerPort || f.dstPort
const transport = port ? `${f.protoName}/${port}` : f.protoName
return <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}`}>
{transport}{f.application && f.application !== transport && f.application !== f.protoName && ` · ${f.application}`} · {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>
+53 -23
View File
@@ -7,7 +7,7 @@ import type { IxLinuxBinding, IxSegment } from "@mmapp/contracts/internet-exchan
import type { FlowMapService, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
import { Badge } from "@/components/reui/badge"
import { Button, buttonVariants } from "@/components/ui/button"
import { Command, CommandDialog, CommandEmpty, CommandInput, CommandItem, CommandList } from "@/components/ui/command"
import { Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command"
import { INIT_USERS } from "@/lib/users"
import { fmtRate } from "@/lib/fmt-rate"
import { formatNetflowRate } from "@/lib/map-netflow-hops"
@@ -18,6 +18,7 @@ import { listAppUsers } from "@/shared/api/users"
type AccessBinding = { id: string; node: string; name: string; kind: string; enabled?: boolean; peerScoped?: boolean; identity?: string }
export type MapAccessUser = { id: string; name: string; login?: string; linux?: true; bindings: AccessBinding[] }
type AccessRate = { rxNow: number | null; txNow: number | null }
type UserTrafficSnapshot = { interfaces: Array<{ bindingId: string }>; observations?: { sampledAt?: string | null } }
const mapUsers = (users: typeof INIT_USERS): MapAccessUser[] => users.map(user => ({
id: user.id, name: user.name || user.login, login: user.login,
@@ -26,10 +27,10 @@ const mapUsers = (users: typeof INIT_USERS): MapAccessUser[] => users.map(user =
}))
const demoUsers = mapUsers(INIT_USERS)
export function useMapAccess(base: string | null, hasIx: boolean, refresh: number, userSelected: boolean) {
export function useMapAccess(base: string | null, hasIx: boolean, refresh: number, userId: string | null) {
const [directory, setDirectory] = useState<{ base: string; users: MapAccessUser[]; unavailable: boolean }>()
const [linux, setLinux] = useState<{ base: string; users: MapAccessUser[]; unavailable: boolean }>()
const [traffic, setTraffic] = useState<{ base: string; rates: Map<string, AccessRate> }>()
const [traffic, setTraffic] = useState<{ base: string; userId: string; user?: UserTrafficSnapshot }>()
useEffect(() => {
if (base === null) return
const controller = new AbortController()
@@ -67,30 +68,35 @@ export function useMapAccess(base: string | null, hasIx: boolean, refresh: numbe
return () => controller.abort()
}, [base, hasIx, refresh])
useEffect(() => {
if (base === null || !userSelected) return
if (base === null || !userId || userId.startsWith("ix:")) return
const controller = new AbortController()
let timer: ReturnType<typeof setTimeout>
async function load() {
const rates = new Map<string, AccessRate>()
try {
const payload = await requestJson<{ interfaces: Array<{ bindingId: string; status?: string }> }>(base!, "/api/traffic/bound-interfaces?range=5m", { signal: controller.signal })
for (const row of payload.interfaces) {
if (row.status === "offline") continue
try { rates.set(row.bindingId, projectTrafficObservations(row)) } catch { /* Invalid measurements remain unknown. */ }
}
const { user } = await requestJson<{ user: UserTrafficSnapshot }>(base!, `/api/traffic/users/${encodeURIComponent(userId!)}?range=5m`, { signal: controller.signal })
if (!controller.signal.aborted) setTraffic({ base: base!, userId: userId!, user })
} catch {
if (!controller.signal.aborted) setTraffic({ base: base!, userId: userId! })
} finally {
if (!controller.signal.aborted) {
setTraffic({ base: base!, rates })
timer = setTimeout(() => { void load().catch(() => {}) }, 15_000)
timer = setTimeout(() => { void load() }, 15_000)
}
}
}
void load().catch(() => {})
void load()
return () => { controller.abort(); clearTimeout(timer) }
}, [base, refresh, userSelected])
}, [base, refresh, userId])
const users = base === null ? demoUsers : directory?.base === base ? directory.users : []
const rates = new Map(base !== null && traffic?.base === base ? traffic.rates : undefined)
const snapshot = traffic?.base === base && traffic.userId === userId ? traffic.user : undefined
const rates = new Map<string, AccessRate>()
let userRate: ReturnType<typeof projectTrafficObservations> | undefined
if (snapshot) {
try { userRate = projectTrafficObservations(snapshot) } catch { /* Invalid measurements remain unknown. */ }
for (const row of snapshot.interfaces ?? []) {
try { rates.set(row.bindingId, projectTrafficObservations(row)) } catch { /* Invalid measurements remain unknown. */ }
}
}
const bindingsByInterface = new Map<string, { user: string; binding: AccessBinding }[]>()
for (const user of users) for (const binding of user.bindings) {
const key = JSON.stringify([binding.node, binding.name])
@@ -109,6 +115,7 @@ export function useMapAccess(base: string | null, hasIx: boolean, refresh: numbe
linuxPending: base !== null && hasIx && linux?.base !== base,
linuxUnavailable: base !== null && hasIx && linux?.base === base && linux.unavailable,
rates,
userRate,
}
}
@@ -128,25 +135,42 @@ export function accessRate(bindings: AccessBinding[], rates?: Map<string, Access
return { measured, total, rx, tx, label: measured ? `${measured < total ? "≥ " : ""}${fmtRate(rx + tx)}` : "Нет замера" }
}
export function MapUserPicker({ open, onOpenChange, users, pending, unavailable, onPick }: {
export function MapUserPicker({ open, onOpenChange, users, pending, unavailable, selectedUser, nodeName, onPick, onClear }: {
open: boolean; onOpenChange: (open: boolean) => void; users: MapAccessUser[]; pending: boolean; unavailable: boolean; onPick: (user: MapAccessUser) => void
selectedUser?: MapAccessUser; nodeName: (id: string) => string; onClear: () => void
}) {
return <CommandDialog open={open} onOpenChange={onOpenChange} title="Выбор пользователя" description="Поиск по имени, логину или интерфейсу">
const ordered = [...users].sort((a, b) => a.name.localeCompare(b.name, "ru"))
return <CommandDialog open={open} onOpenChange={onOpenChange} showCloseButton title="Выбор пользователя" description="Поиск по имени, логину, узлу или интерфейсу">
<Command>
<CommandInput aria-label="Поиск пользователей" placeholder="Имя, логин или интерфейс…" />
<div className="flex flex-col gap-1 px-3 pt-3 pb-2">
<p className="pr-8 text-sm font-semibold">Кого показать на карте?</p>
<p className="text-xs text-muted-foreground">Выберите пользователя, чтобы увидеть его подключения и сервисы.</p>
</div>
<CommandInput aria-label="Поиск пользователей" placeholder="Имя, логин, узел или интерфейс…" />
<CommandList>
<CommandEmpty>{pending ? "Загрузка пользователей…" : unavailable ? "Каталог пользователей недоступен" : "Пользователи не найдены"}</CommandEmpty>
{users.map(user => <CommandItem key={user.id} value={user.id} keywords={[user.name, user.login ?? "", ...user.bindings.map(binding => binding.name)]} onSelect={() => onPick(user)}>
<UsersIcon aria-hidden /><span className="min-w-0 flex-1 truncate">{user.name}</span>
<Badge variant="outline" size="xs">{user.bindings.length}</Badge>
</CommandItem>)}
{selectedUser && <CommandItem value="all-network" keywords={["Вся схема", "Сбросить пользователя"]} onSelect={onClear}>Вся схема</CommandItem>}
<CommandGroup heading={ordered.length ? `Пользователи · ${ordered.length}` : undefined}>
{ordered.map(user => {
const nodes = [...new Set(user.bindings.map(binding => nodeName(binding.node)))].sort()
return <CommandItem key={user.id} value={user.id} keywords={[user.name, user.login ?? "", ...nodes, ...user.bindings.map(binding => binding.name)]} onSelect={() => onPick(user)}>
<UsersIcon aria-hidden /><span className="grid min-w-0 flex-1 gap-0.5">
<span className="truncate font-medium">{user.name}</span>
<span className="truncate text-xs text-muted-foreground" title={nodes.join(", ")}>{[user.login !== user.name && user.login, ...nodes].filter(Boolean).join(" · ")}</span>
</span>
{selectedUser?.id === user.id ? <Badge variant="secondary" size="sm">На карте</Badge> : <Badge variant="outline" size="sm" title="Привязки интерфейсов">{user.bindings.length} инт.</Badge>}
</CommandItem>
})}
</CommandGroup>
</CommandList>
<p className="px-3 py-2 text-xs text-muted-foreground">↑ ↓ выбор · Enter открыть · Esc закрыть</p>
</Command>
</CommandDialog>
}
export function MapUserDetails({ user, groups, paths, services, rates, windowLabel, onClose, onService, nodeName, trafficHref }: {
export function MapUserDetails({ user, groups, paths, services, rates, userRate, windowLabel, onClose, onService, nodeName, trafficHref }: {
user: MapAccessUser; groups: Map<string, AccessBinding[]>; paths: FlowMapServicePath[]; services: FlowMapService[]; rates?: Map<string, AccessRate>; windowLabel: string
userRate?: ReturnType<typeof projectTrafficObservations>
onClose: () => void; onService: (service: FlowMapService) => void; nodeName: (id: string) => string; trafficHref?: string
}) {
return <>
@@ -156,6 +180,11 @@ export function MapUserDetails({ user, groups, paths, services, rates, windowLab
<Button size="icon-xs" variant="ghost" onClick={onClose} aria-label="Закрыть детали пользователя"><XIcon /></Button>
</header>
<div className="flex flex-col gap-3 overflow-y-auto p-3">
{!user.linux && <section className="grid gap-1 text-xs" aria-label="Трафик пользователя">
<h3 className="text-muted-foreground">Счётчики подключений · RouterOS</h3>
<p className="font-mono">RX {fmtRate(userRate?.rxNow ?? null)} · TX {fmtRate(userRate?.txNow ?? null)}</p>
{userRate?.observations?.sampledAt && (userRate.rxNow !== null || userRate.txNow !== null) && <time className="text-muted-foreground" dateTime={userRate.observations.sampledAt}>{new Date(userRate.observations.sampledAt).toLocaleTimeString("ru-RU")}</time>}
</section>}
<section className="grid gap-2"><h3 className="text-xs text-muted-foreground">Подключения</h3>
{[...groups].map(([node, bindings]) => {
const rate = accessRate(bindings, rates)
@@ -170,6 +199,7 @@ export function MapUserDetails({ user, groups, paths, services, rates, windowLab
<section className="grid gap-1 border-t pt-3"><h3 className="text-xs text-muted-foreground">Сервисы · IPFIX · {windowLabel}</h3>
{services.filter(service => paths.some(path => path.serviceId === service.id)).map(service => <Button key={service.id} variant="ghost" size="xs" className="w-full justify-between" onClick={() => onService(service)}>{service.label}<span className="font-mono">{formatNetflowRate(service)}</span></Button>)}
{!paths.length && <p className="text-xs text-muted-foreground">Нет потоков с подтверждённой привязкой к пользователю.</p>}
{!paths.length && user.bindings.some(binding => binding.peerScoped) && <p className="text-xs text-muted-foreground">Для привязки IPFIX к peer последний опрос RouterOS должен подтвердить, что на интерфейсе он один.</p>}
</section>
{trafficHref && <Link href={trafficHref} className={buttonVariants({size:"xs"})}>{user.linux ? "Открыть Linux-клиентов IX" : "Открыть в «Трафике»"}</Link>}
</div>
+49 -25
View File
@@ -1,6 +1,7 @@
"use client"
import type { ReactNode } from "react"
import { useState, type ReactNode } from "react"
import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"
import { FramePanel } from "@/components/reui/frame"
import { Badge } from "@/components/reui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
@@ -16,7 +17,7 @@ export type MapBottomTab = "flows" | "rtt" | "dest" | "events"
function Table({ head, cols, empty, children }: { head: string[]; cols: string; empty: string | null; children: ReactNode }) {
return (
<div className="max-h-[420px] overflow-auto">
<div className="max-h-[min(34svh,310px)] overflow-auto">
<div className="min-w-[720px]">
<div aria-hidden="true" className={cn("bg-muted/55 text-muted-foreground sticky top-0 z-[1] grid h-10 items-center gap-x-3 border-b px-4 text-xs font-medium", cols)}>
{head.map((h) => <span key={h}>{h}</span>)}
@@ -40,45 +41,53 @@ const EVENT_COLS = "grid-cols-[70px_110px_minmax(200px,1.4fr)_minmax(200px,2fr)]
* Рабочая панель под картой (макет v3): потоки NetFlow, RTT каналов, назначения и события.
* Строки выбранного объекта подсвечены.
*/
export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, onEvent, eventsError, stat }: {
export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, destinations, events, onEvent, onFlow, onDestination, eventsError, stat }: {
tab: MapBottomTab
onTab: (tab: MapBottomTab) => void
open: boolean
onOpenChange: (open: boolean) => void
flows: MapFlowRow[]
rtt: MapRttRow[]
destinations: MapDestRow[]
events: MapEventRow[]
onEvent: (event: MapEventRow) => void
onFlow: (id: string) => void
onDestination: (id: string) => void
eventsError: string | null
stat: string
}) {
const [showRoutineEvents, setShowRoutineEvents] = useState(false)
const incidentEvents = events.filter(event => event.tone === "er" || event.tone === "wn")
const visibleEvents = showRoutineEvents ? events : incidentEvents
const tabs: Array<{ id: MapBottomTab; label: string; count: number }> = [
{ id: "flows", label: "Потоки NetFlow", count: flows.length },
{ id: "rtt", label: "RTT каналов", count: rtt.length },
{ id: "dest", label: "Назначения", count: destinations.length },
{ id: "events", label: "События", count: events.length },
{ id: "events", label: "События", count: visibleEvents.length },
]
return (
<SectionFrame aria-label="Рабочая панель карты" bare>
<Tabs value={tab} onValueChange={(value) => onTab(value as MapBottomTab)} className="gap-1">
<div className="flex flex-wrap items-center gap-3 px-2 pt-1.5 pb-1">
<TabsList aria-label="Рабочая панель">
<SectionFrame aria-label="Рабочая панель карты" bare className="min-w-0 shrink-0">
<Tabs value={tab} onValueChange={(value) => { onTab(value as MapBottomTab); onOpenChange(true) }} className="gap-1">
<div className="flex min-w-0 items-center gap-2 px-2 py-1">
<div className="min-w-0 flex-1 overflow-x-auto"><TabsList aria-label="Рабочая панель">
{tabs.map((t) => (
<TabsTrigger key={t.id} value={t.id} className="px-2.5">
<TabsTrigger key={t.id} value={t.id} className="px-2.5" onClick={() => onOpenChange(true)}>
{t.label}
<Badge variant="secondary" size="sm" className="font-mono">{t.count}</Badge>
</TabsTrigger>
))}
</TabsList>
<span className="text-muted-foreground ml-auto text-xs">{stat}</span>
</TabsList></div>
{open && <span className="hidden text-xs text-muted-foreground xl:inline">{stat}</span>}
<Button type="button" variant="ghost" size="icon-sm" aria-expanded={open} aria-controls="network-map-analysis" aria-label={open ? "Свернуть рабочую панель" : "Открыть рабочую панель"} onClick={() => onOpenChange(!open)}>{open ? <ChevronDownIcon /> : <ChevronUpIcon />}</Button>
</div>
<FramePanel className="p-0">
<FramePanel id="network-map-analysis" hidden={!open} className="p-0">
<TabsContent value="flows">
<Table head={["Пользователь", "Выход / экспортёр", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}>
{flows.map((r) => (
<Row key={r.id} cols={FLOW_COLS} hl={r.hl}>
<span className="truncate font-mono">{r.client}</span>
<span className="truncate font-mono">{r.exit}</span>
<span className="truncate">{r.dest}</span>
<Button type="button" variant="link" size="xs" className="min-w-0 justify-start" onClick={() => onFlow(r.id)}><span className="truncate">{r.dest}</span></Button>
<span className="font-mono tabular-nums">{r.rate}</span>
<span className="text-muted-foreground font-mono tabular-nums">{r.volume}</span>
</Row>
@@ -102,7 +111,7 @@ export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, o
<Table head={["Назначение", "Категория", "Скорость", "Доля окна"]} cols={DEST_COLS} empty={destinations.length ? null : "Назначений за окно нет"}>
{destinations.map((r) => (
<Row key={r.id} cols={DEST_COLS} hl={r.hl}>
<span className="truncate font-medium">{r.label}</span>
<Button type="button" variant="link" size="xs" className="min-w-0 justify-start" onClick={() => onDestination(r.id)}><span className="truncate">{r.label}</span></Button>
<span className="text-muted-foreground truncate">{r.category}</span>
<span className="font-mono tabular-nums">{r.rate}</span>
<span className="flex items-center gap-2">
@@ -114,8 +123,13 @@ export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, o
</Table>
</TabsContent>
<TabsContent value="events">
<Table head={["Время", "Тип", "Событие", "Подробности"]} cols={EVENT_COLS} empty={eventsError ? `События недоступны: ${eventsError}` : events.length ? null : "Событий пока нет"}>
{events.map((r) => (
<div className="flex items-center gap-2 border-b px-3 py-1">
<Button type="button" size="xs" variant={showRoutineEvents ? "outline" : "secondary"} aria-pressed={!showRoutineEvents} onClick={() => setShowRoutineEvents(false)}>Сбои и предупреждения</Button>
<Button type="button" size="xs" variant={showRoutineEvents ? "secondary" : "outline"} aria-pressed={showRoutineEvents} onClick={() => setShowRoutineEvents(true)}>Все события</Button>
</div>
{eventsError && <p role="status" className="px-3 py-1 text-xs text-muted-foreground">{eventsError}</p>}
<Table head={["Время", "Тип", "Событие", "Подробности"]} cols={EVENT_COLS} empty={visibleEvents.length ? null : eventsError ? "Нет подтверждённых событий" : showRoutineEvents ? "Событий пока нет" : "В полученных событиях нет сбоев и предупреждений"}>
{visibleEvents.map((r) => (
<Row key={r.id} cols={EVENT_COLS}>
<time dateTime={new Date(r.ts).toISOString()} className="text-muted-foreground font-mono text-xs">{new Date(r.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })}</time>
<span><ToneBadge tone={r.tone} mark={false}>{r.label}</ToneBadge></span>
@@ -135,35 +149,45 @@ export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, o
* «Момент времени» (макет v3): инциденты за 24 часа на шкале и текущий Live-снимок.
* Архив снимков карты не хранится, поэтому прошлые моменты не выбираются.
*/
export function MapTimeline({ events, now, onPick }: { events: MapEventRow[]; now: number; onPick: (event: MapEventRow) => void }) {
export function MapTimeline({ events, now, state, onPick }: { events: MapEventRow[]; now: number; state?: string; onPick: (event: MapEventRow) => void }) {
const from = now - 24 * 3_600_000
const marks = events.filter((e) => e.ts >= from && e.ts <= now)
const hours = new Map<number, MapEventRow[]>()
for (const event of events) {
if (event.ts < from || event.ts > now || event.tone !== "er" && event.tone !== "wn") continue
const hour = Math.min(23, Math.floor((event.ts - from) / 3_600_000))
const group = hours.get(hour) ?? []
group.push(event)
hours.set(hour, group)
}
const at = (t: number) => `calc(10px + (100% - 20px) * ${t.toFixed(4)})`
// Шкала макета v3: остановки (кружок и подпись под ним), инциденты — цветные засечки над линией.
const stop = "absolute top-[7px] flex -translate-x-1/2 flex-col items-center gap-1 text-[11px] leading-none whitespace-nowrap"
return (
<div className="flex shrink-0 items-center gap-3 border-t px-3 pt-1.5 pb-1">
<small className="text-muted-foreground text-xs whitespace-nowrap">Момент времени</small>
<small className="flex flex-col text-xs text-muted-foreground" title={state}>Инциденты{state ? <span role="status" className="hidden sm:inline">{state}</span> : null}</small>
<div role="group" aria-label="Инциденты карты за 24 часа" className="relative mx-3.5 h-9 min-w-0 flex-1">
<span aria-hidden="true" className="bg-border absolute inset-x-2.5 top-[11px] h-0.5 rounded-full" />
{[["−24 ч", 0], ["−6 ч", 0.75], ["−1 ч", 0.9583]].map(([label, t]) => (
<span key={label} aria-hidden="true" className={cn(stop, "text-muted-foreground")} style={{ left: at(Number(t)) }}>
<i className="bg-card border-muted-foreground block size-2.5 rounded-full border-2" />{label}
<i className="bg-card border-muted-foreground block size-2.5 rounded-full border-2" />{label === "−1 ч" ? <span className="hidden xl:inline">{label}</span> : label}
</span>
))}
{marks.map((e) => (
{[...hours].map(([hour, group]) => {
const e = group.find(event => event.tone === "er") ?? group[0]
const label = `${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}${group.length > 1 ? ` · ещё ${group.length - 1}` : ""}`
return (
<button
key={e.id}
type="button"
onClick={() => onPick(e)}
aria-label={`${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}`}
title={`${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}`}
aria-label={label}
title={label}
className="focus-visible:ring-ring absolute top-1 flex h-4 w-3 -translate-x-1/2 justify-center rounded-sm outline-none focus-visible:ring-2"
style={{ left: at((e.ts - from) / (now - from)) }}
style={{ left: at((hour + 0.5) / 24) }}
>
<span aria-hidden="true" className="block h-full w-1.5 rounded-sm" style={{ background: TONE_COLOR[e.tone] }} />
</button>
))}
)})}
<span className={cn(stop, "text-foreground font-semibold")} style={{ left: at(1) }}>
<i className="bg-success border-success block size-2.5 rounded-full border-2 shadow-[0_0_0_4px_color-mix(in_oklch,var(--success)_25%,transparent)]" />Live
</span>
+4 -2
View File
@@ -80,7 +80,9 @@ export function FlowEntityCardView({
{card.site}
</span>
</div>
<TrafficMiniChart rx={card.rxSeries} tx={card.txSeries} />
{card.rxNow === null && card.txNow === null
? <p className="text-xs text-muted-foreground">Нет потоков с подтверждённой привязкой</p>
: <TrafficMiniChart rx={card.rxSeries} tx={card.txSeries} />}
<div className="flex justify-between mt-2 gap-2">
<div className="flex items-center gap-1 text-xs">
<ArrowDownIcon className="size-3 text-success" />
@@ -360,7 +362,7 @@ export function FlowAnalyticsDetail({
}) {
const [slice, setSlice] = useState(initialService ? "sessions" : "applications")
const [sessionFilter, setSessionFilter] = useState<SessionFilter | null>(initialService ? { kind: "map-service", label: initialService, country: initialCountry } : null)
const rxNow = analytics ? analytics.bpsNow / 1_000_000 : (card?.rxNow ?? 0)
const rxNow = analytics?.bytes ? analytics.bpsNow / 1_000_000 : (card?.rxNow ?? null)
const bytes = analytics?.bytes ?? card?.bytes ?? 0
const sessionRows = (analytics?.conversationsList ?? []).filter(row =>
(!mapNodes || mapNodes.includes(row.enId || row.serverId)) && (!sessionFilter || talkerMatchesFilter(row, sessionFilter)))
+13
View File
@@ -3,6 +3,7 @@ import assert from "node:assert/strict"
import {buildServerResourceMap,greTunnelProbe} from "./network-map-layout"
import {mergeGreMetricsWithSpeedProbe} from "./map-gre-speed-probe"
import {servers,greTunnels} from "./data"
import {scopeMapDestinations} from "./network-map-scope"
test("live resources preserve zero, partial poll and unknowns without fake history",()=>{
const base={...servers[0],cpuLoad:undefined,totalMemory:undefined,freeMemory:undefined,uptime:undefined,polledAt:undefined}
const unknown=buildServerResourceMap([base])[base.id]
@@ -19,3 +20,15 @@ test("live GRE does not hash metrics and probe values retain zero and fractions"
const merged=mergeGreMetricsWithSpeedProbe({id:"p",srcServerId:"1",dstServerId:"2",lastPingRttMs:0,lastTxAvgMbps:0,lastRxAvgMbps:0.125},fallback)
assert.deepEqual(merged,{pingMs:0,dlMbps:0,ulMbps:0.125,hasSpeedMonitor:true})
})
test("a filtered topology does not inherit a service's full-network traffic composition", () => {
const service = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 100, bps: 10, share: 1,
trafficTypes: [{transport: "UDP", application: "DNS", bytes: 100}], lastBucketAt: "2026-11-26T18:30:00.000Z"}
const edges = ["1", "2"].map(fromId => ({fromId, toId: service.id, bytes: 50, bps: 5, bpsFwd: 5, bpsRev: 0}))
const partial = scopeMapDestinations([service], edges, [], id => id === "1").services[0]
const complete = scopeMapDestinations([service], edges, [], () => true).services[0]
assert.equal(partial?.trafficTypes, undefined)
assert.equal(partial?.lastBucketAt, undefined)
assert.deepEqual(complete?.trafficTypes, service.trafficTypes)
assert.equal(complete?.lastBucketAt, service.lastBucketAt)
})
+27
View File
@@ -0,0 +1,27 @@
import type { MapBox } from "./network-map-layout"
type Point = { x: number; y: number }
/** Routes IPFIX around cards. A missing route leaves the observation available in service details. */
export function mapObservationRoute(start: Point, end: Point, boxes: readonly MapBox[], usedTracks: readonly number[]) {
if (end.x - start.x < 44) return null
const padding = 8
const obstacles = boxes.filter(box => box.x + box.w > start.x && box.x < end.x)
const first = Math.min(start.x + 20, ...obstacles.map(box => box.x - padding))
const last = Math.max(end.x - 20, ...obstacles.map(box => box.x + box.w + padding))
if (first <= start.x || last >= end.x || last - first < 34) return null
const middle = (start.y + end.y) / 2
const candidates = [middle, start.y, end.y, ...obstacles.flatMap(box => [box.y - 16, box.y + box.h + 16])]
const legal = candidates.flatMap(y => [y, y - 14, y + 14, y - 28, y + 28])
.filter(y => obstacles.every(box => y < box.y - padding || y > box.y + box.h + padding))
.sort((a, b) => Math.abs(a - middle) - Math.abs(b - middle) || a - b)
const y = legal.find(candidate => usedTracks.every(track => Math.abs(candidate - track) >= 18))
if (y === undefined) return null
return {
d: `M ${start.x} ${start.y} H ${first} V ${y} H ${last} V ${end.y} H ${end.x}`,
marker: { x: (first + last) / 2, y },
track: y,
}
}
+4 -1
View File
@@ -56,7 +56,10 @@ export function scopeMapDestinations(
return {
services: services.flatMap(service => {
const total = totals.get(service.id)
return total ? [{ ...service, ...total, share: bytes ? total.bytes / bytes : 0 }] : []
if (!total) return []
const { trafficTypes, serviceEvidence, lastBucketAt, ...destination } = service
return [{ ...destination, ...total, share: bytes ? total.bytes / bytes : 0,
...(total.bytes === service.bytes ? { trafficTypes, serviceEvidence, lastBucketAt } : {}) }]
}).sort((a, b) => b.bytes - a.bytes || a.label.localeCompare(b.label)),
edges: visibleEdges,
paths: visiblePaths,
+15 -2
View File
@@ -215,8 +215,8 @@ export const flowEntityCardSchema = z.object({
site: z.string(),
country: z.string(),
status: z.enum(["online", "offline", "degraded"]),
rxNow: z.number(),
txNow: z.number(),
rxNow: z.number().nullable(),
txNow: z.number().nullable(),
sessions: z.number().int().nonnegative(),
rxSeries: z.array(z.number()),
txSeries: z.array(z.number()),
@@ -366,6 +366,9 @@ export const flowMapHopDtoSchema = z.object({
bpsRev: z.number().nonnegative(),
})
export const flowServiceBasisSchema = z.enum(["catalog", "network", "heuristic", "port", "unknown"])
export type FlowServiceBasis = z.infer<typeof flowServiceBasisSchema>
export const flowMapServiceDtoSchema = z.object({
id: z.string(),
label: z.string(),
@@ -373,6 +376,16 @@ export const flowMapServiceDtoSchema = z.object({
bytes: z.number().nonnegative(),
bps: z.number().nonnegative(),
share: z.number().min(0).max(1),
lastBucketAt: z.string().datetime().optional(),
trafficTypes: z.array(z.object({
transport: z.string(),
application: z.string().nullable(),
bytes: z.number().positive(),
})).max(5).optional(),
serviceEvidence: z.array(z.object({
basis: flowServiceBasisSchema,
bytes: z.number().positive(),
})).max(flowServiceBasisSchema.options.length).optional(),
})
export const flowMapServiceEdgeDtoSchema = z.object({
+3 -3
View File
@@ -13,7 +13,7 @@ for(const change of ["backend","mode"])for(const part of ["snapshot","flow","dns
})
await page.goto("/settings");await page.getByRole("link",{name:/^Карта сети/}).click()
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Прежняя карта",{exact:true})).toBeVisible()
await expect(page.getByText(/NetFlow · 5 мин · ответ/)).toBeVisible()
await expect(page.getByTitle(/NetFlow · 5 мин · ответ/)).toBeVisible()
const path=part==="snapshot"?"/api/servers":part==="flow"?"/api/traffic/flow/map-hops":"/api/network/resolve-hosts"
await page.route("**/api/**",async r=>{
const u=new URL(r.request().url());if(u.port!=="8000"||u.pathname!==path||started)return r.fallback()
@@ -25,8 +25,8 @@ for(const change of ["backend","mode"])for(const part of ["snapshot","flow","dns
if(change==="backend"){const input=page.getByPlaceholder("http://localhost:8000");await input.fill("http://localhost:8101");await input.press("Enter")}
else await page.getByRole("button",{name:"Моковые",exact:true}).click()
await page.getByRole("link",{name:/^Карта сети/}).click()
if(change==="backend"){await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Новая карта",{exact:true})).toBeVisible();await expect(page.getByText(/NetFlow · 5 мин · ответ/)).toBeVisible()}
else await expect(page.getByText("Демо · mock",{exact:true})).toBeVisible()
if(change==="backend"){await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Новая карта",{exact:true})).toBeVisible();await expect(page.getByTitle(/NetFlow · 5 мин · ответ/)).toBeVisible()}
else await expect(page.getByText("Демонстрационные данные",{exact:true})).toBeVisible()
const before=newReads;release();await expect.poll(()=>completed).toBe(true)
await page.evaluate(()=>new Promise<void>(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve()))))
await expect(page.getByText("Старая ошибка карты",{exact:false})).toHaveCount(0)
+1
View File
@@ -41,6 +41,7 @@ test("Карта: неизвестный статус не становится
await page.getByText("Сводка сети", {exact:true}).click()
await expect(page.getByRole("button",{name:"Неизвестно 1",exact:true})).toBeVisible()
await expect(page.getByRole("button",{name:"Оффлайн 0",exact:true})).toBeVisible()
await page.keyboard.press("Escape")
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true}).click()
await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible()
await page.getByRole("button",{name:/^Фильтр/}).click();await page.getByRole("button",{name:"Неизвестно",exact:true}).click()
+35 -5
View File
@@ -27,7 +27,8 @@ test("Карта и трафик сохраняют пользователя и
"/api/filters/gre-tunnels": {tunnels: [], failures: []}, "/api/uptime/speed-probes": {probes: []},
"/api/ix/topology": {links: []}, "/api/ix/segments": {items: [{id: "segment", appliedRevision: 1}]},
"/api/ix/segments/segment/linux": {items: [{serverId: 9, interfaceName: "wg-linux", kind: "wireguard", name: "Linux VPS", enabled: true}]},
"/api/users": {users: [user]}, "/api/traffic/bound-interfaces": observedTrafficFixturePayload({interfaces: counters}),
"/api/users": {users: [user]},
[`/api/traffic/users/${clientId}`]: observedTrafficFixturePayload({user: {...counters[0], rxNow: 8, txNow: 12, interfaces: counters}}),
"/api/traffic/flow/exporters": {exporters: []}, "/api/traffic/flow/clients": {clients: [clientCard]},
"/api/traffic/flows": {exportersOnline: 0, bytesPerMin: 0, uniqueSrc: 0, uniqueDst: 0, topProto: "TCP", talkers: [], listenerBound: true},
[flowPath]: {...empty, totalBytes: dns.bytes, namedBytes: dns.bytes, services: [dns], servicePaths: [path],
@@ -43,11 +44,15 @@ test("Карта и трафик сохраняют пользователя и
await map.getByRole("button", {name: "Сервис DNS", exact: true}).press("Enter")
await panel.getByRole("button", {name: "Фильтр по сервису"}).click()
await page.getByRole("button", {name: "Пользователи", exact: true}).click()
await page.getByRole("combobox", {name: "Поиск пользователей"}).fill("Вход")
await expect(page.getByRole("option", {name:/Алиса.*Вход/})).toBeVisible()
await page.getByRole("option", {name: /Алиса/}).click()
await expect.poll(() => requests.some(request => request === `${flowPath}?range=1m&userId=${clientId}`)).toBe(true)
await expect(panel.getByRole("heading", {name: "Алиса", exact: true})).toBeVisible()
await expect(panel.getByText(/gre-alice · gre, gre-alice-2/)).toBeVisible()
await expect(panel.getByText(/RX 8.*TX 12.*2\/2/)).toBeVisible()
await expect(panel.getByRole("region", {name: "Трафик пользователя"})).toContainText("RX 8.00 Мбит/с · TX 12.0 Мбит/с")
await expect(map.getByRole("button", {name: "Пользователь Алиса"}).locator('rect[fill="var(--card)"]')).toHaveAttribute("stroke", "var(--border)")
await panel.getByRole("button", {name: /DNS/}).click()
await panel.getByRole("link", {name: "Открыть в «Трафике»"}).click()
await expect(page).toHaveURL(/\/traffic\?.*user=alice/)
@@ -64,7 +69,9 @@ test("Карта и трафик сохраняют пользователя и
})
test("Карта не приписывает весь YouTube единственному выходу ARN", async ({page}) => {
const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1}
const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1,
trafficTypes: [{transport: "UDP", application: "QUIC", bytes: 900000}],
serviceEvidence: [{basis: "heuristic", bytes: 900000}], lastBucketAt: "2026-11-26T18:30:00.000Z"}
const edge = {fromId: "1", toId: service.id, bytes: 300000, bps: 8000, bpsFwd: 2000, bpsRev: 6000}
let known = false
await page.route("**/api/**", route => {
@@ -83,6 +90,10 @@ test("Карта не приписывает весь YouTube единствен
})
await page.goto("/network-map")
await page.getByRole("button", {name: "Сервис YouTube", exact: true}).press("Enter")
const composition = page.getByRole("region", {name: "Состав трафика IPFIX"})
await expect(composition.getByText("Оценка по сети и порту")).toBeVisible()
await expect(composition.locator("time")).toHaveAttribute("datetime", service.lastBucketAt)
await expect(page.getByText("IPFIX · среднее за 5 мин")).toBeVisible()
const unknown = page.getByText("Выход не определён", {exact: true}).locator("..")
const badges = page.locator("[data-map-ribbon] > title")
await expect(unknown).toContainText("24 Кбит/с")
@@ -97,7 +108,9 @@ test("Карта не приписывает весь YouTube единствен
test("Карта: DNS виден от экспортёра, пользователи разбиты в обеих карточках", async ({page}) => {
const router = {...server, name: "MSK", type: "jump-host"}
const dns = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 300000, bps: 8000, share: 1}
const dns = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 300000, bps: 8000, share: 1,
trafficTypes: [{transport: "UDP", application: "DNS", bytes: 225000}, {transport: "TCP", application: "DNS over TLS", bytes: 75000}],
serviceEvidence: [{basis: "port", bytes: 300000}]}
const users = [
{clientId: "u1", clientName: "Алиса", bytes: 225000, bps: 6000},
{clientId: "—", clientName: "—", bytes: 75000, bps: 2000},
@@ -117,8 +130,23 @@ test("Карта: DNS виден от экспортёра, пользовате
})
await page.goto("/network-map")
await expect(page.locator("[data-map-ribbon][data-observation] > title")).toContainText("MSK → DNS")
await page.getByRole("button", {name: "Слои", exact: true}).click()
const auxiliary = page.getByRole("button", {name: "Вспомогательные серые линии"})
await auxiliary.click()
await expect(auxiliary).toHaveAttribute("aria-pressed", "false")
await expect(page.locator("[data-map-ribbon][data-observation]")).toHaveCount(0)
await auxiliary.press("Escape")
await expect(page.getByRole("button", {name: "Сервис DNS", exact: true})).toBeVisible()
await page.getByRole("button", {name: "Слои", exact: true}).click()
await auxiliary.click()
await expect(page.locator("[data-map-ribbon][data-observation]")).toHaveCount(1)
await auxiliary.press("Escape")
await page.getByRole("button", {name: "Сервис DNS", exact: true}).press("Enter")
const panel = page.getByRole("complementary", {name: "Детали объекта карты"})
const composition = panel.getByRole("region", {name: "Состав трафика IPFIX"})
await expect(composition.getByText("DNS · UDP").locator("..")).toContainText("75")
await expect(composition.getByText("DNS over TLS · TCP").locator("..")).toContainText("25")
await expect(composition.getByText("По протоколу / порту")).toBeVisible()
const breakdown = panel.getByRole("region", {name: "Трафик по пользователям"})
await expect(breakdown.getByText("Алиса", {exact: true}).locator("..")).toContainText("6 Кбит/с")
await expect(breakdown.getByText("Без привязки к пользователю")).toBeVisible()
@@ -190,7 +218,9 @@ for (const reverse of [false, true]) test(`Карта: малый NetFlow и т
await expect(page.getByText("За интервал · 525 Б · 3 пак.")).toBeVisible()
nativeAvailable = true
await expect(badge).toHaveAccessibleName(/81[.,]0 Мбит\/с/, {timeout: 18000})
await page.getByRole("button", {name:"Сводка сети", exact:true}).click()
await expect(page.getByText("Макс. из замеров · Live", {exact: true}).locator("..")).toContainText("81")
await page.keyboard.press("Escape")
await expect(live).toContainText("↓80")
await expect(panel.getByText("↓14 бит/с ↑0 Кбит/с", { exact: true })).toBeVisible()
})
@@ -265,7 +295,7 @@ for(const malformed of [false,true])test("Карта: NetFlow отказ и по
await expect(page.getByRole("alert").filter({hasText:"Первоначальная загрузка NetFlow"})).toBeVisible()
await expect(page.getByText("Данные NetFlow неизвестны",{exact:true})).toBeVisible()
failing=false;await page.getByRole("button",{name:"Обновить",exact:true}).click()
await expect(page.getByText(malformed?/NetFlow · 2 мин из 5 запрошенных · ответ/:/NetFlow · 5 мин · ответ/)).toContainText("приёмник выключен")
await expect(page.getByTitle(malformed?/NetFlow · 2 мин из 5 запрошенных · ответ/:/NetFlow · 5 мин · ответ/)).toContainText("приёмник выключен")
await expect(page.getByRole("alert").filter({hasText:"NetFlow:"})).toHaveCount(0)
})
test("Карта: NetFlow сохраняет сервис при фоновом сбое",async({page})=>{
@@ -290,5 +320,5 @@ for(const result of ["missing","foreign","unresolved","success"])test("Карт
await page.route("**/api/**",async r=>{const p=new URL(r.request().url()).pathname;if(p===flowPath){requests++;await gate;return r.fulfill({json:empty})}return r.fulfill({json:p==="/api/servers"?[server]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/auth/config"?{required:false}:{}})})
await page.goto("/network-map");await expect.poll(()=>requests).toBe(1)
await page.clock.runFor(5000);expect(requests).toBe(1)
release();await expect(page.getByText(/NetFlow · 5 мин · ответ/)).toBeVisible()
release();await expect(page.getByTitle(/NetFlow · 5 мин · ответ/)).toBeVisible()
})
+20
View File
@@ -34,6 +34,26 @@ for(const width of [1440,390,320])test("Карта: доступные дета
await page.getByRole("button",{name:"Слои",exact:true}).click();await expect(page.getByRole("dialog",{name:"Слои карты"})).toBeVisible()
await page.keyboard.press("Escape");await expect(page.getByRole("button",{name:"Слои",exact:true})).toBeFocused();await expect(page).toHaveURL(/server=1/)
})
test("Карта: шкала и рабочая панель фокусируют сбой устройства",async({page})=>{
const now = new Date().toISOString()
await page.route("**/api/events?*", route => route.fulfill({json:{events:[
{ id:"routine", createdAt:now, level:"info", eventType:"job", sourceModule:"scheduler", title:"Задание завершено", message:"Плановое выполнение", entityType:null, entityId:null },
{ id:"probe", createdAt:now, level:"critical", eventType:"device", sourceModule:"alerts", title:"Узел недоступен", message:"Опрос не получил ответа", entityType:"server", entityId:"2" },
]}}))
await page.goto("/network-map")
const timeline = page.getByRole("group",{name:"Инциденты карты за 24 часа"})
await expect(timeline.getByRole("button",{name:/Узел недоступен/})).toBeVisible()
await expect(timeline.getByRole("button",{name:/Задание завершено/})).toHaveCount(0)
await timeline.getByRole("button",{name:/Узел недоступен/}).click()
await expect(page.getByRole("link",{name:"Трафик узла"})).toHaveAttribute("href",/server=2/)
const analysis = page.getByRole("region",{name:"Рабочая панель карты"})
await expect(analysis.getByRole("tab",{name:/События/})).toHaveAttribute("aria-selected","true")
await expect(analysis.getByRole("button",{name:"Задание завершено",exact:true})).toHaveCount(0)
await analysis.getByRole("button",{name:"Все события",exact:true}).click()
await expect(analysis.getByRole("button",{name:"Задание завершено",exact:true})).toBeVisible()
await analysis.getByRole("button",{name:"Свернуть рабочую панель"}).click()
await expect(analysis.getByRole("button",{name:"Открыть рабочую панель"})).toHaveAttribute("aria-expanded","false")
})
test("Карта: reduced motion и самостоятельный SVG экспорт",async({page})=>{
await page.emulateMedia({reducedMotion:"reduce"});await page.goto("/network-map")
await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
+40
View File
@@ -65,6 +65,46 @@ test("Карта: 3 JH → Exit + IX, параллельные GRE и 8 серв
expect(await page.locator("path > title", { hasText: pair }).count()).toBeGreaterThan(0)
})
test("Карта: группа сервисов сворачивается на холсте, IPFIX огибает карточки", async ({ page }, info) => {
await page.setViewportSize({ width: 867, height: 914 })
const servers = [srv(1, "Узел доступа", "jump-host"), srv(2, "Интернет-выход", "exit-node", "DE")]
const major = { id: "svc:dns", label: "DNS", category: "DNS", bytes: 9_500, bps: 760, share: 0.95 }
const minor = { id: "svc:ntp", label: "NTP", category: "NTP", bytes: 500, bps: 40, share: 0.05 }
const serviceEdges = [major, minor].map(service => ({ fromId: "1", toId: service.id,
bytes: service.bytes, bps: service.bps, bpsFwd: service.bps, bpsRev: 0, observedOnly: true }))
await serve(page, servers, [gre("gre-exit", 1, 2)], { services: [major, minor], serviceEdges, namedBytes: 10_000, totalBytes: 10_000 })
await page.goto("/network-map")
const map = page.getByRole("group", { name: "Интерактивная карта сети" })
const group = map.getByRole("button", { name: /^Остальные сервисы/ })
const closeGroup = map.getByRole("button", { name: "Свернуть остальные", exact: true })
const ntp = map.getByRole("button", { name: "Сервис NTP" })
await expect(group).toHaveAttribute("aria-expanded", "false")
await expect(ntp).toHaveCount(0)
await group.press("Enter")
await expect(closeGroup).toHaveAttribute("aria-expanded", "true")
await expect(ntp).toBeVisible()
await expect(map.locator('[data-map-route="observation"]')).toHaveCount(2)
const intersectsCards = await map.evaluate(svg => {
const cards = [...svg.querySelectorAll('[data-map-box="card"], [data-map-box="dest"]')].map(card => card.getBoundingClientRect())
return [...svg.querySelectorAll<SVGPathElement>('[data-map-route="observation"]')].some(path => {
const length = path.getTotalLength()
const transform = path.getScreenCTM()!
for (let distance = 1; distance < length; distance += 2) {
const p = path.getPointAtLength(distance).matrixTransform(transform)
if (cards.some(rect => p.x > rect.left + 1 && p.x < rect.right - 1 && p.y > rect.top + 1 && p.y < rect.bottom - 1)) return true
}
return false
})
})
expect(intersectsCards).toBe(false)
await closeGroup.press("Enter")
await expect(group).toHaveAttribute("aria-expanded", "false")
await expect(ntp).toHaveCount(0)
await expect.poll(async () => (await map.boundingBox())!.y + (await map.boundingBox())!.height).toBeLessThan(915)
await expect(page.getByRole("button", { name: "Открыть рабочую панель" })).toBeInViewport()
await page.screenshot({path:info.outputPath("карта-сети.png")})
})
test("Карта: сетка JH × Exit и аплинки WAN без наложений подписей", async ({ page }) => {
const wan = (i: number) => ({ id: "w" + i, name: "WAN" + i, iface: "ether" + i, isp: "ISP-" + i, ip: `198.51.100.${i}`, maxDl: 100, maxUl: 50 })
const servers = [
+26 -2
View File
@@ -41,15 +41,39 @@ test('Список трафика: поздний период не заменя
await started
await expect(page.getByText('Загрузка списка трафика…', { exact: true })).toBeVisible()
await expect(page.getByRole('button').filter({ hasText: 'Список 1h' })).toHaveCount(0)
const cancelled = page.waitForEvent('requestfailed', {predicate: r => new URL(r.url()).pathname === '/api/traffic/servers' && r.url().includes('range=24h')})
await page.getByRole('button', { name: '15м', exact: true }).click()
await expect(page.getByRole('button').filter({ hasText: 'Список 15m' })).toBeVisible()
const late = page.waitForResponse(r => new URL(r.url()).pathname === '/api/traffic/servers' && r.url().includes('range=24h'))
control.release()
await late
await cancelled
await expect(page.getByRole('button').filter({ hasText: 'Список 15m' })).toBeVisible()
await expect(page.getByRole('button').filter({ hasText: 'Список 24h' })).toHaveCount(0)
})
test("Трафик клиента обновляет счётчики без перезагрузки", async ({page}) => {
await page.clock.install()
let txNow = 12
await page.route("**/health", route => route.fulfill({json: {ok: true}}))
await page.route("**/api/**", route => {
const path = new URL(route.request().url()).pathname
const rates = {rxNow: 8, txNow, rxPeak: 20, txPeak: 30, rxTotal: 1, txTotal: 1, rxSeries: [8], txSeries: [txNow]}
const iface = {id: "alice-gre", bindingId: "alice-gre", userId: "alice", interfaceName: "gre-alice",
serverId: "1", serverName: "MSK", interfaceType: "gre", status: "online", ...rates}
const user = {id: "alice", login: "alice", displayName: "Алиса", role: "viewer", active: true, interfaces: [iface], ...rates}
const json = path === "/api/auth/config" ? {required: false}
: path === "/api/traffic/users" ? {users: [user]}
: path === "/api/traffic/servers" ? {servers: []}
: path === "/api/traffic/bound-interfaces" ? {interfaces: []} : {}
return route.fulfill({json: observedTrafficFixturePayload(json)})
})
await page.goto("/traffic?user=alice")
const card = page.getByRole("button").filter({hasText: "Алиса"})
await expect(card).toContainText("12.0 Мбит/с")
txNow = 26
await page.clock.fastForward(16_000)
await expect(card).toContainText("26.0 Мбит/с")
})
test('Список трафика: ошибка обновления скрывает сводку; повтор восстанавливает список', async ({ page }) => {
const control = await setup(page)
control.failList = true