diff --git a/app/(main)/network-map/page.tsx b/app/(main)/network-map/page.tsx index b4059297..d0324f0a 100644 --- a/app/(main)/network-map/page.tsx +++ b/app/(main)/network-map/page.tsx @@ -85,9 +85,9 @@ import { import { isFreshMapTrafficSample, useMapInterfaceTraffic } from "@/hooks/use-map-interface-traffic" import { useTrafficLive } from "@/hooks/use-traffic-live" import { formatBytes } from "@/lib/fmt-rate" -import type { FlowMapCountryServiceGroup, FlowMapInterfaceTraffic, FlowMapHop, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow" +import type { FlowMapCountryServiceGroup, FlowMapHopsDto, FlowMapInterfaceTraffic, FlowMapHop, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow" import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon" -import { InspectorMetrics, NodeHistory, ServiceInspector } from "@/components/network-map/inspector-traffic" +import { InspectorMetrics, InspectorUsers, NodeHistory, ServiceInspector, serviceUsers } from "@/components/network-map/inspector-traffic" import { Spinner } from "@/components/ui/spinner" import { CountryFlagSvg } from "@/components/network-map/country-flag-svg" import { Button } from "@/components/ui/button" @@ -100,7 +100,7 @@ import { CableIcon, ActivityIcon, } from "lucide-react" import { cn } from "@/lib/utils" -import { formatServicePathLabel, formatServicePathTitle } from "@/lib/format-service-path-label" +import { formatServicePathLabel, formatServicePathTitle, servicePathKey } from "@/lib/format-service-path-label" import Link from "next/link" import { MapBottomPanel, MapTimeline, type MapBottomTab, type MapEventRow } from "@/components/network-map/map-bottom-panel" import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" @@ -364,11 +364,8 @@ function destDisplayLabel(node: FlowMapService | undefined, mode: DestMode, fall return countryName(node.label) } -function servicePathKey(p: Pick): string { - return `${p.clientId}|${p.viaId}|${p.enId}|${p.serviceId}` -} - function greMatchesPath(e: GreMapEdge, h: { viaId: string; enId: string }): boolean { + if (!h.enId || h.viaId === h.enId) return false const ids = new Set([e.fromServer.id, e.toServer.id]) return ids.has(h.viaId) && ids.has(h.enId) } @@ -636,7 +633,7 @@ function ServicePathList({ paths: FlowMapServicePath[] servers: Server[] services: FlowMapService[] - highlight: { viaId: string; enId: string; serviceId: string } | null + highlight: FlowMapServicePath | null viaMode: "via" | "service" destMode: DestMode onToggle: (p: FlowMapServicePath) => void @@ -652,18 +649,15 @@ function ServicePathList({ const en = servers.find((s) => s.id === p.enId) const svc = services.find((s) => s.id === p.serviceId) const destLabel = destDisplayLabel(svc, destMode, p.serviceId) - const label = formatServicePathLabel(p, viaMode, { + const label = p.enId ? formatServicePathLabel(p, viaMode, { viaName: via?.name, viaSite: via?.site, enName: en?.name, serviceLabel: destLabel, - }) + }) : [p.viaName || p.viaId, p.viaIface, "наблюдение IPFIX"].filter(Boolean).join(" · ") const title = formatServicePathTitle(label, destLabel) const active = Boolean( - highlight - && highlight.viaId === p.viaId - && highlight.enId === p.enId - && highlight.serviceId === p.serviceId, + highlight && servicePathKey(highlight) === rowKey, ) return ( })} - {rates.filter(e => !paths.some(p => p.enId === e.fromId)).map(e =>
{exitName(e.fromId)} → {service.label}{formatNetflowRate({bps:e.bps})}
)} + {rates.filter(e => !paths.some(p => (p.enId || p.viaId) === e.fromId && Boolean(p.enId) !== Boolean(e.observedOnly))).map(e =>
{exitName(e.fromId)} → {service.label}{e.observedOnly && " · наблюдение IPFIX"}{formatNetflowRate(e)}
)} {remainder > 0 &&
Выход не определён{formatNetflowRate({bps:service.bps * remainder / service.bytes})}
} {!paths.length && !rates.length && !remainder &&

Маршрут не определён

} diff --git a/components/network-map/map-bottom-panel.tsx b/components/network-map/map-bottom-panel.tsx index 3aea1dc7..ffebbea7 100644 --- a/components/network-map/map-bottom-panel.tsx +++ b/components/network-map/map-bottom-panel.tsx @@ -71,7 +71,7 @@ export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, e - +
{flows.map((r) => ( {r.client} diff --git a/lib/format-service-path-label.ts b/lib/format-service-path-label.ts index 06818df2..895155af 100644 --- a/lib/format-service-path-label.ts +++ b/lib/format-service-path-label.ts @@ -43,3 +43,7 @@ export function formatServicePathTitle(label: string, serviceLabel: string): str if (label.includes(svc)) return label return `${label} · ${svc}` } + +export function servicePathKey(p: { clientId: string; viaId: string; viaIface?: string; enId: string; serviceId: string }): string { + return JSON.stringify([p.clientId, p.viaId, p.viaIface, p.enId, p.serviceId]) +} diff --git a/lib/network-map-response.ts b/lib/network-map-response.ts index d674a0fb..313a0ef9 100644 --- a/lib/network-map-response.ts +++ b/lib/network-map-response.ts @@ -27,7 +27,7 @@ export function validateNetworkMapSnapshot(servers:unknown,gre:unknown,probes:un import {flowMapHopsDtoSchema} from "@mmapp/contracts/traffic-flow" import {isIpv4String} from "./gre-endpoint-resolve" -export const networkMapFlowSchema = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true, includesCurrentMinute: true }).refine(data => +export const networkMapFlowSchema = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true, includesCurrentMinute: true, nodeUsers: true }).refine(data => (data.includesCurrentMinute ? !data.sourceWindow && data.rangeMinutes === 1 && data.windowSec >= 60 && data.windowSec < 120 : data.windowSec === data.rangeMinutes * 60 && (data.sourceWindow diff --git a/packages/contracts/src/traffic-flow.ts b/packages/contracts/src/traffic-flow.ts index e1c5cd9c..b99dbdcd 100644 --- a/packages/contracts/src/traffic-flow.ts +++ b/packages/contracts/src/traffic-flow.ts @@ -388,6 +388,7 @@ export const flowMapServiceEdgeDtoSchema = z.object({ id: z.string(), name: z.string(), })).optional(), + observedOnly: z.literal(true).optional(), }) export const flowMapServicePathDtoSchema = z.object({ @@ -395,6 +396,8 @@ export const flowMapServicePathDtoSchema = z.object({ clientName: z.string(), viaId: z.string(), viaName: z.string(), + viaIface: z.string().optional(), + /** Empty when IPFIX identified the exporter but the exit could not be inferred. */ enId: z.string(), enName: z.string(), serviceId: z.string(), @@ -412,6 +415,12 @@ export const flowMapCountryServiceGroupDtoSchema = z.object({ export const flowMapHopsDtoSchema = z.object({ sourceWindow: flowSourceWindowSchema.optional(), + nodeUsers: z.record(z.string(), z.array(z.object({ + clientId: z.string(), + clientName: z.string(), + bytes: z.number().nonnegative(), + bps: z.number().nonnegative(), + }))).optional(), includesCurrentMinute: z.literal(true).optional(), /** Link counters include private routed payload. Mesh visibility applies to the inferred graph. */ interfaceTraffic: z.array(z.object({ @@ -463,3 +472,4 @@ export type FlowMapServicePath = z.infer export type FlowMapCountryServiceGroup = z.infer export type FlowMapHopsDto = z.infer export type FlowMapInterfaceTraffic = NonNullable[number] +export type FlowMapUser = NonNullable[string][number] diff --git a/tests/e2e/network-map-detail.spec.ts b/tests/e2e/network-map-detail.spec.ts index 086c7fd9..f0516d13 100644 --- a/tests/e2e/network-map-detail.spec.ts +++ b/tests/e2e/network-map-detail.spec.ts @@ -19,7 +19,11 @@ test("Карта: открытые детали обновляются вмес }) test("Карта: модель WAN не утверждает активный маршрут и RTT линии",async({page})=>{ await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})}) - await page.goto("/network-map");await page.locator("[data-map-legend] summary").click();await expect(page.getByText("Пунктир WAN→JH — модель связности; маршрут не подтверждён.",{exact:true})).toBeVisible();await page.locator("[data-map-legend] summary").click() + await page.goto("/network-map") + const legend = page.getByRole("button", {name:"Легенда",exact:true}) + await legend.click() + await expect(page.getByText("Пунктир WAN→JH — модель связности; маршрут не подтверждён.",{exact:true})).toBeVisible() + await legend.click() await expect(page.locator("svg text").filter({hasText:/^5 мс$/})).toHaveCount(0) await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Домашний",{exact:true}).click() await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:"Интерфейсы"}).click();await expect(page.getByText("Аплинк каталога",{exact:true})).toBeVisible();await expect(page.getByText("Модель связей с JH · Ping модели",{exact:true})).toBeVisible() diff --git a/tests/e2e/network-map-flow.spec.ts b/tests/e2e/network-map-flow.spec.ts index 2c61b87a..e8b3fad4 100644 --- a/tests/e2e/network-map-flow.spec.ts +++ b/tests/e2e/network-map-flow.spec.ts @@ -37,6 +37,41 @@ test("Карта не приписывает весь YouTube единствен await expect(badges).toContainText("↓6 Кбит/с ↑2 Кбит/с") }) +test("Карта: DNS виден от экспортёра, пользователи разбиты в обеих карточках", async ({page}) => { + const router = {...server, name: "MSK", type: "jump-host"} + const dns = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 300000, bps: 8000, share: 1} + const users = [ + {clientId: "u1", clientName: "Алиса", bytes: 225000, bps: 6000}, + {clientId: "—", clientName: "—", bytes: 75000, bps: 2000}, + ] + const servicePaths = users.map(u => ({...u, viaId: "1", viaName: "MSK", viaIface: "ether1", enId: "", enName: "", serviceId: dns.id})) + await page.route("**/api/**", route => { + const url = new URL(route.request().url()) + const path = url.pathname + return route.fulfill({json: path === "/api/auth/config" ? {required: false} + : path === "/api/servers" ? [router] : path === "/api/filters/gre-tunnels" ? {tunnels: [], failures: []} + : path === "/api/uptime/speed-probes" ? {probes: []} : path === flowPath ? { + ...empty, + ...(url.searchParams.get("range") === "24h" ? {rangeMinutes: 1440, windowSec: 86400} : {}), + totalBytes: dns.bytes, services: [dns], servicePaths, nodeUsers: {"1": users}, + serviceEdges: [{fromId: "1", toId: dns.id, observedOnly: true, bytes: dns.bytes, bps: dns.bps, bpsFwd: 0, bpsRev: dns.bps}], + } : {}}) + }) + await page.goto("/network-map") + await expect(page.locator("[data-map-ribbon][data-observation] > title")).toContainText("MSK → DNS") + await page.getByRole("button", {name: "Сервис DNS", exact: true}).press("Enter") + const panel = page.getByRole("complementary", {name: "Детали объекта карты"}) + const breakdown = panel.getByRole("region", {name: "Трафик по пользователям"}) + await expect(breakdown.getByText("Алиса", {exact: true}).locator("..")).toContainText("6 Кбит/с") + await expect(breakdown.getByText("Без привязки к пользователю")).toBeVisible() + await expect(panel.getByText("Экспортёр", {exact: true})).toBeVisible() + await expect(panel.getByText(/интерфейс ether1 · выход не подтверждён/i).first()).toBeVisible() + await panel.getByRole("button").filter({hasText: /Алиса.*Наблюдение IPFIX/}).click() + await expect(panel.getByRole("button", {pressed: true}).filter({hasText: "Наблюдение IPFIX"})).toHaveCount(1) + await page.getByRole("button", {name: "Устройство MSK", exact: true}).press("Enter") + await expect(breakdown.getByText("Алиса", {exact: true}).locator("..")).toContainText("75%") +}) + for (const reverse of [false, true]) test(`Карта: малый NetFlow и текущие RX/TX GRE показаны отдельно, reverse=${reverse}`, async ({ page }) => { const exit = { ...server, name: "ARN", type: "exit-node" } const jump = { ...server, id: 2, name: "MSK-02", host: "192.0.2.2", type: "jump-host" } diff --git a/tests/e2e/network-map-legend.spec.ts b/tests/e2e/network-map-legend.spec.ts index 5075cf83..128dc9dc 100644 --- a/tests/e2e/network-map-legend.spec.ts +++ b/tests/e2e/network-map-legend.spec.ts @@ -17,20 +17,30 @@ test.beforeEach(async ({ page }) => { test("Карта: раскрытая легенда объясняет статусы, типы, линии и неизвестные измерения", async ({ page }) => { await page.goto("/network-map") + const trigger = page.getByRole("button", { name: "Легенда", exact: true }) const legend = page.getByRole("region", { name: "Легенда карты" }) await expect(legend).not.toBeVisible() - await page.locator("[data-map-legend] summary").click() + await trigger.click() await expect(legend).toBeVisible() + const firstStatus = legend.getByText("Онлайн", { exact: true }) + await expect.poll(() => firstStatus.evaluate(element => { + const { x, y, width, height } = element.getBoundingClientRect() + const hit = document.elementFromPoint(x + width / 2, y + height / 2) + return hit !== null && element.contains(hit) + })).toBe(true) for (const text of ["Онлайн", "Внимание", "Оффлайн", "Неизвестно", "JumpHost", "Exit Node", "Home Router", "GRE + IPsec", "Лента NetFlow · толщина = скорость"]) await expect(legend.getByText(text, { exact: true })).toBeVisible() await expect(legend).toContainText("нет измерения") await expect(legend).toContainText("последний замер RX/TX интерфейса RouterOS") await expect(legend).toContainText("среднюю скорость по принятым записям IPFIX") - await page.locator("[data-map-legend] summary").click() + await trigger.click() await expect(legend).not.toBeVisible() - await page.locator("[data-map-legend] summary").press("Enter") + await trigger.press("Enter") await expect(legend).toBeVisible() await legend.getByText("Онлайн", { exact: true }).click() await page.screenshot({ path: "tmp/map270-desktop.png" }) + await page.keyboard.press("Escape") + await expect(legend).not.toBeVisible() + await expect(trigger).toBeFocused() }) test("Карта: мышь не рисует прямоугольную рамку, клавиатурный фокус остаётся видимым", async ({ page }) => { @@ -52,15 +62,16 @@ test("Карта: мышь не рисует прямоугольную рамк test("Карта: легенда помещается на телефоне и сворачивается", async ({ page }) => { await page.setViewportSize({ width: 390, height: 844 }) await page.goto("/network-map") + const trigger = page.getByRole("button", { name: "Легенда", exact: true }) const legend = page.getByRole("region", { name: "Легенда карты" }) - await expect(page.locator("[data-map-legend]")).not.toHaveAttribute("open", "") + await expect(trigger).toHaveAttribute("aria-expanded", "false") await page.screenshot({ path: "tmp/map270-mobile.png" }) - await page.locator("[data-map-legend] summary").click() + await trigger.click() await expect(legend).toBeVisible() const bounds = await legend.boundingBox() expect(bounds!.x).toBeGreaterThanOrEqual(0) expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(390) - await page.locator("[data-map-legend] summary").click() + await trigger.click() await expect(legend).not.toBeVisible() })