feat(network-map): добавить сворачивание групп и категории трафика
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Successful in 11m8s
Docker images / frontend-image (push) Successful in 2m25s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 2m1s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Successful in 11m8s
Docker images / frontend-image (push) Successful in 2m25s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 2m1s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
This commit is contained in:
1 parent
37025f1f94
commit
545a9bbcd2
24 files changed
+1607
-352
No files matched your search
@@ -0,0 +1,13 @@
|
||||
import type { FlowMapService, FlowServiceBasis } from "@mmapp/contracts/traffic-flow"
|
||||
|
||||
export const unknownTrafficCategory = "Не определена"
|
||||
|
||||
type Classification = Pick<FlowMapService, "serviceEvidence">
|
||||
|
||||
export function mapTrafficCategory(service: Classification & { category?: string; serviceBasis?: FlowServiceBasis }, path?: Classification): string {
|
||||
const category = service.category?.trim()
|
||||
const evidence = (path ?? service).serviceEvidence
|
||||
if (!category || category === "Прочее" || (path ? !evidence?.length : service.serviceBasis === "unknown")) return unknownTrafficCategory
|
||||
if (evidence?.length && evidence.every(row => row.basis === "unknown")) return unknownTrafficCategory
|
||||
return category
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import type { GreTunnel, Server } from "./data"
|
||||
import { densityWanKey, projectNetworkMapDensity } from "./network-map-density"
|
||||
import { collectGroupLinks } from "./network-map-group-links"
|
||||
import { buildGreMapEdges, computeNetworkMapLayout, MAP_CARD_H, MAP_WAN_H } from "./network-map-layout"
|
||||
|
||||
function server(id: string, type: Server["type"], site: string, wanCount = 0): Server {
|
||||
return {
|
||||
id, name: id, type, site, enabled: true, status: "online", host: id, country: "", asn: "", os: "", model: "",
|
||||
sessions: 0, latency: null, wanUplinks: Array.from({ length: wanCount }, (_, i) => ({
|
||||
id: String(i), name: "WAN " + i, isp: "", iface: "ether" + i, ip: "", maxDl: 100, maxUl: 100,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
test("12 узлов и 12 WAN сворачиваются независимо, раскрытый столбец растёт без наложений", () => {
|
||||
const home = server("hr", "home-router", "Москва", 12)
|
||||
const members = Array.from({ length: 12 }, (_, i) => server("jh" + i, "jump-host", "Москва"))
|
||||
members[5].status = "offline"
|
||||
members[7].status = "degraded"
|
||||
members[9].status = "unknown"
|
||||
const separate = server("other-site", "jump-host", "Новосибирск")
|
||||
const exit = server("en", "exit-node", "Москва")
|
||||
const servers = [home, ...members, separate, exit]
|
||||
const base = computeNetworkMapLayout(servers)
|
||||
const project = (expanded: string[], reveal?: Parameters<typeof projectNetworkMapDensity>[4]) =>
|
||||
projectNetworkMapDensity(servers, base.nodePos, base.wanSatPos, new Set(expanded), reveal)
|
||||
const closed = project([])
|
||||
const [role, wan] = closed.groups
|
||||
assert.equal(closed.groups.length, 2)
|
||||
assert.deepEqual([role.count, role.problemCount, role.unknownCount, role.expanded], [12, 2, 1, false])
|
||||
assert.deepEqual([wan.count, wan.routerId, wan.expanded], [12, home.id, false])
|
||||
assert.equal(closed.hiddenServers.size, 12)
|
||||
assert.equal(closed.hiddenWans.size, 12)
|
||||
assert.deepEqual(closed.nodePos[exit.id], base.nodePos[exit.id])
|
||||
assert.deepEqual(closed.nodePos.jh6, { x: role.x, y: role.y })
|
||||
assert.deepEqual(closed.wanSatPos.hr[4], { x: wan.x, y: wan.y })
|
||||
|
||||
const found = project([], { serverIds: new Set(["jh6"]) })
|
||||
assert.equal(found.hiddenServers.size, 0)
|
||||
assert.equal(found.hiddenWans.size, 12)
|
||||
const open = project([role.id], { wanKeys: new Set([densityWanKey(home.id, 4)]) })
|
||||
assert.equal(open.hiddenServers.size + open.hiddenWans.size, 0)
|
||||
const [roleHeader, wanHeader] = open.groups
|
||||
function assertSpacing(ys: number[], minGap: number) {
|
||||
ys.sort((a, b) => a - b)
|
||||
for (let i = 1; i < ys.length; i++) assert.ok(ys[i] - ys[i - 1] >= minGap)
|
||||
}
|
||||
assertSpacing([roleHeader.y, ...[...members, separate].map(s => open.nodePos[s.id].y)], MAP_CARD_H + 12)
|
||||
assertSpacing([wanHeader.y, ...open.wanSatPos.hr.map(p => p.y)], MAP_WAN_H + 12)
|
||||
assert.deepEqual(base, computeNetworkMapLayout(servers))
|
||||
assert.deepEqual(project([]), closed)
|
||||
})
|
||||
|
||||
test("шесть однотипных устройств и аплинков остаются отдельными, поиск WAN раскрывает обе родительские группы", () => {
|
||||
const six = Array.from({ length: 6 }, (_, i) => server("hr" + i, "home-router", "", 0))
|
||||
six[0] = server("hr0", "home-router", "—", 6)
|
||||
const project = (servers: Server[], wanKeys?: Set<string>) => {
|
||||
const base = computeNetworkMapLayout(servers)
|
||||
return projectNetworkMapDensity(servers, base.nodePos, base.wanSatPos, new Set(), { wanKeys })
|
||||
}
|
||||
assert.equal(project(six).groups.length, 0)
|
||||
const seven = [...six, server("hr6", "home-router", "", 7)]
|
||||
const closed = project(seven)
|
||||
assert.equal(closed.groups.length, 1)
|
||||
assert.equal(closed.groups[0].label, "Без площадки · Домашние роутеры")
|
||||
assert.equal(closed.hiddenWans.get(densityWanKey("hr6", 3)), closed.groups[0].id)
|
||||
const found = project(seven, new Set([densityWanKey("hr6", 3)]))
|
||||
assert.equal(found.groups.length, 2)
|
||||
assert.ok(found.groups.every(g => g.expanded))
|
||||
assert.equal(found.hiddenServers.size + found.hiddenWans.size, 0)
|
||||
})
|
||||
|
||||
test("обычная колонка сохраняет все координаты вплоть до касания и ручного сдвига по X", () => {
|
||||
const servers = [server("h", "home-router", "A", 3), server("j", "jump-host", "A"), server("k", "jump-host", "B"),
|
||||
server("e", "exit-node", "A"), server("x", "ix-node", "B")]
|
||||
const nodePos = { h: { x: 133, y: -3 }, j: { x: 401, y: 170 }, k: { x: 562, y: 170 },
|
||||
e: { x: 692, y: 280 }, x: { x: 690, y: 280 + MAP_CARD_H } }
|
||||
const wanSatPos = { h: [{ x: 310, y: 3 }, { x: 311, y: 3 + MAP_WAN_H }, { x: 495, y: 3 + MAP_WAN_H }] }
|
||||
const unchanged = projectNetworkMapDensity(servers, nodePos, wanSatPos, new Set())
|
||||
assert.deepEqual(unchanged.nodePos, nodePos)
|
||||
assert.deepEqual(unchanged.wanSatPos, wanSatPos)
|
||||
})
|
||||
|
||||
test("колонка с пересечениями между площадками раздвигается без ложного группирования", () => {
|
||||
const servers = Array.from({ length: 12 }, (_, i) => server("j" + i, "jump-host", "site" + Math.floor(i / 4)))
|
||||
const base = computeNetworkMapLayout(servers)
|
||||
const layout = projectNetworkMapDensity(servers, base.nodePos, base.wanSatPos, new Set())
|
||||
assert.equal(layout.groups.length, 0)
|
||||
const ys = Object.values(layout.nodePos).map(p => p.y).sort((a, b) => a - b)
|
||||
assert.ok(ys.slice(1).every((y, i) => y - ys[i] >= MAP_CARD_H + 12))
|
||||
})
|
||||
|
||||
test("обратный отчёт GRE привязан к нужному WAN, группа считает физические каналы и отказ", () => {
|
||||
const home = server("hr","home-router","Москва",12)
|
||||
home.wanUplinks![1].ip = "192.0.2.2"
|
||||
const jh = server("jh","jump-host","Москва")
|
||||
jh.host = "192.0.2.7"
|
||||
const pair = [home,jh]
|
||||
const base = computeNetworkMapLayout(pair)
|
||||
const reverse: GreTunnel = {
|
||||
id:"jh-report",name:"gre-hr",serverId:jh.id,localAddress:jh.host,remoteAddress:home.wanUplinks![1].ip,
|
||||
localInnerIp:"198.51.100.1",remoteInnerIp:"198.51.100.2",poolId:"",ipsec:null,mtu:1476,keepaliveInterval:0,
|
||||
keepaliveRetries:3,dscp:"inherit",clampTcpMss:true,allowFastPath:true,comment:"",enabled:true,status:"up",
|
||||
}
|
||||
const reports: GreTunnel[] = [reverse, {...reverse,id:"hr-report",serverId:home.id,localAddress:reverse.remoteAddress,
|
||||
remoteAddress:reverse.localAddress,localInnerIp:reverse.remoteInnerIp,remoteInnerIp:reverse.localInnerIp},
|
||||
{...reverse,id:"second",localInnerIp:"198.51.100.5",remoteInnerIp:"198.51.100.6"},
|
||||
{...reverse,id:"third",localInnerIp:"198.51.100.9",remoteInnerIp:"198.51.100.10",status:"down"}]
|
||||
const edges = buildGreMapEdges(reports,pair,base.nodePos,base.wanSatPos)
|
||||
assert.equal(edges.length,3)
|
||||
for (const edge of edges) {
|
||||
assert.equal(edge.fromServer.id,home.id)
|
||||
assert.equal(edge.fromWanIndex,1)
|
||||
assert.deepEqual(edge.from,base.wanSatPos.hr[1])
|
||||
}
|
||||
const [group] = projectNetworkMapDensity(pair,base.nodePos,base.wanSatPos,new Set()).groups
|
||||
const [bundle] = collectGroupLinks(edges.map(gre => ({type:"gre",gre,
|
||||
from:{...group,name:group.label,groupId:group.id,halfWidth:80},to:{...gre.to,id:jh.id,name:jh.name,halfWidth:80}})))
|
||||
assert.deepEqual([bundle.count,bundle.down,bundle.degraded],[3,1,0])
|
||||
})
|
||||
@@ -0,0 +1,158 @@
|
||||
import type { Server, ServerType } from "./data"
|
||||
import { MAP_CARD_H, MAP_CARD_W, MAP_LANES, MAP_WAN_H, MAP_WAN_W, NETWORK_MAP_PIPELINE_Y } from "./network-map-layout"
|
||||
|
||||
export interface MapPoint { x: number; y: number }
|
||||
|
||||
export interface DensityGroup extends MapPoint {
|
||||
id: string
|
||||
kind: "role" | "wan"
|
||||
type: ServerType
|
||||
site: string
|
||||
label: string
|
||||
count: number
|
||||
problemCount: number
|
||||
unknownCount: number
|
||||
serverIds: string[]
|
||||
routerId?: string
|
||||
expanded: boolean
|
||||
}
|
||||
|
||||
export function densityWanKey(serverId: string, index: number) {
|
||||
return `${serverId}:${index}`
|
||||
}
|
||||
|
||||
const groupLimit = 6
|
||||
const roleLane = { "home-router": "home", "jump-host": "jh", "exit-node": "en", "ix-node": "en" } as const
|
||||
const roleLabel = { "home-router": "Домашние роутеры", "jump-host": "Узлы доступа", "exit-node": "Интернет-выходы", "ix-node": "IX" } as const
|
||||
type Lane = "home" | "jh" | "en" | "wan"
|
||||
type Row = { point: MapPoint; height: number; place: (point: MapPoint) => void }
|
||||
type Block = { id: string; center: number; rows: Row[]; grouped?: boolean }
|
||||
|
||||
// Keep a group's header with its children; the world may grow below the original viewport.
|
||||
function placeColumn(blocks: Block[], width: number) {
|
||||
const gap = 12
|
||||
blocks.sort((a, b) => a.center - b.center || a.id.localeCompare(b.id))
|
||||
const needsLayout = blocks.some(block => block.grouped) || blocks.some(({ rows: [row] }, i) => {
|
||||
for (let j = i - 1; j >= 0; j--) {
|
||||
const previous = blocks[j].rows[0]
|
||||
if (row.point.y - previous.point.y >= row.height) break
|
||||
if (Math.abs(row.point.x - previous.point.x) < width) return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
if (!needsLayout) {
|
||||
for (const { rows: [row] } of blocks) row.place(row.point)
|
||||
return
|
||||
}
|
||||
let bottom = 40
|
||||
for (const { center, rows } of blocks) {
|
||||
const height = rows.reduce((sum, row) => sum + row.height, gap * (rows.length - 1))
|
||||
let top = Math.max(bottom + gap, center - height / 2)
|
||||
for (const row of rows) {
|
||||
row.place({ x: row.point.x, y: top + row.height / 2 })
|
||||
top += row.height + gap
|
||||
}
|
||||
bottom = top - gap
|
||||
}
|
||||
}
|
||||
|
||||
export function projectNetworkMapDensity(
|
||||
servers: readonly Server[],
|
||||
baseNodePos: Record<string, MapPoint>,
|
||||
baseWanPos: Record<string, MapPoint[]>,
|
||||
expanded: ReadonlySet<string>,
|
||||
reveal: { serverIds?: ReadonlySet<string>; wanKeys?: ReadonlySet<string> } = {},
|
||||
) {
|
||||
const groups: DensityGroup[] = []
|
||||
const hiddenServers = new Map<string, string>()
|
||||
const hiddenWans = new Map<string, string>()
|
||||
const nodePos = { ...baseNodePos }
|
||||
const wanSatPos = { ...baseWanPos }
|
||||
const columns: Record<Lane, Block[]> = { home: [], jh: [], en: [], wan: [] }
|
||||
const cohorts = new Map<string, Server[]>()
|
||||
const siteOf = (s: Server) => s.site?.trim() === "—" ? "" : s.site?.trim() || ""
|
||||
const serverPoint = (s: Server) => baseNodePos[s.id] ?? { x: MAP_LANES[roleLane[s.type]].cx, y: NETWORK_MAP_PIPELINE_Y }
|
||||
const serverRow = (s: Server): Row => ({
|
||||
point: serverPoint(s), height: MAP_CARD_H, place: p => { nodePos[s.id] = p },
|
||||
})
|
||||
const groupRow = (g: DensityGroup): Row => ({
|
||||
point: g, height: MAP_CARD_H, place: p => { g.x = p.x; g.y = p.y },
|
||||
})
|
||||
const revealWan = (s: Server) => s.wanUplinks?.some((_, index) => reveal.wanKeys?.has(densityWanKey(s.id, index)))
|
||||
|
||||
for (const s of servers) {
|
||||
const id = `role:${s.type}:${siteOf(s)}`
|
||||
const cohort = cohorts.get(id)
|
||||
if (cohort) cohort.push(s)
|
||||
else cohorts.set(id, [s])
|
||||
}
|
||||
for (const [id, members] of cohorts) {
|
||||
const first = members[0], column = columns[roleLane[first.type]]
|
||||
if (members.length <= groupLimit) {
|
||||
for (const s of members) column.push({ id: s.id, center: serverPoint(s).y, rows: [serverRow(s)] })
|
||||
continue
|
||||
}
|
||||
const site = siteOf(first)
|
||||
const center = members.reduce((ys, s) => ys + serverPoint(s).y, 0) / members.length
|
||||
const open = expanded.has(id) || members.some(s => reveal.serverIds?.has(s.id) || revealWan(s))
|
||||
const group: DensityGroup = {
|
||||
id, kind: "role", type: first.type, site, label: `${site || "Без площадки"} · ${roleLabel[first.type]}`,
|
||||
count: members.length, expanded: open, x: serverPoint(first).x, y: center,
|
||||
problemCount: members.filter(s => s.status === "offline" || s.status === "degraded").length,
|
||||
unknownCount: members.filter(s => s.status === "unknown").length, serverIds: members.map(s => s.id),
|
||||
}
|
||||
groups.push(group)
|
||||
const rows = [groupRow(group)]
|
||||
if (open) {
|
||||
for (const s of members.sort((a, b) => a.name.localeCompare(b.name, "ru", { numeric: true }) || a.id.localeCompare(b.id))) rows.push(serverRow(s))
|
||||
} else {
|
||||
for (const s of members) hiddenServers.set(s.id, id)
|
||||
}
|
||||
column.push({ id, center, rows, grouped: true })
|
||||
}
|
||||
for (const lane of ["home", "jh", "en"] as const) placeColumn(columns[lane], MAP_CARD_W)
|
||||
const groupById = new Map(groups.map(g => [g.id, g]))
|
||||
for (const [serverId, groupId] of hiddenServers) {
|
||||
const { x, y } = groupById.get(groupId)!
|
||||
nodePos[serverId] = { x, y }
|
||||
}
|
||||
|
||||
for (const router of servers) {
|
||||
const uplinks = router.wanUplinks ?? []
|
||||
if (router.type !== "home-router" || !uplinks.length) continue
|
||||
wanSatPos[router.id] = [...(baseWanPos[router.id] ?? [])]
|
||||
const ownerGroup = hiddenServers.get(router.id)
|
||||
if (ownerGroup) {
|
||||
uplinks.forEach((_, index) => {
|
||||
hiddenWans.set(densityWanKey(router.id, index), ownerGroup)
|
||||
wanSatPos[router.id][index] = nodePos[router.id]
|
||||
})
|
||||
continue
|
||||
}
|
||||
const rows: Row[] = uplinks.map((_, index) => ({
|
||||
point: baseWanPos[router.id]?.[index] ?? { x: MAP_LANES.wan.cx, y: nodePos[router.id].y },
|
||||
height: MAP_WAN_H, place: p => { wanSatPos[router.id][index] = p },
|
||||
}))
|
||||
if (rows.length <= groupLimit) {
|
||||
rows.forEach((row, i) => columns.wan.push({ id: densityWanKey(router.id, i), center: row.point.y, rows: [row] }))
|
||||
continue
|
||||
}
|
||||
const id = "wan:" + router.id
|
||||
const open = expanded.has(id) || Boolean(revealWan(router))
|
||||
const group: DensityGroup = {
|
||||
id, kind: "wan", type: router.type, site: siteOf(router), label: "WAN · " + router.name, routerId: router.id,
|
||||
count: rows.length, expanded: open, x: rows[0].point.x, y: nodePos[router.id].y, serverIds: [router.id],
|
||||
// The WAN catalog has no per-uplink operational status.
|
||||
problemCount: 0, unknownCount: rows.length,
|
||||
}
|
||||
groups.push(group)
|
||||
const header = groupRow(group)
|
||||
if (!open) {
|
||||
uplinks.forEach((_, index) => hiddenWans.set(densityWanKey(router.id, index), id))
|
||||
header.place = p => { group.y = p.y; rows.forEach(row => row.place(p)) }
|
||||
}
|
||||
columns.wan.push({ id, center: group.y, rows: open ? [header, ...rows] : [header], grouped: true })
|
||||
}
|
||||
placeColumn(columns.wan, MAP_WAN_W)
|
||||
return { groups, hiddenServers, hiddenWans, nodePos, wanSatPos }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { strict as assert } from "node:assert"
|
||||
import { test } from "node:test"
|
||||
import type { FlowMapService, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import { groupMapCategories, mapCategoryId, smallMapServices } from "./network-map-destinations"
|
||||
import { readNetworkMapUrl } from "./network-map-url-state"
|
||||
|
||||
const service: FlowMapService = { id: "s", label: "Example", category: "Видео", bytes: 100, bps: 80, share: 0.4 }
|
||||
const path: FlowMapServicePath = { clientId: "a", clientName: "A", viaId: "1", viaName: "Вход", enId: "", enName: "", serviceId: "s", bytes: 100, bps: 80 }
|
||||
const edge = { fromId: "1", toId: "s", bytes: 100, bps: 80, bpsFwd: 30, bpsRev: 50 }
|
||||
|
||||
test("category drilldown preserves partial evidence, the source window and route certainty", () => {
|
||||
const serviceEvidence = [{ basis: "network" as const, bytes: 60 }, { basis: "unknown" as const, bytes: 40 }]
|
||||
const second = { ...service, id: "second", bytes: 25, bps: 20, share: 0.1 }
|
||||
const layer = groupMapCategories([{ ...service, serviceEvidence }, second], [
|
||||
{ ...edge, observedOnly: true },
|
||||
{ ...edge, toId: second.id, bytes: 25, bps: 20, bpsFwd: 15, bpsRev: 5 },
|
||||
], [{ ...path, serviceEvidence }, { ...path, serviceId: second.id, enId: "1", bytes: 25, bps: 20 }])
|
||||
const video = mapCategoryId("Видео"), unknown = mapCategoryId("Не определена")
|
||||
assert.deepEqual(layer.services.map(s => [s.id, s.bytes, s.bps]), [[video, 85, 68], [unknown, 40, 32]])
|
||||
assert.ok(Math.abs(layer.services[0].share - 0.34) < Number.EPSILON)
|
||||
assert.deepEqual(layer.members.get(video)?.map(s => [s.id, s.bytes]), [["s", 60], ["second", 25]])
|
||||
assert.deepEqual(layer.paths.get(unknown)?.map(p => [p.enId, p.serviceId, p.bytes]), [["", "s", 40]])
|
||||
assert.deepEqual(layer.edges.filter(e => e.toId === video).map(e => [!!e.observedOnly, e.bytes, e.bpsFwd]), [[true, 60, 0], [false, 25, 15]])
|
||||
assert.equal(readNetworkMapUrl(new URLSearchParams("dest=categories&user=a")).dest, "categories")
|
||||
})
|
||||
|
||||
test("services at exactly ten percent collapse only for a known share in the current scope", () => {
|
||||
const items = [0.09, 0.10, 0.1001, 0.01].map((share, i) => ({...service, id: String(i), share}))
|
||||
assert.deepEqual(smallMapServices(items, true, "0", "3").map(s => s.id), ["1"])
|
||||
assert.deepEqual(smallMapServices(items, false, null, null), [])
|
||||
assert.deepEqual(smallMapServices([{ ...items[0], share: 0.9 }], true, null, null), [])
|
||||
})
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import { mapTrafficCategory, unknownTrafficCategory } from "./map-traffic-category"
|
||||
|
||||
export function mapCategoryId(label: string) {
|
||||
return "category:" + label
|
||||
}
|
||||
|
||||
/** Source node and route certainty stay separate when several destinations share a link. */
|
||||
export function groupDestinationEdges(edges: FlowMapServiceEdge[], target: (serviceId: string) => string | undefined) {
|
||||
const grouped = new Map<string, FlowMapServiceEdge>()
|
||||
const missingDirection = new Set<string>()
|
||||
for (const edge of edges) {
|
||||
const toId = target(edge.toId)
|
||||
if (!toId) continue
|
||||
const key = JSON.stringify([edge.fromId, toId, Boolean(edge.observedOnly)])
|
||||
const total = grouped.get(key) ?? {
|
||||
fromId: edge.fromId, toId, bytes: 0, bps: 0, bpsFwd: 0, bpsRev: 0,
|
||||
...(edge.observedOnly && { observedOnly: true as const }),
|
||||
}
|
||||
total.bytes += edge.bytes
|
||||
total.bps += edge.bps
|
||||
total.bpsFwd += edge.bpsFwd
|
||||
total.bpsRev += edge.bpsRev
|
||||
if (edge.bps > 0 && !edge.bpsFwd && !edge.bpsRev) missingDirection.add(key)
|
||||
grouped.set(key, total)
|
||||
}
|
||||
for (const key of missingDirection) {
|
||||
const total = grouped.get(key)!
|
||||
total.bpsFwd = 0
|
||||
total.bpsRev = 0
|
||||
}
|
||||
return [...grouped.values()]
|
||||
}
|
||||
|
||||
/** Every byte belongs to a single bucket, including the part without classification evidence. */
|
||||
function categoryVolumes(service: FlowMapService, bytes: number, evidence: FlowMapService["serviceEvidence"]) {
|
||||
const label = mapTrafficCategory(service)
|
||||
if (!evidence?.length || label === unknownTrafficCategory) return new Map([[label, bytes]])
|
||||
const known = Math.min(bytes, evidence.reduce((sum, row) => sum + (row.basis === "unknown" ? 0 : row.bytes), 0))
|
||||
const volumes = new Map<string, number>()
|
||||
if (known) volumes.set(label, known)
|
||||
if (bytes > known || !bytes) volumes.set(unknownTrafficCategory, bytes - known)
|
||||
return volumes
|
||||
}
|
||||
|
||||
export function groupMapCategories(services: FlowMapService[], edges: FlowMapServiceEdge[], paths: FlowMapServicePath[]) {
|
||||
const categories = new Map<string, FlowMapService>()
|
||||
const members = new Map<string, FlowMapService[]>()
|
||||
const categoryPaths = new Map<string, FlowMapServicePath[]>()
|
||||
const byService = new Map<string, string>()
|
||||
const partialEdges: FlowMapServiceEdge[] = []
|
||||
for (const service of services) {
|
||||
const servicePaths = paths.filter(path => path.serviceId === service.id)
|
||||
const evidence = service.serviceEvidence ?? servicePaths.flatMap(path => path.serviceEvidence ?? [])
|
||||
const volumes = categoryVolumes(service, service.bytes, evidence)
|
||||
const onlyLabel = volumes.size === 1 ? [...volumes.keys()][0] : undefined
|
||||
if (onlyLabel) byService.set(service.id, mapCategoryId(onlyLabel))
|
||||
for (const [label, bytes] of volumes) {
|
||||
const id = mapCategoryId(label)
|
||||
const fraction = service.bytes ? bytes / service.bytes : 1
|
||||
const item = { ...service, bytes, share: service.share * fraction, bps: service.bps * fraction }
|
||||
const category = categories.get(id) ?? { id, label, category: "Категория трафика", bytes: 0, bps: 0, share: 0 }
|
||||
category.bytes += item.bytes
|
||||
category.bps += item.bps
|
||||
category.share += item.share
|
||||
categories.set(id, category)
|
||||
const items = members.get(id) ?? []
|
||||
items.push(item)
|
||||
members.set(id, items)
|
||||
}
|
||||
|
||||
const routed = new Map<string, Map<string, number>>()
|
||||
for (const path of servicePaths) {
|
||||
// Older snapshots can associate a path with a single service category, never split a mixed service by guesswork.
|
||||
const parts = path.serviceEvidence?.length ? categoryVolumes(service, path.bytes, path.serviceEvidence) : onlyLabel ? new Map([[onlyLabel, path.bytes]]) : []
|
||||
const source = JSON.stringify([path.enId || path.viaId, !path.enId])
|
||||
const totals = routed.get(source) ?? new Map<string, number>()
|
||||
for (const [label, bytes] of parts) {
|
||||
const id = mapCategoryId(label)
|
||||
const items = categoryPaths.get(id) ?? []
|
||||
items.push(bytes === path.bytes ? path : {
|
||||
...path, bytes, bps: path.bps * bytes / path.bytes, trafficTypes: undefined,
|
||||
serviceEvidence: path.serviceEvidence?.filter(row => mapTrafficCategory(service, {serviceEvidence:[row]}) === label),
|
||||
})
|
||||
categoryPaths.set(id, items)
|
||||
totals.set(label, (totals.get(label) ?? 0) + bytes)
|
||||
}
|
||||
routed.set(source, totals)
|
||||
}
|
||||
for (const edge of edges.filter(item => item.toId === service.id)) {
|
||||
if (onlyLabel) {
|
||||
partialEdges.push({ ...edge, toId: mapCategoryId(onlyLabel) })
|
||||
continue
|
||||
}
|
||||
const source = JSON.stringify([edge.fromId, Boolean(edge.observedOnly)])
|
||||
for (const [label, bytes] of routed.get(source) ?? []) {
|
||||
if (!edge.bytes || bytes > edge.bytes) continue
|
||||
const whole = bytes === edge.bytes
|
||||
partialEdges.push({ ...edge, toId: mapCategoryId(label), bytes, bps: edge.bps * bytes / edge.bytes,
|
||||
bpsFwd: whole ? edge.bpsFwd : 0, bpsRev: whole ? edge.bpsRev : 0 })
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
services: [...categories.values()].sort((a, b) => b.bytes - a.bytes || a.label.localeCompare(b.label, "ru")),
|
||||
edges: groupDestinationEdges(partialEdges, id => id), members, byService, paths: categoryPaths,
|
||||
}
|
||||
}
|
||||
|
||||
export function smallMapServices(services: FlowMapService[], knownShare: boolean, selectedId: string | null, filteredId: string | null) {
|
||||
return services.filter(service => knownShare && service.share <= 0.1 && service.id !== selectedId && service.id !== filteredId)
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { mapLinkPath, type GreMapEdge } from "./network-map-layout"
|
||||
|
||||
export type GroupLinkEnd = {
|
||||
id: string
|
||||
name: string
|
||||
x: number
|
||||
y: number
|
||||
halfWidth: number
|
||||
groupId?: string
|
||||
}
|
||||
|
||||
type ChannelCounts = { count: number; down: number; degraded: number }
|
||||
type ConnectionType = "gre" | "wan-jh" | "wan" | "ix" | "service" | "observation" | "user"
|
||||
|
||||
export type MapGroupConnection = Partial<ChannelCounts> & {
|
||||
from: GroupLinkEnd
|
||||
to: GroupLinkEnd
|
||||
type: ConnectionType
|
||||
gre?: GreMapEdge
|
||||
}
|
||||
|
||||
/** Unmatched reports from opposite ends of one outer GRE pair can describe the same tunnels. */
|
||||
export function countGroupGre(edges: Iterable<GreMapEdge>): ChannelCounts {
|
||||
const total = { count: 0, down: 0, degraded: 0 }
|
||||
const ambiguous = new Map<string, Map<string, ChannelCounts>>()
|
||||
for (const edge of edges) {
|
||||
const { tunnel, ambiguousPeerKey } = edge
|
||||
let counts = total
|
||||
if (ambiguousPeerKey) {
|
||||
const byOwner = ambiguous.get(ambiguousPeerKey) ?? new Map<string, ChannelCounts>()
|
||||
ambiguous.set(ambiguousPeerKey, byOwner)
|
||||
counts = byOwner.get(tunnel.serverId) ?? { count: 0, down: 0, degraded: 0 }
|
||||
byOwner.set(tunnel.serverId, counts)
|
||||
}
|
||||
counts.count++
|
||||
const status = channelStatus(edge)
|
||||
if (status === "down") counts.down++
|
||||
else if (status === "degraded") counts.degraded++
|
||||
}
|
||||
for (const byOwner of ambiguous.values()) {
|
||||
const reports = [...byOwner.values()]
|
||||
const count = Math.max(...reports.map(row => row.count))
|
||||
const down = Math.min(Math.max(...reports.map(row => row.down)), count - Math.max(...reports.map(row => row.count - row.down)))
|
||||
// Conflicting reports indicate a problem but do not establish that the whole channel is down.
|
||||
const affected = Math.max(...reports.map(row => row.down + row.degraded))
|
||||
total.count += count
|
||||
total.down += down
|
||||
total.degraded += affected - down
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
export function channelStatus({ tunnel, peerTunnel }: GreMapEdge) {
|
||||
return peerTunnel && peerTunnel.status !== tunnel.status ? "degraded" : tunnel.status
|
||||
}
|
||||
|
||||
export function collectGroupLinks(rows: Iterable<MapGroupConnection>) {
|
||||
const buckets = new Map<string, MapGroupConnection[]>()
|
||||
for (const row of rows) {
|
||||
if (!(row.from.groupId || row.to.groupId) || row.from.id === row.to.id) continue
|
||||
const key = JSON.stringify([row.type, ...[row.from.id, row.to.id].sort()])
|
||||
const bucket = buckets.get(key)
|
||||
if (bucket) bucket.push(row)
|
||||
else buckets.set(key, [row])
|
||||
}
|
||||
return [...buckets].map(([id, bucket]) => {
|
||||
const { from, to, type } = bucket[0]
|
||||
const totals = countGroupGre(bucket.flatMap(row => row.gre ? [row.gre] : []))
|
||||
for (const row of bucket) {
|
||||
if (row.gre) continue
|
||||
totals.count += row.count ?? 1
|
||||
totals.down += row.down ?? 0
|
||||
totals.degraded += row.degraded ?? 0
|
||||
}
|
||||
return {
|
||||
id, from, to, type, ...totals,
|
||||
groups: [from.groupId, to.groupId].filter((group): group is string => Boolean(group)),
|
||||
link: mapLinkPath(from, from.halfWidth, to, to.halfWidth),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export type MapGroupLink = ReturnType<typeof collectGroupLinks>[number]
|
||||
@@ -877,35 +877,6 @@ export function greSourceWanIndexOnMap(
|
||||
return wanIdx
|
||||
}
|
||||
|
||||
function greEndpointAnchor(
|
||||
server: Server,
|
||||
tunnel: GreTunnel,
|
||||
role: "source" | "peer",
|
||||
nodePos: Record<string, { x: number; y: number }>,
|
||||
wanSatPos: Record<string, { x: number; y: number }[]>,
|
||||
resolvedIpv4ByHost?: ReadonlyMap<string, string>,
|
||||
): { x: number; y: number } {
|
||||
const center = (): { x: number; y: number } =>
|
||||
nodePos[server.id] ?? { x: W / 2, y: H / 2 }
|
||||
|
||||
if (server.type !== "home-router") return center()
|
||||
|
||||
const wans = server.wanUplinks ?? []
|
||||
let wanIdx: number | null = null
|
||||
if (role === "source") {
|
||||
const la = tunnel.localAddress?.trim() ?? ""
|
||||
if (la === "0.0.0.0" || la === "") wanIdx = wans.length > 0 ? 0 : null
|
||||
else wanIdx = wanIndexMatchingOuterIp(server, tunnel.localAddress, resolvedIpv4ByHost)
|
||||
if (wanIdx == null && wans.length > 0) wanIdx = 0
|
||||
} else {
|
||||
wanIdx = wanIndexMatchingOuterIp(server, tunnel.remoteAddress, resolvedIpv4ByHost)
|
||||
}
|
||||
|
||||
if (wanIdx != null && wanSatPos[server.id]?.[wanIdx])
|
||||
return wanSatPos[server.id][wanIdx]!
|
||||
return center()
|
||||
}
|
||||
|
||||
/** GRE на карте только между узлами каталога; у HR конец туннеля — у соответствующего WAN-спутника. */
|
||||
export interface GreMapEdge {
|
||||
tunnel: GreTunnel
|
||||
@@ -915,6 +886,8 @@ export interface GreMapEdge {
|
||||
to: { x: number; y: number }
|
||||
fromServer: Server
|
||||
toServer: Server
|
||||
fromWanIndex?: number | null
|
||||
toWanIndex?: number | null
|
||||
}
|
||||
|
||||
export function buildGreMapEdges(
|
||||
@@ -974,9 +947,13 @@ export function buildGreMapEdges(
|
||||
toServer = a
|
||||
}
|
||||
|
||||
const from = greEndpointAnchor(fromServer, t, "source", nodePos, wanSatPos, resolvedIpv4ByHost)
|
||||
const to = greEndpointAnchor(toServer, t, "peer", nodePos, wanSatPos, resolvedIpv4ByHost)
|
||||
const edge: GreMapEdge = { tunnel: t, from, to, fromServer, toServer }
|
||||
const sourceWan = greSourceWanIndexOnMap(a, t, resolvedIpv4ByHost)
|
||||
const peerWan = wanIndexMatchingOuterIp(b, t.remoteAddress, resolvedIpv4ByHost)
|
||||
const fromWanIndex = fromServer === a ? sourceWan : peerWan
|
||||
const toWanIndex = toServer === a ? sourceWan : peerWan
|
||||
const point = (server: Server, index: number | null) =>
|
||||
(index !== null && wanSatPos[server.id]?.[index]) || nodePos[server.id] || { x: W / 2, y: H / 2 }
|
||||
const edge: GreMapEdge = { tunnel: t, from:point(fromServer, fromWanIndex), to:point(toServer, toWanIndex), fromServer, toServer, fromWanIndex, toWanIndex }
|
||||
const key = canonicalLinkKey(t, fromServer, toServer)
|
||||
const group = links.get(key)
|
||||
if (group) group.push(edge)
|
||||
|
||||
@@ -34,3 +34,18 @@ test("a filtered topology does not inherit a service's full-network traffic comp
|
||||
assert.equal(complete.share, 0.4)
|
||||
assert.equal(partial.share, 1)
|
||||
})
|
||||
|
||||
test("a scoped service uses only the classification of its contributing paths", () => {
|
||||
const service = {id:"svc:video", label:"Видео", category:"Видео", bytes:100, bps:20, share:1,
|
||||
serviceEvidence:[{basis:"network" as const, bytes:60}, {basis:"heuristic" as const, bytes:40}]}
|
||||
const endpoint = {viaId:"1", viaName:"Экспортёр", enId:"", enName:"", serviceId:service.id}
|
||||
const paths = [
|
||||
{...endpoint, clientId:"a", clientName:"А", bytes:40, bps:8, serviceEvidence:[{basis:"heuristic" as const,bytes:40}]},
|
||||
{...endpoint, clientId:"b", clientName:"Б", bytes:60, bps:12, serviceEvidence:[{basis:"network" as const,bytes:60}]},
|
||||
]
|
||||
const scoped = scopeMapDestinations([service], [], paths, () => true, "a").services[0]
|
||||
assert.deepEqual(scoped.serviceEvidence, paths[0].serviceEvidence)
|
||||
assert.equal(scoped.bytes,40)
|
||||
const legacy = scopeMapDestinations([service], [], paths.map(path => ({...path, serviceEvidence:undefined})), () => true,"a").services[0]
|
||||
assert.equal(legacy.serviceEvidence,undefined)
|
||||
})
|
||||
@@ -12,6 +12,25 @@ export function isolatedIxServers(servers: Pick<Server, "id" | "type">[], links:
|
||||
return new Set(servers.filter(server => server.type === "ix-node" && !connected.has(server.id)).map(server => server.id))
|
||||
}
|
||||
|
||||
function scopedClassification(paths: FlowMapServicePath[], bytes: number) {
|
||||
if (!paths.length || paths.reduce((sum, path) => sum + path.bytes, 0) !== bytes) return {}
|
||||
const bases = new Map<string, NonNullable<FlowMapService["serviceEvidence"]>[number]>()
|
||||
const types = new Map<string, NonNullable<FlowMapService["trafficTypes"]>[number]>()
|
||||
for (const path of paths) {
|
||||
for (const row of path.serviceEvidence ?? []) {
|
||||
bases.set(row.basis, { ...row, bytes: (bases.get(row.basis)?.bytes ?? 0) + row.bytes })
|
||||
}
|
||||
for (const row of path.trafficTypes ?? []) {
|
||||
const key = JSON.stringify([row.transport, row.application])
|
||||
types.set(key, { ...row, bytes: (types.get(key)?.bytes ?? 0) + row.bytes })
|
||||
}
|
||||
}
|
||||
return {
|
||||
...(bases.size && {serviceEvidence: [...bases.values()].sort((a,b) => b.bytes - a.bytes)}),
|
||||
...(types.size && {trafficTypes: [...types.values()].sort((a,b) => b.bytes - a.bytes).slice(0,5)}),
|
||||
}
|
||||
}
|
||||
|
||||
export function scopeMapDestinations(
|
||||
services: FlowMapService[], edges: FlowMapServiceEdge[], paths: FlowMapServicePath[],
|
||||
includes: (id: string) => boolean, userId?: string, retainUnassigned = false,
|
||||
@@ -56,13 +75,14 @@ export function scopeMapDestinations(
|
||||
const shareOfVisible = Boolean(userId) || services.some(service => (totals.get(service.id)?.bytes ?? 0) !== service.bytes)
|
||||
return {
|
||||
shareOfVisible,
|
||||
services: services.flatMap(service => {
|
||||
services: services.flatMap<FlowMapService>(service => {
|
||||
const total = totals.get(service.id)
|
||||
if (!total) return []
|
||||
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 } : {}) }]
|
||||
...(total.bytes === service.bytes ? { trafficTypes, serviceEvidence, lastBucketAt } :
|
||||
scopedClassification(visiblePaths.filter(path => path.serviceId === service.id), total.bytes)) }]
|
||||
}).sort((a, b) => b.bytes - a.bytes || a.label.localeCompare(b.label)),
|
||||
edges: visibleEdges,
|
||||
paths: visiblePaths,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export const networkMapFilters=["all","online","degraded","offline","unknown","jump-host","exit-node","home-router","ix-node"] as const
|
||||
export type NetworkMapFilter=typeof networkMapFilters[number]
|
||||
export type MapDestinationMode = "services" | "countries" | "categories"
|
||||
export function readNetworkMapUrl(params:URLSearchParams){
|
||||
const server=params.get("server"),search=params.get("q")??"",filter=params.get("filter")??"all",dest=params.get("dest")??"services",wan=params.get("wan")
|
||||
let error:string|null=null
|
||||
@@ -7,9 +8,9 @@ export function readNetworkMapUrl(params:URLSearchParams){
|
||||
else if(server!==null&&!/^[a-zA-Z0-9_.:-]{1,64}$/.test(server))error="В ссылке указан некорректный сервер карты."
|
||||
else if(search.length>256)error="Поиск карты в ссылке слишком длинный."
|
||||
else if(!(networkMapFilters as readonly string[]).includes(filter))error="В ссылке указан неизвестный фильтр карты."
|
||||
else if(!["services","countries"].includes(dest))error="В ссылке указан неизвестный режим назначений."
|
||||
else if(!["services","countries","categories"].includes(dest))error="В ссылке указан неизвестный режим назначений."
|
||||
else if(wan!==null&&(!server||!/^\d{1,4}$/.test(wan)))error="В ссылке указан некорректный аплинк карты."
|
||||
return {server,search,filter:filter as NetworkMapFilter,dest:dest as "services"|"countries",wan:wan===null?null:Number(wan),error}
|
||||
return {server,search,filter:filter as NetworkMapFilter,dest:dest as MapDestinationMode,wan:wan===null?null:Number(wan),error}
|
||||
}
|
||||
export function patchNetworkMapUrl(params:URLSearchParams,values:Record<string,string|null>){
|
||||
const next=new URLSearchParams(params)
|
||||
|
||||
Reference in new issue
Block a user