From 4eafc78c8e0df5e871b34d22765ffc6cddad9ffb Mon Sep 17 00:00:00 2001 From: Denozordec Date: Fri, 27 Nov 2026 00:13:40 +0700 Subject: [PATCH] =?UTF-8?q?fix(map):=20=D1=83=D0=BB=D1=83=D1=87=D1=88?= =?UTF-8?q?=D0=B8=D1=82=D1=8C=20=D0=BD=D0=B0=D0=B2=D0=B8=D0=B3=D0=B0=D1=86?= =?UTF-8?q?=D0=B8=D1=8E=20=D0=B8=20=D1=80=D0=B0=D0=B7=D0=B1=D0=BE=D1=80=20?= =?UTF-8?q?=D0=B8=D0=BD=D1=86=D0=B8=D0=B4=D0=B5=D0=BD=D1=82=D0=BE=D0=B2=20?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=BA=D0=B0=D1=80=D1=82=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/(main)/network-map/page.tsx | 240 +++++++++++++------- components/network-map/map-access.tsx | 32 ++- components/network-map/map-bottom-panel.tsx | 74 ++++-- lib/network-map-observation-route.ts | 27 +++ tests/e2e/network-map-context.spec.ts | 6 +- tests/e2e/network-map-data.spec.ts | 1 + tests/e2e/network-map-flow.spec.ts | 8 +- tests/e2e/network-map-layout.spec.ts | 20 ++ tests/e2e/network-map-overlap.spec.ts | 40 ++++ 9 files changed, 322 insertions(+), 126 deletions(-) create mode 100644 lib/network-map-observation-route.ts diff --git a/app/(main)/network-map/page.tsx b/app/(main)/network-map/page.tsx index 8ddd8cc7..eff964ae 100644 --- a/app/(main)/network-map/page.tsx +++ b/app/(main)/network-map/page.tsx @@ -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" @@ -573,6 +574,7 @@ function ServiceNode({ category, rate, compact, + expanded, onClick, onPointerDown, }: { @@ -584,6 +586,7 @@ function ServiceNode({ rate?: string /** Узкая строка: раскрытая страна показывает две колонки назначений. */ compact?: boolean + expanded?: boolean x: number y: number isSel: boolean @@ -604,10 +607,10 @@ function ServiceNode({ const barW = bw - 72 const flagIso = destMode === "countries" && iso && iso !== "Прочее" ? iso : "" return ( - {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 +623,10 @@ function ServiceNode({ {flagIso ? - : - {shortName(label, compact ? 8 : 18)} + {shortName(label, expanded === undefined ? compact ? 8 : 18 : 28)} {compact ? serviceSharePct(share) : category || (destMode === "countries" ? "Страна" : "Сервис")} {!compact && rate ? {rate} : null} {!compact ? {serviceSharePct(share)} : null} @@ -944,6 +948,8 @@ function NetworkMapContent() { const [flowLoading,setFlowLoading]=useState(false) const [userFlow, setUserFlow] = useState<{ key: string; data?: ReturnType; error?: string }>() const [bottomTab, setBottomTab] = useState("flows") + const [analysisOpen, setAnalysisOpen] = useState(false) + const [summaryOpen, setSummaryOpen] = useState(false) const [filteredServiceId, setFilteredServiceId] = useState(null) const [mapEvents, setMapEvents] = useState(null) const [eventsError, setEventsError] = useState(null) @@ -953,9 +959,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() + 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(null) @@ -1271,18 +1289,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( @@ -1350,6 +1367,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 +1556,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,7 +1585,7 @@ 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"] : [])], + [...mainServices.map((s) => s.id), ...(hasMinorServices ? ["minor-services"] : [])], mapServers .filter((s) => s.type === "exit-node") .map((s) => nodePosById[s.id]) @@ -1570,22 +1593,24 @@ function NetworkMapContent() { ) // Раскрытая страна: колонка стран уходит влево, правый 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 autoDestPos = Object.fromEntries(Object.entries(autoServicePos).map(([id, p]) => [id, { x: p.x - countryColShift - compactLanes, 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 +1646,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( [`\n`, new XMLSerializer().serializeToString(clone)], { type: "image/svg+xml;charset=utf-8" }, @@ -1685,16 +1715,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 +1747,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 +1766,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) { @@ -2008,7 +2039,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)), } }) @@ -2124,11 +2157,19 @@ 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" + 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 +2220,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 = ( <> - {useLiveData ? (readAt ? `Live · снимок API ${new Date(readAt).toLocaleTimeString("ru-RU")}` : "Данные карты неизвестны") : "Демо · mock"} - {useLiveData ? <>{" · "}{showNetflow || showServices ? (flowReadAt ? `NetFlow · ${mapWindow}${mapWindowSec >= 120 && mapWindowSec < 300 ? " из 5 запрошенных" : ""} · ответ ${new Date(flowReadAt).toLocaleTimeString("ru-RU")} · ${flowListener ? "приёмник включён" : "приёмник выключен"}` : "Данные NetFlow неизвестны") : "NetFlow: отображение и обновление выключены"} : null} - {" · "} - {`${nodes.length} ${ruPlural(nodes.length, "узел", "узла", "узлов")}, ${mapLinkCount} ${ruPlural(mapLinkCount, "связь", "связи", "связей")}, ${visibleMapServices.length} ${ruPlural(visibleMapServices.length, "назначение", "назначения", "назначений")}`} + {useLiveData ? (readAt ? "Текущий срез" : "Данные карты неизвестны") : "Демонстрационные данные"} + {" · "}{nodes.length} {ruPlural(nodes.length, "узел", "узла", "узлов")} · {mapLinkCount} {ruPlural(mapLinkCount, "связь", "связи", "связей")} + {useLiveData && (showNetflow || showServices) && <>{" · "}{flowReadAt ? = 120 && mapWindowSec < 300 ? " из 5 запрошенных" : ""} · ответ ${new Date(flowReadAt).toLocaleTimeString("ru-RU")} · ${flowListener ? "приёмник включён" : "приёмник выключен"}`}>IPFIX · {mapWindow}{!flowListener ? " · приёмник выключен" : ""} : Данные NetFlow неизвестны}} ) // Подсказки поиска макета: узлы и назначения текущего снимка. @@ -2200,9 +2244,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 +2268,11 @@ function NetworkMapContent() {
-
+
} title="Карта сети" - description={mapHeadSub} + description={{mapHeadSub}} actions={ <> {useLiveData && ( @@ -2235,8 +2287,9 @@ function NetworkMapContent() { } /> -
- Сводка сети + + + Сводка сетиСостояние устройств, туннелей и потоки за текущее окно. 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) }} /> -
- -
- Как читать карту -

Связи GRE и привязки пользователей показывают конфигурацию. IPFIX показывает среднюю скорость за окно. Метка IPFIX на линии означает, что известен экспортёр, а выход не подтверждён.

-
+ + {urlState.server&&((hasSnapshot||!useLiveData)&&!selected||selected&&selWanIdx!==null&&!selected.wanUplinks?.[selWanIdx])&&Объект карты недоступен{!selected?"Устройство "+urlState.server+" отсутствует в текущем снимке.":"Запрошенный WAN отсутствует у выбранного устройства."}} {pickedUserId && !pickedUser && (ixOnly ? access.linuxPending : access.pending) &&

Загрузка пользователя карты…

} {pickedUserId && !pickedUser && !(ixOnly ? access.linuxPending : access.pending) && Пользователь карты недоступен} -
- +
+ {/* Поиск узла или назначения с подсказками */}
{ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setSearchOpen(false) }}> @@ -2360,9 +2409,20 @@ function NetworkMapContent() { {showUsers && } - {pickedUser && } + {pickedUser && } {filterService && } - {showServices && hasMinorServices && } + + + }> + +

Как читать карту

+
    +
  1. Слева выберите пользователя. Карта покажет правее его узлы подключения, выход в интернет и сервисы.
  2. +
  3. Откройте узел или линию. Справа появятся источник данных, состояние связи и доступные измерения.
  4. +
  5. Метка IPFIX показывает, где замечен трафик. Дальнейший маршрут для такой линии требует подтверждения.
  6. +
+
+
{/* Слои */} @@ -2423,7 +2483,7 @@ function NetworkMapContent() { {/* ── Canvas ── */}
-
+

Стрелки перемещают карту, плюс и минус меняют масштаб, F вписывает объекты. Tab выбирает объект, Enter открывает детали.

{([ + ...(showUsers && usersInTopology.length ? [{ lane: { x0: accessPosition.x - 96 + compactLanes, x1: accessPosition.x + 96 + compactLanes }, label: pickedUser ? "ПОЛЬЗОВАТЕЛЬ" : "ПОДКЛЮЧЕНИЯ" }] : []), ...(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.home, label: `ДОМАШНИЕ РОУТЕРЫ · ${nodes.filter(node => node.type === "home-router").length}` }, { lane: MAP_LANES.wan, label: `АПЛИНКИ WAN · ${nodes.reduce((sum, router) => sum + (router.wanUplinks?.length ?? 0), 0)}` }, ] : []), - ...(!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}` : ""}` }, + ...(!ixOnly && nodes.some(node => node.type === "jump-host") ? [{ lane: MAP_LANES.jh, label: `УЗЛЫ ДОСТУПА · ${nodes.filter(server => server.type === "jump-host").length}` }] : []), + ...(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}` : ""}` }] : []), ...(visibleMapServices.length ? [{ lane: MAP_LANES.dest, label: `${destMode === "countries" ? "СТРАНЫ" : "СЕРВИСЫ"} · ${visibleMapServices.length}` }] : []), ]).map(({ lane, label }, i) => ( -
)} -
- -
- - - {/* ── Инспектор: узел, связь или назначение ── */} - {inspectorOpen && + {inspectorOpen && {inspectorOpen && (
@@ -3018,6 +3075,7 @@ function NetworkMapContent() { filtered={filterService?.id === activeService.id} onFilter={() => { setFilteredServiceId(filterService?.id === activeService.id ? null : activeService.id) setBottomTab("flows") + setAnalysisOpen(true) }} /> ) : liveSelectedService ? ( @@ -3554,10 +3612,16 @@ function NetworkMapContent() { )} } +
+ +
+
+
- + unavailable={ixOnly ? access.linuxUnavailable : access.unavailable} selectedUser={pickedUser} nodeName={id => mapServers.find(server => server.id === id)?.name ?? id} onPick={pickMapUser} onClear={returnToNetwork} /> + { const service = destNodes.find(row => row.id === id); if (service && activeService?.id !== id) selectService(service) }} eventsError={useLiveData ? eventsError : null} stat={bottomStat} />
{/* ── Context menu ── */} {ctxMenu&¤tCtxServer&&setCtxMenu(null)} />} diff --git a/components/network-map/map-access.tsx b/components/network-map/map-access.tsx index 5e14ca74..c4b3d3b6 100644 --- a/components/network-map/map-access.tsx +++ b/components/network-map/map-access.tsx @@ -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" @@ -128,19 +128,35 @@ export function accessRate(bindings: AccessBinding[], rates?: Map void; users: MapAccessUser[]; pending: boolean; unavailable: boolean; onPick: (user: MapAccessUser) => void + selectedUser?: MapAccessUser; nodeName: (id: string) => string; onClear: () => void }) { - return + const ordered = [...users].sort((a, b) => a.name.localeCompare(b.name, "ru")) + return - +
+

Кого показать на карте?

+

Выберите пользователя, чтобы увидеть его подключения и сервисы.

+
+ {pending ? "Загрузка пользователей…" : unavailable ? "Каталог пользователей недоступен" : "Пользователи не найдены"} - {users.map(user => binding.name)]} onSelect={() => onPick(user)}> - {user.name} - {user.bindings.length} - )} + {selectedUser && Вся схема} + + {ordered.map(user => { + const nodes = [...new Set(user.bindings.map(binding => nodeName(binding.node)))].sort() + return binding.name)]} onSelect={() => onPick(user)}> + + {user.name} + {[user.login !== user.name && user.login, ...nodes].filter(Boolean).join(" · ")} + + {selectedUser?.id === user.id ? На карте : {user.bindings.length} инт.} + + })} + +

↑ ↓ выбор · Enter открыть · Esc закрыть

} diff --git a/components/network-map/map-bottom-panel.tsx b/components/network-map/map-bottom-panel.tsx index b945220b..aa729439 100644 --- a/components/network-map/map-bottom-panel.tsx +++ b/components/network-map/map-bottom-panel.tsx @@ -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 ( -
+