Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ca40fbb4d |
No files matched your search
@@ -85,9 +85,9 @@ import {
|
||||
import { isFreshMapTrafficSample, useMapInterfaceTraffic } from "@/hooks/use-map-interface-traffic"
|
||||
import { useTrafficLive } from "@/hooks/use-traffic-live"
|
||||
import { formatBytes } from "@/lib/fmt-rate"
|
||||
import type { FlowMapCountryServiceGroup, FlowMapInterfaceTraffic, FlowMapHop, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import type { FlowMapCountryServiceGroup, FlowMapHopsDto, FlowMapInterfaceTraffic, FlowMapHop, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
|
||||
import { InspectorMetrics, NodeHistory, ServiceInspector } from "@/components/network-map/inspector-traffic"
|
||||
import { InspectorMetrics, InspectorUsers, NodeHistory, ServiceInspector, serviceUsers } from "@/components/network-map/inspector-traffic"
|
||||
import { Spinner } from "@/components/ui/spinner"
|
||||
import { CountryFlagSvg } from "@/components/network-map/country-flag-svg"
|
||||
import { Button } from "@/components/ui/button"
|
||||
@@ -100,7 +100,7 @@ import {
|
||||
CableIcon, ActivityIcon,
|
||||
} from "lucide-react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { formatServicePathLabel, formatServicePathTitle } from "@/lib/format-service-path-label"
|
||||
import { formatServicePathLabel, formatServicePathTitle, servicePathKey } from "@/lib/format-service-path-label"
|
||||
import Link from "next/link"
|
||||
import { MapBottomPanel, MapTimeline, type MapBottomTab, type MapEventRow } from "@/components/network-map/map-bottom-panel"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
@@ -364,11 +364,8 @@ function destDisplayLabel(node: FlowMapService | undefined, mode: DestMode, fall
|
||||
return countryName(node.label)
|
||||
}
|
||||
|
||||
function servicePathKey(p: Pick<FlowMapServicePath, "clientId" | "viaId" | "enId" | "serviceId">): string {
|
||||
return `${p.clientId}|${p.viaId}|${p.enId}|${p.serviceId}`
|
||||
}
|
||||
|
||||
function greMatchesPath(e: GreMapEdge, h: { viaId: string; enId: string }): boolean {
|
||||
if (!h.enId || h.viaId === h.enId) return false
|
||||
const ids = new Set([e.fromServer.id, e.toServer.id])
|
||||
return ids.has(h.viaId) && ids.has(h.enId)
|
||||
}
|
||||
@@ -636,7 +633,7 @@ function ServicePathList({
|
||||
paths: FlowMapServicePath[]
|
||||
servers: Server[]
|
||||
services: FlowMapService[]
|
||||
highlight: { viaId: string; enId: string; serviceId: string } | null
|
||||
highlight: FlowMapServicePath | null
|
||||
viaMode: "via" | "service"
|
||||
destMode: DestMode
|
||||
onToggle: (p: FlowMapServicePath) => void
|
||||
@@ -652,18 +649,15 @@ function ServicePathList({
|
||||
const en = servers.find((s) => s.id === p.enId)
|
||||
const svc = services.find((s) => s.id === p.serviceId)
|
||||
const destLabel = destDisplayLabel(svc, destMode, p.serviceId)
|
||||
const label = formatServicePathLabel(p, viaMode, {
|
||||
const label = p.enId ? formatServicePathLabel(p, viaMode, {
|
||||
viaName: via?.name,
|
||||
viaSite: via?.site,
|
||||
enName: en?.name,
|
||||
serviceLabel: destLabel,
|
||||
})
|
||||
}) : [p.viaName || p.viaId, p.viaIface, "наблюдение IPFIX"].filter(Boolean).join(" · ")
|
||||
const title = formatServicePathTitle(label, destLabel)
|
||||
const active = Boolean(
|
||||
highlight
|
||||
&& highlight.viaId === p.viaId
|
||||
&& highlight.enId === p.enId
|
||||
&& highlight.serviceId === p.serviceId,
|
||||
highlight && servicePathKey(highlight) === rowKey,
|
||||
)
|
||||
return (
|
||||
<button type="button"
|
||||
@@ -906,6 +900,7 @@ function NetworkMapContent() {
|
||||
}, [apiFetch, useLiveData, hasIxNodes])
|
||||
const [speedProbes, setSpeedProbes] = useState<GreSpeedProbeSnapshot[]>([])
|
||||
const [mapHops, setMapHops] = useState<FlowMapHop[]>([])
|
||||
const [mapNodeUsers, setMapNodeUsers] = useState<FlowMapHopsDto["nodeUsers"]>()
|
||||
const [interfaceTraffic, setInterfaceTraffic] = useState<FlowMapInterfaceTraffic[]>()
|
||||
const [mapServices, setMapServices] = useState<FlowMapService[]>([])
|
||||
const [mapServiceEdges, setMapServiceEdges] = useState<FlowMapServiceEdge[]>([])
|
||||
@@ -1116,7 +1111,7 @@ function NetworkMapContent() {
|
||||
const expandedCountry = expandedCountryId
|
||||
? mapCountries.find((c) => c.id === expandedCountryId) ?? null
|
||||
: null
|
||||
const [highlightedPath, setHighlightedPath] = useState<{ viaId: string; enId: string; serviceId: string } | null>(null)
|
||||
const [highlightedPath, setHighlightedPath] = useState<FlowMapServicePath | null>(null)
|
||||
const selWanIdx=urlState.wan
|
||||
function setSelWanIdx(value:React.SetStateAction<number|null>){const next=typeof value==="function"?value(selWanIdx):value;updateUrl({wan:next==null?null:String(next)})}
|
||||
const [hoveredId, setHoveredId] = useState<string | null>(null)
|
||||
@@ -1168,6 +1163,7 @@ function NetworkMapContent() {
|
||||
if (!useLiveData) {
|
||||
queueMicrotask(() => {
|
||||
setMapHops([])
|
||||
setMapNodeUsers(undefined)
|
||||
setInterfaceTraffic(undefined)
|
||||
setMapServices(MOCK_MAP_SERVICES)
|
||||
setMapServiceEdges(MOCK_MAP_SERVICE_EDGES)
|
||||
@@ -1198,6 +1194,7 @@ function NetworkMapContent() {
|
||||
if (cancelled||request!==epoch) return
|
||||
const res=networkMapFlowSchema.parse(raw)
|
||||
setMapHops(res.hops)
|
||||
setMapNodeUsers(res.nodeUsers)
|
||||
setInterfaceTraffic(res.interfaceTraffic)
|
||||
setMapServices(res.services)
|
||||
setMapServiceEdges(res.serviceEdges)
|
||||
@@ -1438,9 +1435,11 @@ function NetworkMapContent() {
|
||||
? destEdges.filter(edge => nodePosById[edge.fromId] && visibleMapServices.some(service => service.id === edge.toId))
|
||||
: []
|
||||
|
||||
const selectedExitEdges = destEdges.filter(edge => edge.toId === liveSelectedService?.id)
|
||||
const selectedDestEdges = destEdges.filter(edge => edge.toId === liveSelectedService?.id)
|
||||
const selectedDestPaths = (selectedNestedService ? expandedCountryGroup?.paths ?? [] : destPaths)
|
||||
.filter(p => p.serviceId === liveSelectedService?.id).sort((a, b) => b.bps - a.bps)
|
||||
const unassignedBytes = liveSelectedService
|
||||
? liveSelectedService.bytes - selectedExitEdges.reduce((sum, edge) => sum + edge.bytes, 0)
|
||||
? liveSelectedService.bytes - selectedDestEdges.reduce((sum, edge) => sum + edge.bytes, 0)
|
||||
: 0
|
||||
|
||||
const nodes = mapServers
|
||||
@@ -1786,14 +1785,7 @@ function NetworkMapContent() {
|
||||
}
|
||||
|
||||
function togglePathHighlight(p: FlowMapServicePath) {
|
||||
setHighlightedPath((prev) => (
|
||||
prev
|
||||
&& prev.viaId === p.viaId
|
||||
&& prev.enId === p.enId
|
||||
&& prev.serviceId === p.serviceId
|
||||
? null
|
||||
: { viaId: p.viaId, enId: p.enId, serviceId: p.serviceId }
|
||||
))
|
||||
setHighlightedPath(prev => prev && servicePathKey(prev) === servicePathKey(p) ? null : p)
|
||||
}
|
||||
|
||||
function openWanJhSpeedDetail(ev: React.SyntheticEvent<SVGElement>, edge: WanJhEdge) {
|
||||
@@ -2017,8 +2009,8 @@ function NetworkMapContent() {
|
||||
const tablePaths = filterService ? (selectedNestedService ? expandedCountryGroup?.paths ?? [] : destPaths).filter(p => p.serviceId === filterService.id) : destPaths
|
||||
const flowRows = [...tablePaths].sort((a, b) => b.bps - a.bps).slice(0, 100).map(p => ({
|
||||
id: servicePathKey(p),
|
||||
client: p.clientName || p.viaName || p.viaId,
|
||||
exit: p.enName || p.enId,
|
||||
client: p.clientId === "—" ? "Без привязки" : p.clientName,
|
||||
exit: p.enName || p.enId || `IPFIX · ${p.viaName || p.viaId}`,
|
||||
dest: filterService?.label ?? destDisplayLabel(destNodes.find(svc => svc.id === p.serviceId), destMode, p.serviceId),
|
||||
rate: rateOf(p.bytes, p.bps),
|
||||
volume: formatBytes(p.bytes),
|
||||
@@ -2092,7 +2084,7 @@ function NetworkMapContent() {
|
||||
servers={mapServers}
|
||||
tunnels={mapGreTunnels}
|
||||
downRoutes={[...new Set(greEdges.filter((e) => e.tunnel.status === "down").map((e) => `${mapCardName(e.fromServer.name, 999).text} → ${mapCardName(e.toServer.name, 999).text}`))]}
|
||||
exits={[...destEdges.reduce((m, e) => m.set(e.fromId, (m.get(e.fromId) ?? 0) + e.bps), new Map<string, number>())].map(([id, bps]) => ({ name: mapCardName(mapServers.find((s) => s.id === id)?.name ?? id, 999).text, bps }))}
|
||||
exits={[...destEdges.filter(e => !e.observedOnly).reduce((m, e) => m.set(e.fromId, (m.get(e.fromId) ?? 0) + e.bps), new Map<string, number>())].map(([id, bps]) => ({ name: mapCardName(mapServers.find((s) => s.id === id)?.name ?? id, 999).text, bps }))}
|
||||
liveLink={busiestLiveLink}
|
||||
netflowBytes={mapTotalBytes > 0 ? mapTotalBytes : useLiveData && flowReadAt ? 0 : null}
|
||||
windowSec={mapWindowSec}
|
||||
@@ -2286,10 +2278,11 @@ function NetworkMapContent() {
|
||||
</g>
|
||||
))}
|
||||
|
||||
{/* ── Ленты NetFlow: Exit → назначения (толщина — скорость) ── */}
|
||||
{/* Ленты NetFlow от выходов и экспортёров к назначениям. */}
|
||||
{destRibbons.map(({ edge, d, w }) => {
|
||||
const hop = destinationRate(edge)
|
||||
const pathHit = Boolean(highlightedPath && highlightedPath.enId === edge.fromId && highlightedPath.serviceId === edge.toId)
|
||||
const selectedDestinationId = highlightedPath?.serviceId.split("|")[0]
|
||||
const pathHit = Boolean(highlightedPath && (highlightedPath.enId || highlightedPath.viaId) === edge.fromId && selectedDestinationId === edge.toId)
|
||||
const hl = pathHit || (!highlightedPath && (selectedService?.id === edge.toId || selected?.id === edge.fromId || expandedCountryId === edge.toId))
|
||||
const countryDim = !hl && Boolean(expandedCountryGroup) && edge.toId !== expandedCountryId
|
||||
const svc = visibleMapServices.find((s) => s.id === edge.toId)
|
||||
@@ -2297,12 +2290,14 @@ function NetworkMapContent() {
|
||||
const clientLabel = edge.clients?.map((c) => c.name).filter(Boolean).join(", ") || edge.clientName || "—"
|
||||
const rate = hopHasRate(hop) ? ` · ${formatNetflowRate(hop)} (${formatNetflowDir(hop)})` : ""
|
||||
return (
|
||||
<g key={`${edge.fromId}|${edge.toId}`} data-map-ribbon opacity={highlightedPath && !pathHit ? 0.08 : hl ? 0.75 : countryDim ? 0.12 : 0.42}
|
||||
<g key={`${edge.fromId}|${edge.toId}`} data-map-ribbon data-observation={edge.observedOnly || undefined} opacity={highlightedPath && !pathHit ? 0.08 : hl ? 0.75 : countryDim ? 0.12 : 0.42}
|
||||
style={{ transition: "opacity 0.3s", cursor: "pointer" }}
|
||||
onPointerDown={(ev) => { ev.stopPropagation() }}
|
||||
onClick={(ev) => { ev.stopPropagation(); if (svc) selectService(svc) }}>
|
||||
<title>{`${clientLabel} → ${enName} → ${destDisplayLabel(svc, destMode, edge.toId)}${rate}`}</title>
|
||||
<path d={d} fill="none" stroke="var(--chart-4)" strokeWidth={w} />
|
||||
<title>{edge.observedOnly
|
||||
? `Наблюдение IPFIX · ${enName} → ${destDisplayLabel(svc, destMode, edge.toId)}${rate} · выход не подтверждён`
|
||||
: `${clientLabel} → ${enName} → ${destDisplayLabel(svc, destMode, edge.toId)}${rate}`}</title>
|
||||
<path d={d} fill="none" stroke="var(--chart-4)" strokeWidth={w} strokeDasharray={edge.observedOnly ? "7 4" : undefined} />
|
||||
<path d={d} fill="none" stroke="transparent" strokeWidth={Math.max(12, w)} />
|
||||
{showAnimDots && !reducedMotion && hopHasRate(hop) && (
|
||||
<circle r="2.5" fill="var(--foreground)" opacity="0.7" pointerEvents="none">
|
||||
@@ -2809,8 +2804,8 @@ function NetworkMapContent() {
|
||||
</>
|
||||
) : liveSelectedService && (destMode === "services" || selectedNestedService) ? (
|
||||
<ServiceInspector key={liveSelectedService.id} service={liveSelectedService}
|
||||
paths={(selectedNestedService ? expandedCountryGroup?.paths ?? [] : destPaths).filter(p => p.serviceId === liveSelectedService.id).sort((a, b) => b.bps - a.bps)}
|
||||
exits={selectedNestedService ? [] : selectedExitEdges}
|
||||
paths={selectedDestPaths}
|
||||
exits={selectedNestedService ? [] : selectedDestEdges}
|
||||
exitName={id => mapServers.find(s => s.id === id)?.name ?? id}
|
||||
country={selectedNestedService ? expandedCountry?.label : undefined}
|
||||
base={useLiveData ? backendUrl : null} refresh={flowRefresh} windowLabel={mapWindow} flowAt={flowReadAt} stale={Boolean(flowError)}
|
||||
@@ -2896,6 +2891,7 @@ function NetworkMapContent() {
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<InspectorUsers users={serviceUsers(liveSelectedService, selectedDestPaths)} windowLabel={mapWindow} />
|
||||
{expandedCountryGroup && liveSelectedService.id === expandedCountryGroup.countryId && (
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground mb-2">Сервисы в стране</p>
|
||||
@@ -2920,7 +2916,7 @@ function NetworkMapContent() {
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground mb-2">Выход</p>
|
||||
<p className="text-xs font-semibold text-muted-foreground mb-2">Выходы и наблюдения</p>
|
||||
<div className="flex flex-col gap-3">
|
||||
{unassignedBytes > 0 && (
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
@@ -2928,16 +2924,13 @@ function NetworkMapContent() {
|
||||
<span className="font-mono">{formatNetflowRate({ bps: liveSelectedService.bps * unassignedBytes / liveSelectedService.bytes })}</span>
|
||||
</div>
|
||||
)}
|
||||
{selectedExitEdges.map((e) => {
|
||||
{selectedDestEdges.map((e) => {
|
||||
const src = mapServers.find((s) => s.id === e.fromId)
|
||||
const enPaths = destPaths
|
||||
.filter((p) => p.serviceId === liveSelectedService.id && p.enId === e.fromId)
|
||||
.slice()
|
||||
.sort((a, b) => b.bps - a.bps)
|
||||
const enPaths = selectedDestPaths.filter(p => (p.enId || p.viaId) === e.fromId)
|
||||
return (
|
||||
<div key={`${e.fromId}|${e.toId}`} className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
<span className="font-mono truncate">{src?.name ?? e.fromId}</span>
|
||||
<span className="font-mono truncate">{src?.name ?? e.fromId}{e.observedOnly && " · IPFIX"}</span>
|
||||
<span className="font-mono text-emerald-400 tabular-nums">
|
||||
{formatNetflowRate({ bytes: e.bytes, bps: e.bps, bpsFwd: e.bpsFwd, bpsRev: e.bpsRev })}
|
||||
</span>
|
||||
@@ -2995,6 +2988,7 @@ function NetworkMapContent() {
|
||||
]} />
|
||||
})()}
|
||||
<NodeHistory key={selected.id} id={selected.id} base={useLiveData ? backendUrl : null} refresh={flowRefresh} degraded={selected.status === "degraded"} />
|
||||
<InspectorUsers users={mapNodeUsers && (mapNodeUsers[selected.id] ?? [])} windowLabel={mapWindow} />
|
||||
{(() => {
|
||||
const res = srvResMap[selected.id]
|
||||
const ram = res?.ramUsed != null && res.ramTotal ? Math.round(res.ramUsed / res.ramTotal * 100) : null
|
||||
|
||||
@@ -49,7 +49,7 @@ export function registerFlowMapActions(register: typeof add) {
|
||||
await authorize()
|
||||
const output = { serverId: server.id, userId: input.userId ?? null, interface: input.interface ?? null, map: projected, pages, sourceWindow,
|
||||
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false, listenerBound,
|
||||
source: "closed minutes for all rates; retained flows for services, exit exporter or observed GRE peer/next hop for paths; interfaceTraffic includes private routed traffic before top-N",
|
||||
source: "closed minutes for all rates; retained flows for services and user breakdowns; paths use an exit exporter or observed GRE peer/next hop, otherwise identify the observing exporter; interfaceTraffic includes private routed traffic before top-N",
|
||||
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,
|
||||
referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false,
|
||||
rowSumIsNetworkTotal: false, historicalOwnershipVerified: false,
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
resetFlowMapHopsCacheForTests,
|
||||
} from "./traffic-flow-map-hops.js"
|
||||
import { withPgOrSkip } from "../test/pg.js"
|
||||
import { seedFlowTopologyForTests, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { loadFlowTopology, resolveClient, seedFlowTopologyForTests, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { disableCatalogFetchForTests, resetFlowCatalogForTests } from "./traffic-flow-classify.js"
|
||||
import {
|
||||
disableRipeEnqueueForTests,
|
||||
@@ -698,7 +698,7 @@ try {
|
||||
const googleEdge = wan.serviceEdges?.find((e) => e.toId === "svc:google")
|
||||
assert.ok(googleEdge, "Google с WAN JH")
|
||||
assert.equal(googleEdge.fromId, "9", "якорь на EN, не на JH")
|
||||
assert.ok(!(wan.serviceEdges ?? []).some((e) => e.fromId === "7"), "нет пунктира с JH")
|
||||
assert.ok(!(wan.serviceEdges ?? []).some((e) => e.fromId === "7"), "исторический снимок сопоставил GRE с Exit")
|
||||
const viaGre = wan.serviceEdges?.find((e) => e.toId === "svc:google")
|
||||
assert.ok(viaGre?.clients?.some((c) => c.name === "Alice") || viaGre?.clientName === "Alice")
|
||||
} finally {
|
||||
@@ -730,15 +730,20 @@ ingestClosed(7, [
|
||||
outIface: "1",
|
||||
nextHop: "",
|
||||
},
|
||||
{ ...payloadFlow("1.2.3.4", 6000), proto: 17, dstPort: 53, inIface: "gre-client", outIface: "ether1", nextHop: "" },
|
||||
])
|
||||
try {
|
||||
resetFlowMapHopsCacheForTests()
|
||||
const wanOnly = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
|
||||
assert.equal(wanOnly.services?.find(s => s.id === "svc:youtube")?.bytes, 9000)
|
||||
assert.deepEqual(wanOnly.serviceEdges, [])
|
||||
assert.deepEqual(wanOnly.servicePaths, [])
|
||||
assert.deepEqual(wanOnly.countryEdges, [])
|
||||
assert.ok(wanOnly.countryServiceGroups?.every(group => !group.edges.length && !group.paths.length))
|
||||
const dns = wanOnly.serviceEdges?.find(e => e.toId === "svc:dns")
|
||||
assert.deepEqual(dns && [dns.fromId, dns.observedOnly, dns.bytes], ["7", true, 6000])
|
||||
const dnsPath = wanOnly.servicePaths?.find(p => p.serviceId === "svc:dns")
|
||||
assert.deepEqual(dnsPath && [dnsPath.viaId, dnsPath.viaIface, dnsPath.enId, dnsPath.clientName], ["7", "ether1", "", "Alice"])
|
||||
assert.ok(wanOnly.countryEdges?.every(e => e.observedOnly && e.fromId === "7"))
|
||||
assert.ok(wanOnly.countryServiceGroups?.some(group => group.edges.some(e => e.toId.endsWith("|svc:dns"))))
|
||||
assert.deepEqual(wanOnly.nodeUsers?.["7"]?.map(u => [u.clientName, u.bytes]), [["—", 9000], ["Alice", 6000]])
|
||||
assert.equal(wanOnly.nodeUsers?.["9"], undefined)
|
||||
|
||||
} finally {
|
||||
seedFlowTopologyForTests(null)
|
||||
@@ -788,6 +793,8 @@ try {
|
||||
assert.ok(googleEdge)
|
||||
assert.equal(googleEdge.bytes, 120_000)
|
||||
assert.equal(dual.totalBytes, 120_000, "объём крупнейшей копии с атрибуцией маршрута JH")
|
||||
assert.equal(dual.nodeUsers?.["7"]?.find(u => u.clientName === "Alice")?.bytes, 12_000)
|
||||
assert.equal(dual.nodeUsers?.["9"]?.find(u => u.clientName === "Alice")?.bytes, 120_000)
|
||||
assert.equal(googleEdge.bps, googlePaths[0]?.bps)
|
||||
} finally {
|
||||
seedFlowTopologyForTests(null)
|
||||
@@ -1037,8 +1044,10 @@ try {
|
||||
try {
|
||||
const map = await buildFlowMapHops({ serverId: 7, minutes: 5, minSharePct: 0 })
|
||||
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.bytes, 12000)
|
||||
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes]), [["10", 2000], ["9", 1000]])
|
||||
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 3000)
|
||||
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes, Boolean(e.observedOnly)]), [["7", 9000, true], ["10", 2000, false], ["9", 1000, false]])
|
||||
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 12000)
|
||||
assert.equal(map.nodeUsers?.["7"]?.find(u => u.clientName === "Alice")?.bytes, 12000)
|
||||
assert.equal(map.nodeUsers?.["9"]?.find(u => u.clientName === "Alice")?.bytes, 1000)
|
||||
|
||||
const recent = await buildFlowMapHops({ serverId: 7, minutes: 1, includeCurrentMinute: true, minSharePct: 0 })
|
||||
assert.equal(recent.windowSec, 90)
|
||||
@@ -1104,12 +1113,28 @@ try {
|
||||
ingestClosed(sid, [split], bucket - 60000)
|
||||
const mixed = await buildFlowMapHops({serverId: sid, minutes: 5, iface: "mixed-lan"})
|
||||
assert.equal(mixed.totalBytes, 6000)
|
||||
assert.deepEqual(mixed.serviceEdges, [])
|
||||
assert.ok(mixed.serviceEdges?.every(e => e.observedOnly && e.fromId === String(sid)))
|
||||
assert.ok(mixed.servicePaths?.every(p => !p.enId))
|
||||
await flushEngineNow({ prune: false })
|
||||
assert.deepEqual((await dbQuery("SELECT out_iface,next_hop FROM flow_buckets WHERE server_id=? AND in_iface='mixed-lan'", [sid])).rows,
|
||||
[{out_iface: "", next_hop: null}, {out_iface: "", next_hop: null}])
|
||||
const user = await buildFlowMapHops({serverId: sid, minutes: 5, userId: "no-interface-binding"})
|
||||
assert.equal(user.interfaceTraffic, undefined)
|
||||
const alice = `map-alice-${sid}`, bob = `map-bob-${sid}`
|
||||
try {
|
||||
await dbQuery("INSERT INTO app_users(id,login,name) VALUES (?,?,'Alice'),(?,?,'Bob')", [alice, alice, bob, bob])
|
||||
await dbQuery(`
|
||||
INSERT INTO user_interface_bindings(id,user_id,server_id,interface_name,interface_type,peer_public_key)
|
||||
VALUES (?, ?, ?, 'wg-shared', 'wg', 'alice-key'), (?, ?, ?, 'wg-shared', 'wg', 'bob-key'), (?, ?, ?, 'gre-owner', 'gre', '')
|
||||
`, [alice + "-wg", alice, sid, bob + "-wg", bob, sid, alice + "-gre", alice, sid])
|
||||
seedFlowTopologyForTests(null)
|
||||
for (const topology of [await loadFlowTopology(), await loadFlowTopology([sid])]) {
|
||||
assert.equal(resolveClient(topology, sid, "wg-shared"), null, "общий WG не присваивается одному пользователю")
|
||||
assert.equal(resolveClient(topology, sid, "gre-owner")?.userId, alice)
|
||||
}
|
||||
} finally {
|
||||
await dbQuery("DELETE FROM app_users WHERE id IN (?,?)", [alice, bob])
|
||||
}
|
||||
console.log("CHR NetFlow v5 through PostgreSQL and map: GRE A RX / GRE B TX both 192 B, 3 packets; Top-200 and GRE encapsulation verified")
|
||||
} finally {
|
||||
await dbQuery("DELETE FROM servers WHERE id=?", [sid])
|
||||
|
||||
@@ -17,7 +17,7 @@ import { destCtxForIface, flowRateDirection, mapInternetBrand } from "./traffic-
|
||||
import { resolveFlowEndpoints } from "./traffic-flow-ip.js"
|
||||
import { geoipReadersStatus, resolveFlowIp } from "./traffic-flow-geoip.js"
|
||||
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
|
||||
import { loadFlowTopology, resolveClient, getServerCatalog, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { loadFlowTopology, resolveClient, getServerCatalog, type FlowClientBinding, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM } from "./traffic-flow-engine.js"
|
||||
|
||||
export const DEFAULT_MAP_SERVICE_MIN_SHARE_PCT = 5
|
||||
@@ -64,6 +64,7 @@ interface ClientAcc {
|
||||
interface FromAcc {
|
||||
exporterId: string
|
||||
enId: string
|
||||
viaIface?: string
|
||||
reverseBytes: number
|
||||
bytes: number
|
||||
clients: Map<string, ClientAcc>
|
||||
@@ -91,6 +92,7 @@ interface DestEdgeAcc {
|
||||
bytesFwd: number
|
||||
bytesRev: number
|
||||
clients: Map<string, string>
|
||||
observedOnly?: true
|
||||
}
|
||||
|
||||
interface DestPathAcc {
|
||||
@@ -98,6 +100,7 @@ interface DestPathAcc {
|
||||
clientName: string
|
||||
viaId: string
|
||||
viaName: string
|
||||
viaIface?: string
|
||||
enId: string
|
||||
enName: string
|
||||
serviceId: string
|
||||
@@ -115,12 +118,12 @@ function bumpClient(clients: Map<string, ClientAcc>, bytes: number, client: { us
|
||||
clients.set(id, { name, bytes })
|
||||
}
|
||||
|
||||
function bumpFrom(acc: DstAcc, exporterId: string, enId: string, bytes: number, reverse: boolean, client: { userId: string; name: string } | null): void {
|
||||
const key = exporterId + "|" + enId
|
||||
const from = acc.fromBytes.get(key) ?? { exporterId, enId, bytes: 0, reverseBytes: 0, clients: new Map<string, ClientAcc>() }
|
||||
function bumpFrom(acc: DstAcc, exporterId: string, enId: string, viaIface: string | undefined, bytes: number, reverse: boolean, client: FlowClientBinding | null | undefined): void {
|
||||
const key = JSON.stringify([exporterId, enId, viaIface])
|
||||
const from = acc.fromBytes.get(key) ?? { exporterId, enId, viaIface, bytes: 0, reverseBytes: 0, clients: new Map<string, ClientAcc>() }
|
||||
from.bytes += bytes
|
||||
if (reverse) from.reverseBytes += bytes
|
||||
bumpClient(from.clients, bytes, client)
|
||||
bumpClient(from.clients, bytes, client ?? null)
|
||||
acc.fromBytes.set(key, from)
|
||||
}
|
||||
|
||||
@@ -171,7 +174,7 @@ function bumpDestFrom(
|
||||
enName: string,
|
||||
viaName: string,
|
||||
/** fromId ребра, если отличается от EN (вложенный слой: страна → сервис). */
|
||||
edgeFromId: string = fromId,
|
||||
edgeFromId: string = fromId || exporterId,
|
||||
): void {
|
||||
const edgeKey = `${edgeFromId}|${toId}`
|
||||
const prevEdge = edges.get(edgeKey)
|
||||
@@ -192,10 +195,11 @@ function bumpDestFrom(
|
||||
bytesFwd: from.bytes - from.reverseBytes,
|
||||
bytesRev: from.reverseBytes,
|
||||
clients: namedClients,
|
||||
...(!fromId && edgeFromId === exporterId ? { observedOnly: true as const } : {}),
|
||||
})
|
||||
}
|
||||
for (const [clientId, c] of from.clients) {
|
||||
const pathKey = `${clientId}|${exporterId}|${fromId}|${toId}`
|
||||
const pathKey = JSON.stringify([clientId, exporterId, fromId, toId, from.viaIface])
|
||||
const prevPath = paths.get(pathKey)
|
||||
if (prevPath) {
|
||||
prevPath.bytes += c.bytes
|
||||
@@ -206,6 +210,7 @@ function bumpDestFrom(
|
||||
clientName: c.name,
|
||||
viaId: exporterId,
|
||||
viaName,
|
||||
...(from.viaIface ? { viaIface: from.viaIface } : {}),
|
||||
enId: fromId,
|
||||
enName,
|
||||
serviceId: toId,
|
||||
@@ -253,6 +258,7 @@ function finalizeDestLayer(
|
||||
bps: (e.bytes * 8) / windowSec,
|
||||
bpsFwd: (e.bytesFwd * 8) / windowSec,
|
||||
bpsRev: (e.bytesRev * 8) / windowSec,
|
||||
...(e.observedOnly ? { observedOnly: e.observedOnly } : {}),
|
||||
...(first ? { clientId: first.id, clientName: first.name } : {}),
|
||||
...(clients.length ? { clients } : {}),
|
||||
}
|
||||
@@ -265,6 +271,7 @@ function finalizeDestLayer(
|
||||
clientName: p.clientName,
|
||||
viaId: p.viaId,
|
||||
viaName: p.viaName,
|
||||
...(p.viaIface ? { viaIface: p.viaIface } : {}),
|
||||
enId: p.enId,
|
||||
enName: p.enName,
|
||||
serviceId: p.serviceId,
|
||||
@@ -341,18 +348,6 @@ function hopsQueryKey(q: FlowMapHopsQuery, minSharePct: number): string {
|
||||
})
|
||||
}
|
||||
|
||||
async function userIfaceAllow(userId: string): Promise<Map<number, Set<string>> | null> {
|
||||
if (!userId) return null
|
||||
const binds = await flowReadDbAll<{serverId:number;interfaceName:string}>('SELECT server_id AS "serverId",interface_name AS "interfaceName" FROM user_interface_bindings WHERE user_id=?',[userId])
|
||||
const allow = new Map<number, Set<string>>()
|
||||
for (const b of binds) {
|
||||
const set = allow.get(b.serverId) ?? new Set<string>()
|
||||
set.add(b.interfaceName)
|
||||
allow.set(b.serverId, set)
|
||||
}
|
||||
return allow
|
||||
}
|
||||
|
||||
function ifaceUsable(name: string): boolean {
|
||||
return Boolean(name) && name !== "—"
|
||||
}
|
||||
@@ -362,9 +357,11 @@ function resolveMapClient(
|
||||
serverId: number,
|
||||
inName: string,
|
||||
outName: string,
|
||||
) {
|
||||
return resolveClient(topo, serverId, inName)
|
||||
?? (ifaceUsable(outName) ? resolveClient(topo, serverId, outName) : null)
|
||||
): FlowClientBinding | null | undefined {
|
||||
const ingress = resolveClient(topo, serverId, inName)
|
||||
const egress = resolveClient(topo, serverId, outName)
|
||||
if (ingress && egress && ingress.userId !== egress.userId) return null
|
||||
return ingress ?? egress ?? undefined
|
||||
}
|
||||
|
||||
function bump(acc: Map<string, HopAcc>, key: string, seed: Omit<HopAcc, "bytes" | "bytesFwd" | "bytesRev">, bytes: number, dir: "fwd" | "rev" | "both"): void {
|
||||
@@ -499,21 +496,24 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const excludeOverlay = q.excludeOverlay !== false
|
||||
await authorize()
|
||||
const topo = await loadFlowTopology(scope?.serverIds, authorize)
|
||||
let allow: Map<number, Set<string>> | null = null
|
||||
if (q.userId) {
|
||||
if (!scope) allow = await userIfaceAllow(q.userId)
|
||||
else {
|
||||
allow = new Map()
|
||||
for (const binding of topo.clientByIface.values()) if (binding.userId === q.userId) {
|
||||
const names = allow.get(binding.serverId) ?? new Set<string>(); names.add(binding.interfaceName); allow.set(binding.serverId, names)
|
||||
}
|
||||
if (!allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
|
||||
const allow = q.userId ? new Map<number, Set<string>>() : null
|
||||
if (allow) {
|
||||
for (const binding of topo.clientByIface.values()) if (binding.userId === q.userId) {
|
||||
const names = allow.get(binding.serverId) ?? new Set<string>()
|
||||
names.add(binding.interfaceName)
|
||||
allow.set(binding.serverId, names)
|
||||
}
|
||||
if (scope && !allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
|
||||
}
|
||||
|
||||
function rowClient(r: (typeof raw)[number]) {
|
||||
return resolveMapClient(topo, r.serverId, resolveIfaceName(r.serverId, r.inIface).name, resolveIfaceName(r.serverId, r.outIface).name)
|
||||
}
|
||||
|
||||
const matches = (serverId: number, iface: string) =>
|
||||
flowRowMatchesFilter({ serverId, inIface: iface }, resolveIfaceName(serverId, iface).name, q, allow)
|
||||
const selected = raw.filter(r => matches(r.serverId, r.inIface) || matches(r.serverId, r.outIface))
|
||||
const selected = raw.filter(r => (!q.userId || rowClient(r)?.userId === q.userId) &&
|
||||
(matches(r.serverId, r.inIface) || matches(r.serverId, r.outIface)))
|
||||
const { rows } = collapseGreEspRows(selected, r => {
|
||||
if (ifaceFilter) {
|
||||
const ingress = matches(r.serverId, r.inIface), egress = matches(r.serverId, r.outIface)
|
||||
@@ -551,16 +551,14 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
}
|
||||
await authorize()
|
||||
const peers = await readMapGrePeers(working)
|
||||
const observed = new Map<(typeof working)[number], { endpoints: ReturnType<typeof resolveFlowEndpoints>; exitId?: number; reverse: boolean }>()
|
||||
const observed = new Map<(typeof working)[number], {
|
||||
endpoints: ReturnType<typeof resolveFlowEndpoints>; exitId?: number; viaIface?: string; reverse: boolean
|
||||
client: ReturnType<typeof rowClient>; nodeBytes: Map<number, number>
|
||||
}>()
|
||||
const nodeUsers = new Map<number, Map<string, ClientAcc>>()
|
||||
const enIds = new Set(topo.enNodes.map((n) => n.id))
|
||||
let totalBytes = 0
|
||||
|
||||
function rowClient(r: (typeof working)[number]) {
|
||||
const inName = resolveIfaceName(r.serverId, r.inIface).name
|
||||
const outName = resolveIfaceName(r.serverId, r.outIface).name
|
||||
return resolveMapClient(topo, r.serverId, inName, outName)
|
||||
}
|
||||
|
||||
for (const r of working) {
|
||||
const inRes = resolveIfaceName(r.serverId, r.inIface)
|
||||
const outRes = resolveIfaceName(r.serverId, r.outIface)
|
||||
@@ -626,7 +624,14 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const reverse = !!endpoints.internetPeer && (endpoints.internetPeer === endpoints.packetSrc || endpoints.internetPeer === r.natSrc)
|
||||
const serviceSide = endpoints.internetPeer ? (reverse ? inId : outId) : peerId
|
||||
const exitId = enIds.has(r.serverId) ? r.serverId : serviceSide ?? undefined
|
||||
observed.set(r, { endpoints, exitId, reverse })
|
||||
const serviceIface = reverse ? inName : outName
|
||||
const otherIface = reverse ? outName : inName
|
||||
const viaIface = exitId === undefined
|
||||
? ifaceUsable(serviceIface) ? serviceIface : ifaceUsable(otherIface) ? otherIface : undefined
|
||||
: undefined
|
||||
const nodeBytes = new Map([[r.serverId, r.bytes]])
|
||||
if (exitId !== undefined) nodeBytes.set(exitId, r.bytes)
|
||||
observed.set(r, { endpoints, exitId, viaIface, reverse, client: resolveMapClient(topo, r.serverId, inName, outName), nodeBytes })
|
||||
if (peerId && peerId !== r.serverId) {
|
||||
const toId = String(peerId)
|
||||
const dir = outId === peerId ? "fwd" : "rev"
|
||||
@@ -668,33 +673,44 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const payloadBytes = new Map<(typeof working)[number], number>()
|
||||
const payloadRows = wantDedup
|
||||
? dedupFlowRowsAcrossExporters(working, (a, b) => {
|
||||
const aRouted = observed.get(a)?.exitId !== undefined
|
||||
const bRouted = observed.get(b)?.exitId !== undefined
|
||||
const aCli = Boolean(rowClient(a))
|
||||
const bCli = Boolean(rowClient(b))
|
||||
const observationA = observed.get(a)!
|
||||
const observationB = observed.get(b)!
|
||||
const aRouted = observationA.exitId !== undefined
|
||||
const bRouted = observationB.exitId !== undefined
|
||||
const aCli = Boolean(observationA.client)
|
||||
const bCli = Boolean(observationB.client)
|
||||
const attributed = aRouted !== bRouted ? (aRouted ? a : b)
|
||||
: aCli !== bCli ? (aCli ? a : b)
|
||||
: a.bytes >= b.bytes ? a : b
|
||||
// Route/client evidence and the largest byte observation can come from different exporters.
|
||||
payloadBytes.set(attributed, Math.max(payloadBytes.get(a) ?? a.bytes, b.bytes))
|
||||
const clientA = observationA.client, clientB = observationB.client
|
||||
const chosen = observed.get(attributed)!
|
||||
chosen.client = clientA === null || clientB === null || (clientA && clientB && clientA.userId !== clientB.userId)
|
||||
? null : clientA ?? clientB
|
||||
for (const [id, bytes] of (attributed === a ? observationB : observationA).nodeBytes) {
|
||||
chosen.nodeBytes.set(id, Math.max(chosen.nodeBytes.get(id) ?? 0, bytes))
|
||||
}
|
||||
return attributed
|
||||
})
|
||||
: working
|
||||
|
||||
for (const r of payloadRows) {
|
||||
const inName = resolveIfaceName(r.serverId, r.inIface).name
|
||||
const outName = resolveIfaceName(r.serverId, r.outIface).name
|
||||
const bytes = payloadBytes.get(r) ?? r.bytes
|
||||
totalBytes += bytes
|
||||
const { endpoints: ep, exitId, reverse } = observed.get(r)!
|
||||
const { endpoints: ep, exitId, viaIface, reverse, client, nodeBytes } = observed.get(r)!
|
||||
for (const [id, observedBytes] of nodeBytes) {
|
||||
const users = nodeUsers.get(id) ?? new Map<string, ClientAcc>()
|
||||
bumpClient(users, observedBytes, client ?? null)
|
||||
nodeUsers.set(id, users)
|
||||
}
|
||||
const dst = ep.internetPeer
|
||||
const dstPort = ep.peerPort || r.dstPort
|
||||
const srcPort = ep.otherPort || r.srcPort
|
||||
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : ""
|
||||
const client = resolveMapClient(topo, r.serverId, inName, outName)
|
||||
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, proto: r.proto, dstPort, srcPort, fromBytes: new Map<string, FromAcc>() }
|
||||
acc.bytes += bytes
|
||||
if (exitId !== undefined) bumpFrom(acc, String(r.serverId), String(exitId), bytes, reverse, client)
|
||||
bumpFrom(acc, String(r.serverId), exitId === undefined ? "" : String(exitId), viaIface, bytes, reverse, client)
|
||||
dstAcc.set(destKey, acc)
|
||||
}
|
||||
|
||||
@@ -767,6 +783,9 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
await authorize()
|
||||
return {
|
||||
...(interfaceTraffic ? { interfaceTraffic } : {}),
|
||||
nodeUsers: Object.fromEntries([...nodeUsers].map(([id, users]) => [id, [...users].map(([clientId, { name, bytes }]) => (
|
||||
{ clientId, clientName: name, bytes, bps: bytes * 8 / windowSec }
|
||||
)).sort((a, b) => b.bytes - a.bytes)])),
|
||||
hops: [...hops.values()]
|
||||
.map((a) => toHop(a, windowSec))
|
||||
.sort((a, b) => a.bytes === b.bytes ? 0 : b.bytes - a.bytes),
|
||||
|
||||
@@ -124,23 +124,37 @@ export async function loadFlowTopology(serverIds?: readonly number[], authorize:
|
||||
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=u.id AND NOT(hidden.server_id=ANY(?::bigint[]))) LIMIT 1001
|
||||
`, [serverIds, serverIds])
|
||||
await authorize()
|
||||
const binds = serverIds === undefined ? await flowReadDbAll<{userId:string;serverId:number;interfaceName:string}>('SELECT user_id AS "userId",server_id AS "serverId",interface_name AS "interfaceName" FROM user_interface_bindings') : await flowReadDbAll<{ userId: string; serverId: number; interfaceName: string }>(`
|
||||
const binds = serverIds === undefined ? await flowReadDbAll<{userId:string;serverId:number;interfaceName:string;peerPublicKey?:string}>(
|
||||
'SELECT user_id AS "userId",server_id AS "serverId",interface_name AS "interfaceName",peer_public_key AS "peerPublicKey" FROM user_interface_bindings',
|
||||
) : await flowReadDbAll<{ userId: string; serverId: number; interfaceName: string; peerPublicKey?: string }>(`
|
||||
SELECT b.user_id AS "userId",b.server_id AS "serverId",b.interface_name AS "interfaceName" FROM user_interface_bindings b
|
||||
WHERE b.server_id=ANY(?::bigint[]) AND b.peer_public_key='' AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=b.user_id AND NOT(hidden.server_id=ANY(?::bigint[]))) ORDER BY b.id
|
||||
WHERE b.server_id=ANY(?::bigint[]) AND b.peer_public_key=''
|
||||
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=b.user_id AND NOT(hidden.server_id=ANY(?::bigint[])))
|
||||
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings conflict WHERE conflict.server_id=b.server_id
|
||||
AND conflict.interface_name=b.interface_name AND (conflict.peer_public_key<>'' OR conflict.user_id<>b.user_id))
|
||||
ORDER BY b.id
|
||||
LIMIT 1001
|
||||
`, [serverIds, serverIds])
|
||||
if (serverIds !== undefined && (binds.length > 1000 || users.length > 1000)) throw new Error("Превышен предел топологии NetFlow")
|
||||
const loginById = new Map(users.map((u) => [u.id, u]))
|
||||
const clientIfaces = new Map<number, Set<string>>()
|
||||
const clientByIface = new Map<string, FlowClientBinding>()
|
||||
const ambiguousIfaces = new Set<string>()
|
||||
const allClientNames = new Set<string>()
|
||||
for (const b of binds) {
|
||||
const set = clientIfaces.get(b.serverId) ?? new Set<string>()
|
||||
set.add(b.interfaceName)
|
||||
clientIfaces.set(b.serverId, set)
|
||||
allClientNames.add(b.interfaceName)
|
||||
const key = ifaceKey(b.serverId, b.interfaceName)
|
||||
const previous = clientByIface.get(key)
|
||||
if (b.peerPublicKey || previous && previous.userId !== b.userId) {
|
||||
ambiguousIfaces.add(key)
|
||||
clientByIface.delete(key)
|
||||
}
|
||||
if (ambiguousIfaces.has(key)) continue
|
||||
const user = loginById.get(b.userId)
|
||||
clientByIface.set(ifaceKey(b.serverId, b.interfaceName), {
|
||||
clientByIface.set(key, {
|
||||
userId: b.userId,
|
||||
login: user?.login || b.userId,
|
||||
name: user?.name || user?.login || b.userId,
|
||||
|
||||
@@ -1,24 +1,21 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useRef } from "react"
|
||||
import { InfoIcon } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
|
||||
|
||||
const STATUS = [["var(--success)", "Онлайн"], ["var(--warning)", "Внимание"], ["var(--destructive)", "Оффлайн"], ["var(--muted-foreground)", "Неизвестно"]] as const
|
||||
const ROLES = [["HR", "Home Router", "var(--chart-2)"], ["JH", "JumpHost", "var(--chart-1)"], ["EN", "Exit Node", "var(--chart-3)"], ["IX", "IX Node", "var(--chart-4)"]] as const
|
||||
|
||||
/** Легенда карты макета v3: статус, роли узлов, виды связей и что значат подписи. */
|
||||
export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
|
||||
const details = useRef<HTMLDetailsElement>(null)
|
||||
useEffect(() => {
|
||||
if (compact && details.current) details.current.open = false
|
||||
}, [compact])
|
||||
const head = "text-muted-foreground mt-1 text-[11px] font-semibold tracking-wider uppercase"
|
||||
return (
|
||||
<details ref={details} data-map-legend className="relative">
|
||||
<summary className="border-border bg-background hover:bg-muted/60 text-foreground flex h-8 cursor-pointer list-none items-center gap-1.5 rounded-lg border px-2.5 text-[13px] font-medium transition-colors focus-visible:outline-2 focus-visible:outline-ring [&::-webkit-details-marker]:hidden [[open]>&]:bg-muted">
|
||||
<Popover key={compact ? "compact" : "overview"}>
|
||||
<PopoverTrigger render={<Button type="button" variant="outline" className="text-[13px]" />}>
|
||||
<InfoIcon aria-hidden="true" className="size-4" />Легенда
|
||||
</summary>
|
||||
<div role="region" aria-label="Легенда карты" className="bg-popover text-popover-foreground absolute top-full right-0 z-30 mt-1 max-sm:fixed max-sm:inset-x-4 max-sm:top-auto max-sm:w-auto flex max-h-[60vh] w-[310px] max-w-[calc(100vw-2rem)] flex-col gap-2 overflow-y-auto rounded-lg border p-3 text-xs shadow-lg">
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="end" role="region" aria-label="Легенда карты" className="max-h-[min(60vh,var(--available-height))] w-[310px] max-w-[calc(100vw-2rem)] gap-2 overflow-y-auto border p-3 text-xs">
|
||||
<p className={head}>Статус</p>
|
||||
<div className="grid grid-cols-2 gap-x-2.5 gap-y-1.5">
|
||||
{STATUS.map(([color, label]) => (
|
||||
@@ -43,9 +40,10 @@ export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeWidth="2" /></svg>Home Router → аплинк</span>
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeWidth="2" strokeDasharray="2 6" strokeLinecap="round" /></svg>Пунктир WAN→JH — модель связности; маршрут не подтверждён.</span>
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="12" viewBox="0 0 32 12"><path d="M0 3 C16 3 16 9 32 9" fill="none" stroke="var(--chart-4)" strokeOpacity="0.55" strokeWidth="6" /></svg>Лента NetFlow · толщина = скорость</span>
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="12" viewBox="0 0 32 12"><path d="M0 3 C16 3 16 9 32 9" fill="none" stroke="var(--chart-4)" strokeWidth="3" strokeDasharray="5 3" /></svg>Наблюдение IPFIX · выход не подтверждён</span>
|
||||
</div>
|
||||
<p className="text-muted-foreground leading-snug">Live — последний замер RX/TX интерфейса RouterOS. «≈» и ленты NetFlow показывают среднюю скорость по принятым записям IPFIX. RTT — задержка пробы, «—» означает, что нет измерения.</p>
|
||||
</div>
|
||||
</details>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useEffect, useState, type ReactNode } from "react"
|
||||
import Link from "next/link"
|
||||
import { ChevronRightIcon, XIcon } from "lucide-react"
|
||||
import type { FlowAnalyticsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import type { FlowAnalyticsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath, FlowMapUser } from "@mmapp/contracts/traffic-flow"
|
||||
import { flowMapHopsDtoSchema } from "@mmapp/contracts/traffic-flow"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Sparkline } from "@/components/sparkline"
|
||||
@@ -12,6 +12,7 @@ import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { formatBytes, fmtRate } from "@/lib/fmt-rate"
|
||||
import { formatNetflowRate } from "@/lib/map-netflow-hops"
|
||||
import { servicePathKey } from "@/lib/format-service-path-label"
|
||||
import { projectTrafficObservations } from "@/lib/traffic-observations"
|
||||
import { getFlowAnalytics, getFlowMapHops } from "@/shared/api/traffic-flow"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
@@ -25,6 +26,46 @@ export function InspectorMetrics({ rows }: { rows: [string, ReactNode, string?][
|
||||
</dl>
|
||||
}
|
||||
|
||||
export function serviceUsers(service: FlowMapService, paths: FlowMapServicePath[]): FlowMapUser[] {
|
||||
const users = new Map<string, FlowMapUser>()
|
||||
function add(clientId: string, clientName: string, bytes: number, bps: number) {
|
||||
const user = users.get(clientId) ?? { clientId, clientName, bytes: 0, bps: 0 }
|
||||
user.bytes += bytes
|
||||
user.bps += bps
|
||||
users.set(clientId, user)
|
||||
}
|
||||
let attributedBytes = 0
|
||||
for (const p of paths) {
|
||||
add(p.clientId, p.clientName, p.bytes, p.bps)
|
||||
attributedBytes += p.bytes
|
||||
}
|
||||
if (service.bytes > attributedBytes) {
|
||||
const bytes = service.bytes - attributedBytes
|
||||
add("—", "—", bytes, service.bps * bytes / service.bytes)
|
||||
}
|
||||
return [...users.values()]
|
||||
}
|
||||
|
||||
export function InspectorUsers({ users, windowLabel }: { users?: FlowMapUser[]; windowLabel: string }) {
|
||||
const ranked = [...(users ?? [])].sort((a, b) => b.bytes - a.bytes || a.clientName.localeCompare(b.clientName))
|
||||
const total = ranked.reduce((sum, user) => sum + user.bytes, 0)
|
||||
return <section aria-label="Трафик по пользователям" title="Сохранённые потоки NetFlow и привязки интерфейсов. Узел может быть определён по наблюдаемому GRE-соседу." className="space-y-2 border-b px-3.5 py-3">
|
||||
<h3 className="flex justify-between gap-2 font-mono text-[11px] text-muted-foreground">
|
||||
<span>Пользователи</span><span>NetFlow · {windowLabel}</span>
|
||||
</h3>
|
||||
{!ranked.length && <p className="text-xs text-muted-foreground">{users ? "Нет сохранённых потоков в этом интервале" : "Разбивка в этом снимке недоступна"}</p>}
|
||||
{ranked.length > 0 && <ul className="max-h-52 space-y-2 overflow-y-auto">
|
||||
{ranked.map(user => <li key={user.clientId} className="flex items-start justify-between gap-2 text-xs">
|
||||
<span className="min-w-0 font-medium [overflow-wrap:anywhere]">{user.clientId === "—" ? "Без привязки к пользователю" : user.clientName}</span>
|
||||
<span className="shrink-0 text-right font-mono tabular-nums">
|
||||
{formatNetflowRate(user)}
|
||||
<span className="block text-[10px] text-muted-foreground">{formatBytes(user.bytes)}{total > 0 && ` · ${Math.round(user.bytes / total * 100)}%`}</span>
|
||||
</span>
|
||||
</li>)}
|
||||
</ul>}
|
||||
</section>
|
||||
}
|
||||
|
||||
export function NodeHistory({ base, id, refresh, degraded }: { base: string | null; id: string; refresh: number; degraded: boolean }) {
|
||||
const [sample, setSample] = useState<ReturnType<typeof projectTrafficObservations> | null>(null)
|
||||
const [unavailable, setUnavailable] = useState(false)
|
||||
@@ -64,7 +105,7 @@ export function NodeHistory({ base, id, refresh, degraded }: { base: string | nu
|
||||
export function ServiceInspector({ service, paths, exits, exitName, country, base, refresh, windowLabel, flowAt, stale, activePath, onPath, onClose, filtered, onFilter }: {
|
||||
service: FlowMapService; paths: FlowMapServicePath[]; exits: FlowMapServiceEdge[]; exitName: (id: string) => string
|
||||
country?: string; base: string | null; refresh: number; windowLabel: string; flowAt: string | null; stale: boolean
|
||||
activePath: { viaId: string; enId: string; serviceId: string } | null; onPath: (path: FlowMapServicePath) => void
|
||||
activePath: FlowMapServicePath | null; onPath: (path: FlowMapServicePath) => void
|
||||
onClose: () => void; filtered: boolean; onFilter: () => void
|
||||
}) {
|
||||
const [recent, setRecent] = useState<{ data: FlowAnalyticsDto; at: string } | null>(null)
|
||||
@@ -100,7 +141,8 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
|
||||
.sort((a, b) => b.bps - a.bps).slice(0, 5) ?? []
|
||||
const asns = [...new Set(flows.flatMap(flow => flow.dstAsn ? [flow.dstAsn] : []))]
|
||||
const rates = [...exits].sort((a, b) => b.bps - a.bps)
|
||||
const exitIds = [...new Set([...rates.map(e => e.fromId), ...paths.map(p => p.enId)])]
|
||||
const exitIds = [...new Set([...rates.filter(e => !e.observedOnly).map(e => e.fromId), ...paths.map(p => p.enId).filter(Boolean)])]
|
||||
const exporterIds = [...new Set([...rates.filter(e => e.observedOnly).map(e => e.fromId), ...paths.filter(p => !p.enId).map(p => p.viaId)])]
|
||||
const attributedBytes = (country ? paths : exits).reduce((sum, entry) => sum + entry.bytes, 0)
|
||||
const remainder = Math.max(0, service.bytes - attributedBytes)
|
||||
const observed = service.bytes > 0 && !stale
|
||||
@@ -118,17 +160,25 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
|
||||
["Скорость", formatNetflowRate({ bps: service.bps }), "Средняя скорость NetFlow за " + windowLabel],
|
||||
[country ? "Доля страны" : "Доля трафика", new Intl.NumberFormat("ru-RU", {style:"percent", maximumFractionDigits:1}).format(service.share)],
|
||||
["Объём · " + (currentVolume ? windowLabel : volume?.window ?? "24 ч"), <>{currentVolume ? formatBytes(service.bytes) : volume?.bytes == null ? "—" : formatBytes(volume.bytes)}{volume && <time dateTime={volume.at} title={new Date(volume.at).toLocaleString("ru-RU")} className="block text-[10px] font-normal text-muted-foreground">ответ {new Date(volume.at).toLocaleTimeString("ru-RU")}</time>}</>],
|
||||
["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder ? "Часть трафика без подтверждённого выхода" : undefined],
|
||||
exitIds.length || !exporterIds.length
|
||||
? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined]
|
||||
: ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"],
|
||||
]} />
|
||||
<InspectorUsers users={serviceUsers(service, paths)} windowLabel={windowLabel} />
|
||||
<section className="space-y-2 border-b px-3.5 py-3"><h3 className="text-[11px] text-muted-foreground">Путь трафика</h3>
|
||||
{paths.map(p => {
|
||||
const parts = [p.clientName !== "—" ? p.clientName : "", p.viaId !== p.enId ? p.viaName : "", p.enName, service.label].filter(Boolean)
|
||||
const active = activePath?.viaId === p.viaId && activePath.enId === p.enId && activePath.serviceId === p.serviceId
|
||||
return <button type="button" key={JSON.stringify([p.clientId,p.viaId,p.enId])} onClick={() => onPath(p)} aria-pressed={active} title={formatNetflowRate({bps:p.bps})} className={cn("flex w-full flex-wrap items-center gap-1 rounded-sm text-left", active && "ring-1 ring-primary")}>
|
||||
const parts = [p.clientName !== "—" ? p.clientName : "", p.viaId !== p.enId ? p.viaName : "",
|
||||
p.enName, service.label].filter(Boolean)
|
||||
const key = servicePathKey(p)
|
||||
const active = activePath && servicePathKey(activePath) === key
|
||||
return <button type="button" key={key} onClick={() => onPath(p)} aria-pressed={Boolean(active)} title={formatNetflowRate(p)} className={cn("flex w-full flex-wrap items-center gap-1 rounded-sm text-left", active && "ring-1 ring-primary")}>
|
||||
{parts.map((name, i) => <span key={i} className="inline-flex max-w-full items-center gap-1">{i > 0 && <ChevronRightIcon aria-hidden className="size-3 shrink-0 text-muted-foreground" />}<span className={cn("truncate rounded-md bg-muted px-1.5 py-1 font-mono text-[10px] font-semibold", i === parts.length - 1 && "bg-chart-4/20")}>{name}</span></span>)}
|
||||
{!p.enId && <span className="basis-full text-[10px] text-muted-foreground">
|
||||
Наблюдение IPFIX{p.viaIface ? ` · интерфейс ${p.viaIface}` : ""} · выход не подтверждён
|
||||
</span>}
|
||||
</button>
|
||||
})}
|
||||
{rates.filter(e => !paths.some(p => p.enId === e.fromId)).map(e => <div key={e.fromId} className="flex justify-between gap-2 text-xs"><span>{exitName(e.fromId)} → {service.label}</span><span className="shrink-0 font-mono">{formatNetflowRate({bps:e.bps})}</span></div>)}
|
||||
{rates.filter(e => !paths.some(p => (p.enId || p.viaId) === e.fromId && Boolean(p.enId) !== Boolean(e.observedOnly))).map(e => <div key={e.fromId} className="flex justify-between gap-2 text-xs"><span>{exitName(e.fromId)} → {service.label}{e.observedOnly && " · наблюдение IPFIX"}</span><span className="shrink-0 font-mono">{formatNetflowRate(e)}</span></div>)}
|
||||
{remainder > 0 && <div className="flex justify-between gap-2 text-xs text-muted-foreground"><span>Выход не определён</span><span className="font-mono">{formatNetflowRate({bps:service.bps * remainder / service.bytes})}</span></div>}
|
||||
{!paths.length && !rates.length && !remainder && <p className="text-xs text-muted-foreground">Маршрут не определён</p>}
|
||||
</section>
|
||||
|
||||
@@ -71,7 +71,7 @@ export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, e
|
||||
</div>
|
||||
<FramePanel className="p-0">
|
||||
<TabsContent value="flows">
|
||||
<Table head={["Источник", "Exit", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}>
|
||||
<Table head={["Пользователь", "Выход / экспортёр", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}>
|
||||
{flows.map((r) => (
|
||||
<Row key={r.id} cols={FLOW_COLS} hl={r.hl}>
|
||||
<span className="truncate font-mono">{r.client}</span>
|
||||
|
||||
@@ -43,3 +43,7 @@ export function formatServicePathTitle(label: string, serviceLabel: string): str
|
||||
if (label.includes(svc)) return label
|
||||
return `${label} · ${svc}`
|
||||
}
|
||||
|
||||
export function servicePathKey(p: { clientId: string; viaId: string; viaIface?: string; enId: string; serviceId: string }): string {
|
||||
return JSON.stringify([p.clientId, p.viaId, p.viaIface, p.enId, p.serviceId])
|
||||
}
|
||||
@@ -27,7 +27,7 @@ export function validateNetworkMapSnapshot(servers:unknown,gre:unknown,probes:un
|
||||
|
||||
import {flowMapHopsDtoSchema} from "@mmapp/contracts/traffic-flow"
|
||||
import {isIpv4String} from "./gre-endpoint-resolve"
|
||||
export const networkMapFlowSchema = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true, includesCurrentMinute: true }).refine(data =>
|
||||
export const networkMapFlowSchema = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true, includesCurrentMinute: true, nodeUsers: true }).refine(data =>
|
||||
(data.includesCurrentMinute
|
||||
? !data.sourceWindow && data.rangeMinutes === 1 && data.windowSec >= 60 && data.windowSec < 120
|
||||
: data.windowSec === data.rangeMinutes * 60 && (data.sourceWindow
|
||||
|
||||
@@ -388,6 +388,7 @@ export const flowMapServiceEdgeDtoSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
})).optional(),
|
||||
observedOnly: z.literal(true).optional(),
|
||||
})
|
||||
|
||||
export const flowMapServicePathDtoSchema = z.object({
|
||||
@@ -395,6 +396,8 @@ export const flowMapServicePathDtoSchema = z.object({
|
||||
clientName: z.string(),
|
||||
viaId: z.string(),
|
||||
viaName: z.string(),
|
||||
viaIface: z.string().optional(),
|
||||
/** Empty when IPFIX identified the exporter but the exit could not be inferred. */
|
||||
enId: z.string(),
|
||||
enName: z.string(),
|
||||
serviceId: z.string(),
|
||||
@@ -412,6 +415,12 @@ export const flowMapCountryServiceGroupDtoSchema = z.object({
|
||||
|
||||
export const flowMapHopsDtoSchema = z.object({
|
||||
sourceWindow: flowSourceWindowSchema.optional(),
|
||||
nodeUsers: z.record(z.string(), z.array(z.object({
|
||||
clientId: z.string(),
|
||||
clientName: z.string(),
|
||||
bytes: z.number().nonnegative(),
|
||||
bps: z.number().nonnegative(),
|
||||
}))).optional(),
|
||||
includesCurrentMinute: z.literal(true).optional(),
|
||||
/** Link counters include private routed payload. Mesh visibility applies to the inferred graph. */
|
||||
interfaceTraffic: z.array(z.object({
|
||||
@@ -463,3 +472,4 @@ export type FlowMapServicePath = z.infer<typeof flowMapServicePathDtoSchema>
|
||||
export type FlowMapCountryServiceGroup = z.infer<typeof flowMapCountryServiceGroupDtoSchema>
|
||||
export type FlowMapHopsDto = z.infer<typeof flowMapHopsDtoSchema>
|
||||
export type FlowMapInterfaceTraffic = NonNullable<FlowMapHopsDto["interfaceTraffic"]>[number]
|
||||
export type FlowMapUser = NonNullable<FlowMapHopsDto["nodeUsers"]>[string][number]
|
||||
@@ -19,7 +19,11 @@ test("Карта: открытые детали обновляются вмес
|
||||
})
|
||||
test("Карта: модель WAN не утверждает активный маршрут и RTT линии",async({page})=>{
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.goto("/network-map");await page.locator("[data-map-legend] summary").click();await expect(page.getByText("Пунктир WAN→JH — модель связности; маршрут не подтверждён.",{exact:true})).toBeVisible();await page.locator("[data-map-legend] summary").click()
|
||||
await page.goto("/network-map")
|
||||
const legend = page.getByRole("button", {name:"Легенда",exact:true})
|
||||
await legend.click()
|
||||
await expect(page.getByText("Пунктир WAN→JH — модель связности; маршрут не подтверждён.",{exact:true})).toBeVisible()
|
||||
await legend.click()
|
||||
await expect(page.locator("svg text").filter({hasText:/^5 мс$/})).toHaveCount(0)
|
||||
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Домашний",{exact:true}).click()
|
||||
await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:"Интерфейсы"}).click();await expect(page.getByText("Аплинк каталога",{exact:true})).toBeVisible();await expect(page.getByText("Модель связей с JH · Ping модели",{exact:true})).toBeVisible()
|
||||
|
||||
@@ -37,6 +37,41 @@ test("Карта не приписывает весь YouTube единствен
|
||||
await expect(badges).toContainText("↓6 Кбит/с ↑2 Кбит/с")
|
||||
})
|
||||
|
||||
test("Карта: DNS виден от экспортёра, пользователи разбиты в обеих карточках", async ({page}) => {
|
||||
const router = {...server, name: "MSK", type: "jump-host"}
|
||||
const dns = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 300000, bps: 8000, share: 1}
|
||||
const users = [
|
||||
{clientId: "u1", clientName: "Алиса", bytes: 225000, bps: 6000},
|
||||
{clientId: "—", clientName: "—", bytes: 75000, bps: 2000},
|
||||
]
|
||||
const servicePaths = users.map(u => ({...u, viaId: "1", viaName: "MSK", viaIface: "ether1", enId: "", enName: "", serviceId: dns.id}))
|
||||
await page.route("**/api/**", route => {
|
||||
const url = new URL(route.request().url())
|
||||
const path = url.pathname
|
||||
return route.fulfill({json: path === "/api/auth/config" ? {required: false}
|
||||
: path === "/api/servers" ? [router] : path === "/api/filters/gre-tunnels" ? {tunnels: [], failures: []}
|
||||
: path === "/api/uptime/speed-probes" ? {probes: []} : path === flowPath ? {
|
||||
...empty,
|
||||
...(url.searchParams.get("range") === "24h" ? {rangeMinutes: 1440, windowSec: 86400} : {}),
|
||||
totalBytes: dns.bytes, services: [dns], servicePaths, nodeUsers: {"1": users},
|
||||
serviceEdges: [{fromId: "1", toId: dns.id, observedOnly: true, bytes: dns.bytes, bps: dns.bps, bpsFwd: 0, bpsRev: dns.bps}],
|
||||
} : {}})
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
await expect(page.locator("[data-map-ribbon][data-observation] > title")).toContainText("MSK → DNS")
|
||||
await page.getByRole("button", {name: "Сервис DNS", exact: true}).press("Enter")
|
||||
const panel = page.getByRole("complementary", {name: "Детали объекта карты"})
|
||||
const breakdown = panel.getByRole("region", {name: "Трафик по пользователям"})
|
||||
await expect(breakdown.getByText("Алиса", {exact: true}).locator("..")).toContainText("6 Кбит/с")
|
||||
await expect(breakdown.getByText("Без привязки к пользователю")).toBeVisible()
|
||||
await expect(panel.getByText("Экспортёр", {exact: true})).toBeVisible()
|
||||
await expect(panel.getByText(/интерфейс ether1 · выход не подтверждён/i).first()).toBeVisible()
|
||||
await panel.getByRole("button").filter({hasText: /Алиса.*Наблюдение IPFIX/}).click()
|
||||
await expect(panel.getByRole("button", {pressed: true}).filter({hasText: "Наблюдение IPFIX"})).toHaveCount(1)
|
||||
await page.getByRole("button", {name: "Устройство MSK", exact: true}).press("Enter")
|
||||
await expect(breakdown.getByText("Алиса", {exact: true}).locator("..")).toContainText("75%")
|
||||
})
|
||||
|
||||
for (const reverse of [false, true]) test(`Карта: малый NetFlow и текущие RX/TX GRE показаны отдельно, reverse=${reverse}`, async ({ page }) => {
|
||||
const exit = { ...server, name: "ARN", type: "exit-node" }
|
||||
const jump = { ...server, id: 2, name: "MSK-02", host: "192.0.2.2", type: "jump-host" }
|
||||
|
||||
@@ -17,20 +17,30 @@ test.beforeEach(async ({ page }) => {
|
||||
|
||||
test("Карта: раскрытая легенда объясняет статусы, типы, линии и неизвестные измерения", async ({ page }) => {
|
||||
await page.goto("/network-map")
|
||||
const trigger = page.getByRole("button", { name: "Легенда", exact: true })
|
||||
const legend = page.getByRole("region", { name: "Легенда карты" })
|
||||
await expect(legend).not.toBeVisible()
|
||||
await page.locator("[data-map-legend] summary").click()
|
||||
await trigger.click()
|
||||
await expect(legend).toBeVisible()
|
||||
const firstStatus = legend.getByText("Онлайн", { exact: true })
|
||||
await expect.poll(() => firstStatus.evaluate(element => {
|
||||
const { x, y, width, height } = element.getBoundingClientRect()
|
||||
const hit = document.elementFromPoint(x + width / 2, y + height / 2)
|
||||
return hit !== null && element.contains(hit)
|
||||
})).toBe(true)
|
||||
for (const text of ["Онлайн", "Внимание", "Оффлайн", "Неизвестно", "JumpHost", "Exit Node", "Home Router", "GRE + IPsec", "Лента NetFlow · толщина = скорость"]) await expect(legend.getByText(text, { exact: true })).toBeVisible()
|
||||
await expect(legend).toContainText("нет измерения")
|
||||
await expect(legend).toContainText("последний замер RX/TX интерфейса RouterOS")
|
||||
await expect(legend).toContainText("среднюю скорость по принятым записям IPFIX")
|
||||
await page.locator("[data-map-legend] summary").click()
|
||||
await trigger.click()
|
||||
await expect(legend).not.toBeVisible()
|
||||
await page.locator("[data-map-legend] summary").press("Enter")
|
||||
await trigger.press("Enter")
|
||||
await expect(legend).toBeVisible()
|
||||
await legend.getByText("Онлайн", { exact: true }).click()
|
||||
await page.screenshot({ path: "tmp/map270-desktop.png" })
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(legend).not.toBeVisible()
|
||||
await expect(trigger).toBeFocused()
|
||||
})
|
||||
|
||||
test("Карта: мышь не рисует прямоугольную рамку, клавиатурный фокус остаётся видимым", async ({ page }) => {
|
||||
@@ -52,15 +62,16 @@ test("Карта: мышь не рисует прямоугольную рамк
|
||||
test("Карта: легенда помещается на телефоне и сворачивается", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.goto("/network-map")
|
||||
const trigger = page.getByRole("button", { name: "Легенда", exact: true })
|
||||
const legend = page.getByRole("region", { name: "Легенда карты" })
|
||||
await expect(page.locator("[data-map-legend]")).not.toHaveAttribute("open", "")
|
||||
await expect(trigger).toHaveAttribute("aria-expanded", "false")
|
||||
await page.screenshot({ path: "tmp/map270-mobile.png" })
|
||||
await page.locator("[data-map-legend] summary").click()
|
||||
await trigger.click()
|
||||
await expect(legend).toBeVisible()
|
||||
const bounds = await legend.boundingBox()
|
||||
expect(bounds!.x).toBeGreaterThanOrEqual(0)
|
||||
expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(390)
|
||||
await page.locator("[data-map-legend] summary").click()
|
||||
await trigger.click()
|
||||
await expect(legend).not.toBeVisible()
|
||||
})
|
||||
|
||||
|
||||
Reference in new issue
Block a user