Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4eafc78c8e |
No files matched your search
+152
-88
@@ -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 (
|
||||
<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 +623,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}
|
||||
@@ -944,6 +948,8 @@ function NetworkMapContent() {
|
||||
const [flowLoading,setFlowLoading]=useState(false)
|
||||
const [userFlow, setUserFlow] = useState<{ key: string; data?: ReturnType<typeof networkMapFlowSchema.parse>; 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 +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<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)
|
||||
@@ -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(
|
||||
[`<?xml version="1.0" encoding="UTF-8"?>\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<SVGSVGElement>) {
|
||||
@@ -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 = (
|
||||
<>
|
||||
<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 · ${mapWindow}${mapWindowSec >= 120 && mapWindowSec < 300 ? " из 5 запрошенных" : ""} · ответ ${new Date(flowReadAt).toLocaleTimeString("ru-RU")} · ${flowListener ? "приёмник включён" : "приёмник выключен"}`}>IPFIX · {mapWindow}{!flowListener ? " · приёмник выключен" : ""}</span> : <span>Данные NetFlow неизвестны</span>}</>}
|
||||
</>
|
||||
)
|
||||
// Подсказки поиска макета: узлы и назначения текущего снимка.
|
||||
@@ -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() {
|
||||
<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 +2287,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 +2300,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 +2409,20 @@ 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>
|
||||
</ol>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{/* Слои */}
|
||||
<Popover modal open={showLayers} onOpenChange={setShowLayers}>
|
||||
@@ -2423,7 +2483,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 +2507,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: 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) => (
|
||||
<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>
|
||||
<g key={label} aria-hidden="true" pointerEvents="none" transform={`translate(${-compactLanes},0)`}>
|
||||
<rect x={lane.x0} y={lanesTop} width={lane.x1 - lane.x0} height={lanesBottom - lanesTop} fill="var(--foreground)" fillOpacity={i % 2 ? 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>)}
|
||||
{/* Наблюдаемые пути от выходов и экспортёров к сервисам. */}
|
||||
{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>
|
||||
@@ -2646,8 +2709,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
|
||||
@@ -2786,14 +2849,8 @@ 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">
|
||||
@@ -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() {
|
||||
)}
|
||||
</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&¤tCtxServer&&<ContextMenu menu={{...ctxMenu,server:currentCtxServer}} trafficHref={nodeTrafficHref(currentCtxServer.id)} onClose={()=>setCtxMenu(null)} />}
|
||||
|
||||
@@ -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<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>
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -43,6 +43,8 @@ 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()
|
||||
@@ -190,7 +192,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 +269,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 +294,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()
|
||||
})
|
||||
@@ -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()
|
||||
|
||||
@@ -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 = [
|
||||
|
||||
Reference in new issue
Block a user