diff --git a/app/(main)/network-map/page.tsx b/app/(main)/network-map/page.tsx index 013d450e..a3688f4b 100644 --- a/app/(main)/network-map/page.tsx +++ b/app/(main)/network-map/page.tsx @@ -26,7 +26,8 @@ import { type ServerStatus, type ServerType, } from "@/lib/data" -import {validateNetworkMapSnapshot,networkMapFlowSchema,validateNetworkMapDns,type NetworkMapServerRow} from "@/lib/network-map-response" +import {validateNetworkMapSnapshot,networkMapFlowSchema,recentMapFlowSchema,validateNetworkMapDns,type NetworkMapServerRow} from "@/lib/network-map-response" +import { getFlowMapHops } from "@/shared/api/traffic-flow" import { useDataSource } from "@/lib/data-source" import { requestJson } from "@/shared/api/http-client" import { @@ -196,6 +197,30 @@ function makeApiFetch(backendUrl: string) { } } +function useServiceSnapshot(base: string | null, range: "1m" | "5m", userId: string | undefined, refresh: number) { + const key = JSON.stringify([base, range, userId]) + const [snapshot, setSnapshot] = useState<{ key: string; refresh: number; data?: ReturnType; at?: string; error?: string }>() + useEffect(() => { + if (base === null) return + const controller = new AbortController() + let timer: ReturnType + const poll = async () => { + try { + const raw = await getFlowMapHops(base, { range, userId }, { signal: controller.signal }) + const data = (range === "1m" ? recentMapFlowSchema : networkMapFlowSchema).parse(raw) + if (!controller.signal.aborted) setSnapshot({ key, refresh, data, at: new Date().toISOString() }) + } catch { + if (!controller.signal.aborted) setSnapshot(last => ({ ...(last?.key === key ? last : undefined), key, refresh, error: "Не удалось обновить данные IPFIX" })) + } finally { + if (!controller.signal.aborted) timer = setTimeout(poll, range === "1m" ? 4000 : 15_000) + } + } + queueMicrotask(() => { if (!controller.signal.aborted) void poll() }) + return () => { controller.abort(); clearTimeout(timer) } + }, [base, range, userId, refresh, key]) + return base !== null && snapshot?.key === key ? snapshot : undefined +} + function fmtMB(mb: number | null): string { if(mb==null)return "—" if (mb >= 1024) return `${(mb / 1024).toFixed(mb >= 10240 ? 0 : 1)} ГБ` @@ -952,11 +977,11 @@ function NetworkMapContent() { const [flowReadAt,setFlowReadAt]=useState(null) const [flowListener,setFlowListener]=useState(false) const [flowLoading,setFlowLoading]=useState(false) - const [userFlow, setUserFlow] = useState<{ key: string; data?: ReturnType; at?: string; error?: string }>() const [bottomTab, setBottomTab] = useState("flows") const [analysisOpen, setAnalysisOpen] = useState(false) const [summaryOpen, setSummaryOpen] = useState(false) - const [filteredServiceId, setFilteredServiceId] = useState(null) + const [filterService, setFilterService] = useState | null>(null) + const filteredServiceId = filterService?.id ?? null const [mapEvents, setMapEvents] = useState(null) const [eventsError, setEventsError] = useState(null) const [eventsAt, setEventsAt] = useState(() => Date.now()) @@ -1133,7 +1158,7 @@ function NetworkMapContent() { function setDestMode(mode: DestMode) { updateUrl({dest:mode==="services"?null:mode,service:null}) setSelectedService(null) - setFilteredServiceId(null) + setFilterService(null) setExpandedCountryId(null) setHighlightedPath(null) try { sessionStorage.setItem(DEST_MODE_KEY, mode) } catch { /* private mode */ } @@ -1327,38 +1352,25 @@ function NetworkMapContent() { const usersInTopology = [...(ixOnly ? [] : access.users), ...access.linux].filter(user => user.bindings.some(binding => topologyIds.has(binding.node))) const pickedUser = usersInTopology.find(user => user.id === pickedUserId) const scopeUser = pickedUser && !pickedUser.linux ? pickedUser.id : undefined - const scopeKey = JSON.stringify([backendUrl, scopeUser, flowRefresh]) - const userSnapshot = useLiveData && scopeUser && userFlow?.key === scopeKey ? userFlow : undefined - const destinationWindowSec = userSnapshot?.data?.windowSec ?? mapWindowSec - const destinationWindow = formatMapFlowWindow(destinationWindowSec) - const destinationReadAt = pickedUserId ? userSnapshot?.at ?? null : flowReadAt - const destinationTotalBytes = pickedUserId ? userSnapshot?.data?.totalBytes : mapTotalBytes - const destinationNamedBytes = pickedUserId ? userSnapshot?.data?.namedBytes : mapNamedBytes - useEffect(() => { - if (!useLiveData || !scopeUser || !showServices) return - const controller = new AbortController() - let timer: ReturnType - async function refresh() { - try { - const raw = await apiFetch(`/api/traffic/flow/map-hops?${new URLSearchParams({range:"5m",userId:scopeUser!})}`, {signal:controller.signal}) - const data = networkMapFlowSchema.parse(raw) - if (!controller.signal.aborted) setUserFlow({ key: scopeKey, data, at: new Date().toISOString() }) - } catch { - if (!controller.signal.aborted) setUserFlow(last => ({ ...(last?.key === scopeKey ? last : undefined), key: scopeKey, error: "Снимок потоков пользователя недоступен" })) - } finally { - if (!controller.signal.aborted) timer = setTimeout(() => { void refresh() }, 15_000) - } - } - void refresh() - return () => { controller.abort(); clearTimeout(timer) } - }, [useLiveData, scopeUser, showServices, scopeKey, apiFetch]) - const rawPaths = destMode === "countries" ? mapCountryPaths : mapServicePaths - const filterPaths = filteredServiceId?.includes("|") ? mapCountryServiceGroups.find(group => group.countryId === filteredServiceId.split("|")[0])?.paths ?? [] : rawPaths + const liveServiceView = useLiveData && destMode === "services" + const requestRecent = liveServiceView && (showServices || showNetflow) && (!pickedUserId || Boolean(scopeUser)) + const recent = useServiceSnapshot(requestRecent ? backendUrl : null, "1m", scopeUser, flowRefresh) + const history = useServiceSnapshot(liveServiceView && scopeUser && (selectedService || linkedService) ? backendUrl : null, "5m", scopeUser, flowRefresh) + const destinationWindowSec = liveServiceView ? recent?.data?.windowSec ?? 60 : mapWindowSec + const destinationWindow = liveServiceView && !recent?.data ? "—" : formatMapFlowWindow(destinationWindowSec) + const destinationReadAt = liveServiceView ? recent?.at ?? null : flowReadAt + const destinationListener = liveServiceView ? recent?.data?.live : flowListener + const destinationTotalBytes = liveServiceView ? recent?.data?.totalBytes : mapTotalBytes + const destinationNamedBytes = liveServiceView ? recent?.data?.namedBytes : mapNamedBytes + const initialDestNodes = liveServiceView ? recent?.data?.services ?? [] : destMode === "countries" ? mapCountries : mapServices + const initialDestEdges = liveServiceView ? recent?.data?.serviceEdges ?? [] : destMode === "countries" ? mapCountryEdges : mapServiceEdges + const rawPaths = liveServiceView ? recent?.data?.servicePaths ?? [] : destMode === "countries" ? mapCountryPaths : mapServicePaths + const filterPaths = filteredServiceId?.includes("|") ? mapCountryServiceGroups.find(group => group.countryId === filteredServiceId.split("|")[0])?.paths ?? [] : scopeUser ? mapServicePaths : rawPaths const topologyPaths = rawPaths.filter(path => topologyIds.has(path.enId || path.viaId)) const servicePaths = filteredServiceId ? filterPaths.filter(path => topologyIds.has(path.enId || path.viaId) && path.serviceId === filteredServiceId) : [] const userIdsForService = new Set(servicePaths.map(path => path.clientId)) const pickerUsers = filteredServiceId ? usersInTopology.filter(user => !user.linux && userIdsForService.has(user.id)) : usersInTopology - const pickedPaths = pickedUser && !pickedUser.linux ? (userSnapshot?.data?.servicePaths ?? topologyPaths).filter(path => path.clientId === pickedUser.id && topologyIds.has(path.enId || path.viaId)) : [] + const pickedPaths = pickedUser && !pickedUser.linux ? topologyPaths.filter(path => path.clientId === pickedUser.id) : [] const accessGroups = new Map() for (const user of showUsers ? (pickedUser ? [pickedUser] : pickerUsers) : []) { const bindings = new Set(user.bindings.map(binding => binding.node)) @@ -1366,11 +1378,11 @@ function NetworkMapContent() { } const focusedNodeIds = new Set([...(pickedUser?.bindings.map(binding => binding.node) ?? accessGroups.keys()), ...pickedPaths.flatMap(path => [path.viaId, path.enId])]) const serviceNodeIds = new Set([...accessGroups.keys(), ...servicePaths.flatMap(path => [path.viaId, path.enId]), - ...(destMode === "countries" ? mapCountryEdges : mapServiceEdges).filter(edge => edge.toId === filteredServiceId).map(edge => edge.fromId)]) + ...initialDestEdges.filter(edge => edge.toId === filteredServiceId).map(edge => edge.fromId)]) const onMap = (id: string) => topologyIds.has(id) && (pickedUserId ? focusedNodeIds.has(id) && Boolean(pickedUser) : !filteredServiceId || !serviceNodeIds.size || serviceNodeIds.has(id)) const userDetailsOpen = Boolean(pickedUser && inspectUser && !selected && !selectedGreStored && !selectedService && !params.has("service")) function changeMapView(ix: boolean) { - setSelectedGreEdge(null); setSelectedService(null); setHighlightedPath(null); setFilteredServiceId(null) + setSelectedGreEdge(null); setSelectedService(null); setHighlightedPath(null); setFilterService(null) setExpandedCountryId(null); setShowSmallServices(false) updateUrl({ filter: ix ? "ix-node" : null, server: null, wan: null, user: null, service: null, q: null, dest: null }) } @@ -1547,14 +1559,15 @@ function NetworkMapContent() { return m }, [homeRouters, mapHops, showNetflow]) - const initialDestNodes = destMode === "countries" ? mapCountries : mapServices - const initialDestEdges = destMode === "countries" ? mapCountryEdges : mapServiceEdges - const scoped = pickedUserId && !pickedUser ? { services: [], edges: [], paths: [] } : userSnapshot?.data - ? scopeMapDestinations(userSnapshot.data.services, userSnapshot.data.serviceEdges, userSnapshot.data.servicePaths, id => topologyIds.has(id)) - : pickedUser || ixOnly || splitIx && isolatedIx.size > 0 - ? scopeMapDestinations(initialDestNodes, initialDestEdges, pickedUser?.linux ? [] : rawPaths, id => topologyIds.has(id), pickedUser?.id, !ixOnly && !pickedUser) - : { services: initialDestNodes, edges: initialDestEdges, paths: rawPaths } - const { services: destNodes, edges: destEdges, paths: destPaths } = scoped + function inMapScope(services: FlowMapService[], edges: FlowMapServiceEdge[], paths: FlowMapServicePath[]) { + if (pickedUserId && !pickedUser) return { services: [], edges: [], paths: [], shareOfVisible: false } + const localUser = liveServiceView && scopeUser ? undefined : pickedUser?.id + return localUser || ixOnly || splitIx && isolatedIx.size > 0 + ? scopeMapDestinations(services, edges, pickedUser?.linux ? [] : paths, id => topologyIds.has(id), localUser, !ixOnly && !pickedUser) + : { services, edges, paths, shareOfVisible: false } + } + const { services: destNodes, edges: destEdges, paths: destPaths, shareOfVisible } = inMapScope(initialDestNodes, initialDestEdges, rawPaths) + const destinationShareLabel = shareOfVisible ? "трафика показанных назначений" : "трафика окна" const countryGroup = destMode === "countries" ? mapCountryServiceGroups.find(group => group.countryId === expandedCountryId) : undefined const expandedCountryGroup = countryGroup && splitIx && isolatedIx.size > 0 ? (() => { const paths = countryGroup.paths.filter(path => topologyIds.has(path.enId || path.viaId)) @@ -1562,10 +1575,17 @@ function NetworkMapContent() { const result = scopeMapDestinations(countryGroup.services, edges, paths, () => true) return { countryId: countryGroup.countryId, ...result } })() : countryGroup + const countryShareOfVisible = Boolean(expandedCountryGroup && "shareOfVisible" in expandedCountryGroup && expandedCountryGroup.shareOfVisible) const nestedServices = useMemo(() => expandedCountryGroup?.services ?? [], [expandedCountryGroup]) const activeServiceId = selectedService?.id ?? linkedService const selectedNestedService = nestedServices.find(service => service.id === activeServiceId) const activeService = destNodes.find(service => service.id === activeServiceId) ?? selectedNestedService ?? null + const historyWindowSec = scopeUser ? history?.data?.windowSec : mapWindowSec + const networkHistory = flowReadAt && !flowError ? {services: mapServices, serviceEdges: mapServiceEdges, servicePaths: mapServicePaths} : undefined + const serviceHistory = scopeUser ? (history?.error ? undefined : history?.data) : networkHistory + const archivedService = liveServiceView && activeService && serviceHistory + ? inMapScope(serviceHistory.services, serviceHistory.serviceEdges, serviceHistory.servicePaths).services.find(row => row.id === activeService.id) + : undefined const liveSelectedService = activeService const expandedCountry = destNodes.find(service => service.id === expandedCountryId) const minorServices = destMode === "services" ? destNodes.filter(service => service.share <= 0.1) : [] @@ -1739,7 +1759,7 @@ function NetworkMapContent() { 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}:${Math.round(canvasPx.w)}x${Math.round(canvasPx.h)}` + const viewKey = `${ixOnly}:${pickedUser?.id ?? ""}:${filteredServiceId ?? ""}:${showSmallServices}:${splitIx}:${fitWidth !== W}:${Boolean(recent?.data)}:${showUsers && usersInTopology.length > 0}:${Math.round(canvasPx.w)}x${Math.round(canvasPx.h)}` const lastViewKey = useRef(viewKey) const lastUserView = useRef(pickedUser?.id) useEffect(() => { @@ -2202,7 +2222,6 @@ function NetworkMapContent() { return { id: e.id, ts: eventsAt - (m ? Number(m[1]) * unitMs[m[2]] : 0), ...eventTone(e.sev === "destructive" ? "critical" : e.sev), title: e.title, message: e.message } }) ).filter(e => Number.isFinite(e.ts)).sort((a, b) => b.ts - a.ts) - const filterService = initialDestNodes.find(service => service.id === filteredServiceId) ?? (liveSelectedService?.id === filteredServiceId ? liveSelectedService : null) const tablePaths = filterService ? (selectedNestedService ? expandedCountryGroup?.paths ?? [] : destPaths).filter(p => p.serviceId === filterService.id) : destPaths const flowRows = [...tablePaths].sort((a, b) => b.bps - a.bps).slice(0, 100).map(p => ({ id: servicePathKey(p), @@ -2244,7 +2263,7 @@ function NetworkMapContent() { <> {useLiveData ? (readAt ? "Снимок сети" : "Данные карты неизвестны") : "Демонстрационные данные"} {" · "}{nodes.length} {ruPlural(nodes.length, "узел", "узла", "узлов")} · {mapLinkCount} {ruPlural(mapLinkCount, "связь", "связи", "связей")} - {useLiveData && (showNetflow || showServices) && <>{" · "}{flowReadAt ? = 120 && destinationWindowSec < 300 ? " из 5 запрошенных" : ""} · ответ ${new Date(destinationReadAt ?? flowReadAt).toLocaleTimeString("ru-RU")} · ${flowListener ? "приёмник включён" : "приёмник выключен"} · средняя скорость по сохранённым потокам`}>IPFIX · среднее за {destinationWindow}{!flowListener ? " · приёмник выключен" : ""} : Данные NetFlow неизвестны}} + {useLiveData && (showNetflow || showServices) && <>{" · "}{destinationReadAt ? IPFIX · среднее за {destinationWindow}{!destinationListener ? " · приёмник выключен" : ""} : Данные NetFlow неизвестны}} ) // Подсказки поиска макета: узлы и назначения текущего снимка. @@ -2254,8 +2273,10 @@ function NetworkMapContent() { ...(showServices ? destNodes : []).filter((d) => !sq || destDisplayLabel(d, destMode).toLowerCase().includes(sq)).map((d) => ({ key: "d:" + d.id, label: destDisplayLabel(d, destMode), sub: `${destMode === "countries" ? "Страна" : d.category || "Сервис"} · ${formatNetflowRate({ bps: d.bps })}`, dot: "var(--chart-4)", pick: () => selectService(d) })), ].slice(0, 8) : [] const statusFilterLabel = ({ online: "Онлайн", degraded: "Внимание", offline: "Оффлайн", unknown: "Неизвестно", "jump-host": "JumpHost", "exit-node": "Exit Node", "home-router": "Home Router" } as Record)[filter] - const bottomStat = `Окно ${mapWindow}${flowReadAt ? " · " + new Date(flowReadAt).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }) : ""}${filterService && bottomTab === "flows" ? " · фильтр: " + filterService.label : selected || selectedService || selectedGreEdge ? " · строки выбранного объекта подсвечены" : ""}` - const refreshBusy = dataLoading || flowLoading && (showNetflow || showServices) || Boolean(useLiveData && scopeUser && showServices && !userSnapshot) + const bottomServiceTab = bottomTab === "flows" || bottomTab === "dest" + const bottomReadAt = bottomServiceTab ? destinationReadAt : flowReadAt + const bottomStat = `Окно ${bottomServiceTab ? destinationWindow : mapWindow}${bottomReadAt ? " · " + new Date(bottomReadAt).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }) : ""}${filterService && bottomTab === "flows" ? " · фильтр: " + filterService.label : selected || selectedService || selectedGreEdge ? " · строки выбранного объекта подсвечены" : ""}` + const refreshBusy = dataLoading || flowLoading && (showNetflow || showServices) || requestRecent && recent?.refresh !== flowRefresh const inspectorOpen = detailsOpen function inspectEvent(event: MapEventRow) { setInspectedEvent(event) @@ -2426,7 +2447,7 @@ function NetworkMapContent() { {pickedUser?.name ?? (ixOnly ? "Linux-клиенты" : "Пользователи")} } {pickedUser && } - {filterService && } + {filterService && } }> @@ -2479,12 +2500,12 @@ function NetworkMapContent() { - {(inspectedEvent || userSnapshot?.error) && + {(inspectedEvent || recent?.error) && {inspectedEvent && <>

{inspectedEvent.title}

{new Date(inspectedEvent.ts).toLocaleString("ru-RU")} · {inspectedEvent.message}

{inspectedEvent.serverId && Трафик узла} } - {userSnapshot?.error &&

{userSnapshot.error}. Показаны подтверждённые строки из доступного снимка.

} + {recent?.error &&

{recent.error}. {recent.data ? "Показан предыдущий снимок сервисов." : "Скорости сервисов пока недоступны."}

}
} {/* Состояние данных: загрузка и ошибки снимка, NetFlow и DNS */} @@ -2727,7 +2748,7 @@ function NetworkMapContent() { })} {minorPosition && 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)} />} + x={minorPosition.x} y={minorPosition.y} destMode="services" shareLabel={destinationShareLabel} expanded={showSmallServices} isSel={false} isVis isDragged={false} onPointerDown={() => {}} onClick={() => setShowSmallServices(value => !value)} />} {visibleMapServices.map((svc) => { const pos = servicePosById[svc.id] if (!pos) return null @@ -2736,6 +2757,7 @@ function NetworkMapContent() { key={svc.id} label={destDisplayLabel(svc, destMode)} share={svc.share} + shareLabel={destinationShareLabel} category={destMode === "countries" ? "Страна" : serviceMapSubtitle(svc)} rate={formatNetflowRate({ bytes: svc.bytes, bps: svc.bps, bpsFwd: svc.bps, bpsRev: 0 })} compact={Boolean(expandedCountryGroup)} @@ -2778,7 +2800,7 @@ function NetworkMapContent() { isVis isDragged={draggedSvcId === svc.id} destMode="services" - shareLabel="трафика страны" + shareLabel={countryShareOfVisible ? "трафика показанных сервисов страны" : "трафика страны"} onPointerDown={(e) => onServicePointerDown(e, svc.id, pos.x, pos.y)} onClick={() => { if (suppressClickRef.current) { suppressClickRef.current = false; return } @@ -3080,17 +3102,19 @@ function NetworkMapContent() { ) : activeService && (destMode === "services" || selectedNestedService) ? ( - mapServers.find(s => s.id === id)?.name ?? id} country={selectedNestedService ? expandedCountry?.label : undefined} - base={useLiveData ? backendUrl : null} refresh={flowRefresh} windowLabel={destinationWindow} flowAt={destinationReadAt} stale={Boolean(pickedUserId ? userSnapshot?.error : flowError)} + shareOfVisible={selectedNestedService ? countryShareOfVisible : shareOfVisible} + base={useLiveData ? backendUrl : null} refresh={flowRefresh} windowLabel={destinationWindow} flowAt={destinationReadAt} stale={Boolean(liveServiceView ? recent?.error : flowError)} + history={liveServiceView ? {service: archivedService, window: formatMapFlowWindow(historyWindowSec ?? 300)} : undefined} activePath={highlightedPath} onPath={togglePathHighlight} onClose={() => { setSelectedService(null); updateUrl({service:null}); returnToMapControl() }} userId={pickedUser?.id} ix={ixOnly} topology={ixOnly || splitIx && isolatedIx.size > 0 ? topologyIds : undefined} filtered={filterService?.id === activeService.id} onFilter={() => { - setFilteredServiceId(filterService?.id === activeService.id ? null : activeService.id) + setFilterService(filterService?.id === activeService.id ? null : {id: activeService.id, label: activeService.label}) setBottomTab("flows") setAnalysisOpen(true) }} @@ -3123,7 +3147,7 @@ function NetworkMapContent() {
- Доля окна + Доля {destinationShareLabel} {serviceSharePct(liveSelectedService.share)}
{destinationTotalBytes !== undefined && destinationTotalBytes > 0 && destinationNamedBytes !== undefined && ( diff --git a/components/network-map/inspector-traffic.tsx b/components/network-map/inspector-traffic.tsx index 622ed4f6..cec42421 100644 --- a/components/network-map/inspector-traffic.tsx +++ b/components/network-map/inspector-traffic.tsx @@ -112,9 +112,11 @@ 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, userId, ix, topology }: { +export function ServiceInspector({ service, paths, exits, exitName, country, base, refresh, windowLabel, history, shareOfVisible, flowAt, stale, activePath, onPath, onClose, filtered, onFilter, userId, ix, topology }: { service: FlowMapService; paths: FlowMapServicePath[]; exits: FlowMapServiceEdge[]; exitName: (id: string) => string country?: string; base: string | null; refresh: number; windowLabel: string; flowAt: string | null; stale: boolean + history?: {service?: FlowMapService; window: string} + shareOfVisible: boolean activePath: FlowMapServicePath | null; onPath: (path: FlowMapServicePath) => void onClose: () => void; filtered: boolean; onFilter: () => void userId?: string; ix?: boolean; topology?: ReadonlySet @@ -157,6 +159,9 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas const remainder = Math.max(0, service.bytes - attributedBytes) const observed = service.bytes > 0 && !stale const currentVolume = base === null || scoped + const average = history ? history.service : service + const averageWindow = history?.window ?? windowLabel + const volumeBytes = currentVolume ? average?.bytes : volume?.bytes const trafficTypes = service.trafficTypes ?? [] const serviceEvidence = service.serviceEvidence ?? [] const otherTypeBytes = Math.max(0, service.bytes - trafficTypes.reduce((sum, row) => sum + row.bytes, 0)) @@ -181,9 +186,9 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
{currentVolume ? formatBytes(service.bytes) : volume?.bytes == null ? "—" : formatBytes(volume.bytes)}{volume && }], + ["Средняя за " + averageWindow, average ? formatNetflowRate(average) : "—", "Скорость по сохранённым потокам IPFIX"], + [shareOfVisible ? "Доля показанных сервисов" : country ? "Доля страны" : "Доля трафика", percent.format(service.share), "IPFIX · " + windowLabel], + ["Объём · " + (currentVolume ? averageWindow : volume?.window ?? "24 ч"), <>{volumeBytes == null ? "—" : formatBytes(volumeBytes)}{!currentVolume && volume && }], exitIds.length || !exporterIds.length ? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined] : ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"], diff --git a/lib/network-map-metrics.test.ts b/lib/network-map-metrics.test.ts index eebdc447..4a81c375 100644 --- a/lib/network-map-metrics.test.ts +++ b/lib/network-map-metrics.test.ts @@ -22,7 +22,7 @@ test("live GRE does not hash metrics and probe values retain zero and fractions" }) test("a filtered topology does not inherit a service's full-network traffic composition", () => { - const service = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 100, bps: 10, share: 1, + const service = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 100, bps: 10, share: 0.4, trafficTypes: [{transport: "UDP", application: "DNS", bytes: 100}], lastBucketAt: "2026-11-26T18:30:00.000Z"} const edges = ["1", "2"].map(fromId => ({fromId, toId: service.id, bytes: 50, bps: 5, bpsFwd: 5, bpsRev: 0})) const partial = scopeMapDestinations([service], edges, [], id => id === "1").services[0] @@ -31,4 +31,6 @@ test("a filtered topology does not inherit a service's full-network traffic comp assert.equal(partial?.lastBucketAt, undefined) assert.deepEqual(complete?.trafficTypes, service.trafficTypes) assert.equal(complete?.lastBucketAt, service.lastBucketAt) + assert.equal(complete.share, 0.4) + assert.equal(partial.share, 1) }) diff --git a/lib/network-map-response.test.ts b/lib/network-map-response.test.ts index c8c3d96f..cfdc9837 100644 --- a/lib/network-map-response.test.ts +++ b/lib/network-map-response.test.ts @@ -31,7 +31,7 @@ test("network map refuses partial GRE and foreign failure/probe contexts",()=>{ assert.throws(()=>validateNetworkMapSnapshot([server],{tunnels:[]},{probes:[probe]}),/неизвестному/) }) -import {networkMapFlowSchema,validateNetworkMapDns} from "./network-map-response" +import {networkMapFlowSchema,recentMapFlowSchema,validateNetworkMapDns} from "./network-map-response" test("map Flow envelope retains zeros and refuses missing metadata and contradictory totals",()=>{ const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false} assert.equal(networkMapFlowSchema.parse(empty).totalBytes,0) @@ -49,6 +49,11 @@ test("map Flow envelope retains zeros and refuses missing metadata and contradic assert.throws(()=>networkMapFlowSchema.parse(recent)) assert.throws(()=>networkMapFlowSchema.parse({...recent,windowSec:120})) assert.throws(()=>networkMapFlowSchema.parse({...recent,includesCurrentMinute:undefined})) + assert.equal(recentMapFlowSchema.parse(recent).windowSec,90.125) + for (const windowSec of [60,119.999]) assert.equal(recentMapFlowSchema.parse({...recent,windowSec}).windowSec,windowSec) + for (const invalid of [empty,{...recent,windowSec:59},{...recent,windowSec:120},{...recent,includesCurrentMinute:undefined},{...recent,sourceWindow:shorter.sourceWindow}]) { + assert.throws(()=>recentMapFlowSchema.parse(invalid)) + } }) test("map DNS matches exactly requested names and accepts explicit unresolved null",()=>{ assert.deepEqual(validateNetworkMapDns({results:{"router.example":null}},["router.example"]),{"router.example":null}) diff --git a/lib/network-map-response.ts b/lib/network-map-response.ts index 4d676c3a..80d8df59 100644 --- a/lib/network-map-response.ts +++ b/lib/network-map-response.ts @@ -27,11 +27,17 @@ 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, nodeUsers: true }).refine(data => +const mapFlowResponse = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true, includesCurrentMinute: true, nodeUsers: true }).refine(data => + data.namedBytes <= data.totalBytes && data.unclassifiedBytes <= data.totalBytes +) +export const networkMapFlowSchema = mapFlowResponse.refine(data => !data.includesCurrentMinute && data.windowSec === data.rangeMinutes * 60 && (data.sourceWindow ? data.sourceWindow.requestedMinutes === 5 && data.sourceWindow.effectiveMinutes === data.rangeMinutes - : data.rangeMinutes === 5) && - data.namedBytes <= data.totalBytes && data.unclassifiedBytes <= data.totalBytes + : data.rangeMinutes === 5) +) +export const recentMapFlowSchema = mapFlowResponse.refine(data => + data.includesCurrentMinute === true && data.rangeMinutes === 1 && data.windowSec >= 60 && data.windowSec < 120 && + (!data.sourceWindow || data.sourceWindow.requestedMinutes === 1 && data.sourceWindow.effectiveMinutes === 1) ) export function validateNetworkMapDns(raw:unknown,hosts:string[]){ const data=z.object({results:z.record(z.string(),z.string().refine(isIpv4String).nullable())}).parse(raw) diff --git a/lib/network-map-scope.ts b/lib/network-map-scope.ts index 87369f4e..d16adb26 100644 --- a/lib/network-map-scope.ts +++ b/lib/network-map-scope.ts @@ -53,12 +53,15 @@ export function scopeMapDestinations( bytes += unassigned totals.set(service.id, total) } + const shareOfVisible = Boolean(userId) || services.some(service => (totals.get(service.id)?.bytes ?? 0) !== service.bytes) return { + shareOfVisible, services: services.flatMap(service => { const total = totals.get(service.id) if (!total) return [] const { trafficTypes, serviceEvidence, lastBucketAt, ...destination } = service - return [{ ...destination, ...total, share: bytes ? total.bytes / bytes : 0, + const visibleShare = bytes ? total.bytes / bytes : 0 + return [{ ...destination, ...total, share: shareOfVisible ? visibleShare : service.share, ...(total.bytes === service.bytes ? { trafficTypes, serviceEvidence, lastBucketAt } : {}) }] }).sort((a, b) => b.bytes - a.bytes || a.label.localeCompare(b.label)), edges: visibleEdges, diff --git a/tests/e2e/fixtures/map-flow.ts b/tests/e2e/fixtures/map-flow.ts new file mode 100644 index 00000000..00bab5fd --- /dev/null +++ b/tests/e2e/fixtures/map-flow.ts @@ -0,0 +1,11 @@ +export function emptyMapFlow(requestUrl: string | URL) { + const range = new URL(requestUrl).searchParams.get("range") + const recent = range === "1m" + const rangeMinutes = recent ? 1 : range === "24h" ? 1440 : 5 + return { + hops: [], live: false, rangeMinutes, windowSec: recent ? 90 : rangeMinutes * 60, ...(recent ? {includesCurrentMinute: true} : {}), + totalBytes: 0, namedBytes: 0, unclassifiedBytes: 0, asnLoaded: false, countryLoaded: false, + services: [], serviceEdges: [], servicePaths: [], countries: [], countryEdges: [], countryPaths: [], countryServiceGroups: [], + mapServiceMinSharePct: 5, dedupApplied: false, excludeMeshApplied: false, excludeOverlayApplied: false, + } +} diff --git a/tests/e2e/network-map-context.spec.ts b/tests/e2e/network-map-context.spec.ts index f21a8901..7d250282 100644 --- a/tests/e2e/network-map-context.spec.ts +++ b/tests/e2e/network-map-context.spec.ts @@ -1,6 +1,6 @@ import { openSettings } from "./fixtures/open-settings" import {test,expect} from "@playwright/test" -const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false} +import { emptyMapFlow } from "./fixtures/map-flow" const headers={"access-control-allow-origin":"*","access-control-allow-methods":"GET,POST,OPTIONS","access-control-allow-headers":"Content-Type,Authorization"} const wan={id:"w",name:"WAN",iface:"ether1",isp:"ISP",ip:"router.example",maxDl:100,maxUl:100} const row=(name:string)=>({id:1,name,host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online",wanUplinks:[wan]}) @@ -9,30 +9,30 @@ for(const change of ["backend","mode"])for(const part of ["snapshot","flow","dns await page.route("**/health",r=>r.fulfill({headers,json:{ok:true}})) await page.route("**/api/**",r=>{ const u=new URL(r.request().url()),p=u.pathname;if(u.port==="8101")newReads++ - return r.fulfill({headers,json:p==="/api/auth/config"?{required:false}:p==="/api/servers"?[row(u.port==="8101"?"Новая карта":"Прежняя карта")]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/network/resolve-hosts"?{results:{"router.example":"192.0.2.2"}}:{}}) + return r.fulfill({headers,json:p==="/api/auth/config"?{required:false}:p==="/api/servers"?[row(u.port==="8101"?"Новая карта":"Прежняя карта")]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(u):p==="/api/network/resolve-hosts"?{results:{"router.example":"192.0.2.2"}}:{}}) }) await page.goto("/settings");await page.getByRole("link",{name:/^Карта сети/}).click() - await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Прежняя карта",{exact:true})).toBeVisible() - await expect(page.getByTitle(/NetFlow · 5 мин · ответ/)).toBeVisible() + await expect(page.getByRole("button",{name:"Устройство Прежняя карта",exact:true})).toBeVisible({timeout:20_000}) + await expect(page.getByText(/IPFIX · среднее за 1 мин 30 с/)).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() started=true;await gate - try{await r.fulfill(fails?{headers,status:503,json:{error:"Старая ошибка карты"}}:{headers,json:part==="snapshot"?[row("Поздняя карта")]:part==="flow"?{...empty,services:[{id:"svc:late",label:"Поздний сервис",category:"Web",bytes:1,bps:1,share:1}]}:{results:{"router.example":null}}})}catch{}finally{completed=true} + try{await r.fulfill(fails?{headers,status:503,json:{error:"Старая ошибка карты"}}:{headers,json:part==="snapshot"?[row("Поздняя карта")]:part==="flow"?{...emptyMapFlow(u),services:[{id:"svc:late",label:"Поздний сервис",category:"Web",bytes:1,bps:1,share:1}]}:{results:{"router.example":null}}})}catch{}finally{completed=true} }) await page.getByRole("button",{name:"Обновить",exact:true}).click() await expect.poll(()=>started).toBe(true);await openSettings(page) 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.getByTitle(/NetFlow · 5 мин · ответ/)).toBeVisible()} + if(change==="backend"){await expect(page.getByRole("button",{name:"Устройство Новая карта",exact:true})).toBeVisible();await expect(page.getByText(/IPFIX · среднее за 1 мин 30 с/)).toBeVisible()} else await expect(page.getByText("Демонстрационные данные",{exact:true})).toBeVisible() const before=newReads;release();await expect.poll(()=>completed).toBe(true) await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve())))) await expect(page.getByText("Старая ошибка карты",{exact:false})).toHaveCount(0) - await expect(page.getByText("Поздняя карта",{exact:false})).toHaveCount(0) + await expect(page.getByRole("button",{name:"Устройство Поздняя карта",exact:true})).toHaveCount(0) await expect(page.getByText("Поздний сервис",{exact:false})).toHaveCount(0) await expect(page.getByRole("alert").filter({hasText:"DNS не разрешён"})).toHaveCount(0) - if(change==="backend")await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Новая карта",{exact:true})).toBeVisible() + if(change==="backend")await expect(page.getByRole("button",{name:"Устройство Новая карта",exact:true})).toBeVisible() expect(newReads).toBe(before) }) diff --git a/tests/e2e/network-map-detail.spec.ts b/tests/e2e/network-map-detail.spec.ts index f898f84a..44bca990 100644 --- a/tests/e2e/network-map-detail.spec.ts +++ b/tests/e2e/network-map-detail.spec.ts @@ -1,5 +1,5 @@ import {test,expect} from "@playwright/test" -const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false} +import { emptyMapFlow } from "./fixtures/map-flow" const wan={id:"w",name:"WAN",iface:"ether1",isp:"ISP",ip:"192.0.2.1",maxDl:100,maxUl:100} const home={id:1,name:"Домашний",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online",latency:2,wanUplinks:[wan]} const jh={id:2,name:"Jump",host:"192.0.2.2",type:"jump-host",country:"RU",enabled:true,status:"online",latency:3} @@ -7,7 +7,7 @@ const tunnel={id:"t1",serverId:"1",name:"gre-home",localAddress:"192.0.2.1",remo test.beforeEach(async({page})=>{await page.route("**/health",r=>r.fulfill({json:{ok:true}}))}) test("Карта: открытые детали обновляются вместе со снимком",async({page})=>{ let changed=false - await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...jh,name:changed?"Новый Jump":"Jump",status:changed?null:"online",cpuLoad:changed?0:20}]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})}) + await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...jh,name:changed?"Новый Jump":"Jump",status:changed?null:"online",cpuLoad:changed?0:20}]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})}) await page.goto("/network-map");await page.getByRole("button",{name:"Устройство Jump",exact:true}).click() const metrics=page.getByText("CPU · RAM",{exact:true}).locator("..") await expect(metrics).toContainText("20% · —") @@ -18,7 +18,7 @@ test("Карта: открытые детали обновляются вмес await expect(page.getByText("Jump",{exact:true})).toHaveCount(0);await expect(page.getByText("Новый Jump",{exact:true}).last()).toBeVisible() }) 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.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"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})}) await page.goto("/network-map") const legend = page.getByRole("button", {name:"Легенда",exact:true}) await legend.click() @@ -31,7 +31,7 @@ test("Карта: модель WAN не утверждает активный м }) test("Карта: выбранный GRE обновляется и неизвестный IPsec не означает Plain",async({page})=>{ let changed=false - 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:[{...tunnel,name:changed?"gre-new":"gre-home",status:changed?"down":"up"}],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})}) + 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:[{...tunnel,name:changed?"gre-new":"gre-home",status:changed?"down":"up"}],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})}) await page.goto("/network-map") await page.locator("g").filter({has:page.locator("title",{hasText:"RTT неизвестен."})}).last().click() await expect(page.getByText("gre-home",{exact:true}).last()).toBeVisible();await expect(page.getByText("Ping неизвестен",{exact:true})).toBeVisible() @@ -42,7 +42,7 @@ test("Карта: выбранный GRE обновляется и неизве test("Карта: GRE сохраняет частичное измерение, ноль Ping и дату пробы",async({page})=>{ const probe={id:"measured-probe",srcServerId:"1",dstServerId:"2",srcInterface:"gre-home",dstInterface:"",enabled:true,lastPingRttMs:0,lastPingLossPct:0,lastTxAvgMbps:0.125,lastRxAvgMbps:null,lastPingAt:"2020-01-01T00:00:00Z"} - 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:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[probe]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})}) + 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:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[probe]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})}) await page.goto("/network-map") await page.locator("g").filter({has:page.locator("title",{hasText:"Проба measured-probe"})}).last().click() await expect(page.getByText("0 мс",{exact:true}).last()).toBeVisible() @@ -68,7 +68,7 @@ test("Карточки Exit, JumpHost и сервиса показывают и const data = endpoint === "/api/servers" ? [exit, jump] : endpoint === "/api/filters/gre-tunnels" ? { tunnels: [], failures: [] } : endpoint === "/api/uptime/speed-probes" ? {probes: []} - : endpoint === "/api/traffic/flow/map-hops" ? {...empty,rangeMinutes:daily?1440:5,windowSec:daily?86400:300,totalBytes:daily?4100000000:3103448,namedBytes:daily?4100000000:service.bytes,services:[{...service,bytes:daily?4100000000:service.bytes}],servicePaths:[path],serviceEdges:[edge],countries:[country],countryServiceGroups:[{countryId:country.id,services:[dns],paths:[{...path,serviceId:dns.id,bytes:100000,bps:100000*8/300}],edges:[]}]} + : endpoint === "/api/traffic/flow/map-hops" ? {...emptyMapFlow(url),totalBytes:daily?4100000000:3103448,namedBytes:daily?4100000000:service.bytes,services:[{...service,bytes:daily?4100000000:service.bytes}],servicePaths:[path],serviceEdges:[edge],countries:[country],countryServiceGroups:[{countryId:country.id,services:[dns],paths:[{...path,serviceId:dns.id,bytes:100000,bps:100000*8/300}],edges:[]}]} : endpoint === "/api/traffic/flow/analytics" ? {bpsNow:8000,bytes:1000,packets:1,conversations:3,uniqueSrc:1,uniqueDst:3,topProto:"TCP",rxSeries:[],txSeries:[],applications:[],protocols:[],sources:[],destinations:[],interfaces:[],conversationsList:[record,...["unknown","US"].map(dstCountry=>({...record,service:"Прочее",category:"DNS",dstCountry,dst:dstCountry==="US"?"192.0.2.53":"198.51.100.53",dstPort:53}))],ifaces:[],live:true} : endpoint === "/api/traffic/servers/3" ? {server:{...sample,id:"3"}} : endpoint === "/api/traffic/servers/2" ? {server:{...sample,id:"2",observations:{...sample.observations,currentState:"error",error:"RouterOS API 401 на /interface",lastAttemptAt:"2026-11-25T09:31:08Z"}}} @@ -85,7 +85,7 @@ test("Карточки Exit, JumpHost и сервиса показывают и await card.getByRole("button",{name:/YouTube/}).click() await expect(card.getByText("Объём · 24 ч",{exact:true}).locator("..")).toContainText("4.10 ГБ") await expect(card.getByText("10.20.4.18 → 142.250.74.14",{exact:true})).toBeVisible() - await expect(card.getByText("TCP/443",{exact:true})).toBeVisible() + await expect(card.getByText("TCP/443 · " + exit.name,{exact:true})).toBeVisible() await card.screenshot({path:info.outputPath("service.png")}) await card.getByRole("button",{name:"Фильтр по сервису"}).click() await expect(page.getByText(/фильтр: YouTube/)).toBeVisible() @@ -105,11 +105,11 @@ test("Карточки Exit, JumpHost и сервиса показывают и test("Обновление NetFlow отображается внутри кнопки", async ({page}) => { let release!: () => void - const wait = new Promise(resolve => { release = resolve }) + let wait = new Promise(resolve => { release = resolve }) await page.route("**/api/**", async route => { - const path = new URL(route.request().url()).pathname - if (path === "/api/traffic/flow/map-hops") await wait - return route.fulfill({json:path === "/api/traffic/flow/map-hops" ? empty : path === "/api/servers" ? [jh] : path === "/api/filters/gre-tunnels" ? {tunnels:[],failures:[]} : path === "/api/uptime/speed-probes" ? {probes:[]} : path === "/api/auth/config" ? {required:false} : {}}) + const url = new URL(route.request().url()), path = url.pathname + if (path === "/api/traffic/flow/map-hops" && url.searchParams.get("range") === "1m") await wait + return route.fulfill({json:path === "/api/traffic/flow/map-hops" ? emptyMapFlow(route.request().url()) : path === "/api/servers" ? [jh] : path === "/api/filters/gre-tunnels" ? {tunnels:[],failures:[]} : path === "/api/uptime/speed-probes" ? {probes:[]} : path === "/api/auth/config" ? {required:false} : {}}) }) await page.goto("/network-map") const refresh = page.getByRole("button",{name:"Обновить",exact:true}) @@ -118,4 +118,10 @@ test("Обновление NetFlow отображается внутри кно release() await expect(refresh).toBeEnabled() await expect(refresh.locator("[data-slot=spinner]")).toHaveCount(0) + wait = new Promise(resolve => { release = resolve }) + await Promise.all([page.waitForResponse("**/api/traffic/flow/map-hops?range=5m"), refresh.click()]) + await expect(refresh).toBeDisabled() + await expect(refresh.locator("[data-slot=spinner]")).toBeVisible() + release() + await expect(refresh).toBeEnabled() }) diff --git a/tests/e2e/network-map-flow.spec.ts b/tests/e2e/network-map-flow.spec.ts index d34ac58c..ffd5de5d 100644 --- a/tests/e2e/network-map-flow.spec.ts +++ b/tests/e2e/network-map-flow.spec.ts @@ -1,18 +1,22 @@ import {test,expect} from "@playwright/test" import { installOpenLiveStream } from "./live-stream-fixture" import { observedTrafficFixturePayload } from "./traffic-observation-fixture" -const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false} +import { emptyMapFlow } from "./fixtures/map-flow" const flowPath="/api/traffic/flow/map-hops" test.beforeEach(async({page})=>{await page.route("**/health",r=>r.fulfill({json:{ok:true}}))}) const server={id:1,name:"Router",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online"} -test("Карта и трафик сохраняют пользователя и сервис, IX остаётся отдельным", async ({page}) => { - const clientId = "alice" +function mapUser(clientId: string, name: string) { const timestamps = { createdAt: "2026-11-26T12:00:00Z", updatedAt: "2026-11-26T12:00:00Z" } const binding = { ...timestamps, userId: clientId, id: "a1", serverId: 1, - serverName: "Вход", serverSite: "MSK", serverCountry: "RU", interfaceName: "gre-alice", interfaceType: "gre", comment: "" } - const user = { ...timestamps, id: clientId, name: "Алиса", login: "alice", email: "alice@example.test", role: "viewer", active: true, - avatar: "A", lastSeen: null, sections: [], servers: [], bindings: [binding, {...binding, id: "a2", interfaceName: "gre-alice-2"}] } + serverName: "Вход", serverSite: "MSK", serverCountry: "RU", interfaceName: "gre-" + clientId, interfaceType: "gre", comment: "" } + return { ...timestamps, id: clientId, name, login: clientId, email: clientId + "@example.test", role: "viewer", active: true, + avatar: name[0], lastSeen: null, sections: [], servers: [], bindings: [binding, {...binding, id: "a2", interfaceName: binding.interfaceName + "-2"}] } +} + +test("Карта и трафик сохраняют пользователя и сервис, IX остаётся отдельным", async ({page}) => { + const clientId = "alice" + const user = mapUser(clientId, "Алиса") const counters = ["a1", "a2"].map(bindingId => ({bindingId, status: "online", rxNow: 4, txNow: 6, rxPeak: 4, txPeak: 6, rxTotal: 0, txTotal: 0, rxSeries: [4], txSeries: [6]})) const dns = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 300000, bps: 8000, share: 1} const path = {clientId, clientName: "Алиса", viaId: "1", viaName: "Вход", enId: "", enName: "", serviceId: dns.id, bytes: dns.bytes, bps: dns.bps} @@ -31,7 +35,7 @@ test("Карта и трафик сохраняют пользователя и [`/api/traffic/users/${clientId}`]: observedTrafficFixturePayload({user: {...counters[0], rxNow: 8, txNow: 12, interfaces: counters}}), "/api/traffic/flow/exporters": {exporters: []}, "/api/traffic/flow/clients": {clients: [clientCard]}, "/api/traffic/flows": {exportersOnline: 0, bytesPerMin: 0, uniqueSrc: 0, uniqueDst: 0, topProto: "TCP", talkers: [], listenerBound: true}, - [flowPath]: {...empty, totalBytes: dns.bytes, namedBytes: dns.bytes, services: [dns], servicePaths: [path], + [flowPath]: {...emptyMapFlow(url), totalBytes: dns.bytes, namedBytes: dns.bytes, services: [dns], servicePaths: [path], serviceEdges: [{fromId: "1", toId: dns.id, observedOnly: true, bytes: dns.bytes, bps: dns.bps, bpsFwd: 0, bpsRev: dns.bps}]}, } return route.fulfill({json: replies[url.pathname] ?? {}}) @@ -47,7 +51,7 @@ test("Карта и трафик сохраняют пользователя и 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=5m&userId=${clientId}`)).toBe(true) + await expect.poll(() => requests.includes(`${flowPath}?range=1m&userId=${clientId}`)).toBe(true) await expect(panel.getByRole("heading", {name: "Алиса", exact: true})).toBeVisible() await expect(panel.getByText(/gre-alice · gre, gre-alice-2/)).toBeVisible() await expect(panel.getByText(/RX 8.*TX 12.*2\/2/)).toBeVisible() @@ -68,6 +72,79 @@ test("Карта и трафик сохраняют пользователя и await expect(panel.getByText("Нет потоков с подтверждённой привязкой к пользователю.")).toBeVisible() }) +test("Карта показывает скорость и долю за короткое окно и отдельные пять минут для выбранного пользователя", async ({page}) => { + const users = [mapUser("alice", "Алиса"), mapUser("boris", "Борис")] + const ratesByScope: Record = { + alice: {recent: 32_000, average: 8_000}, + boris: {recent: 48_000, average: 12_000}, + network: {recent: 72_000, average: 16_000}, + } + let borisRead: "failed" | "populated" | "empty" = "failed" + await page.route("**/api/**", route => { + const url = new URL(route.request().url()) + if (url.pathname === flowPath) { + const userId = url.searchParams.get("userId") + const recent = url.searchParams.get("range") === "1m" + if (recent && userId === "boris" && borisRead !== "populated") { + return route.fulfill(borisRead === "empty" ? {json: {...emptyMapFlow(url), live: true}} + : {status: 503, json: {error: "Не удалось получить минуту Бориса"}}) + } + const snapshot = emptyMapFlow(url) + const ratesForUser = ratesByScope[userId ?? "network"] + const dnsBps = recent ? ratesForUser.recent : ratesForUser.average + const totalBps = recent ? 100_000 : 40_000 + const rates = {DNS: dnsBps, HTTPS: totalBps - dnsBps} + const services = Object.entries(rates).map(([label, bps]) => ({ + id: "svc:" + label.toLowerCase(), label, category: label, bps, bytes: bps * snapshot.windowSec / 8, share: bps / totalBps, + })) + const totalBytes = totalBps * snapshot.windowSec / 8 + return route.fulfill({json: {...snapshot, live: true, totalBytes, namedBytes: totalBytes, services, + serviceEdges: services.map(s => ({fromId: "1", toId: s.id, observedOnly: true, bytes: s.bytes, bps: s.bps, bpsFwd: 0, bpsRev: s.bps})), + servicePaths: services.map(s => ({clientId: userId ?? "boris", clientName: userId === "alice" ? "Алиса" : "Борис", viaId: "1", viaName: "Вход", enId: "", enName: "", serviceId: s.id, bytes: s.bytes, bps: s.bps})), + }}) + } + const responses: Record = { + "/api/auth/config": {required: false}, "/api/servers": [{...server, name: "Вход", type: "jump-host"}], "/api/users": {users}, + "/api/filters/gre-tunnels": {tunnels: [], failures: []}, "/api/uptime/speed-probes": {probes: []}, + } + return route.fulfill({json: responses[url.pathname] ?? {}}) + }) + await page.goto("/network-map") + const map = page.getByRole("group", {name: "Интерактивная карта сети"}) + const dns = map.getByRole("button", {name: "Сервис DNS", exact: true}) + const card = page.getByRole("complementary", {name: "Детали объекта карты"}) + await expect(dns).toContainText("72 Кбит/с") + await expect(dns).toContainText("72%") + await dns.press("Enter") + await expect(card.getByText("Средняя за 5 мин", {exact: true}).locator("..")).toContainText("16 Кбит/с") + await expect(card.getByText("Объём · 24 ч", {exact: true}).locator("..")).toContainText("172.8 МБ") + await page.getByRole("button", {name: "Пользователи", exact: true}).click() + await page.getByRole("option", {name: /Алиса/}).click() + await expect(dns).toContainText("32 Кбит/с") + await expect(dns).toContainText("32%") + await dns.press("Enter") + await expect(card.getByText("Средняя за 5 мин", {exact: true}).locator("..")).toContainText("8 Кбит/с") + await expect(card.getByText("Объём · 5 мин", {exact: true}).locator("..")).toContainText("300.0 КБ") + const borisResponse = (status: number) => page.waitForResponse(response => { + const url = new URL(response.url()) + return url.pathname === flowPath && url.searchParams.get("range") === "1m" && url.searchParams.get("userId") === "boris" && response.status() === status + }) + await page.getByRole("button", {name: "Алиса", exact: true}).click() + await Promise.all([borisResponse(503), page.getByRole("option", {name: /Борис/}).click()]) + await expect(card.getByRole("heading", {name: "Борис", exact: true})).toBeVisible() + await expect(page.getByRole("status").filter({hasText: "Скорости сервисов пока недоступны"})).toBeVisible() + await expect(dns).toHaveCount(0) + const refresh = page.getByRole("button", {name: "Обновить", exact: true}) + borisRead = "populated" + await Promise.all([borisResponse(200), refresh.click()]) + await expect(dns).toContainText("48 Кбит/с") + borisRead = "empty" + await Promise.all([borisResponse(200), refresh.click()]) + await expect(dns).toHaveCount(0) + await page.getByRole("button", {name: "Вся схема пользователей"}).click() + await expect(dns).toContainText("72 Кбит/с") +}) + test("Карта не приписывает весь YouTube единственному выходу ARN", async ({page}) => { const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1, trafficTypes: [{transport: "UDP", application: "QUIC", bytes: 900000}], @@ -78,13 +155,12 @@ test("Карта не приписывает весь YouTube единствен const url = new URL(route.request().url()) const path = url.pathname if (path === flowPath && url.searchParams.get("range") === "24h") { - return route.fulfill({ json: { ...empty, rangeMinutes: 1440, windowSec: 86400, totalBytes: service.bytes, namedBytes: service.bytes, services: [service] } }) + return route.fulfill({ json: { ...emptyMapFlow(url), totalBytes: service.bytes, namedBytes: service.bytes, services: [service] } }) } - if (path === flowPath) expect(url.searchParams.get("range")).toBe("5m") const responses: Record = { "/api/auth/config": {required: false}, "/api/servers": [{...server, type: "exit-node", name: "ARN"}], "/api/filters/gre-tunnels": {tunnels: [], failures: []}, "/api/uptime/speed-probes": {probes: []}, - [flowPath]: {...empty, totalBytes: service.bytes, namedBytes: service.bytes, services: [service], serviceEdges: known ? [edge] : []}, + [flowPath]: {...emptyMapFlow(url), totalBytes: service.bytes, namedBytes: service.bytes, services: [service], serviceEdges: known ? [edge] : []}, } return route.fulfill({json: responses[path] ?? {}}) }) @@ -93,7 +169,7 @@ test("Карта не приписывает весь YouTube единствен const composition = page.getByRole("region", {name: "Состав трафика IPFIX"}) await expect(composition.getByText("Оценка по сети и порту")).toBeVisible() await expect(composition.locator("time")).toHaveAttribute("datetime", service.lastBucketAt) - await expect(page.getByText("IPFIX · среднее за 5 мин")).toBeVisible() + await expect(page.getByText("IPFIX · среднее за 1 мин 30 с")).toBeVisible() const unknown = page.getByText("Выход не определён", {exact: true}).locator("..") const badges = page.locator("[data-map-ribbon] > title") await expect(unknown).toContainText("24 Кбит/с") @@ -122,8 +198,7 @@ test("Карта: DNS виден от экспортёра, пользовате 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} : {}), + ...emptyMapFlow(url), 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}], } : {}}) @@ -195,7 +270,7 @@ for (const reverse of [false, true]) test(`Карта: малый NetFlow и т "/api/servers": [exit, jump], "/api/filters/gre-tunnels": { tunnels: reverse ? [tunnel, opposite] : [tunnel], failures: [] }, "/api/uptime/speed-probes": { probes: [] }, - [flowPath]: { ...empty, live: true, hops: [estimate, { ...exact, fromId: String(peer.id), fromLabel: peer.name }], + [flowPath]: { ...emptyMapFlow(url), live: true, hops: [estimate, { ...exact, fromId: String(peer.id), fromLabel: peer.name }], interfaceTraffic: [{ serverId: observer.serverId, iface: observer.name, rxBytes: exactNetflow && !reverse ? 525 : 0, txBytes: exactNetflow && reverse ? 525 : 0, rxPackets: exactNetflow && !reverse ? 3 : 0, txPackets: exactNetflow && reverse ? 3 : 0, inWindow: exactNetflow, lastBucketAt: "2026-11-23T07:00:00Z" }] }, @@ -255,7 +330,7 @@ test("Карта: параллельные GRE с разными владель } return route.fulfill({ json: path === "/api/servers" ? [{ ...server, type: "jump-host" }, peer] : path === "/api/filters/gre-tunnels" ? { tunnels, failures: [] } - : path === flowPath ? { ...empty, live: true, interfaceTraffic } + : path === flowPath ? { ...emptyMapFlow(url), live: true, interfaceTraffic } : path === "/api/uptime/speed-probes" ? { probes: [] } : path === "/api/auth/config" ? { required: false } : {} }) }) await page.goto("/network-map") @@ -271,7 +346,7 @@ test("Карта: параллельные GRE с разными владель test("Карта: карточка узла показывает отдельно фактические RX/TX RouterOS", async ({ page }) => { await page.route("**/api/**", route => { const path = new URL(route.request().url()).pathname - return route.fulfill({ json: path === "/api/servers" ? [server] : path === flowPath ? empty + return route.fulfill({ json: path === "/api/servers" ? [server] : path === flowPath ? emptyMapFlow(route.request().url()) : path === "/api/filters/gre-tunnels" ? { tunnels: [], failures: [] } : path === "/api/uptime/speed-probes" ? { probes: [] } : path === "/api/auth/config" ? { required: false } : {} }) }) @@ -289,25 +364,29 @@ test("Карта: карточка узла показывает отдельн for(const malformed of [false,true])test("Карта: NetFlow отказ и повтор "+malformed,async({page})=>{ let failing=true - const recovered=malformed?{...empty,rangeMinutes:2,windowSec:120,sourceWindow:{requestedMinutes:5,effectiveMinutes:2}}:empty - await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill(p===flowPath?(failing?(malformed?{json:{}}:{status:503,json:{error:"NetFlow недоступен"}}):{json:recovered}):{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.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill(p===flowPath?(failing?(malformed?{json:{}}:{status:503,json:{error:"NetFlow недоступен"}}):{json:{...emptyMapFlow(r.request().url()),...(malformed && new URL(r.request().url()).searchParams.get("range") === "5m" ? {rangeMinutes:2,windowSec:120,sourceWindow:{requestedMinutes:5,effectiveMinutes:2}} : {})}}):{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(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.getByTitle(malformed?/NetFlow · 2 мин из 5 запрошенных · ответ/:/NetFlow · 5 мин · ответ/)).toContainText("приёмник выключен") + await expect(page.getByText("IPFIX · среднее за 1 мин 30 с · приёмник выключен")).toBeVisible() + if (malformed) { + await page.getByRole("button", {name: "Страны", exact: true}).click() + await expect(page.getByText(/IPFIX · среднее за 2 мин/)).toHaveAttribute("title", /2 мин из 5 запрошенных/) + } await expect(page.getByRole("alert").filter({hasText:"NetFlow:"})).toHaveCount(0) }) test("Карта: NetFlow сохраняет сервис при фоновом сбое",async({page})=>{ let failing=false - await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill(p===flowPath?(failing?{status:403,json:{error:"Нет доступа к NetFlow"}}:{json:{...empty,live:true,totalBytes:100,namedBytes:100,services:[{id:"svc:one",label:"Сервис сохранён",category:"Web",bytes:100,bps:0,share:1}]}}):{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.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill(p===flowPath?(failing?{status:403,json:{error:"Нет доступа к NetFlow"}}:{json:{...emptyMapFlow(r.request().url()),live:true,totalBytes:100,namedBytes:100,services:[{id:"svc:one",label:"Сервис сохранён",category:"Web",bytes:100,bps:0,share:1}]}}):{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(page.getByText("Сервис сохранён",{exact:true}).first()).toBeVisible() failing=true;await page.getByRole("button",{name:"Обновить",exact:true}).click() await expect(page.getByRole("alert").filter({hasText:"Сохранён предыдущий снимок NetFlow"})).toBeVisible() + await expect(page.getByRole("status").filter({hasText:"Показан предыдущий снимок сервисов"})).toBeVisible() await expect(page.getByText("Сервис сохранён",{exact:true}).first()).toBeVisible() }) for(const result of ["missing","foreign","unresolved","success"])test("Карта: DNS "+result,async({page})=>{ - await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p===flowPath?empty:p==="/api/servers"?[{...server,wanUplinks:[{id:"w",name:"WAN",iface:"ether1",isp:"ISP",ip:"router.example",maxDl:100,maxUl:100}]}]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/network/resolve-hosts"?(result==="missing"?{}:{results:result==="foreign"?{"foreign.example":"192.0.2.2"}:{"router.example":result==="unresolved"?null:"192.0.2.2"}}):p==="/api/auth/config"?{required:false}:{}})}) + await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p===flowPath?emptyMapFlow(r.request().url()):p==="/api/servers"?[{...server,wanUplinks:[{id:"w",name:"WAN",iface:"ether1",isp:"ISP",ip:"router.example",maxDl:100,maxUl:100}]}]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/network/resolve-hosts"?(result==="missing"?{}:{results:result==="foreign"?{"foreign.example":"192.0.2.2"}:{"router.example":result==="unresolved"?null:"192.0.2.2"}}):p==="/api/auth/config"?{required:false}:{}})}) await page.goto("/network-map") await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Router",{exact:true})).toBeVisible() if(result==="success")await expect(page.getByRole("alert").filter({hasText:"DNS:"})).toHaveCount(0) @@ -315,10 +394,10 @@ for(const result of ["missing","foreign","unresolved","success"])test("Карт }) test("Карта: медленный NetFlow не прерывается периодическим опросом",async({page})=>{ - let requests=0,release!:()=>void;const gate=new Promise(resolve=>{release=resolve}) + const ranges: string[] = [];let release!:()=>void;const gate=new Promise(resolve=>{release=resolve}) await page.clock.install() - 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.getByTitle(/NetFlow · 5 мин · ответ/)).toBeVisible() + await page.route("**/api/**",async r=>{const p=new URL(r.request().url()).pathname;if(p===flowPath){ranges.push(new URL(r.request().url()).searchParams.get("range")!);await gate;return r.fulfill({json:emptyMapFlow(r.request().url())})}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(()=>[...ranges].sort()).toEqual(["1m","5m"]) + await page.clock.runFor(5000);expect([...ranges].sort()).toEqual(["1m","5m"]) + release();await expect(page.getByText(/IPFIX · среднее за 1 мин 30 с/)).toBeVisible() }) diff --git a/tests/e2e/network-map-layout.spec.ts b/tests/e2e/network-map-layout.spec.ts index dedfc933..abd335d2 100644 --- a/tests/e2e/network-map-layout.spec.ts +++ b/tests/e2e/network-map-layout.spec.ts @@ -1,12 +1,12 @@ import {test,expect} from "@playwright/test" -const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false} +import { emptyMapFlow } from "./fixtures/map-flow" const wan={id:"w",name:"WAN",iface:"ether1",isp:"ISP",ip:"192.0.2.1",maxDl:100,maxUl:100} const home={id:1,name:"Домашний",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online",latency:2,wanUplinks:[wan]} const jh={id:2,name:"Jump",host:"192.0.2.2",type:"jump-host",country:"RU",enabled:true,status:"online",latency:3} const tunnel={id:"t1",serverId:"1",name:"gre-home",localAddress:"192.0.2.1",remoteAddress:"192.0.2.2",localInnerIp:"10.0.0.1",remoteInnerIp:"10.0.0.2",poolId:"",ipsec:null,mtu:1476,keepaliveInterval:10,keepaliveRetries:3,dscp:"inherit",clampTcpMss:true,allowFastPath:false,comment:"",enabled:true,status:"up"} test.beforeEach(async({page})=>{ await page.route("**/health",r=>r.fulfill({json:{ok:true}})) - await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...home,name:"Домашний роутер с очень длинным названием и описанием устройства"},{...jh,name:"Промежуточный узел с длинной подписью"}]:p==="/api/filters/gre-tunnels"?{tunnels:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})}) + await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...home,name:"Домашний роутер с очень длинным названием и описанием устройства"},{...jh,name:"Промежуточный узел с длинной подписью"}]:p==="/api/filters/gre-tunnels"?{tunnels:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})}) }) for(const width of [1440,390,320])test("Карта: доступные детали и адаптивная оболочка "+width,async({page},testInfo)=>{ await page.setViewportSize({width,height:900});await page.goto("/network-map") diff --git a/tests/e2e/network-map-legend.spec.ts b/tests/e2e/network-map-legend.spec.ts index f5e1372f..9356f734 100644 --- a/tests/e2e/network-map-legend.spec.ts +++ b/tests/e2e/network-map-legend.spec.ts @@ -1,5 +1,5 @@ import { test, expect } from "@playwright/test" -const emptyFlow = { hops: [], live: false, rangeMinutes: 5, windowSec: 300, totalBytes: 0, namedBytes: 0, unclassifiedBytes: 0, asnLoaded: false, countryLoaded: false, services: [], serviceEdges: [], servicePaths: [], countries: [], countryEdges: [], countryPaths: [], countryServiceGroups: [], mapServiceMinSharePct: 5, dedupApplied: false, excludeMeshApplied: false, excludeOverlayApplied: false } +import { emptyMapFlow } from "./fixtures/map-flow" test.beforeEach(async ({ page }) => { await page.route("**/health", r => r.fulfill({ json: { ok: true } })) @@ -10,7 +10,7 @@ test.beforeEach(async ({ page }) => { { id: 2, name: "Тест EN", host: "192.0.2.2", type: "exit-node", country: "SE", enabled: true, status: "online" }, ] : path === "/api/filters/gre-tunnels" ? { tunnels: [], failures: [] } : path === "/api/uptime/speed-probes" ? { probes: [] } - : path === "/api/traffic/flow/map-hops" ? emptyFlow + : path === "/api/traffic/flow/map-hops" ? emptyMapFlow(r.request().url()) : path === "/api/auth/config" ? { required: false } : {} }) }) }) diff --git a/tests/e2e/network-map-overlap.spec.ts b/tests/e2e/network-map-overlap.spec.ts index c8272337..c550058a 100644 --- a/tests/e2e/network-map-overlap.spec.ts +++ b/tests/e2e/network-map-overlap.spec.ts @@ -1,7 +1,7 @@ import { test, expect, type Page } from "@playwright/test" // Подписи и карточки холста не наезжают друг на друга: проверяем видимые тела (data-map-box), а не фоновые полосы. -const empty = { hops: [], live: true, rangeMinutes: 5, windowSec: 300, totalBytes: 0, namedBytes: 0, unclassifiedBytes: 0, asnLoaded: false, countryLoaded: false, services: [], serviceEdges: [], servicePaths: [], countries: [], countryEdges: [], countryPaths: [], countryServiceGroups: [], mapServiceMinSharePct: 0, dedupApplied: false, excludeMeshApplied: false, excludeOverlayApplied: false } +import { emptyMapFlow } from "./fixtures/map-flow" const srv = (id: number, name: string, type: string, country = "RU", status = "online") => ({ id, name, host: `192.0.2.${id}`, type, country, enabled: true, status, latency: 10 + id }) const gre = (id: string, owner: number, peer: number, status = "up") => ({ @@ -14,7 +14,7 @@ async function serve(page: Page, servers: unknown[], tunnels: ReturnType { const p = new URL(r.request().url()).pathname const json = p === "/api/servers" ? servers : p === "/api/filters/gre-tunnels" ? { tunnels, failures: [] } - : p === "/api/uptime/speed-probes" ? { probes: [] } : p === "/api/traffic/flow/map-hops" ? { ...empty, ...flow } + : p === "/api/uptime/speed-probes" ? { probes: [] } : p === "/api/traffic/flow/map-hops" ? { ...emptyMapFlow(r.request().url()), live: true, mapServiceMinSharePct: 0, ...flow } : p === "/api/ix/topology" ? { links: [] } : p === "/api/auth/config" ? { required: false } : {} return r.fulfill({ json }) }) diff --git a/tests/e2e/network-map-url.spec.ts b/tests/e2e/network-map-url.spec.ts index 1937200d..ba3ed3d1 100644 --- a/tests/e2e/network-map-url.spec.ts +++ b/tests/e2e/network-map-url.spec.ts @@ -1,9 +1,9 @@ import {test,expect} from "@playwright/test" -const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false} +import { emptyMapFlow } from "./fixtures/map-flow" const server={id:1,name:"Router URL",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:null,wanUplinks:[{id:"w",name:"WAN URL",iface:"ether1",isp:"ISP",ip:"192.0.2.1",maxDl:100,maxUl:100}]} test.beforeEach(async({page})=>{ await page.route("**/health",r=>r.fulfill({json:{ok:true}})) - await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[server]: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.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[server]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})}) }) test("Карта URL: устройство/WAN, фильтр, поиск, назначения, reload и история",async({page})=>{ await page.goto("/network-map?server=1&wan=0&filter=unknown&q=Router&dest=countries&tag=keep#anchor")