Compare commits

..
3 Commits
Author SHA1 Message Date
Denozordec c44bcd8f59 fix(map): показывать скорость сервисов по короткому окну IPFIX
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 3s
Docker images / frontend-image (push) Successful in 2m14s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 31s
Docker images / backend-image (push) Successful in 15s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
2026-11-27 13:08:08 +07:00
Denozordec ed7b1e0350 fix(map): восстановить учёт трафика сервисов и привязку к выходным узлам
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m50s
Docker images / backend-image (push) Successful in 2m5s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 41s
Docker images / frontend-image (push) Successful in 2m13s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-27 02:34:26 +07:00
Denozordec 4097e1a6fc fix(traffic): восстановить распознавание видеосервисов на карте
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m55s
Docker images / backend-image (push) Successful in 1m58s
Docker images / frontend-image (push) Successful in 2m17s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
Показать среднюю скорость и время последней минуты с потоками.
2026-11-27 01:40:50 +07:00
29 changed files with 719 additions and 243 deletions

No files matched your search

+92 -67
View File
@@ -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<typeof networkMapFlowSchema.parse>; at?: string; error?: string }>()
useEffect(() => {
if (base === null) return
const controller = new AbortController()
let timer: ReturnType<typeof setTimeout>
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<string|null>(null)
const [flowListener,setFlowListener]=useState(false)
const [flowLoading,setFlowLoading]=useState(false)
const [userFlow, setUserFlow] = useState<{ key: string; data?: ReturnType<typeof networkMapFlowSchema.parse>; at?: string; error?: string }>()
const [bottomTab, setBottomTab] = useState<MapBottomTab>("flows")
const [analysisOpen, setAnalysisOpen] = useState(false)
const [summaryOpen, setSummaryOpen] = useState(false)
const [filteredServiceId, setFilteredServiceId] = useState<string | null>(null)
const [filterService, setFilterService] = useState<Pick<FlowMapService, "id" | "label"> | null>(null)
const filteredServiceId = filterService?.id ?? null
const [mapEvents, setMapEvents] = useState<EventItem[] | null>(null)
const [eventsError, setEventsError] = useState<string | null>(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 */ }
@@ -1242,7 +1267,7 @@ function NetworkMapContent() {
setFlowLoading(true)
ac?.abort()
ac = new AbortController()
apiFetch<unknown>("/api/traffic/flow/map-hops?range=1m", { signal: ac.signal })
apiFetch<unknown>("/api/traffic/flow/map-hops?range=5m", { signal: ac.signal })
.then((raw) => {
if (cancelled||request!==epoch) return
const res=networkMapFlowSchema.parse(raw)
@@ -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<typeof setTimeout>
async function refresh() {
try {
const raw = await apiFetch<unknown>(`/api/traffic/flow/map-hops?${new URLSearchParams({range:"1m",userId:scopeUser!})}`, {signal:controller.signal})
const data = networkMapFlowSchema.parse(raw)
if (!controller.signal.aborted) setUserFlow({ key: scopeKey, data, 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<string, typeof usersInTopology>()
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(() => {
@@ -2179,11 +2199,12 @@ function NetworkMapContent() {
if (!from || !to) return []
const direct = edge.observedOnly || from.type === "jump-host" || from.type === "home-router"
if (direct && !showAuxLinks) return []
const detour = direct ? mapObservationRoute({ x: from.x + MAP_CARD_W / 2, y: from.y }, { x: to.x - destHalfW, y: to.y }, mapObstacles, observationTracks) : null
const link = mapLinkPath(from, MAP_CARD_W / 2, to, destHalfW)
const detour = direct ? mapObservationRoute(link, mapObstacles, observationTracks) : null
if (detour) observationTracks.push(detour.track)
return [{ edge, direct, detour, link: mapLinkPath(from, MAP_CARD_W / 2, to, destHalfW) }]
return [{ edge, direct, detour, link }]
})
const observationMarkers = destRibbons.flatMap(({ edge, detour }) => edge.observedOnly && detour ? [{ x: detour.marker.x - 17, y: detour.marker.y - 7, w: 34, h: 14 }] : [])
const observationMarkers = destRibbons.flatMap(({ edge, detour }) => edge.observedOnly && detour?.marker ? [{ x: detour.marker.x - 17, y: detour.marker.y - 7, w: 34, h: 14 }] : [])
const linkLabels = placeMapLinkLabels([...accessLinks.filter(link => link.texts[0]), ...greLabels, ...wanLabels], [...mapObstacles, ...observationMarkers])
const nestedRibbons = mapRibbons((expandedCountryGroup?.edges ?? []).flatMap((edge) => {
const from = servicePosById[edge.fromId], to = nestedPosById[edge.toId]
@@ -2201,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),
@@ -2241,9 +2261,9 @@ function NetworkMapContent() {
const recentIncidents = eventRows.filter(event => (event.tone === "er" || event.tone === "wn") && event.ts >= eventsAt - 86_400_000)
const mapHeadSub = (
<>
<span title={readAt ? `Снимок API ${new Date(readAt).toLocaleTimeString("ru-RU")}` : undefined}>{useLiveData ? (readAt ? "Текущий срез" : "Данные карты неизвестны") : "Демонстрационные данные"}</span>
<span title={readAt ? `Снимок API ${new Date(readAt).toLocaleTimeString("ru-RU")}` : undefined}>{useLiveData ? (readAt ? "Снимок сети" : "Данные карты неизвестны") : "Демонстрационные данные"}</span>
{" · "}<span>{nodes.length} {ruPlural(nodes.length, "узел", "узла", "узлов")} · {mapLinkCount} {ruPlural(mapLinkCount, "связь", "связи", "связей")}</span>
{useLiveData && (showNetflow || showServices) && <>{" · "}{flowReadAt ? <span title={`NetFlow · ${mapWindow}${mapWindowSec >= 120 && mapWindowSec < 300 ? " из 5 запрошенных" : ""} · ответ ${new Date(flowReadAt).toLocaleTimeString("ru-RU")} · ${flowListener ? "приёмник включён" : "приёмник выключен"}`}>IPFIX · {mapWindow}{!flowListener ? " · приёмник выключен" : ""}</span> : <span>Данные NetFlow неизвестны</span>}</>}
{useLiveData && (showNetflow || showServices) && <>{" · "}{destinationReadAt ? <span title={`NetFlow · ${destinationWindow}${!liveServiceView && destinationWindowSec < 300 ? " из 5 запрошенных" : ""} · средняя скорость по принятым записям IPFIX · ответ ${new Date(destinationReadAt).toLocaleTimeString("ru-RU")}`}>IPFIX · среднее за {destinationWindow}{!destinationListener ? " · приёмник выключен" : ""}</span> : <span>Данные NetFlow неизвестны</span>}</>}
</>
)
// Подсказки поиска макета: узлы и назначения текущего снимка.
@@ -2253,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<string, string>)[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)
@@ -2425,7 +2447,7 @@ function NetworkMapContent() {
<UsersIcon aria-hidden />{pickedUser?.name ?? (ixOnly ? "Linux-клиенты" : "Пользователи")}
</Button>}
{pickedUser && <Button type="button" variant="ghost" size="icon-sm" aria-label="Вся схема пользователей" onClick={returnToNetwork}><XIcon /></Button>}
{filterService && <Button type="button" variant="outline" size="sm" aria-label={`Сбросить фильтр сервиса ${filterService.label}`} onClick={() => setFilteredServiceId(null)}>{filterService.label}<XIcon aria-hidden /></Button>}
{filterService && <Button type="button" variant="outline" size="sm" aria-label={`Сбросить фильтр сервиса ${filterService.label}`} onClick={() => setFilterService(null)}>{filterService.label}<XIcon aria-hidden /></Button>}
<Button type="button" variant="ghost" size="sm" onClick={() => setSummaryOpen(true)}>Сводка сети</Button>
<Popover>
<PopoverTrigger render={<Button type="button" variant="ghost" size="icon-sm" aria-label="Как читать карту" />}><CircleHelpIcon aria-hidden /></PopoverTrigger>
@@ -2435,6 +2457,7 @@ function NetworkMapContent() {
<li>Слева выберите пользователя. Карта покажет правее его узлы подключения, выход в интернет и сервисы.</li>
<li>Откройте узел или линию. Справа появятся источник данных, состояние связи и доступные измерения.</li>
<li>Метка IPFIX показывает, где замечен трафик. Дальнейший маршрут для такой линии требует подтверждения.</li>
<li>На сервисах показана средняя скорость по сохранённым потокам IPFIX. RX/TX на узлах берутся из счётчиков RouterOS.</li>
</ol>
</PopoverContent>
</Popover>
@@ -2477,12 +2500,12 @@ function NetworkMapContent() {
<NetworkMapLegend compact={Boolean(selected || selectedGreEdge || selectedService || (nodes.length && !nodes.some(isVisible)))} />
</FramePanel>
{(inspectedEvent || userSnapshot?.error) && <FramePanel className="flex flex-col gap-2" aria-label="Разбор события">
{(inspectedEvent || recent?.error) && <FramePanel className="flex flex-col gap-2" aria-label="Разбор события">
{inspectedEvent && <>
<div className="flex items-start justify-between gap-2"><div className="min-w-0"><h2 className="text-sm font-semibold">{inspectedEvent.title}</h2><p className="text-xs text-muted-foreground">{new Date(inspectedEvent.ts).toLocaleString("ru-RU")} · {inspectedEvent.message}</p></div><Button variant="ghost" size="icon-xs" aria-label="Закрыть разбор" onClick={() => setInspectedEvent(null)}><XIcon /></Button></div>
{inspectedEvent.serverId && <Link className={buttonVariants({variant:"outline",size:"xs",className:"self-start"})} href={nodeTrafficHref(inspectedEvent.serverId)}>Трафик узла</Link>}
</>}
{userSnapshot?.error && <p role="status" className="text-xs text-muted-foreground">{userSnapshot.error}. Показаны подтверждённые строки из доступного снимка.</p>}
{recent?.error && <p role="status" className="text-xs text-muted-foreground">{recent.error}. {recent.data ? "Показан предыдущий снимок сервисов." : "Скорости сервисов пока недоступны."}</p>}
</FramePanel>}
{/* Состояние данных: загрузка и ошибки снимка, NetFlow и DNS */}
@@ -2546,7 +2569,7 @@ function NetworkMapContent() {
const pathHit = Boolean(highlightedPath && (highlightedPath.enId || highlightedPath.viaId) === edge.fromId && selectedDestinationId === edge.toId)
const hl = pathHit || (!highlightedPath && (activeService?.id === edge.toId || selected?.id === edge.fromId || expandedCountryId === edge.toId || filteredServiceId === edge.toId))
const countryDim = !hl && Boolean(expandedCountryGroup) && edge.toId !== expandedCountryId
const d = direct ? detour?.d : link.d
const d = detour?.d ?? link.d
const svc = visibleMapServices.find((s) => s.id === edge.toId)
const enName = mapServers.find((s) => s.id === edge.fromId)?.name ?? edge.fromId
const clientLabel = edge.clients?.map((c) => c.name).filter(Boolean).join(", ") || edge.clientName || "—"
@@ -2559,14 +2582,13 @@ function NetworkMapContent() {
<title>{edge.observedOnly
? `Наблюдение IPFIX · ${enName} → ${destDisplayLabel(svc, destMode, edge.toId)}${rate} · выход не подтверждён`
: `${clientLabel} → ${enName} → ${destDisplayLabel(svc, destMode, edge.toId)}${rate}`}</title>
{d && <path data-map-route={direct ? "observation" : "service"} d={d} fill="none" stroke={direct ? "var(--muted-foreground)" : "var(--chart-4)"} strokeLinejoin="round" strokeWidth={hl ? 2.5 : 1.5} />}
{d && <path d={d} fill="none" stroke="transparent" strokeWidth="12" />}
{edge.observedOnly && detour && <g transform={`translate(${detour.marker.x},${detour.marker.y})`}>
<path data-map-route={direct ? "observation" : "service"} d={d} fill="none" stroke={direct ? "var(--muted-foreground)" : "var(--chart-4)"} strokeLinejoin="round" strokeWidth={hl ? 2.5 : 1.5} />
<path d={d} fill="none" stroke="transparent" strokeWidth="12" />
{edge.observedOnly && detour?.marker && <g transform={`translate(${detour.marker.x},${detour.marker.y})`}>
<rect x="-17" y="-7" width="34" height="14" rx="7" fill="var(--card)" stroke="var(--muted-foreground)" />
<text textAnchor="middle" y="3.5" fill="var(--foreground)" fontSize="9">IPFIX</text>
</g>}
{!d && <circle cx={link.x2 - 5} cy={link.y2} r="4" fill="var(--muted-foreground)" />}
{d && !direct && showAnimDots && !reducedMotion && hl && hopHasRate(hop) && (
{!direct && showAnimDots && !reducedMotion && hl && hopHasRate(hop) && (
<circle r="2.5" fill="var(--foreground)" opacity="0.7" pointerEvents="none">
<animateMotion dur="2.6s" repeatCount="indefinite" path={d} />
</circle>
@@ -2726,7 +2748,7 @@ function NetworkMapContent() {
})}
{minorPosition && <ServiceNode label={showSmallServices ? "Свернуть остальные" : `Остальные сервисы (${groupedServices.length})`} share={groupedServices.reduce((sum, service) => sum + service.share, 0)} category={showSmallServices ? `${groupedServices.length} в группе` : "Доля каждого ≤ 10%"}
x={minorPosition.x} y={minorPosition.y} destMode="services" expanded={showSmallServices} isSel={false} isVis isDragged={false} onPointerDown={() => {}} onClick={() => setShowSmallServices(value => !value)} />}
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
@@ -2735,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)}
@@ -2777,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 }
@@ -3079,17 +3102,19 @@ function NetworkMapContent() {
</div>
</>
) : activeService && (destMode === "services" || selectedNestedService) ? (
<ServiceInspector key={activeService.id} service={activeService}
<ServiceInspector key={JSON.stringify([pickedUserId, ixOnly, activeService.id])} service={activeService}
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={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)
}}
@@ -3122,7 +3147,7 @@ function NetworkMapContent() {
<div className="flex-1 min-h-0 overflow-y-auto px-4 py-4 flex flex-col gap-4">
<div className="flex flex-col gap-0">
<div className="flex items-center justify-between py-2 border-b border-border/50">
<span className="text-xs text-muted-foreground">Доля окна</span>
<span className="text-xs text-muted-foreground">Доля {destinationShareLabel}</span>
<span className="text-xs font-mono font-medium text-cyan-400">{serviceSharePct(liveSelectedService.share)}</span>
</div>
{destinationTotalBytes !== undefined && destinationTotalBytes > 0 && destinationNamedBytes !== undefined && (
@@ -12,11 +12,12 @@ import {
uptimeSpeedProbes,
} from "../db/schema.js"
import { listServersRead } from "../modules/servers/service/servers-service.js"
import { rosIdToIfIndex } from "./traffic-flow-ifindex.js"
import { MikrotikClient } from "./mikrotik.js"
import type { InternetPathRunSnapshot } from "../types/scheduler-run-snapshot.js"
import { SCHEDULER_RUN_SNAPSHOT_VERSION } from "../types/scheduler-run-snapshot.js"
import { collectConfirmedInternetPath, readInternetPathRows } from "./internet-path-snapshot.js"
import { collectConfirmedInternetPath, observedGrePeers, readGreEnrichment, readInternetPathRows } from "./internet-path-snapshot.js"
const INTERNET_TARGET = "1.1.1.1"
let collecting = false
@@ -177,12 +178,22 @@ function parseInnerIps(comment: string): { localInnerIp: string; remoteInnerIp:
async function collectGreTunnels() {
const enabled = await db.select().from(servers).where(eq(servers.enabled, true))
const assignedAddresses = new Map<string, Set<string>>()
const all = await Promise.all(enabled.map(async (srv) => {
try {
const client = MikrotikClient.fromServer(srv)
const rows = await client.get<unknown>("/interface/gre").then(raw => readInternetPathRows(raw, "GRE " + srv.id, [".id", "name", "local-address", "remote-address"]))
if (!rows.length) return []
const [addresses, interfaces] = await Promise.all([
readGreEnrichment(() => client.get<unknown>("/ip/address"), "GRE addresses " + srv.id, ["interface", "address"]),
readGreEnrichment(() => client.get<unknown>("/interface"), "interfaces " + srv.id, [".id", "name"]),
])
const activeAddresses = addresses.filter(a => !isTrue(a.disabled) && !isTrue(a.invalid))
assignedAddresses.set(String(srv.id), new Set(activeAddresses.map(a => a.address!.split("/")[0]!)))
return rows.map((g, idx) => {
const keepalive = String(g.keepalive ?? "0,0").split(",")
const identities = interfaces.filter(row => row.name === g.name)
const identity = identities.length === 1 ? identities[0] : undefined
const inner = parseInnerIps(String(g.comment ?? ""))
return {
id: String(g.name ?? g[".id"] ?? `gre-${srv.id}-${idx}`),
@@ -190,6 +201,10 @@ async function collectGreTunnels() {
serverId: String(srv.id),
localAddress: String(g["local-address"] ?? ""),
remoteAddress: String(g["remote-address"] ?? ""),
currentRemoteAddress: String(g["current-remote-address"] ?? ""),
nativeIndex: rosIdToIfIndex(identity?.[".id"]),
ifIndex: /^[1-9][0-9]*$/.test(identity?.ifindex ?? "") ? Number(identity!.ifindex) : null,
observedAddresses: activeAddresses.filter(a => a.interface === g.name).map(a => a.address!),
localInnerIp: inner.localInnerIp,
remoteInnerIp: inner.remoteInnerIp,
poolId: "live",
@@ -212,7 +227,7 @@ async function collectGreTunnels() {
throw new Error(`Internet path: GRE устройства ${srv.id}: ${error instanceof Error ? error.message : String(error)}`)
}
}))
return all.flat()
return observedGrePeers(all.flat(), new Map(enabled.map(server => [String(server.id), server.host])), assignedAddresses)
}
export async function getInternetPathSettings() {
@@ -1,5 +1,5 @@
import assert from "node:assert/strict"
import {collectConfirmedInternetPath, readInternetPathRows, readStoredInternetPathPayload, mapStoredInternetPathResponse} from "./internet-path-snapshot.js"
import {collectConfirmedInternetPath, observedGrePeers, readGreEnrichment, readInternetPathRows, readStoredInternetPathPayload, mapStoredInternetPathResponse} from "./internet-path-snapshot.js"
const servers=[{id:1,type:"home-router",enabled:true},{id:2,type:"home-router",enabled:false},{id:3,type:"exit-node",enabled:true}]
const sampledAt="2026-10-04T00:00:00Z"
const defaults={servers:async()=>servers,gre:async()=>[],filters:async()=>[],speed:async()=>[],route:async(id:number)=>{assert.equal(id,1);return {gateway:null,routingMark:null}},wan:async(id:number)=>{assert.equal(id,1);return {defaultGateway:null,defaultInterface:null,uplinks:[]}}}
@@ -35,3 +35,29 @@ for (const stored of ["2026-10-04 07:00:00+07", "2026-10-04T00:00:00Z"]) {
for (const invalid of ["", "bad", null]) assert.throws(()=>mapStoredInternetPathResponse({payloadJson:good,sampledAt:invalid as string}))
assert.throws(()=>mapStoredInternetPathResponse({payloadJson:"bad",sampledAt}))
console.log("internet path HTTP timestamp: PostgreSQL/ISO instant preserved; invalid metadata rejected")
const jh = { serverId: "7", enabled: true, localAddress: "0.0.0.0", remoteAddress: "198.51.100.9", observedAddresses: ["10.200.100.53/30"] }
const exit = { serverId: "9", enabled: true, localAddress: "198.51.100.9", remoteAddress: "198.51.100.7", observedAddresses: ["10.200.100.54/30"] }
const hosts = new Map([["7", "198.51.100.7"], ["9", "198.51.100.9"]])
assert.deepEqual(observedGrePeers([jh, exit], hosts, new Map()).map(t => t.observedNextHops), [[{ip:"10.200.100.54",serverId:"9"}],[{ip:"10.200.100.53",serverId:"7"}]])
for (const incomplete of [[jh], [jh, exit, {...exit, serverId:"18"}], [jh, {...exit, enabled:false}], [jh, {...exit, remoteAddress:"198.51.100.8"}], [jh, {...exit, observedAddresses:["10.200.100.55/30"]}]]) {
assert.ok(observedGrePeers(incomplete, hosts, new Map()).every(t => !t.observedNextHops.length))
}
const wildcard = observedGrePeers([
{...jh, localAddress:"0.0.0.0",remoteAddress:"exit.example",currentRemoteAddress:"198.51.100.2"},
{...exit,localAddress:"0.0.0.0",remoteAddress:"198.51.100.1"},
], new Map([["7","jump.example"],["9","exit.example"]]), new Map([["7",new Set(["198.51.100.1"])],["9",new Set(["198.51.100.2"])]]))
assert.deepEqual(wildcard[0]?.observedNextHops, [{ip:"10.200.100.54",serverId:"9"}])
for (const read of [async () => { throw Error("forbidden") }, async () => ({ message:"invalid response" })]) {
const observed = await readGreEnrichment(read, "GRE", ["address","interface"])
const [base] = observedGrePeers([{...jh, observedAddresses:observed.map(a => a.address!),localInnerIp:"10.0.0.1/30"}],hosts,new Map())
assert.equal(base?.localInnerIp,"10.0.0.1/30")
assert.deepEqual(base?.observedNextHops,[])
}
const staleDns = observedGrePeers([
{...jh, remoteAddress:"exit.example",currentRemoteAddress:"192.0.2.11"}, exit,
], new Map([["7","198.51.100.7"],["9","exit.example"]]), new Map())
assert.ok(staleDns.every(t => !t.observedNextHops.length))
@@ -1,3 +1,5 @@
import { ipv4ToInt, parseCidrV4 } from "./traffic-flow-ip.js"
// No database or RouterOS imports: this boundary can be checked with injected readers.
type PathServer = {id: number | string; type: string; enabled: boolean}
export async function collectConfirmedInternetPath<S extends PathServer, G, F, P, R extends object, W extends object>(sampledAt: string, readers: {
@@ -36,3 +38,50 @@ export function mapStoredInternetPathResponse(row: { payloadJson: unknown; sampl
if (typeof row.sampledAt !== "string" || !row.sampledAt.trim()) throw new Error("Сохранённая дата Internet path повреждена")
return { snapshot: readStoredInternetPathPayload(row.payloadJson), sampledAt: new Date(row.sampledAt).toISOString() }
}
// Enrichment may be unauthorized on otherwise observable GRE routers.
export async function readGreEnrichment(read: () => Promise<unknown>, source: string, fields: string[]) {
try { return readInternetPathRows(await read(), source, fields) } catch { return [] }
}
// A shared point-to-point subnet and matching outer peers identify the exact next hop on this exporter.
export function observedGrePeers<T extends {serverId: string; enabled: boolean; localAddress: string; remoteAddress: string; currentRemoteAddress?: string; localInnerIp?: string; observedAddresses: string[]}>(
tunnels: T[], hosts: Map<string, string>, assignedAddresses: Map<string, Set<string>>,
) {
const subnets = new Map<string, Array<{ tunnel: T; ip: string }>>()
const peers = new Map<T, Array<{ ip: string; serverId: string }>>()
for (const tunnel of tunnels) {
if (!tunnel.enabled) continue
for (const cidr of tunnel.observedAddresses) {
if (!/^[0-9.]+\/(30|31)$/.test(cidr)) continue
const parsed = parseCidrV4(cidr)
const ip = cidr.split("/")[0]!
if (!parsed || (parsed.prefixLen === 30 && (ipv4ToInt(ip) === parsed.net || ipv4ToInt(ip) === parsed.net + 3))) continue
const key = parsed.net + "/" + parsed.prefixLen
const entries = subnets.get(key) ?? []
entries.push({ tunnel, ip })
subnets.set(key, entries)
}
}
function pointsTo(local: T, peer: T) {
const current = local.currentRemoteAddress?.trim().toLowerCase()
const remote = current && current !== "0.0.0.0" ? current : local.remoteAddress.trim().toLowerCase()
return remote && remote !== "0.0.0.0" && (remote === peer.localAddress.toLowerCase() ||
remote === hosts.get(peer.serverId)?.toLowerCase() || assignedAddresses.get(peer.serverId)?.has(remote))
}
for (const endpoints of subnets.values()) {
if (endpoints.length !== 2) continue
const [a, b] = endpoints as [typeof endpoints[number], typeof endpoints[number]]
if (a.ip === b.ip || a.tunnel.serverId === b.tunnel.serverId || !pointsTo(a.tunnel, b.tunnel) || !pointsTo(b.tunnel, a.tunnel)) continue
for (const [local, peer] of [[a, b], [b, a]] as const) {
const matches = peers.get(local.tunnel) ?? []
matches.push({ ip: peer.ip, serverId: peer.tunnel.serverId })
peers.set(local.tunnel, matches)
}
}
return tunnels.map(tunnel => {
const { observedAddresses, ...rest } = tunnel
return { ...rest, localInnerIp: observedAddresses[0] ?? tunnel.localInnerIp ?? "", observedNextHops: peers.get(tunnel) ?? [] }
})
}
@@ -421,8 +421,8 @@ try {
assert.equal(def.excludeOverlayApplied, true)
assert.equal(def.excludeMeshApplied, true)
assert.ok(!def.conversationsList.some((r) => r.proto === 47))
assert.equal(def.conversationsList[0]?.service, "Google")
assert.equal(def.conversationsList[0]?.category, "Веб")
assert.equal(def.conversationsList[0]?.service, "YouTube")
assert.equal(def.conversationsList[0]?.category, "Видео / стриминг")
assert.equal(def.conversationsList[0]?.clientName, "Alice")
assert.equal(def.conversationsList[0]?.enName, "NSK-SERVHOST-RTK")
assert.equal(def.conversationsList[0]?.plane, "payload")
@@ -520,8 +520,8 @@ try {
const google = rev.conversationsList.find((r) => r.src === "74.125.104.196")
const cf = rev.conversationsList.find((r) => r.src === "104.18.35.51")
const fastly = rev.conversationsList.find((r) => r.src === "146.75.118.132")
assert.equal(google?.service, "Google")
assert.equal(google?.category, "Веб")
assert.equal(google?.service, "YouTube")
assert.equal(google?.category, "Видео / стриминг")
assert.equal(google?.internetPeer, "74.125.104.196")
assert.equal(google?.internetPeerPort, 443)
assert.equal(google?.clientIp, "10.200.100.53")
@@ -85,11 +85,16 @@ assert.equal(isSteamGamePort(6, 443, 50000), false)
assert.equal(resolveFlowBrand("104.18.35.51", 32590, "VALVE-CORPORATION", 6, 443, 1)?.service, "Cloudflare")
assert.equal(resolveFlowBrand("203.0.113.9", 32590, "", 17, 27015, 50000)?.service, "Steam")
assert.equal(resolveFlowBrand("8.8.8.8", 15169, "GOOGLE", 6, 443, 51234)?.service, "Google")
assert.equal(resolveFlowBrand("173.194.160.163", 15169, "GOOGLE", 6, 443, 51234)?.service, "Google")
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 17, 443, 50000)?.service, "Google")
assert.equal(resolveFlowBrand("173.194.160.163", 15169, "GOOGLE", 6, 443, 51234)?.service, "YouTube")
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 17, 443, 50000)?.service, "YouTube")
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 6, 80, 50000)?.service, "Google")
assert.equal(resolveFlowBrand("2001:4860:4860::8888", 15169, "GOOGLE", 17, 53, 53000)?.service, "Google")
assert.equal(resolveFlowBrand("2001:4860:4860::8888", 15169, "GOOGLE", 17, 443, 50000)?.service, "Google")
assert.equal(resolveFlowBrand("2001:4860:4860:0:0:0:0:8844/128", 15169, "GOOGLE", 6, 443)?.service, "Google")
assert.equal(resolveFlowBrand("::ffff:8.8.4.4", 15169, "", 17, 443)?.service, "Google")
assert.equal(resolveFlowBrand("2607:f8b0::123", 15169, "", 17, 443)?.service, "YouTube")
assert.equal(resolveFlowBrand("64.233.161.1", 396982, "", 6, 443)?.service, "Google")
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 6, 50000, 443)?.service, "Google", "443 на стороне клиента")
assert.equal(brandByAsn(32934)?.service, "Meta")
assert.equal(lookupBrand("157.240.12.52", 0)?.service, "Meta")
@@ -99,13 +104,13 @@ assert.equal(mapServiceNodeId("Instagram"), "svc:instagram")
assert.equal(isNamedInternetService("Instagram", "Видео / стриминг"), true)
assert.equal(
resolveFlowBrand("157.240.12.52", 32934, "FACEBOOK", 6, 443, 51234)?.service,
"Meta",
"Общий адрес Meta не идентифицирует Instagram",
"Instagram",
"HTTPS в сети Meta",
)
assert.equal(
resolveFlowBrand("57.144.22.192", 0, "", 17, 443, 50000)?.service,
"Meta",
"Общий префикс Meta не идентифицирует Instagram",
"Instagram",
"QUIC в префиксе Meta без ASN",
)
assert.equal(
resolveFlowBrand("157.240.12.52", 32934, "FACEBOOK", 6, 80, 50000)?.service,
+21 -4
View File
@@ -1,10 +1,12 @@
import { ipInCidrV4, parseCidrV4 } from "./traffic-flow-ip.js"
import { canonicalIp, ipInCidrV4, ipv6ToInt, parseCidrV4 } from "./traffic-flow-ip.js"
export const OTHER_SERVICE = "Прочее"
export interface BrandHit {
service: string
category: string
operator?: string
heuristic?: true
}
const CDN = { category: "CDN" } as const
@@ -40,7 +42,7 @@ const TIMEWEB: BrandHit = { service: "Timeweb", ...CDN }
const BEGET: BrandHit = { service: "Beget", ...CDN }
const DDOS_GUARD: BrandHit = { service: "DDoS-Guard", ...CDN }
const META: BrandHit = { service: "Meta", ...CDN }
const INSTAGRAM: BrandHit = { service: "Instagram", ...VIDEO }
const INSTAGRAM: BrandHit = { service: "Instagram", operator: META.service, ...VIDEO }
const GOOGLE: BrandHit = { service: "Google", ...WEB }
const GITHUB: BrandHit = { service: "GitHub", ...WEB }
@@ -55,7 +57,9 @@ const WIKIPEDIA: BrandHit = { service: "Wikipedia", ...WEB }
const PAYPAL: BrandHit = { service: "PayPal", ...WEB }
const SALESFORCE: BrandHit = { service: "Salesforce", ...WEB }
const YOUTUBE: BrandHit = { service: "YouTube", ...VIDEO }
const YOUTUBE: BrandHit = { service: "YouTube", operator: GOOGLE.service, ...VIDEO }
const LIKELY_YOUTUBE: BrandHit = { ...YOUTUBE, heuristic: true }
const LIKELY_INSTAGRAM: BrandHit = { ...INSTAGRAM, heuristic: true }
const NETFLIX: BrandHit = { service: "Netflix", ...VIDEO }
const TWITCH: BrandHit = { service: "Twitch", ...VIDEO }
const TIKTOK: BrandHit = { service: "TikTok", ...VIDEO }
@@ -223,6 +227,14 @@ const HOLDER_BRANDS: Array<{ re: RegExp; hit: BrandHit }> = [
const NON_ISO = new Set(["EU", "AP", "ZZ", "XX", "A1", "A2", "O1"])
const STEAM_ASN = 32590
const GOOGLE_DNS_V6 = new Set([ipv6ToInt("2001:4860:4860::8888")!, ipv6ToInt("2001:4860:4860::8844")!])
function isGooglePublicDns(ip: string): boolean {
const host = canonicalIp(ip)
if (host === "8.8.8.8" || host === "8.8.4.4") return true
const ipv6 = host.includes(":") ? ipv6ToInt(host) : null
return ipv6 !== null && GOOGLE_DNS_V6.has(ipv6)
}
export function isIsoCountry(code: string): boolean {
const c = String(code ?? "").trim().toUpperCase()
@@ -286,7 +298,7 @@ export function lookupBrand(ip: string, asn: number): BrandHit | null {
/**
* Cloudflare CIDR бьёт holder (витрина на CF не становится Steam).
* Holder (YouTube / Instagram и др.) бьёт остальные CIDR/ASN.
* Общий ASN Google или Meta сообщает об операторе, а не о приложении.
* На порту 443 интернет-узла общие сети Google и Meta дают вероятную атрибуцию.
* Порты Steam — только AS32590 и не выше Cloudflare CIDR.
*/
export function resolveFlowBrand(
@@ -303,6 +315,11 @@ export function resolveFlowBrand(
if (holderBrand) return holderBrand
const asnBrand = brandByAsn(asn)
const fromLookup = cidrBrand || asnBrand
if (asnBrand === YOUTUBE && cidrBrand === GOOGLE) return YOUTUBE
if ((proto === 6 || proto === 17) && dstPort === 443) {
if (fromLookup === GOOGLE && (!asn || asn === 15169) && !isGooglePublicDns(ip)) return LIKELY_YOUTUBE
if (fromLookup === META && (!asn || asn === 32934 || asn === 63293)) return LIKELY_INSTAGRAM
}
if (fromLookup) return fromLookup
if (asn === STEAM_ASN && isSteamGamePort(proto, dstPort, srcPort)) return STEAM
return null
@@ -8,6 +8,9 @@ seedFlowCatalogForTests({
cidrs: [{ cidr: "192.0.2.0/24", purpose: "steam-gaming" },
{ cidr: "198.51.100.0/25", purpose: "Игры" },
{ cidr: "198.51.100.128/25", purpose: "Видео / стриминг" },
{ cidr: "173.194.0.0/16", purpose: "GOOGLE" },
{ cidr: "173.194.1.0/24", purpose: "Work" },
{ cidr: "57.144.0.0/16", purpose: "Meta" },
{ cidr: "203.0.113.128/25", purpose: "main" }],
})
@@ -39,11 +42,11 @@ const google = classifyFlowDst("173.194.160.163", 6, 443, 1, {
ok: true,
fetchedAt: Date.now(),
})
assert.equal(google.service, "Google")
assert.equal(google.category, "Веб")
assert.deepEqual(google, { service: "YouTube", category: "Видео / стриминг", basis: "heuristic" })
assert.equal(classifyFlowDst("173.194.1.1", 17, 443, 50000, null).service, "Work")
const googleCidr = classifyFlowDst("173.194.151.65", 6, 80, 50000, null)
assert.equal(googleCidr.service, "Google")
assert.equal(googleCidr.service, "GOOGLE")
assert.equal(googleCidr.category, "Веб")
const youtube = classifyFlowDst("173.194.160.163", 6, 443, 1, {
@@ -58,6 +61,8 @@ const youtube = classifyFlowDst("173.194.160.163", 6, 443, 1, {
})
assert.equal(youtube.service, "YouTube")
assert.equal(youtube.category, "Видео / стриминг")
assert.equal(youtube.basis, "network")
assert.equal(classifyFlowDst("208.65.153.1", 17, 443, 50000, null).basis, "network")
const valve = classifyFlowDst("203.0.113.40", 17, 27015, 50000, {
prefix: "203.0.113.0/24",
@@ -174,8 +179,7 @@ const instagram = classifyFlowDst("157.240.12.52", 6, 443, 62598, {
ok: true,
fetchedAt: Date.now(),
})
assert.equal(instagram.service, "Meta")
assert.equal(instagram.category, "CDN")
assert.deepEqual(instagram, { service: "Instagram", category: "Видео / стриминг", basis: "heuristic" })
const metaHttp = classifyFlowDst("157.240.12.52", 6, 80, 50000, {
prefix: "157.240.0.0/16",
@@ -201,10 +205,10 @@ const igHolder = classifyFlowDst("203.0.113.80", 6, 443, 1, {
fetchedAt: Date.now(),
})
assert.equal(igHolder.service, "Instagram")
assert.equal(igHolder.basis, "network")
const igCidr = classifyFlowDst("57.144.22.192", 17, 443, 50000, null)
assert.equal(igCidr.service, "Meta")
assert.equal(igCidr.category, "CDN")
assert.deepEqual(igCidr, { service: "Instagram", category: "Видео / стриминг", basis: "heuristic" })
const esp = classifyFlowDst("198.51.100.1", 50, 0, 0, null)
assert.equal(esp.category, "Туннель")
@@ -97,13 +97,14 @@ export function classifyFlowDst(
const prefixPurpose = servicePurpose(matchCidr(dst,opts?.catalog?.cidrs)?.purpose)
const holder = ripe?.holder ?? ""
const brand = resolveFlowBrand(dst, ripe?.asn ?? 0, holder, proto, dstPort, srcPort)
if (prefixPurpose && prefixPurpose.toLowerCase() !== brand?.operator?.toLowerCase()) {
return { service: prefixPurpose, category: categoryFromPurpose(prefixPurpose, proto, dstPort, srcPort), basis: "catalog" }
}
if (brand) return { service: brand.service, category: brand.category, basis: brand.heuristic ? "heuristic" : "network" }
const asnName = ripe?.asn ? servicePurpose((opts?.catalog?.asnPurpose??asnPurpose).get(ripe.asn)) : undefined
const service = prefixPurpose || brand?.service || asnName || OTHER_SERVICE
const category = prefixPurpose
? categoryFromPurpose(prefixPurpose, proto, dstPort, srcPort)
: (brand?.category || categoryFromPurpose(asnName || "", proto, dstPort, srcPort))
const basis = prefixPurpose ? "catalog" : brand ? "network" : asnName ? "catalog" : category !== OTHER_SERVICE ? "port" : "unknown"
return { service, category, basis }
const category = categoryFromPurpose(asnName || "", proto, dstPort, srcPort)
const basis = asnName ? "catalog" : category !== OTHER_SERVICE ? "port" : "unknown"
return { service: asnName || OTHER_SERVICE, category, basis }
}
/** Copies already-observed data only; never fetches the EvoBGP catalog. */
@@ -185,8 +185,8 @@ assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, {
ok: true,
fetchedAt: Date.now(),
}).service, "Google")
assert.equal(mapInternetBrand("64.233.161.1", 17, 443, 50000, null).service, "Google")
assert.equal(mapInternetBrand("142.250.1.10", 6, 443, 1, null).service, "Google")
assert.equal(mapInternetBrand("64.233.161.1", 17, 443, 50000, null).service, "YouTube")
assert.equal(mapInternetBrand("142.250.1.10", 6, 443, 1, null).service, "YouTube")
{
const meta = resolveInternetDest({
@@ -200,7 +200,7 @@ assert.equal(mapInternetBrand("142.250.1.10", 6, 443, 1, null).service, "Google"
topo,
})
assert.equal(meta.dest, "74.125.104.196")
assert.equal(meta.classified.service, "Google")
assert.equal(meta.classified.service, "YouTube")
assert.notEqual(meta.classified.service, "Прочее")
assert.equal(meta.endpoints.direction, "to_client")
assert.equal(meta.endpoints.clientIp, "10.200.100.53")
@@ -117,7 +117,7 @@ assert.equal(v6meta?.asn, 15169)
assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, v6meta).service, "Google")
assert.notEqual(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, v6meta).service, "Прочее")
const cidrYt = mapInternetBrand("64.233.161.1", 17, 443, 50000, resolveFlowIp("64.233.161.1"))
assert.equal(cidrYt.service, "Google")
assert.equal(cidrYt.service, "YouTube")
// ── движок: dims country/asn наполняются из geoip-ридеров ────────────────────
resetEngineForTests()
@@ -114,8 +114,9 @@ const { rows: [snapshot] } = await dbQuery<{id: number}>(`
INSERT INTO internet_path_snapshots(sampled_at,payload_json) VALUES (?,?::jsonb) RETURNING id
`, [new Date(bucket).toISOString(), JSON.stringify({ collectionComplete: true, greTunnels: [
{serverId: "7", name: "gre-jh-en", remoteAddress: "198.51.100.1", enabled: true},
{serverId: "7", name: "SWE-VEESP", remoteAddress: "198.51.100.1", enabled: true},
{serverId: "7", name: "gre-second", remoteAddress: "198.51.100.2", enabled: true},
{serverId: "7", name: "SWE-VEESP", remoteAddress: "198.51.100.1", enabled: true, nativeIndex:4, ifIndex:6, observedNextHops:[{ip:"10.200.100.54", serverId:"9"}]},
{serverId:"7", name:"gre-client", remoteAddress:"192.0.2.77", enabled:true,nativeIndex:5,ifIndex:7},
{serverId: "7", name: "gre-second", remoteAddress: "198.51.100.2", enabled: true, nativeIndex:12, ifIndex:4, observedNextHops:[{ip:"10.200.101.54",serverId:"10"}]},
] })])
const topo: FlowTopology = {
@@ -462,13 +463,13 @@ try {
assert.equal(leak.totalBytes, 30_000)
assert.equal(leak.namedBytes, 10_000)
assert.equal(leak.unclassifiedBytes, 20_000)
const google = leak.services?.find((s) => s.id === "svc:google")
const youtube = leak.services?.find((s) => s.id === "svc:youtube")
const other = leak.services?.find((s) => s.id === "svc:other")
assert.ok(google, "Общий диапазон Google без RIPE")
assert.ok(youtube, "YouTube по общему диапазону Google без RIPE")
assert.ok(other, "dest без бренда → Прочее")
assert.equal(google.bytes, 10_000)
assert.equal(youtube.bytes, 10_000)
assert.equal(other.bytes, 20_000)
assert.ok(Math.abs(google.share - 10 / 30) < 0.01)
assert.ok(Math.abs(youtube.share - 10 / 30) < 0.01)
assert.ok(Math.abs(other.share - 20 / 30) < 0.01)
assert.equal((leak.serviceEdges ?? []).reduce((n, e) => n + e.bytes, 0), hop.bytes)
} finally {
@@ -658,9 +659,9 @@ ingestClosed(7, [
try {
resetFlowMapHopsCacheForTests()
const rev = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
assert.ok(rev.services?.some((s) => s.id === "svc:google"), "Публичная сторона ответного потока относится к Google")
assert.ok(rev.services?.some((s) => s.id === "svc:youtube"), "Ответный поток с порта 443 сети Google учитывается как YouTube")
assert.ok(rev.services?.some((s) => s.id === "svc:cloudflare"), "реверс Cloudflare:443 → 10.x")
assert.ok(rev.serviceEdges?.some((e) => e.toId === "svc:google" && e.fromId === "9"))
assert.ok(rev.serviceEdges?.some((e) => e.toId === "svc:youtube" && e.fromId === "9"))
} finally {
seedFlowTopologyForTests(null)
resetFlowRingsForTests()
@@ -737,9 +738,10 @@ ingestClosed(7, [
try {
resetFlowMapHopsCacheForTests()
const wanOnly = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
assert.equal(wanOnly.services?.find(s => s.id === "svc:google")?.bytes, 9000)
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:google")?.trafficTypes,
[{transport: "TCP", application: "HTTPS", bytes: 9000}])
const youtube = wanOnly.services?.find(s => s.id === "svc:youtube")
assert.equal(youtube?.bytes, 9000)
assert.deepEqual(youtube.serviceEvidence, [{basis: "heuristic", bytes: 9000}])
assert.deepEqual(youtube.trafficTypes, [{transport: "TCP", application: "HTTPS", bytes: 9000}])
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.trafficTypes,
[{transport: "UDP", application: "DNS", bytes: 6000}])
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.serviceEvidence, [{basis: "port", bytes: 6000}])
@@ -1050,7 +1052,8 @@ try {
const clock = mock.method(Date, "now", () => bucket + 90_000)
try {
const map = await buildFlowMapHops({ serverId: 7, minutes: 5, minSharePct: 0 })
assert.equal(map.services?.find(s => s.id === "svc:google")?.bytes, 12000)
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.bytes, 12000)
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, new Date(bucket).toISOString())
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes, Boolean(e.observedOnly)]), [["7", 9000, true], ["10", 2000, false], ["9", 1000, false]])
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 12000)
assert.equal(map.nodeUsers?.["7"]?.find(u => u.clientName === "Alice")?.bytes, 12000)
@@ -1058,8 +1061,51 @@ try {
const recent = await buildFlowMapHops({ serverId: 7, minutes: 1, includeCurrentMinute: true, minSharePct: 0 })
assert.equal(recent.windowSec, 90)
assert.equal(recent.services?.find(s => s.id === "svc:google")?.bps, 900_012_000 * 8 / 90)
const lastMinute = new Date(bucket + 60_000).toISOString()
assert.equal(recent.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, lastMinute)
assert.equal(recent.countryServiceGroups?.flatMap(g => g.services).find(s => s.label === "YouTube")?.lastBucketAt, lastMinute)
assert.equal(recent.services?.find(s => s.id === "svc:youtube")?.bps, 900_012_000 * 8 / 90)
assert.equal(recent.serviceEdges?.find(edge => edge.fromId === "9")?.bps, 900_001_000 * 8 / 90)
const later = bucket + 150_000
clock.mock.mockImplementation(() => later)
ingestParsedFlowsForServerForTests(7, [{ ...flow, bytes: 0, packets: 1, outIface: "ether1" }])
const idle = await buildFlowMapHops({ serverId: 7, minutes: 3, includeCurrentMinute: true, minSharePct: 0 })
assert.equal(idle.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, lastMinute)
resetFlowRingsForTests()
resetFlowMapHopsCacheForTests()
clock.mock.mockImplementation(() => bucket + 90_000)
const forward = { ...flow, src:"10.10.0.1", inIface:"5", outIface:"4", nextHop:"10.200.100.54", bytes:1000 }
const reverse = { ...forward, src:forward.dst, dst:forward.src, srcPort:forward.dstPort, dstPort:forward.srcPort, inIface:"4", outIface:"5", nextHop:"0.0.0.0", bytes:9000 }
ingestClosed(7, [forward, reverse])
rememberServerIfaces(7, [{".id":"*4",name:"ether1"},{".id":"*5",name:"wrong-client"}])
const direct = await buildFlowMapHops({serverId:7, minutes:1, minSharePct:0})
assert.equal(direct.nodeUsers?.["9"]?.find(u => u.clientName === "Alice")?.bytes, 10000)
const own = await buildFlowMapHops({serverId:7, userId:"u1", minutes:1, minSharePct:0})
assert.equal(own.totalBytes, 10000)
assert.deepEqual(direct.serviceEdges?.map(e => [e.fromId,e.bytes]), [["9",10000]])
resetFlowRingsForTests()
resetFlowMapHopsCacheForTests()
ingestClosed(7, [reverse, {...forward, outIface:"ether1", bytes:500}, {...forward, src:"10.10.0.2", outIface:"48", bytes:250}])
const unproven = await buildFlowMapHops({serverId:7, minutes:1, minSharePct:0})
assert.deepEqual(unproven.serviceEdges?.map(e => [e.fromId,e.observedOnly,e.bytes]), [["7",true,9750]])
resetFlowRingsForTests()
resetFlowMapHopsCacheForTests()
ingestClosed(7, [forward, reverse, {...forward, src:"10.10.0.2", nextHop:"10.200.101.54"}])
const ambiguous = await buildFlowMapHops({serverId:7, minutes:1, minSharePct:0})
assert.ok(ambiguous.serviceEdges?.every(e => e.observedOnly), "conflicting paths for one raw index")
const scoped = await buildFlowMapHops({serverId:7,userId:"u1", minutes:1,minSharePct:0})
assert.equal(scoped.totalBytes,0, "a conflicting interface namespace cannot establish client scope")
resetFlowRingsForTests()
resetFlowMapHopsCacheForTests()
clock.mock.mockImplementation(() => bucket + 150_000)
ingestClosed(7, [forward])
ingestClosed(7, [reverse], bucket + 60_000)
const otherMinute = await buildFlowMapHops({serverId:7,minutes:2,minSharePct:0})
assert.equal(otherMinute.serviceEdges?.find(e => e.fromId === "9")?.bytes, 1000)
assert.equal(otherMinute.serviceEdges?.find(e => e.observedOnly)?.bytes, 9000)
} finally { clock.mock.restore() }
} finally {
await dbQuery("DELETE FROM internet_path_snapshots WHERE id=?", [snapshot.id])
@@ -1067,6 +1113,31 @@ try {
seedFlowTopologyForTests(null)
}
// A video download can arrive in an earlier receipt minute than the latest HTTPS traffic.
seedFlowTopologyForTests(topo)
try {
const youtube = (bytes: number) => ({ ...payloadFlow("173.194.151.65", bytes), proto: 17 })
ingestClosed(7, [youtube(224_932_500)], bucket - 120_000)
ingestClosed(7, [youtube(67_500), payloadFlow("104.18.35.51", 69_075_000)], bucket)
const clock = mock.method(Date, "now", () => bucket + 90_000)
try {
const query = { serverId: 7, minSharePct: 0 }
const recent = await buildFlowMapHops({ ...query, minutes: 1, includeCurrentMinute: true })
assert.equal(recent.services?.find(s => s.id === "svc:youtube")?.bps, 6_000)
assert.equal(recent.services?.find(s => s.id === "svc:cloudflare")?.bps, 6_140_000)
const map = await buildFlowMapHops({ ...query, minutes: 5 })
assert.equal(map.windowSec, 300)
const video = map.services?.find(s => s.id === "svc:youtube")
assert.equal(video?.bytes, 225_000_000)
assert.equal(video.bps, 6_000_000)
assert.equal(map.services?.find(s => s.id === "svc:cloudflare")?.bytes, 69_075_000)
} finally { clock.mock.restore() }
} finally {
resetFlowRingsForTests()
seedFlowTopologyForTests(null)
}
// Captured on the test CHR. Three 64-byte UDP packets traversed GRE A -> GRE B.
// RouterOS also exported three 88-byte outer GRE packets on GRE B -> underlay.
const datagram = Buffer.from(
+104 -34
View File
@@ -1,3 +1,4 @@
import { FlowSourceWindowTooLarge, FlowSqlSourceTooLarge } from "./traffic-flow-read-window.js"
import { flowReadDbAll } from "./traffic-flow-read-policy.js"
import { isDeepStrictEqual } from "node:util"
import { readFlowMapSourceLimits } from "./traffic-flow-source-limits.js"
@@ -19,7 +20,7 @@ import { resolveFlowEndpoints } from "./traffic-flow-ip.js"
import { geoipReadersStatus, resolveFlowIp } from "./traffic-flow-geoip.js"
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
import { loadFlowTopology, resolveFlowClient, flowClientInterfaces, getServerCatalog, type FlowClientBinding } from "./traffic-flow-topology.js"
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM } from "./traffic-flow-engine.js"
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM, minuteBucketIso } from "./traffic-flow-engine.js"
export const DEFAULT_MAP_SERVICE_MIN_SHARE_PCT = 5
export const MAP_SERVICE_NODE_CAP = 20
@@ -74,6 +75,7 @@ interface FromAcc {
interface DstAcc {
dst: string
bytes: number
lastBucketAt: string
proto: number
dstPort: number
srcPort: number
@@ -85,6 +87,7 @@ interface DestTotal {
label: string
category: string
bytes: number
lastBucketAt: string
trafficTypes?: Map<string, NonNullable<FlowMapService["trafficTypes"]>[number]>
serviceEvidence?: Map<FlowServiceBasis, number>
}
@@ -159,10 +162,11 @@ export function pickMapServices(
.slice(0, cap)
}
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number,
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number, lastBucketAt: string,
detail?: { transport: string; application: string | null; basis: FlowServiceBasis }): void {
const total = totals.get(id) ?? { label, category, bytes: 0 }
const total = totals.get(id) ?? { label, category, bytes: 0, lastBucketAt }
total.bytes += bytes
if (lastBucketAt > total.lastBucketAt) total.lastBucketAt = lastBucketAt
if (detail && bytes > 0) {
const { transport, application, basis } = detail
const types = total.trafficTypes ??= new Map()
@@ -249,6 +253,7 @@ function finalizeDestLayer(
label: s.label,
category: s.category,
bytes: s.bytes,
...(s.lastBucketAt ? { lastBucketAt: minuteBucketIso(Date.parse(s.lastBucketAt)) } : {}),
bps: (s.bytes * 8) / windowSec,
share: shareBase > 0 ? s.bytes / shareBase : 0,
...(s.trafficTypes ? { trafficTypes: [...s.trafficTypes.values()].sort((a, b) => b.bytes - a.bytes).slice(0, 5) } : {}),
@@ -444,16 +449,49 @@ async function readInterfaceTraffic(serverIds: number[], iface: string, q: FlowM
}
// Interface names are local to the exporter; match them against the GRE inventory for the flow minute.
async function readMapGrePeers(rows: { serverId: number; bucketAt: string; inIface: string; outIface: string }[]) {
async function readMapGrePeers(rows: { serverId: number; bucketAt: string; inIface: string; outIface: string; nextHop: string }[]) {
const peers = new Map<string, Map<string, string>>()
if (!rows.length) return peers
const buckets = new Set<string>(), names = new Set<string>()
const nextHops = new Map<string, { serverId: number; iface: string; native: number | null; explicit: number | null } | null>()
const ingress = new Map<string, { serverId: number; iface: string } | null>()
const names = new Map<string, string>()
const namespace = new Map<string, number>()
const keyFor = (bucket: string, server: number | string) => JSON.stringify([bucket, String(server)])
const ifaceName = (row: typeof rows[number], raw: string) => {
const key = keyFor(row.bucketAt, row.serverId)
const mode = namespace.get(key)
const cached = resolveIfaceName(row.serverId, raw).name
if (!/^[1-9][0-9]*$/.test(raw)) return cached
const native = names.get(JSON.stringify([key, 1, Number(raw)]))
const explicit = names.get(JSON.stringify([key, 2, Number(raw)]))
if (mode === 1 || mode === 2) {
const exact = mode === 1 ? native : explicit
if (exact !== undefined) return exact || "#" + raw
if (native !== undefined || explicit !== undefined) return "#" + raw
}
// The current alias cache cannot resolve conflicting historical interface identities.
if ([native, explicit].some(name => name !== undefined && name !== cached)) return "#" + raw
return cached
}
if (!rows.length) return { peers, nextHops, ingress, ifaceName }
const buckets = new Set<string>()
for (const row of rows) {
buckets.add(row.bucketAt)
for (const iface of [row.inIface, row.outIface]) names.add(row.serverId + "|" + resolveIfaceName(row.serverId, iface).name)
}
const bindings = await flowReadDbAll<{ bucket: string; key: string; remote: string }>(`
SELECT b.bucket, (t->>'serverId') || '|' || (t->>'name') AS key, t->>'remoteAddress' AS remote
const targets = new Set<string>()
const hops = new Set<string>()
for (const row of rows) {
for (const raw of [row.inIface, row.outIface]) {
targets.add(row.serverId + "|" + raw)
targets.add(row.serverId + "|" + resolveIfaceName(row.serverId, raw).name)
}
if (row.nextHop && row.nextHop !== "0.0.0.0" && row.nextHop !== "::") hops.add(row.serverId + "|" + row.nextHop)
}
const bindings = await flowReadDbAll<{ bucket: string; key: string; remote: string; owner: string; iface: string; native: number | null; explicit: number | null; next_hops: Array<{ip: string; serverId: string}> }>(`
SELECT b.bucket, (t->>'serverId') || '|' || (t->>'name') AS key, t->>'remoteAddress' AS remote,
t->>'serverId' AS owner, t->>'name' AS iface, t->'nativeIndex' AS native, t->'ifIndex' AS explicit,
(SELECT COALESCE(jsonb_agg(p), '[]'::jsonb) FROM jsonb_array_elements(CASE WHEN jsonb_typeof(t->'observedNextHops')='array'
THEN t->'observedNextHops' ELSE '[]'::jsonb END) AS p
WHERE p->>'serverId' ~ '^[1-9][0-9]*$' AND p->>'ip' <> '') AS next_hops
FROM unnest(?::text[]) AS b(bucket)
CROSS JOIN LATERAL (
SELECT payload_json FROM internet_path_snapshots
@@ -464,15 +502,43 @@ async function readMapGrePeers(rows: { serverId: number; bucketAt: string; inIfa
CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(payload_json->'greTunnels')='array'
THEN payload_json->'greTunnels' ELSE '[]'::jsonb END) AS t
WHERE payload_json->>'collectionComplete'='true' AND t->>'serverId' ~ '^[1-9][0-9]*$'
AND ((t->>'serverId') || '|' || (t->>'name'))=ANY(?::text[])
AND (EXISTS (SELECT 1 FROM unnest(ARRAY[t->>'name',t->>'nativeIndex',t->>'ifIndex']) AS idx
WHERE (t->>'serverId') || '|' || idx = ANY(?::text[]))
OR EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(t->'observedNextHops')='array'
THEN t->'observedNextHops' ELSE '[]'::jsonb END) AS p WHERE (t->>'serverId') || '|' || (p->>'ip') = ANY(?::text[])))
AND t->>'enabled'='true' AND t->>'name'<>'' AND t->>'remoteAddress'<>''
`, [[...buckets], [...names]])
`, [[...buckets], [...targets], [...hops]]).catch(error => {
if (error instanceof FlowSqlSourceTooLarge) throw new FlowSourceWindowTooLarge()
throw error
})
for (const row of bindings) {
const interfaces = peers.get(row.bucket) ?? new Map<string, string>()
interfaces.set(row.key, interfaces.has(row.key) ? "" : row.remote.trim().toLowerCase())
peers.set(row.bucket, interfaces)
const ownerKey = keyFor(row.bucket, row.owner)
for (const [mode, index] of [[1, row.native], [2, row.explicit]] as const) {
if (!index) continue
const key = JSON.stringify([ownerKey, mode, index])
names.set(key, names.has(key) ? "" : row.iface)
}
for (const peer of row.next_hops) {
const key = JSON.stringify([row.bucket, row.owner, peer.ip])
nextHops.set(key, nextHops.has(key) ? null : { serverId: Number(peer.serverId), iface: row.iface, native: row.native, explicit: row.explicit })
}
}
return peers
// Bind raw IPFIX indexes only to a directly observed next hop for this exporter and minute.
for (const row of rows) {
if (!/^[1-9][0-9]*$/.test(row.outIface)) continue
const peer = nextHops.get(JSON.stringify([row.bucketAt, String(row.serverId), row.nextHop]))
if (peer === undefined) continue
const key = JSON.stringify([row.bucketAt, row.serverId, row.outIface])
const prev = ingress.get(key)
const mode = (peer?.native === Number(row.outIface) ? 1 : 0) | (peer?.explicit === Number(row.outIface) ? 2 : 0)
const ownerKey = keyFor(row.bucketAt, row.serverId)
namespace.set(ownerKey, (namespace.get(ownerKey) ?? 3) & mode)
ingress.set(key, !peer || !mode || prev === null || prev && (prev.serverId !== peer.serverId || prev.iface !== peer.iface) ? null : peer)
}
return { peers, nextHops, ingress, ifaceName }
}
async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number, scope?: ScopedFlowAnalyticsRead): Promise<FlowMapHopsDto> {
@@ -501,33 +567,33 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
const allow = q.userId ? flowClientInterfaces(topo, q.userId) : null
if (scope && allow && !allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
const { peers, nextHops, ingress, ifaceName } = await readMapGrePeers(raw)
function rowClient(r: (typeof raw)[number]) {
return resolveFlowClient(topo, r.serverId, resolveIfaceName(r.serverId, r.inIface).name, resolveIfaceName(r.serverId, r.outIface).name)
return resolveFlowClient(topo, r.serverId, ifaceName(r, r.inIface), ifaceName(r, r.outIface))
}
const matches = (serverId: number, iface: string) =>
flowRowMatchesFilter({ serverId, inIface: iface }, resolveIfaceName(serverId, iface).name, q, allow)
const matches = (r: (typeof raw)[number], iface: string) =>
flowRowMatchesFilter({ serverId: r.serverId, inIface: iface }, ifaceName(r, iface), q, allow)
const selected = raw.filter(r => (!q.userId || rowClient(r)?.userId === q.userId) &&
(matches(r.serverId, r.inIface) || matches(r.serverId, r.outIface)))
(matches(r, r.inIface) || matches(r, r.outIface)))
const { rows } = collapseGreEspRows(selected, r => {
if (ifaceFilter) {
const ingress = matches(r.serverId, r.inIface), egress = matches(r.serverId, r.outIface)
const ingress = matches(r, r.inIface), egress = matches(r, r.outIface)
return ingress === egress ? null : ingress ? "rx" : "tx"
}
return flowRateDirection(r.serverId, r, topo, catalog.byId.get(r.serverId)?.host)
})
const matched = []
for (const r of rows) {
const resolved = resolveIfaceName(r.serverId, r.inIface)
const outResolved = resolveIfaceName(r.serverId, r.outIface)
const plane = classifyFlowPlane({
src: r.src,
dst: r.dst,
proto: r.proto,
srcPort: r.srcPort,
dstPort: r.dstPort,
inIface: resolved.name,
outIface: outResolved.name,
inIface: ifaceName(r, r.inIface),
outIface: ifaceName(r, r.outIface),
}, topo.plane)
if (!shouldKeepPlane(plane, { excludeMesh, excludeOverlay })) continue
matched.push(r)
@@ -545,7 +611,7 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
hostIds.set(key, previous === undefined || previous === node.id ? node.id : null)
}
await authorize()
const peers = await readMapGrePeers(working)
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>
@@ -555,10 +621,8 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
let totalBytes = 0
for (const r of working) {
const inRes = resolveIfaceName(r.serverId, r.inIface)
const outRes = resolveIfaceName(r.serverId, r.outIface)
const inName = inRes.name
const outName = outRes.name
const inName = ifaceName(r, r.inIface)
const outName = ifaceName(r, r.outIface)
const fromId = String(r.serverId)
const fromLabel = nameById.get(r.serverId) ?? fromId
const wanSet = topo.wanIfaces.get(r.serverId)
@@ -600,8 +664,13 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
const bindings = peers.get(r.bucketAt)
const outPeer = bindings?.get(fromId + "|" + outName)
const outId = outPeer === undefined ? hostIds.get(r.nextHop) : hostIds.get(outPeer)
const inId = hostIds.get(bindings?.get(fromId + "|" + inName) ?? "")
const nextHop = nextHops.get(JSON.stringify([r.bucketAt, fromId, r.nextHop]))
const verifiedOutput = nextHop && (r.outIface === nextHop.iface || ingress.get(JSON.stringify([r.bucketAt, r.serverId, r.outIface]))?.iface === nextHop.iface)
const outId = nextHop === undefined ? (outPeer === undefined ? hostIds.get(r.nextHop) : hostIds.get(outPeer))
: verifiedOutput && enIds.has(nextHop.serverId) ? nextHop.serverId : undefined
const input = ingress.get(JSON.stringify([r.bucketAt, r.serverId, r.inIface]))
const inId = input === undefined ? hostIds.get(bindings?.get(fromId + "|" + inName) ?? "")
: input && enIds.has(input.serverId) ? input.serverId : undefined
const peerId = outId && inId && outId !== inId ? null : outId ?? inId
const endpoints = resolveFlowEndpoints({
src: r.src,
@@ -617,7 +686,7 @@ 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 serviceSide = endpoints.internetPeer ? (reverse ? inId : outId) : undefined
const exitId = enIds.has(r.serverId) ? r.serverId : serviceSide ?? undefined
const serviceIface = reverse ? inName : outName
const otherIface = reverse ? outName : inName
@@ -630,7 +699,7 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
if (peerId && peerId !== r.serverId) {
const toId = String(peerId)
const dir = outId === peerId ? "fwd" : "rev"
const greIface = dir === "fwd" && ifaceUsable(outName) ? outName : (ifaceUsable(inName) ? inName : undefined)
const greIface = dir === "fwd" ? nextHop?.iface ?? (ifaceUsable(outName) ? outName : undefined) : input?.iface ?? (ifaceUsable(inName) ? inName : undefined)
bump(hops, JSON.stringify(["gre", fromId, toId, greIface]), {
fromId,
fromLabel,
@@ -704,8 +773,9 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
const srcPort = ep.otherPort || r.srcPort
const application = flowPortApplication(r.proto, dstPort) ?? flowPortApplication(r.proto, srcPort)
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : JSON.stringify([r.proto, application])
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, proto: r.proto, dstPort, srcPort, application, fromBytes: new Map<string, FromAcc>() }
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, lastBucketAt: "", proto: r.proto, dstPort, srcPort, application, fromBytes: new Map<string, FromAcc>() }
acc.bytes += bytes
if (bytes > 0 && r.bucketAt > acc.lastBucketAt) acc.lastBucketAt = r.bucketAt
bumpFrom(acc, String(r.serverId), exitId === undefined ? "" : String(exitId), viaIface, bytes, reverse, client)
dstAcc.set(destKey, acc)
}
@@ -739,11 +809,11 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
: OTHER_BRAND
const svcId = mapServiceNodeId(classified.service)
const detail = { transport: protoName(acc.proto), application: acc.application, basis: classified.basis }
bumpDestTotal(svcTotals, svcId, classified.service, classified.category, acc.bytes, detail)
bumpDestTotal(svcTotals, svcId, classified.service, classified.category, acc.bytes, acc.lastBucketAt, detail)
const country = countryDestFromRipe(ripe, dst)
bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes)
bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes, acc.lastBucketAt)
const nestedId = mapCountryServiceNodeId(country.id, svcId)
bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes, detail)
bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes, acc.lastBucketAt, detail)
for (const from of acc.fromBytes.values()) {
const { exporterId, enId: fromId } = from
const enName = nodeName(fromId)
+17 -5
View File
@@ -22,6 +22,7 @@ const evidenceLabel: Record<FlowServiceBasis, string> = {
catalog: "По каталогу",
network: "По IP / ASN",
port: "По протоколу / порту",
heuristic: "Оценка по сети и порту",
unknown: "Сервис не определён",
}
const percent = new Intl.NumberFormat("ru-RU", {style: "percent", maximumFractionDigits: 1})
@@ -111,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<string>
@@ -156,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))
@@ -180,9 +186,9 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
</header>
<div className="mx-0.5 mb-0.5 min-h-0 overflow-y-auto rounded-lg border">
<InspectorMetrics rows={[
["Скорость", formatNetflowRate({ bps: service.bps }), "Средняя скорость NetFlow за " + windowLabel],
[country ? "Доля страны" : "Доля трафика", percent.format(service.share)],
["Объём · " + (currentVolume ? windowLabel : volume?.window ?? "24 ч"), <>{currentVolume ? formatBytes(service.bytes) : volume?.bytes == null ? "—" : formatBytes(volume.bytes)}{volume && <time dateTime={volume.at} title={new Date(volume.at).toLocaleString("ru-RU")} className="block text-[10px] font-normal text-muted-foreground">ответ {new Date(volume.at).toLocaleTimeString("ru-RU")}</time>}</>],
["Средняя за " + averageWindow, average ? formatNetflowRate(average) : "—", "Скорость по сохранённым потокам IPFIX"],
[shareOfVisible ? "Доля показанных сервисов" : country ? "Доля страны" : "Доля трафика", percent.format(service.share), "IPFIX · " + windowLabel],
["Объём · " + (currentVolume ? averageWindow : volume?.window ?? "24 ч"), <>{volumeBytes == null ? "—" : formatBytes(volumeBytes)}{!currentVolume && volume && <time dateTime={volume.at} title={new Date(volume.at).toLocaleString("ru-RU")} className="block text-[10px] font-normal text-muted-foreground">ответ {new Date(volume.at).toLocaleTimeString("ru-RU")}</time>}</>],
exitIds.length || !exporterIds.length
? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined]
: ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"],
@@ -197,8 +203,14 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
{otherTypeBytes > 0 && <div className="flex justify-between gap-2"><dt>Остальные типы</dt><dd className="font-mono tabular-nums">{typeShare(otherTypeBytes)}</dd></div>}
</dl>
{trafficTypes.some(row => row.application) && <p className="text-muted-foreground">Приложения определены по портам.</p>}
{service.lastBucketAt && <p className="text-muted-foreground">Последняя минута с потоками <time dateTime={service.lastBucketAt} className="font-mono">{new Date(service.lastBucketAt).toLocaleTimeString("ru-RU", {hour: "2-digit", minute: "2-digit"})}</time></p>}
{serviceEvidence.length ? <ul aria-label="Основание классификации" className="flex flex-wrap gap-1">
{serviceEvidence.map(row => <li key={row.basis}><Badge size="sm" variant="secondary">{evidenceLabel[row.basis]}{serviceEvidence.length > 1 && ` · ${typeShare(row.bytes)}`}</Badge></li>)}
{serviceEvidence.map(row => <li key={row.basis}>
<Badge size="sm" variant={row.basis === "heuristic" ? "info-light" : "secondary"}
title={row.basis === "heuristic" ? "Сервис предполагается по сети назначения и порту 443" : undefined}>
{evidenceLabel[row.basis]}{serviceEvidence.length > 1 && ` · ${typeShare(row.bytes)}`}
</Badge>
</li>)}
</ul> : null}
</section>}
<InspectorUsers users={serviceUsers(service, paths)} windowLabel={windowLabel} />
+10 -4
View File
@@ -22,9 +22,15 @@ 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,
trafficTypes: [{transport: "UDP", application: "DNS", bytes: 100}]}
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}))
assert.equal(scopeMapDestinations([service], edges, [], id => id === "1").services[0]?.trafficTypes, undefined)
assert.deepEqual(scopeMapDestinations([service], edges, [], () => true).services[0]?.trafficTypes, service.trafficTypes)
const partial = scopeMapDestinations([service], edges, [], id => id === "1").services[0]
const complete = scopeMapDestinations([service], edges, [], () => true).services[0]
assert.equal(partial?.trafficTypes, undefined)
assert.equal(partial?.lastBucketAt, undefined)
assert.deepEqual(complete?.trafficTypes, service.trafficTypes)
assert.equal(complete?.lastBucketAt, service.lastBucketAt)
assert.equal(complete.share, 0.4)
assert.equal(partial.share, 1)
})
+22 -19
View File
@@ -1,27 +1,30 @@
import type { MapBox } from "./network-map-layout"
import type { MapBox, MapLink } from "./network-map-layout"
type Point = { x: number; y: number }
/** Routes IPFIX around cards. A missing route leaves the observation available in service details. */
export function mapObservationRoute(start: Point, end: Point, boxes: readonly MapBox[], usedTracks: readonly number[]) {
if (end.x - start.x < 44) return null
const padding = 8
const obstacles = boxes.filter(box => box.x + box.w > start.x && box.x < end.x)
const first = Math.min(start.x + 20, ...obstacles.map(box => box.x - padding))
const last = Math.max(end.x - 20, ...obstacles.map(box => box.x + box.w + padding))
if (first <= start.x || last >= end.x || last - first < 34) return null
const middle = (start.y + end.y) / 2
const candidates = [middle, start.y, end.y, ...obstacles.flatMap(box => [box.y - 16, box.y + box.h + 16])]
const legal = candidates.flatMap(y => [y, y - 14, y + 14, y - 28, y + 28])
.filter(y => obstacles.every(box => y < box.y - padding || y > box.y + box.h + padding))
/** Find a clear horizontal track between the sides facing the connection after dragging. */
export function mapObservationRoute(link: MapLink, boxes: readonly MapBox[], usedTracks: readonly number[]) {
const { x1, y1, x2, y2, cx } = link
const stub = (x: number) => x + Math.sign(cx - x) * Math.min(20, Math.abs(cx - x))
const first = stub(x1), last = stub(x2)
const middle = (y1 + y2) / 2
const obstacles = boxes.filter(box => box.x < Math.max(x1, first, last, x2) && box.x + box.w > Math.min(x1, first, last, x2))
const crosses = (a: number, b: number, low: number, size: number) => Math.min(a, b) < low + size && Math.max(a, b) > low
const horizontal = (a: number, b: number, y: number) =>
obstacles.some(box => y > box.y && y < box.y + box.h && crosses(a, b, box.x, box.w))
const vertical = (x: number, a: number, b: number) =>
obstacles.some(box => x > box.x && x < box.x + box.w && crosses(a, b, box.y, box.h))
if (horizontal(x1, first, y1) || horizontal(last, x2, y2)) return null
const candidates = [middle, y1, y2, ...obstacles.flatMap(box => [box.y - 16, box.y + box.h + 16]),
...usedTracks.flatMap(y => [y - 18, y + 18])]
const legal = candidates.filter(y => !vertical(first, y1, y) && !horizontal(first, last, y) && !vertical(last, y, y2))
.sort((a, b) => Math.abs(a - middle) - Math.abs(b - middle) || a - b)
const y = legal.find(candidate => usedTracks.every(track => Math.abs(candidate - track) >= 18))
const markerX = (first + last) / 2
const markerFits = (y: number) => !boxes.some(box => crosses(markerX - 17, markerX + 17, box.x, box.w) && crosses(y - 7, y + 7, box.y, box.h))
const y = legal.find(candidate => markerFits(candidate) && usedTracks.every(track => Math.abs(candidate - track) >= 18)) ?? legal[0]
if (y === undefined) return null
return {
d: `M ${start.x} ${start.y} H ${first} V ${y} H ${last} V ${end.y} H ${end.x}`,
marker: { x: (first + last) / 2, y },
d: `M ${x1} ${y1} H ${first} V ${y} H ${last} V ${y2} H ${x2}`,
marker: markerFits(y) ? { x: markerX, y } : undefined,
track: y,
}
}
+7 -2
View File
@@ -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)
@@ -46,9 +46,14 @@ test("map Flow envelope retains zeros and refuses missing metadata and contradic
assert.throws(()=>networkMapFlowSchema.parse({...shorter,rangeMinutes:1,windowSec:60}))
assert.throws(()=>networkMapFlowSchema.parse({...shorter,windowSec:300}))
const recent={...empty,rangeMinutes:1,windowSec:90.125,includesCurrentMinute:true}
assert.equal(networkMapFlowSchema.parse(recent).windowSec,90.125)
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})
+10 -6
View File
@@ -27,14 +27,18 @@ 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 =>
(data.includesCurrentMinute
? !data.sourceWindow && data.rangeMinutes === 1 && data.windowSec >= 60 && data.windowSec < 120
: data.windowSec === data.rangeMinutes * 60 && (data.sourceWindow
? data.sourceWindow.requestedMinutes === 5 && data.sourceWindow.effectiveMinutes === data.rangeMinutes
: data.rangeMinutes === 5)) &&
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)
)
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)
const requested=new Set(hosts.map(host=>host.toLowerCase()))
+6 -3
View File
@@ -53,13 +53,16 @@ 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, ...destination } = service
return [{ ...destination, ...total, share: bytes ? total.bytes / bytes : 0,
...(total.bytes === service.bytes ? { trafficTypes, serviceEvidence } : {}) }]
const { trafficTypes, serviceEvidence, lastBucketAt, ...destination } = service
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,
paths: visiblePaths,
+3 -2
View File
@@ -366,7 +366,7 @@ export const flowMapHopDtoSchema = z.object({
bpsRev: z.number().nonnegative(),
})
export const flowServiceBasisSchema = z.enum(["catalog", "network", "port", "unknown"])
export const flowServiceBasisSchema = z.enum(["catalog", "network", "heuristic", "port", "unknown"])
export type FlowServiceBasis = z.infer<typeof flowServiceBasisSchema>
export const flowMapServiceDtoSchema = z.object({
@@ -376,6 +376,7 @@ export const flowMapServiceDtoSchema = z.object({
bytes: z.number().nonnegative(),
bps: z.number().nonnegative(),
share: z.number().min(0).max(1),
lastBucketAt: z.string().datetime().optional(),
trafficTypes: z.array(z.object({
transport: z.string(),
application: z.string().nullable(),
@@ -384,7 +385,7 @@ export const flowMapServiceDtoSchema = z.object({
serviceEvidence: z.array(z.object({
basis: flowServiceBasisSchema,
bytes: z.number().positive(),
})).max(4).optional(),
})).max(flowServiceBasisSchema.options.length).optional(),
})
export const flowMapServiceEdgeDtoSchema = z.object({
+11
View File
@@ -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,
}
}
+8 -8
View File
@@ -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<void>(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)
})
+17 -11
View File
@@ -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<void>(resolve => { release = resolve })
let wait = new Promise<void>(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<void>(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()
})
+112 -27
View File
@@ -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=1m&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,26 +72,104 @@ test("Карта и трафик сохраняют пользователя и
await expect(panel.getByText("Нет потоков с подтверждённой привязкой к пользователю.")).toBeVisible()
})
test("Карта показывает скорость и долю за короткое окно и отдельные пять минут для выбранного пользователя", async ({page}) => {
const users = [mapUser("alice", "Алиса"), mapUser("boris", "Борис")]
const ratesByScope: Record<string, {recent: number; average: number}> = {
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<string, unknown> = {
"/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}
const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1,
trafficTypes: [{transport: "UDP", application: "QUIC", bytes: 900000}],
serviceEvidence: [{basis: "heuristic", bytes: 900000}], lastBucketAt: "2026-11-26T18:30:00.000Z"}
const edge = {fromId: "1", toId: service.id, bytes: 300000, bps: 8000, bpsFwd: 2000, bpsRev: 6000}
let known = false
await page.route("**/api/**", route => {
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("1m")
const responses: Record<string, unknown> = {
"/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] ?? {}})
})
await page.goto("/network-map")
await page.getByRole("button", {name: "Сервис YouTube", exact: true}).press("Enter")
const composition = page.getByRole("region", {name: "Состав трафика IPFIX"})
await expect(composition.getByText("Оценка по сети и порту")).toBeVisible()
await expect(composition.locator("time")).toHaveAttribute("datetime", service.lastBucketAt)
await expect(page.getByText("IPFIX · среднее за 1 мин 30 с")).toBeVisible()
const unknown = page.getByText("Выход не определён", {exact: true}).locator("..")
const badges = page.locator("[data-map-ribbon] > title")
await expect(unknown).toContainText("24 Кбит/с")
@@ -116,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}],
} : {}})
@@ -189,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" }] },
@@ -249,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")
@@ -265,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 } : {} })
})
@@ -283,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)
@@ -309,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<void>(resolve=>{release=resolve})
const ranges: string[] = [];let release!:()=>void;const gate=new Promise<void>(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()
})
+2 -2
View File
@@ -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")
+2 -2
View File
@@ -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 } : {} })
})
})
+47 -2
View File
@@ -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<typeof
await page.route("**/api/**", (r) => {
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 })
})
@@ -105,6 +105,51 @@ test("Карта: группа сервисов сворачивается на
await page.screenshot({path:info.outputPath("карта-сети.png")})
})
test("Связи Cloudflare остаются на гранях экспортёра и подтверждённого выхода при перетаскивании", async ({ page }) => {
const service = { id: "svc:cloudflare", label: "Cloudflare", category: "Cloud", bytes: 10000, bps: 800, share: 1 }
const edge = { toId: service.id, bytes: 5000, bps: 400, bpsFwd: 400, bpsRev: 0 }
await serve(page, [srv(1, "nov-gw01", "jump-host"), srv(2, "ARN", "exit-node")], [], {
services: [service], serviceEdges: [{ ...edge, fromId: "1", observedOnly: true }, { ...edge, fromId: "2" }],
namedBytes: service.bytes, totalBytes: service.bytes,
})
await page.goto("/network-map")
const map = page.getByRole("group", { name: "Интерактивная карта сети" })
const arn = map.getByRole("button", { name: "Устройство ARN" })
const cloudflare = map.getByRole("button", { name: "Сервис Cloudflare" })
const exporter = map.getByRole("button", { name: "Устройство nov-gw01" })
await expect(cloudflare).toBeVisible()
async function attached() {
const connections = await map.evaluate(svg => {
const card = (name: string) => svg.querySelector(`[aria-label="${name}"] [data-map-box]`)!.getBoundingClientRect()
const atSide = (p: DOMPoint, r: DOMRect) =>
Math.min(Math.abs(p.x - r.left), Math.abs(p.x - r.right)) < 1 && Math.abs(p.y - (r.top + r.bottom) / 2) < 1
return [...svg.querySelectorAll<SVGPathElement>("[data-map-route]")].map(path => {
const transform = path.getScreenCTM()!
const start = path.getPointAtLength(0).matrixTransform(transform)
const end = path.getPointAtLength(path.getTotalLength()).matrixTransform(transform)
const source = path.dataset.mapRoute === "observation" ? "Устройство nov-gw01" : "Устройство ARN"
return atSide(start, card(source)) && atSide(end, card("Сервис Cloudflare"))
})
})
expect(connections).toEqual([true, true])
}
await attached()
async function center(node: typeof arn) {
const rect = (await node.boundingBox())!
return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }
}
const a = await center(arn)
await arn.dragTo(map, { targetPosition: { x: a.x - (await map.boundingBox())!.x + 30, y: a.y - (await map.boundingBox())!.y - 65 } })
expect(Math.abs((await center(arn)).y - a.y)).toBeGreaterThan(20)
await attached()
// Same column: before the fix the IPFIX route was replaced by a disconnected dot.
const jh = await center(exporter)
const bounds = (await map.boundingBox())!
await cloudflare.dragTo(map, {targetPosition: {x: jh.x - bounds.x, y: jh.y - bounds.y + 85}})
expect(Math.abs((await center(cloudflare)).x - (await center(exporter)).x)).toBeLessThan(15)
await attached()
})
test("Карта: сетка JH × Exit и аплинки WAN без наложений подписей", async ({ page }) => {
const wan = (i: number) => ({ id: "w" + i, name: "WAN" + i, iface: "ether" + i, isp: "ISP-" + i, ip: `198.51.100.${i}`, maxDl: 100, maxUl: 50 })
const servers = [
+2 -2
View File
@@ -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")
+12
View File
@@ -1,6 +1,7 @@
import { test } from "node:test"
import assert from "node:assert/strict"
import { MAP_CARD_H, MAP_CARD_W, MAP_PILL_H, mapLinkPath, mapLinkPoint, mapRibbons, placeMapLinkLabels, type MapBox } from "../../lib/network-map-layout"
import { mapObservationRoute } from "../../lib/network-map-observation-route"
const card = (x: number, y: number): MapBox => ({ x: x - MAP_CARD_W / 2, y: y - MAP_CARD_H / 2, w: MAP_CARD_W, h: MAP_CARD_H })
const hit = (a: MapBox, b: MapBox) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
@@ -13,6 +14,17 @@ test("кривая связи проходит через концы и сере
assert.deepEqual(mapLinkPoint(l, 0.5), { x: 100, y: 50 })
})
test("наблюдение IPFIX огибает промежуточный узел в обоих направлениях", () => {
const blocker = card(400, 100)
for (const [sourceX, serviceX] of [[100, 800], [800, 100]]) {
const link = mapLinkPath({x: sourceX, y: 100}, 80, {x: serviceX, y: 100}, 140)
const route = mapObservationRoute(link, [blocker], [])
assert.ok(route)
assert.ok(route.d.startsWith(`M ${link.x1} 100 `) && route.d.endsWith(`H ${link.x2}`))
assert.ok(route.track < blocker.y || route.track > blocker.y + blocker.h)
}
})
test("подписи не наезжают на карточки и друг на друга, длинная — укорачивается или пропадает", () => {
// Три JH слева сходятся в один EN справа; у каждой пары — длинный и короткий вариант подписи.
const jh = [100, 180, 260].map((y) => ({ x: 542, y }))