Compare commits

..
4 Commits
Author SHA1 Message Date
Denozordec 545a9bbcd2 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
2026-12-03 09:58:24 +07:00
Denozordec 37025f1f94 fix(mcp): учитывать отдельную таблицу маршрутизации пира
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 11m54s
Docker images / frontend-image (push) Successful in 2m21s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 2m2s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
2026-12-02 01:05:02 +07:00
Denozordec c49e01299c fix(mcp): сократить описание чтения RIB для реестра операций
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 12m0s
Docker images / frontend-image (push) Successful in 3m48s
Docker images / updater-image (push) Successful in 1m47s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 3m11s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-12-01 22:07:28 +07:00
Denozordec 187a0cd45e fix(mcp): учитывать отключённую статику и имя сессии при чтении RIB
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Failing after 3m28s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 4m54s
Docker images / updater-image (push) Successful in 2m8s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
2026-12-01 22:00:11 +07:00
29 changed files with 1709 additions and 374 deletions

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -61,7 +61,13 @@ async function readState(input: Record<string, unknown>) {
if (!["false", "no"].includes(String(effectiveInstance.disabled))) throw new Error("BGP instance disabled/unknown") if (!["false", "no"].includes(String(effectiveInstance.disabled))) throw new Error("BGP instance disabled/unknown")
Object.assign(instance, effectiveInstance) Object.assign(instance, effectiveInstance)
const instanceContext = await readBgpInstanceContext(client, instance) const instanceContext = await readBgpInstanceContext(client, instance)
if (unique("vrf", instanceContext.vrf)[".id"] !== vrf[".id"] || unique("routing_table", instanceContext.table)[".id"] !== table[".id"]) throw new Error("BGP instance/connection contexts disagree") if (unique("vrf", instanceContext.vrf)[".id"] !== vrf[".id"]) throw new Error("BGP instance/connection VRFs disagree")
const instanceTable = unique("routing_table", instanceContext.table)
const separateTables = instanceTable[".id"] !== table[".id"]
if (separateTables && snapshots.find(row => row.resource === "vrf")!.rows.some(owner =>
owner[".id"] !== vrf[".id"] && (owner.name === table.name || owner.name === instanceTable.name))) {
throw new Error("BGP routing table belongs to a different VRF")
}
const filters = nativeBgpRows(await client.get("/routing/filter/rule")) const filters = nativeBgpRows(await client.get("/routing/filter/rule"))
if (filters.length > 1000) throw new McpError("LIMIT_EXCEEDED", "Каталог BGP filters превышает 1000 строк", 409) if (filters.length > 1000) throw new McpError("LIMIT_EXCEEDED", "Каталог BGP filters превышает 1000 строк", 409)
const selected = filters.filter(row => row.chain === desired) const selected = filters.filter(row => row.chain === desired)
@@ -71,13 +77,14 @@ async function readState(input: Record<string, unknown>) {
const protections = (await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=$1 OR (object_ref->>'kind'='server' AND object_ref->>'id'=$1) LIMIT 1001", [String(serverId)])).rows const protections = (await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=$1 OR (object_ref->>'kind'='server' AND object_ref->>'id'=$1) LIMIT 1001", [String(serverId)])).rows
if (protections.length > 1000) throw new Error("BGP protection closure exceeds limit") if (protections.length > 1000) throw new Error("BGP protection closure exceeds limit")
const objects: ChangeEvidence["objects"] = [{ kind: "bgp-policy", id, serverId }, { kind: "bgp_connection", id, serverId }, const objects: ChangeEvidence["objects"] = [{ kind: "bgp-policy", id, serverId }, { kind: "bgp_connection", id, serverId },
...[["bgp_instance", instance], ["vrf", vrf], ["routing_table", table]].map(([kind, row]) => ({ kind: String(kind), id: String((row as Record<string, unknown>)[".id"]), serverId })), ...[["bgp_instance", instance], ["vrf", vrf], ["routing_table", table], ["routing_table", instanceTable]].map(([kind, row]) => ({ kind: String(kind), id: String((row as Record<string, unknown>)[".id"]), serverId })),
...filters.map(row => ({ kind: "routing_filter", id: row[".id"], serverId })), ...[...used.keys()].map(nativeId => ({ kind: "bgp_template", id: nativeId, serverId })), ...filters.map(row => ({ kind: "routing_filter", id: row[".id"], serverId })), ...[...used.keys()].map(nativeId => ({ kind: "bgp_template", id: nativeId, serverId })),
...protections.map(({ object_ref: ref }) => ({ kind: ref.kind, id: ref.id, serverId }))] ...protections.map(({ object_ref: ref }) => ({ kind: ref.kind, id: ref.id, serverId }))]
const uniqueObjects = [...new Map(objects.map(row => [fingerprint(row), row])).values()] const uniqueObjects = [...new Map(objects.map(row => [fingerprint(row), row])).values()]
if (uniqueObjects.length > 1000) throw new Error("BGP dependency closure exceeds limit") if (uniqueObjects.length > 1000) throw new Error("BGP dependency closure exceeds limit")
const canonicalConnection = { ...stableBgpPolicyRow(connection), [property]: effectiveChain } const canonicalConnection = { ...stableBgpPolicyRow(connection), [property]: effectiveChain }
const dependencyProof = await proof(serverId, id, "dependencies", { serverProof, otherConnections: connections.filter(row => row[".id"] !== id).map(stableBgpPolicyRow), instance: stableBgpPolicyRow(instance), instanceContext, vrf: { ...stableBgpPolicyRow(vrf), ...(vrf.interfaces !== undefined ? { interfaces: canonicalVrfMembers(vrf.interfaces) } : {}) }, table: stableBgpPolicyRow(table), const dependencyProof = await proof(serverId, id, "dependencies", { serverProof, otherConnections: connections.filter(row => row[".id"] !== id).map(stableBgpPolicyRow), instance: stableBgpPolicyRow(instance), instanceContext, vrf: { ...stableBgpPolicyRow(vrf), ...(vrf.interfaces !== undefined ? { interfaces: canonicalVrfMembers(vrf.interfaces) } : {}) }, table: stableBgpPolicyRow(table),
...(separateTables ? { instanceTable: stableBgpPolicyRow(instanceTable) } : {}),
filters: filters.map(stableBgpPolicyRow), used: [...used.values()], references, protections }) filters: filters.map(stableBgpPolicyRow), used: [...used.values()], references, protections })
const before = { serverId, id, direction: input.direction, property, instance: instance.name, vrf: vrf.name, table: table.name, localChain, inheritedChain, effectiveChain, const before = { serverId, id, direction: input.direction, property, instance: instance.name, vrf: vrf.name, table: table.name, localChain, inheritedChain, effectiveChain,
selectedRuleCount: selected.length, selectedEnabledRuleCount: effectiveFilters.filter(row => ["false", "no"].includes(String(row.disabled))).length, serverProof, dependencyProof, selectedRuleCount: selected.length, selectedEnabledRuleCount: effectiveFilters.filter(row => ["false", "no"].includes(String(row.disabled))).length, serverProof, dependencyProof,
@@ -19,8 +19,8 @@ async function access(context: ActionContext) {
if (fingerprint(current.policy) !== fingerprint(context.connection.policy)) throw new McpError("RESET_REQUIRED", "Область чтения BGP изменилась", 409) if (fingerprint(current.policy) !== fingerprint(context.connection.policy)) throw new McpError("RESET_REQUIRED", "Область чтения BGP изменилась", 409)
} }
export function registerBgpPrefixActions(register: typeof add) { export function registerBgpPrefixActions(register: typeof add) {
const observation = bgpRibSelection.extend({ serverId: z.number().int().positive().safe() }) const observation = bgpRibSelection.safeExtend({ serverId: z.number().int().positive().safe() })
register("routing.bgp.rib.read", "mm_bgp_rib_get", "Нативная IPv4 BGP RIB по таблице: count-only или страницы всех путей, включая filtered. В следующих страницах передавайте expectedFingerprint первой страницы", "bgp", permissions, "read", "servers", observation, { read: async (input, context) => { register("routing.bgp.rib.read", "mm_bgp_rib_get", "IPv4 BGP RIB с filtered-путями. Для соседа укажите sessionName или peerCacheId. Для следующих страниц сохраните expectedFingerprint первой страницы", "bgp", permissions, "read", "servers", observation, { read: async (input, context) => {
const { serverId, ...selection } = observation.parse(input) const { serverId, ...selection } = observation.parse(input)
await access(context) await access(context)
const source = await createRoutingSourceContext(await readRoutingEndpoints([serverId])) const source = await createRoutingSourceContext(await readRoutingEndpoints([serverId]))
@@ -19,7 +19,7 @@ function route(index: number, overrides: Record<string, string> = {}): Record<st
} }
function fixture(rows: Record<string, string>[]) { function fixture(rows: Record<string, string>[]) {
const reads = { routePages: 0, counts: 0 } const reads = { routePages: 0, counts: 0, sessionFilters: new Set<string>() }
const client = { const client = {
async get<T>(path: string, _timeout?: number, _signal?: AbortSignal, maxResponseBytes?: number) { async get<T>(path: string, _timeout?: number, _signal?: AbortSignal, maxResponseBytes?: number) {
assert((maxResponseBytes ?? 8 * 1024 * 1024) <= 8 * 1024 * 1024, "MikrotikClient rejects GET limits above 8 MiB") assert((maxResponseBytes ?? 8 * 1024 * 1024) <= 8 * 1024 * 1024, "MikrotikClient rejects GET limits above 8 MiB")
@@ -40,14 +40,17 @@ function fixture(rows: Record<string, string>[]) {
const query = body[".query"] const query = body[".query"]
assert(Array.isArray(query)) assert(Array.isArray(query))
const peer = query.find(word => word.startsWith("bgp.peer-cache-id="))?.split("=")[1] const peer = query.find(word => word.startsWith("bgp.peer-cache-id="))?.split("=")[1]
const session = query.find(word => word.startsWith("bgp.session="))?.slice("bgp.session=".length)
assert.deepEqual(query, [ assert.deepEqual(query, [
"routing-table=" + table, "bgp=true", "afi=ip", "afi=ip4", "#|", "routing-table=" + table, "bgp=true", "afi=ip", "afi=ip4", "#|",
...(peer ? ["bgp.peer-cache-id=" + peer] : []), ...(peer ? ["bgp.peer-cache-id=" + peer] : []),
...(session ? ["bgp.session=" + session] : []),
]) ])
reads.counts++ reads.counts++
if (session !== undefined) reads.sessionFilters.add(session)
const count = rows.filter(row => const count = rows.filter(row =>
row["routing-table"] === table && row.bgp === "true" && (row.afi === "ip" || row.afi === "ip4") && row["routing-table"] === table && row.bgp === "true" && (row.afi === "ip" || row.afi === "ip4") &&
(!peer || row["bgp.peer-cache-id"] === peer), (!peer || row["bgp.peer-cache-id"] === peer) && (!session || row["bgp.session"] === session),
).length ).length
return { ret: String(count) } as T return { ret: String(count) } as T
}, },
@@ -100,6 +103,45 @@ test("matching peer paths include filtered and inactive alternatives with distin
assert.equal(otherPeer.items?.[0]?.id, filtered[".id"]) assert.equal(otherPeer.items?.[0]?.id, filtered[".id"])
}) })
test("RouterOS static rows without afi coexist with BGP paths identified by session name", async () => {
const nativeStatic = {
".id": "*800002F2", "dst-address": "5.180.136.242/32", "routing-table": table,
contribution: "(unknown)", static: "true",
}
const sessionName = "ibgp-jh-test-anycast-1"
const received = route(0, { "bgp.session": sessionName })
delete received["bgp.peer-cache-id"]
const { client, reads } = fixture([nativeStatic, received])
const mixed = await readBgpRib(client, selection)
assert.equal(mixed.total, 1)
assert.deepEqual(mixed.items.map(item => [item.id, item.prefix, item.peerCacheId, item.session]), [
[received[".id"], received["dst-address"], null, sessionName],
])
const bySession = await readBgpRib(client, { ...selection, sessionName })
assert.equal(bySession.sessionName, sessionName)
assert.equal(bySession.total, 1)
assert.equal(bySession.items[0].id, received[".id"])
assert.equal((await readBgpRib(client, { ...selection, mode: "count", sessionName: "ibgp-other-1" })).total, 0)
assert.deepEqual(reads.sessionFilters, new Set([sessionName, "ibgp-other-1"]))
assert(bySession.fingerprint)
await assert.rejects(readBgpRib(client, { ...selection, expectedFingerprint: bySession.fingerprint }))
await assert.rejects(readBgpRib(client, { ...selection, sessionName, peerCacheId: primary }))
await assert.rejects(readBgpRib(fixture([received, route(1)]).client, { ...selection, mode: "count", sessionName: "ibgp-other-1" }))
for (const invalid of [" ", sessionName + "\r"]) {
const malformed = fixture([{ ...received, "bgp.session": invalid }]).client
await assert.rejects(readBgpRib(malformed, { ...selection, mode: "count", sessionName }))
}
const onlyStatic = fixture([nativeStatic])
assert.equal((await readBgpRib(onlyStatic.client, { ...selection, mode: "count" })).total, 0)
assert.equal(onlyStatic.reads.routePages, 1)
const noOrigin: Record<string, string> = { ...nativeStatic }
delete noOrigin.static
for (const ambiguous of [noOrigin, { ...nativeStatic, "bgp.session": "ibgp-to-jh-1" }, { ...noOrigin, bgp: "true" }]) {
await assert.rejects(readBgpRib(fixture([ambiguous]).client, { ...selection, mode: "count" }))
}
})
test("missing table and missing peer attribution cannot prove a scoped zero", async () => { test("missing table and missing peer attribution cannot prove a scoped zero", async () => {
const { client } = fixture([]) const { client } = fixture([])
const missingTable = { ...client, get: async <T>() => [] as T } const missingTable = { ...client, get: async <T>() => [] as T }
+21 -13
View File
@@ -5,14 +5,17 @@ import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
import type { MikrotikClient } from "./mikrotik.js" import type { MikrotikClient } from "./mikrotik.js"
const rosId = z.string().regex(/^\*[0-9a-z]+$/i).max(64) const rosId = z.string().regex(/^\*[0-9a-z]+$/i).max(64)
const exactName = z.string().min(1).refine(name => name.trim() === name && !/[\u0000-\u001f\u007f]/.test(name))
const sessionIdentity = exactName.max(512)
export const bgpRibSelection = z.object({ export const bgpRibSelection = z.object({
table: z.string().min(1).max(100).refine(name => name.trim() === name && !/[\u0000-\u001f\u007f]/.test(name)), table: exactName.max(100),
peerCacheId: rosId.optional(), peerCacheId: rosId.optional(),
sessionName: sessionIdentity.optional(),
mode: z.enum(["count", "page"]).default("count"), mode: z.enum(["count", "page"]).default("count"),
offset: z.number().int().min(0).max(100_000).default(0), offset: z.number().int().min(0).max(100_000).default(0),
limit: z.number().int().min(1).max(500).default(100), limit: z.number().int().min(1).max(500).default(100),
expectedFingerprint: z.string().regex(/^[a-f0-9]{64}$/).optional(), expectedFingerprint: z.string().regex(/^[a-f0-9]{64}$/).optional(),
}).strict() }).strict().refine(input => !(input.peerCacheId && input.sessionName), { message: "Choose only one BGP peer selector" })
const nativeRow = z.record(z.string(), z.unknown()) const nativeRow = z.record(z.string(), z.unknown())
const otherProtocols = ["static", "connect", "ospf", "dhcp", "rip", "isis", "modem", "slaac", "vpn", "fantasy"] const otherProtocols = ["static", "connect", "ospf", "dhcp", "rip", "isis", "modem", "slaac", "vpn", "fantasy"]
@@ -33,9 +36,11 @@ function optionalFlag(value: unknown) {
function ipv4Row(row: Record<string, unknown>, table: string) { function ipv4Row(row: Record<string, unknown>, table: string) {
if (row["routing-table"] !== table) throw new Error("Unexpected native route table") if (row["routing-table"] !== table) throw new Error("Unexpected native route table")
if (otherFamilies.has(String(row.afi))) return null if (otherFamilies.has(String(row.afi))) return null
if (row.afi !== "ip" && row.afi !== "ip4") throw new Error("Unrecognized RouterOS address family")
const bgp = optionalFlag(row.bgp) const bgp = optionalFlag(row.bgp)
const other = otherProtocols.some(key => optionalFlag(row[key]) === true) const other = otherProtocols.some(key => optionalFlag(row[key]) === true)
// Disabled static routes on RouterOS can omit afi. Their explicit origin still has to agree with the BGP evidence below.
const missingNonBgpAfi = row.afi === undefined && other && bgp !== true
if (row.afi !== "ip" && row.afi !== "ip4" && !missingNonBgpAfi) throw new Error("Unrecognized RouterOS address family")
if (bgp !== true) { if (bgp !== true) {
// Missing origin flags occur on some RouterOS REST projections. Do not lose filtered paths or certify a false zero. // Missing origin flags occur on some RouterOS REST projections. Do not lose filtered paths or certify a false zero.
if (row["bgp.peer-cache-id"] || row["bgp.session"] || /\bbgp\b/i.test(String(row["belongs-to"] ?? "")) || bgp === null && !other) throw new Error("Unconfirmed native route origin") if (row["bgp.peer-cache-id"] || row["bgp.session"] || /\bbgp\b/i.test(String(row["belongs-to"] ?? "")) || bgp === null && !other) throw new Error("Unconfirmed native route origin")
@@ -56,7 +61,7 @@ function ipv4Row(row: Record<string, unknown>, table: string) {
id, prefix, table, peerCacheId, contribution, id, prefix, table, peerCacheId, contribution,
active: activeFlag ?? (known ? contribution === "active" : null), active: activeFlag ?? (known ? contribution === "active" : null),
filtered: filteredFlag ?? (known ? contribution === "filtered" : null), filtered: filteredFlag ?? (known ? contribution === "filtered" : null),
session: text.nullable().parse(row["bgp.session"] ?? null), session: sessionIdentity.nullable().parse(row["bgp.session"] ?? null),
gateway: text.nullable().parse(row.gateway ?? null), immediateGateway: text.nullable().parse(row["immediate-gw"] ?? null), gateway: text.nullable().parse(row.gateway ?? null), immediateGateway: text.nullable().parse(row["immediate-gw"] ?? null),
} }
} }
@@ -64,9 +69,11 @@ function ipv4Row(row: Record<string, unknown>, table: string) {
/** Counts run on RouterOS. Page offsets use deterministic route IDs and a digest over the full selection. */ /** Counts run on RouterOS. Page offsets use deterministic route IDs and a digest over the full selection. */
export async function readBgpRib(client: Pick<MikrotikClient, "get" | "post">, input: Selection, export async function readBgpRib(client: Pick<MikrotikClient, "get" | "post">, input: Selection,
beforeRead: () => Promise<unknown> = async () => {}, signal?: AbortSignal) { beforeRead: () => Promise<unknown> = async () => {}, signal?: AbortSignal) {
const { table, peerCacheId, mode, limit, offset, expectedFingerprint } = bgpRibSelection.parse(input) const { table, peerCacheId, sessionName, mode, limit, offset, expectedFingerprint } = bgpRibSelection.parse(input)
if (offset > 0 && !expectedFingerprint || mode === "count" && (offset || expectedFingerprint)) throw new Error("Invalid RIB page cursor") if (offset > 0 && !expectedFingerprint || mode === "count" && (offset || expectedFingerprint)) throw new Error("Invalid RIB page cursor")
const query = ["routing-table=" + table, "bgp=true", "afi=ip", "afi=ip4", "#|"] const query = ["routing-table=" + table, "bgp=true", "afi=ip", "afi=ip4", "#|"]
const peer = peerCacheId ? { field: "peerCacheId", native: "bgp.peer-cache-id", value: peerCacheId } as const
: sessionName ? { field: "session", native: "bgp.session", value: sessionName } as const : null
const tablePath = "/routing/table?.proplist=.id,name,disabled,invalid&name=" + encodeURIComponent(table) const tablePath = "/routing/table?.proplist=.id,name,disabled,invalid&name=" + encodeURIComponent(table)
const tableIdentity = async () => { const tableIdentity = async () => {
const raw = await client.get<unknown>(tablePath, 10_000, signal, 16_384, beforeRead) const raw = await client.get<unknown>(tablePath, 10_000, signal, 16_384, beforeRead)
@@ -75,8 +82,8 @@ export async function readBgpRib(client: Pick<MikrotikClient, "get" | "post">, i
if (row.name !== table || optionalFlag(row.disabled) || optionalFlag(row.invalid)) throw new Error("Routing table unavailable") if (row.name !== table || optionalFlag(row.disabled) || optionalFlag(row.invalid)) throw new Error("Routing table unavailable")
return rosId.parse(row[".id"]) return rosId.parse(row[".id"])
} }
const nativeCount = async (peer?: string) => { const nativeCount = async (scoped = false) => {
const filter = peer ? [...query, "bgp.peer-cache-id=" + peer] : query const filter = scoped && peer ? [...query, peer.native + "=" + peer.value] : query
const raw = await client.post<unknown>("/routing/route/print", { "count-only": "", ".query": filter }, 15_000, signal, beforeRead) const raw = await client.post<unknown>("/routing/route/print", { "count-only": "", ".query": filter }, 15_000, signal, beforeRead)
const { ret } = z.object({ ret: z.string().regex(/^(?:0|[1-9]\d{0,14})$/) }).strict().parse(raw) const { ret } = z.object({ ret: z.string().regex(/^(?:0|[1-9]\d{0,14})$/) }).strict().parse(raw)
return Number(ret) return Number(ret)
@@ -85,7 +92,7 @@ export async function readBgpRib(client: Pick<MikrotikClient, "get" | "post">, i
const allCount = await nativeCount() const allCount = await nativeCount()
type Item = NonNullable<ReturnType<typeof ipv4Row>> type Item = NonNullable<ReturnType<typeof ipv4Row>>
let items: Item[] = [], fingerprint: string | null = null, total = allCount, nextOffset: number | null = null let items: Item[] = [], fingerprint: string | null = null, total = allCount, nextOffset: number | null = null
if (mode === "page" || peerCacheId || allCount === 0) { if (mode === "page" || peer || allCount === 0) {
if (allCount > 100_000) throw new Error("RIB row limit exceeded") if (allCount > 100_000) throw new Error("RIB row limit exceeded")
const path = "/routing/route?.proplist=" + properties + "&routing-table=" + encodeURIComponent(table) const path = "/routing/route?.proplist=" + properties + "&routing-table=" + encodeURIComponent(table)
const raw = await client.get<unknown>(path, 30_000, signal, 8 * 1024 * 1024, beforeRead) const raw = await client.get<unknown>(path, 30_000, signal, 8 * 1024 * 1024, beforeRead)
@@ -96,19 +103,20 @@ export async function readBgpRib(client: Pick<MikrotikClient, "get" | "post">, i
if (!observed) continue if (!observed) continue
if (ids.has(observed.id)) throw new Error("Duplicate native RIB identity") if (ids.has(observed.id)) throw new Error("Duplicate native RIB identity")
ids.add(observed.id) ids.add(observed.id)
if (peerCacheId && !observed.peerCacheId) throw new Error("Native peer identity unavailable") if (peer && !observed[peer.field]) throw new Error("Native peer identity unavailable")
if (!peerCacheId || observed.peerCacheId === peerCacheId) selected.push(observed) if (!peer || observed[peer.field] === peer.value) selected.push(observed)
} }
if (allCount !== ids.size || selected.length !== await nativeCount(peerCacheId)) throw new BgpRibChanged("Native RIB count changed or view incomplete") if (allCount !== ids.size || selected.length !== await nativeCount(true)) throw new BgpRibChanged("Native RIB count changed or view incomplete")
total = selected.length total = selected.length
if (mode === "page") { if (mode === "page") {
selected.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0) selected.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
fingerprint = createHash("sha256").update(JSON.stringify([table, identity, peerCacheId ?? null, selected])).digest("hex") const peerScope = sessionName ? { sessionName } : peerCacheId ?? null
fingerprint = createHash("sha256").update(JSON.stringify([table, identity, peerScope, selected])).digest("hex")
if (expectedFingerprint && fingerprint !== expectedFingerprint || offset > total) throw new BgpRibChanged("RIB snapshot changed; restart at offset 0") if (expectedFingerprint && fingerprint !== expectedFingerprint || offset > total) throw new BgpRibChanged("RIB snapshot changed; restart at offset 0")
items = selected.slice(offset, offset + limit) items = selected.slice(offset, offset + limit)
nextOffset = offset + items.length < total ? offset + items.length : null nextOffset = offset + items.length < total ? offset + items.length : null
} }
} }
if (identity !== await tableIdentity()) throw new BgpRibChanged("Routing table changed during observation") if (identity !== await tableIdentity()) throw new BgpRibChanged("Routing table changed during observation")
return { family: "ipv4", table, peerCacheId: peerCacheId ?? null, mode, total, items, nextOffset, fingerprint, source: "/routing/route", atomicSnapshot: false } return { family: "ipv4", table, peerCacheId: peerCacheId ?? null, sessionName: sessionName ?? null, mode, total, items, nextOffset, fingerprint, source: "/routing/route", atomicSnapshot: false }
} }
@@ -423,6 +423,7 @@ try {
assert.ok(!def.conversationsList.some((r) => r.proto === 47)) assert.ok(!def.conversationsList.some((r) => r.proto === 47))
assert.equal(def.conversationsList[0]?.service, "YouTube") assert.equal(def.conversationsList[0]?.service, "YouTube")
assert.equal(def.conversationsList[0]?.category, "Видео / стриминг") assert.equal(def.conversationsList[0]?.category, "Видео / стриминг")
assert.equal(def.conversationsList[0]?.serviceBasis, "heuristic")
assert.equal(def.conversationsList[0]?.clientName, "Alice") assert.equal(def.conversationsList[0]?.clientName, "Alice")
assert.equal(def.conversationsList[0]?.enName, "NSK-SERVHOST-RTK") assert.equal(def.conversationsList[0]?.enName, "NSK-SERVHOST-RTK")
assert.equal(def.conversationsList[0]?.plane, "payload") assert.equal(def.conversationsList[0]?.plane, "payload")
@@ -382,7 +382,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
const pathKey = JSON.stringify([client?.userId ?? "unknown", r.serverId, en?.id ?? "", dst, resolved.name, outIface, const pathKey = JSON.stringify([client?.userId ?? "unknown", r.serverId, en?.id ?? "", dst, resolved.name, outIface,
classified.service, classified.category, plane]) classified.service, classified.category, plane])
const ckey = JSON.stringify([flowTupleKey(r), pathKey, accounted.name, app, asnId, dstCountry, ep.internetPeer, const ckey = JSON.stringify([flowTupleKey(r), pathKey, accounted.name, app, asnId, dstCountry, ep.internetPeer,
ep.clientIp, ep.peerPort, ep.direction, r.nextHop]) ep.clientIp, ep.peerPort, ep.direction, r.nextHop, classified.basis])
const prev = conv.get(ckey) const prev = conv.get(ckey)
if (prev) { if (prev) {
prev.rawBytes += r.bytes prev.rawBytes += r.bytes
@@ -411,6 +411,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
application: app, application: app,
category: classified.category, category: classified.category,
service: classified.service, service: classified.service,
serviceBasis: classified.basis,
dstCountry, dstCountry,
dstAsn: destMeta.asn || undefined, dstAsn: destMeta.asn || undefined,
clientId: client?.userId, clientId: client?.userId,
@@ -734,6 +734,7 @@ ingestClosed(7, [
nextHop: "", nextHop: "",
}, },
{ ...payloadFlow("1.2.3.4", 6000), proto: 17, dstPort: 53, inIface: "gre-client", outIface: "ether1", nextHop: "" }, { ...payloadFlow("1.2.3.4", 6000), proto: 17, dstPort: 53, inIface: "gre-client", outIface: "ether1", nextHop: "" },
{ ...payloadFlow("1.2.3.4", 3000), proto: 6, dstPort: 53, inIface: "ether1", outIface: "ether1", nextHop: "" },
]) ])
try { try {
resetFlowMapHopsCacheForTests() resetFlowMapHopsCacheForTests()
@@ -743,15 +744,24 @@ try {
assert.deepEqual(youtube.serviceEvidence, [{basis: "heuristic", bytes: 9000}]) assert.deepEqual(youtube.serviceEvidence, [{basis: "heuristic", bytes: 9000}])
assert.deepEqual(youtube.trafficTypes, [{transport: "TCP", application: "HTTPS", bytes: 9000}]) assert.deepEqual(youtube.trafficTypes, [{transport: "TCP", application: "HTTPS", bytes: 9000}])
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.trafficTypes, assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.trafficTypes,
[{transport: "UDP", application: "DNS", bytes: 6000}]) [{transport: "UDP", application: "DNS", bytes: 6000}, {transport: "TCP", application: "DNS", bytes: 3000}])
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.serviceEvidence, [{basis: "port", bytes: 6000}]) assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.serviceEvidence, [{basis: "port", bytes: 9000}])
const dns = wanOnly.serviceEdges?.find(e => e.toId === "svc:dns") const dns = wanOnly.serviceEdges?.find(e => e.toId === "svc:dns")
assert.deepEqual(dns && [dns.fromId, dns.observedOnly, dns.bytes], ["7", true, 6000]) assert.deepEqual(dns && [dns.fromId, dns.observedOnly, dns.bytes], ["7", true, 9000])
const dnsPath = wanOnly.servicePaths?.find(p => p.serviceId === "svc:dns") const dnsPath = wanOnly.servicePaths?.find(p => p.serviceId === "svc:dns" && p.clientId === "u1")
assert.deepEqual(dnsPath && [dnsPath.viaId, dnsPath.viaIface, dnsPath.enId, dnsPath.clientName], ["7", "ether1", "", "Alice"]) assert.deepEqual(dnsPath && [dnsPath.viaId, dnsPath.viaIface, dnsPath.enId, dnsPath.clientName], ["7", "ether1", "", "Alice"])
const dnsPaths = wanOnly.servicePaths?.filter(p => p.serviceId === "svc:dns")
const nestedDnsPaths = wanOnly.countryServiceGroups?.flatMap(group => group.paths.filter(p => p.serviceId.endsWith("|svc:dns")))
for (const paths of [dnsPaths, nestedDnsPaths]) {
assert.deepEqual(paths?.map(p => [p.clientName, p.trafficTypes, p.serviceEvidence]), [
["Alice", [{transport: "UDP", application: "DNS", bytes: 6000}], [{basis: "port", bytes: 6000}]],
["—", [{transport: "TCP", application: "DNS", bytes: 3000}], [{basis: "port", bytes: 3000}]],
])
}
assert.ok(wanOnly.countryPaths?.every(p => p.serviceEvidence === undefined && p.trafficTypes === undefined))
assert.ok(wanOnly.countryEdges?.every(e => e.observedOnly && e.fromId === "7")) assert.ok(wanOnly.countryEdges?.every(e => e.observedOnly && e.fromId === "7"))
assert.ok(wanOnly.countryServiceGroups?.some(group => group.edges.some(e => e.toId.endsWith("|svc:dns")))) assert.ok(wanOnly.countryServiceGroups?.some(group => group.edges.some(e => e.toId.endsWith("|svc:dns"))))
assert.deepEqual(wanOnly.nodeUsers?.["7"]?.map(u => [u.clientName, u.bytes]), [["—", 9000], ["Alice", 6000]]) assert.deepEqual(wanOnly.nodeUsers?.["7"]?.map(u => [u.clientName, u.bytes]), [["—", 12000], ["Alice", 6000]])
assert.equal(wanOnly.nodeUsers?.["9"], undefined) assert.equal(wanOnly.nodeUsers?.["9"], undefined)
} finally { } finally {
+39 -21
View File
@@ -83,13 +83,18 @@ interface DstAcc {
fromBytes: Map<string, FromAcc> fromBytes: Map<string, FromAcc>
} }
interface DestTotal { interface ClassificationCounters {
trafficTypes?: Map<string, NonNullable<FlowMapService["trafficTypes"]>[number]>
serviceEvidence?: Map<FlowServiceBasis, number>
}
type ClassificationDetail = { transport: string; application: string | null; basis: FlowServiceBasis }
interface DestTotal extends ClassificationCounters {
label: string label: string
category: string category: string
bytes: number bytes: number
lastBucketAt: string lastBucketAt: string
trafficTypes?: Map<string, NonNullable<FlowMapService["trafficTypes"]>[number]>
serviceEvidence?: Map<FlowServiceBasis, number>
} }
interface DestEdgeAcc { interface DestEdgeAcc {
@@ -102,7 +107,7 @@ interface DestEdgeAcc {
observedOnly?: true observedOnly?: true
} }
interface DestPathAcc { interface DestPathAcc extends ClassificationCounters {
clientId: string clientId: string
clientName: string clientName: string
viaId: string viaId: string
@@ -162,11 +167,7 @@ export function pickMapServices(
.slice(0, cap) .slice(0, cap)
} }
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number, lastBucketAt: string, function bumpClassification(total: ClassificationCounters, bytes: number, detail?: ClassificationDetail): void {
detail?: { transport: string; application: string | null; basis: FlowServiceBasis }): void {
const total = totals.get(id) ?? { label, category, bytes: 0, lastBucketAt }
total.bytes += bytes
if (lastBucketAt > total.lastBucketAt) total.lastBucketAt = lastBucketAt
if (detail && bytes > 0) { if (detail && bytes > 0) {
const { transport, application, basis } = detail const { transport, application, basis } = detail
const types = total.trafficTypes ??= new Map() const types = total.trafficTypes ??= new Map()
@@ -177,6 +178,21 @@ function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string
const evidence = total.serviceEvidence ??= new Map() const evidence = total.serviceEvidence ??= new Map()
evidence.set(basis, (evidence.get(basis) ?? 0) + bytes) evidence.set(basis, (evidence.get(basis) ?? 0) + bytes)
} }
}
function classificationFields(total: ClassificationCounters) {
return {
...(total.trafficTypes ? { trafficTypes: [...total.trafficTypes.values()].sort((a, b) => b.bytes - a.bytes).slice(0, 5) } : {}),
...(total.serviceEvidence ? { serviceEvidence: [...total.serviceEvidence].map(([basis, bytes]) => ({ basis, bytes })).sort((a, b) => b.bytes - a.bytes) } : {}),
}
}
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number, lastBucketAt: string,
detail?: ClassificationDetail): void {
const total = totals.get(id) ?? { label, category, bytes: 0, lastBucketAt }
total.bytes += bytes
if (lastBucketAt > total.lastBucketAt) total.lastBucketAt = lastBucketAt
bumpClassification(total, bytes, detail)
totals.set(id, total) totals.set(id, total)
} }
@@ -189,6 +205,7 @@ function bumpDestFrom(
fromId: string, fromId: string,
enName: string, enName: string,
viaName: string, viaName: string,
detail?: ClassificationDetail,
/** fromId ребра, если отличается от EN (вложенный слой: страна → сервис). */ /** fromId ребра, если отличается от EN (вложенный слой: страна → сервис). */
edgeFromId: string = fromId || exporterId, edgeFromId: string = fromId || exporterId,
): void { ): void {
@@ -216,12 +233,9 @@ function bumpDestFrom(
} }
for (const [clientId, c] of from.clients) { for (const [clientId, c] of from.clients) {
const pathKey = JSON.stringify([clientId, exporterId, fromId, toId, from.viaIface]) const pathKey = JSON.stringify([clientId, exporterId, fromId, toId, from.viaIface])
const prevPath = paths.get(pathKey) let path = paths.get(pathKey)
if (prevPath) { if (!path) {
prevPath.bytes += c.bytes path = {
if (prevPath.clientName === "—" && c.name !== "—") prevPath.clientName = c.name
} else {
paths.set(pathKey, {
clientId, clientId,
clientName: c.name, clientName: c.name,
viaId: exporterId, viaId: exporterId,
@@ -230,9 +244,13 @@ function bumpDestFrom(
enId: fromId, enId: fromId,
enName, enName,
serviceId: toId, serviceId: toId,
bytes: c.bytes, bytes: 0,
}) }
paths.set(pathKey, path)
} }
if (path.clientName === "—" && c.name !== "—") path.clientName = c.name
path.bytes += c.bytes
bumpClassification(path, c.bytes, detail)
} }
} }
@@ -256,8 +274,7 @@ function finalizeDestLayer(
...(s.lastBucketAt ? { lastBucketAt: minuteBucketIso(Date.parse(s.lastBucketAt)) } : {}), ...(s.lastBucketAt ? { lastBucketAt: minuteBucketIso(Date.parse(s.lastBucketAt)) } : {}),
bps: (s.bytes * 8) / windowSec, bps: (s.bytes * 8) / windowSec,
share: shareBase > 0 ? s.bytes / shareBase : 0, share: shareBase > 0 ? s.bytes / shareBase : 0,
...(s.trafficTypes ? { trafficTypes: [...s.trafficTypes.values()].sort((a, b) => b.bytes - a.bytes).slice(0, 5) } : {}), ...classificationFields(s),
...(s.serviceEvidence ? { serviceEvidence: [...s.serviceEvidence].map(([basis, bytes]) => ({ basis, bytes })).sort((a, b) => b.bytes - a.bytes) } : {}),
})) }))
.sort((a, b) => b.bytes - a.bytes), .sort((a, b) => b.bytes - a.bytes),
minSharePct, minSharePct,
@@ -296,6 +313,7 @@ function finalizeDestLayer(
serviceId: p.serviceId, serviceId: p.serviceId,
bytes: p.bytes, bytes: p.bytes,
bps: (p.bytes * 8) / windowSec, bps: (p.bytes * 8) / windowSec,
...classificationFields(p),
})) }))
.sort((a, b) => b.bps - a.bps) .sort((a, b) => b.bps - a.bps)
return { nodes, edges: outEdges, paths: outPaths } return { nodes, edges: outEdges, paths: outPaths }
@@ -818,9 +836,9 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
const { exporterId, enId: fromId } = from const { exporterId, enId: fromId } = from
const enName = nodeName(fromId) const enName = nodeName(fromId)
const viaName = nodeName(exporterId) const viaName = nodeName(exporterId)
bumpDestFrom(svcEdges, svcPaths, svcId, from, exporterId, fromId, enName, viaName) bumpDestFrom(svcEdges, svcPaths, svcId, from, exporterId, fromId, enName, viaName, detail)
bumpDestFrom(ccEdges, ccPaths, country.id, from, exporterId, fromId, enName, viaName) bumpDestFrom(ccEdges, ccPaths, country.id, from, exporterId, fromId, enName, viaName)
bumpDestFrom(nestedEdges, nestedPaths, nestedId, from, exporterId, fromId, enName, viaName, country.id) bumpDestFrom(nestedEdges, nestedPaths, nestedId, from, exporterId, fromId, enName, viaName, detail, country.id)
} }
} }
+26 -3
View File
@@ -51,7 +51,7 @@ export async function verifyMcpBgpFilterBinding(actor: AuthUser) {
try { try {
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,username,password) VALUES(79,'binding-fixture','127.0.0.1',$1,false,'fixture','NEVER_BIND_LOGIN')", [address.port]) await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,username,password) VALUES(79,'binding-fixture','127.0.0.1',$1,false,'fixture','NEVER_BIND_LOGIN')", [address.port])
const issued = await create(), principal = await authenticateMcpToken(issued.token) const issued = await create(), principal = await authenticateMcpToken(issued.token)
const prepare = (chain = "in", direction = "input") => invokeMcpTool(principal, "mm_bgp_filter_binding_plan", { serverId: 79, id: "*peer", chain, direction }) as Promise<{ planId: string; state: string }> const prepare = (chain = "in", direction = "input") => invokeMcpTool(principal, "mm_bgp_filter_binding_plan", { serverId: 79, id: "*peer", chain, direction }) as Promise<{ planId: string; state: string; changes: { objects: { kind: string; id: string }[] } }>
const wait = async (id: string) => { for (let n = 0; n < 400; n++) { const row = (await pool.query("SELECT id,state,error_code FROM mcp_operations WHERE id=$1", [id])).rows[0]; if (row && !["pending", "running"].includes(row.state)) return row; await delay(25) } assert.fail("Binding operation did not terminate") } const wait = async (id: string) => { for (let n = 0; n < 400; n++) { const row = (await pool.query("SELECT id,state,error_code FROM mcp_operations WHERE id=$1", [id])).rows[0]; if (row && !["pending", "running"].includes(row.state)) return row; await delay(25) } assert.fail("Binding operation did not terminate") }
const apply = async (planId: string) => { await approvePlan(planId, actor, true); return wait((await applyPlan(principal, planId, randomUUID())).id) } const apply = async (planId: string) => { await approvePlan(planId, actor, true); return wait((await applyPlan(principal, planId, randomUUID())).id) }
for (const permission of permissions) { const denied = await create(permissions.filter(value => value !== permission)), before = reads; await assert.rejects(invokeMcpTool(await authenticateMcpToken(denied.token), "mm_bgp_filter_binding_plan", { serverId: 79, id: "*peer", chain: "in", direction: "input" })); assert.equal(reads, before) } for (const permission of permissions) { const denied = await create(permissions.filter(value => value !== permission)), before = reads; await assert.rejects(invokeMcpTool(await authenticateMcpToken(denied.token), "mm_bgp_filter_binding_plan", { serverId: 79, id: "*peer", chain: "in", direction: "input" })); assert.equal(reads, before) }
@@ -70,12 +70,35 @@ export async function verifyMcpBgpFilterBinding(actor: AuthUser) {
Object.assign(peer, context); Object.assign(collections["/routing/bgp/instance"][0], { vrf: "lab", "routing-table": "lab" }) Object.assign(peer, context); Object.assign(collections["/routing/bgp/instance"][0], { vrf: "lab", "routing-table": "lab" })
Object.assign(peer, { instance: "*instance", vrf: "*vrf", "routing-table": "*table" }); assert.equal((await apply((await prepare()).planId)).state, "applied"); Object.assign(peer, context) Object.assign(peer, { instance: "*instance", vrf: "*vrf", "routing-table": "*table" }); assert.equal((await apply((await prepare()).planId)).state, "applied"); Object.assign(peer, context)
collections["/ip/vrf"].push({ ".id": "*mainVrf", name: "main", interfaces: "all" }) collections["/ip/vrf"].push({ ".id": "*mainVrf", name: "main", interfaces: "all" })
collections["/routing/table"].push({ ".id": "*mainTable", name: "main", fib: "" }) const mainTable: Record<string, string> = { ".id": "*mainTable", name: "main", fib: "" }
const peerTable: Record<string, string> = { ".id": "*peerTable", name: "rtab-antiblock", fib: "true" }
collections["/routing/table"].push(mainTable, peerTable)
const instance = collections["/routing/bgp/instance"][0] const instance = collections["/routing/bgp/instance"][0]
delete instance.vrf; delete instance["routing-table"] delete instance.vrf; delete instance["routing-table"]
Object.assign(peer, { vrf: "main", "routing-table": "main" }); unsetInstanceContext = true Object.assign(peer, { vrf: "main", "routing-table": "main" }); unsetInstanceContext = true
assert.equal((await apply((await prepare()).planId)).state, "applied") assert.equal((await apply((await prepare()).planId)).state, "applied")
peer["routing-table"] = "lab"; await assert.rejects(prepare()) Object.assign(instance, { vrf: "main", "routing-table": "main" })
peer["routing-table"] = peerTable.name
for (const table of [mainTable, peerTable]) {
const stale = await prepare("in", "output")
const writesBefore: number = writes
table.comment = "changed after preview"
assert.notEqual((await apply(stale.planId)).state, "applied")
assert.equal(writes, writesBefore)
delete table.comment
}
const overrideTablePlan = await prepare("in", "output")
assert.deepEqual(overrideTablePlan.changes.objects.filter(row => row.kind === "routing_table").map(row => row.id).sort(), ["*mainTable", "*peerTable"])
assert.equal((await apply(overrideTablePlan.planId)).state, "applied")
assert.equal(local["output.filter-chain"], "in")
assert.equal(peer["routing-table"], "rtab-antiblock")
assert.equal(instance["routing-table"], "main")
peer.vrf = "lab"; await assert.rejects(prepare()); peer.vrf = "main"
for (const foreignTableRef of ["lab", "*table"]) {
peer["routing-table"] = foreignTableRef
await assert.rejects(prepare(), "A table owned by another VRF cannot override the main instance table")
}
peer["routing-table"] = "lab"
Object.assign(instance, { vrf: "main", "routing-table": "lab" }) Object.assign(instance, { vrf: "main", "routing-table": "lab" })
assert.equal((await apply((await prepare("out", "output")).planId)).state, "applied") assert.equal((await apply((await prepare("out", "output")).planId)).state, "applied")
Object.assign(peer, context); Object.assign(instance, { vrf: "lab", "routing-table": "lab" }); unsetInstanceContext = false Object.assign(peer, context); Object.assign(instance, { vrf: "lab", "routing-table": "lab" }); unsetInstanceContext = false
+91
View File
@@ -0,0 +1,91 @@
"use client"
import { ChevronDownIcon, ChevronRightIcon } from "lucide-react"
import type { KeyboardEvent } from "react"
import { MAP_CARD_H, MAP_CARD_W, placeMapLinkLabels, type MapBox } from "@/lib/network-map-layout"
import type { MapGroupLink } from "@/lib/network-map-group-links"
function activate(event: KeyboardEvent<SVGGElement>, action: () => void) {
if (event.key !== "Enter" && event.key !== " ") return
event.preventDefault()
event.stopPropagation()
action()
}
const roleColors: Record<string, string> = {
HR: "var(--chart-2)", JH: "var(--chart-1)", EN: "var(--chart-3)", IX: "var(--chart-4)", WAN: "var(--muted-foreground)",
}
export function MapGroupMark({ id, x, y, name, code, count, expanded, problems = 0, unknownCount = 0, onToggle, visible = true }: {
id: string; x: number; y: number; name: string; code: string; count: number; expanded: boolean
problems?: number; unknownCount?: number; onToggle: () => void; visible?: boolean
}) {
const width = MAP_CARD_W, height = MAP_CARD_H
const color = roleColors[code] ?? "var(--muted-foreground)"
const Chevron = expanded ? ChevronDownIcon : ChevronRightIcon
const health = problems ? `Проблемы · ${problems}` : unknownCount ? `Нет данных · ${unknownCount}` : ""
const label = [name, `${code} × ${count}`, health, problems && unknownCount ? `Нет данных · ${unknownCount}` : ""].filter(Boolean).join(" · ")
return <g transform={`translate(${x - width / 2},${y - height / 2})`} data-map-group={id}
role="button" tabIndex={visible ? 0 : -1} aria-expanded={expanded} aria-label={`${expanded ? "Свернуть" : "Раскрыть"} группу · ${label}`}
className="network-map-focusable cursor-pointer" opacity={visible ? 1 : 0.1}
onPointerDown={event => event.stopPropagation()} onClick={event => { event.stopPropagation(); onToggle() }}
onKeyDown={event => activate(event, onToggle)}>
<title>{label}</title>
<rect className="network-map-focus-ring" x="-4" y="-4" width={width + 8} height={height + 8} rx="14" fill="none" stroke="var(--ring)" strokeWidth="2" />
<rect data-map-box="group" width={width} height={height} rx="11" fill="var(--card)" stroke={problems ? "var(--warning)" : "var(--border)"} strokeWidth="1.5" strokeDasharray={expanded ? "4 3" : undefined} />
<rect x="8" y="7" width="50" height="19" rx="5" fill={color} fillOpacity=".15" />
<text x="33" y="20" textAnchor="middle" fill={color} fontSize="10.5" fontFamily="Geist Mono,monospace" fontWeight="600">{code} ×{count}</text>
<text x="64" y="20" fill={problems ? "var(--status-degraded-fg)" : "var(--muted-foreground)"} fontSize="10.5">{health}</text>
<Chevron x={width - 19} y="32" width="14" height="14" color="var(--muted-foreground)" />
<text x="10" y="43" fill="var(--foreground)" fontSize={name.length > 18 ? 11 : 12} fontWeight="600">{name.length > 21 ? name.slice(0, 20) + "…" : name}</text>
</g>
}
const linkNames: Record<MapGroupLink["type"], string> = {
gre: "GRE", "wan-jh": "WAN → JH", wan: "WAN", ix: "IX", user: "Привязки", service: "Пути к назначению", observation: "Наблюдения IPFIX",
}
function linkColor(link: MapGroupLink) {
if (link.down === link.count) return "var(--status-offline)"
if (link.down || link.degraded) return "var(--status-degraded)"
if (link.type === "gre") return "var(--status-online)"
if (link.type === "user") return "var(--chart-2)"
if (link.type === "service" || link.type === "ix") return "var(--chart-4)"
return "var(--muted-foreground)"
}
export function MapGroupLinks({ links, obstacles, onExpand, layer = "all" }: {
links: MapGroupLink[]; obstacles: MapBox[]; onExpand: (ids: string[]) => void; layer?: "all" | "lines" | "labels"
}) {
// Place outage labels first so that a routine count cannot occupy their available space.
const entries = [...links].sort((a, b) => b.down - a.down || b.degraded - a.degraded).map(row => {
const type = linkNames[row.type], color = linkColor(row)
const summary = [`${type} ×${row.count}`, row.down ? `недоступно ${row.down} из ${row.count}` : "", row.degraded ? `ухудшено · ${row.degraded}` : ""].filter(Boolean).join(" · ")
const texts = row.down ? [`Недоступно ${row.down} из ${row.count}`, `↓ ${row.down}/${row.count}`] :
row.degraded ? [`Ухудшено ${row.degraded} из ${row.count}`, `! ${row.degraded}/${row.count}`] : [`${type} ×${row.count}`, `×${row.count}`]
return { ...row, color, texts, title: `${row.from.name} → ${row.to.name} · ${summary}` }
})
const labels = layer === "lines" ? [] : placeMapLinkLabels(entries, obstacles)
return <>
{layer !== "labels" && entries.map(row => (
<g key={row.id} data-map-group-link={row.type} data-channel-count={row.count} data-channel-down={row.down} role="button" tabIndex={0}
aria-label={`${row.title} · Раскрыть группу`} className="network-map-focusable cursor-pointer"
onPointerDown={event => event.stopPropagation()} onClick={event => { event.stopPropagation(); onExpand(row.groups) }}
onKeyDown={event => activate(event, () => onExpand(row.groups))}>
<title>{row.title}</title>
<path className="network-map-focus-ring" d={row.link.d} fill="none" stroke="var(--ring)" strokeWidth="6" />
<path d={row.link.d} fill="none" stroke={row.color} strokeWidth={row.type === "gre" ? 2.5 : 1.7}
strokeDasharray={row.down || row.degraded || row.type === "observation" ? "5 4" : undefined} strokeLinecap="round" />
<path d={row.link.d} fill="none" stroke="transparent" strokeWidth="16" />
</g>
))}
{labels.map(row => (
<g key={row.id} transform={`translate(${row.x},${row.y})`} data-map-group-link-label={row.type} className="cursor-pointer" aria-hidden="true"
onPointerDown={event => event.stopPropagation()} onClick={event => { event.stopPropagation(); onExpand(row.groups) }}>
<title>{row.title}</title>
<rect data-map-box="pill" x={-row.w / 2} y="-10" width={row.w} height="20" rx="10" fill="var(--card)" stroke={row.down || row.degraded ? row.color : "var(--border)"} />
<text textAnchor="middle" dy="4" fill={row.down === row.count ? "var(--status-offline-fg)" : row.down || row.degraded ? "var(--status-degraded-fg)" : "var(--foreground)"} fontSize="11" fontFamily="Geist Mono,monospace">{row.text}</text>
</g>
))}
</>
}
+50 -23
View File
@@ -17,6 +17,7 @@ import { projectTrafficObservations } from "@/lib/traffic-observations"
import { getFlowAnalytics, getFlowMapHops } from "@/shared/api/traffic-flow" import { getFlowAnalytics, getFlowMapHops } from "@/shared/api/traffic-flow"
import { requestJson } from "@/shared/api/http-client" import { requestJson } from "@/shared/api/http-client"
import { matchesMapService } from "@/lib/flow-map-service-match" import { matchesMapService } from "@/lib/flow-map-service-match"
import { mapTrafficCategory } from "@/lib/map-traffic-category"
const evidenceLabel: Record<FlowServiceBasis, string> = { const evidenceLabel: Record<FlowServiceBasis, string> = {
catalog: "По каталогу", catalog: "По каталогу",
@@ -27,6 +28,27 @@ const evidenceLabel: Record<FlowServiceBasis, string> = {
} }
const percent = new Intl.NumberFormat("ru-RU", {style: "percent", maximumFractionDigits: 1}) const percent = new Intl.NumberFormat("ru-RU", {style: "percent", maximumFractionDigits: 1})
function CategoryEvidence({service, path, onCategory}: {
service: FlowMapService
path?: FlowMapServicePath
onCategory?: (category: string) => void
}) {
const category = mapTrafficCategory(service, path)
const observation = path ?? service
const evidence = observation.serviceEvidence ?? []
return <div className="space-y-1.5 text-xs">
<div className="flex flex-wrap items-baseline gap-x-2">
<span className="text-muted-foreground">Категория трафика</span>
{onCategory ? <Button type="button" size="xs" variant="link" className="h-auto p-0" onClick={() => onCategory(category)}>{category}</Button> : <strong>{category}</strong>}
</div>
{evidence.length ? <ul aria-label="Основание классификации" className="flex flex-wrap gap-1">
{evidence.map(row => <li key={row.basis}><Badge size="sm" variant={row.basis === "heuristic" ? "info-light" : "secondary"}>
{evidenceLabel[row.basis]}{observation.bytes > 0 && row.bytes < observation.bytes && ` · ${percent.format(row.bytes / observation.bytes)}`}
</Badge></li>)}
</ul> : <p className="text-muted-foreground">Основание классификации в этом снимке не передано</p>}
</div>
}
export function InspectorMetrics({ rows }: { rows: [string, ReactNode, string?][] }) { export function InspectorMetrics({ rows }: { rows: [string, ReactNode, string?][] }) {
return <dl className="grid grid-cols-2 gap-px overflow-hidden rounded-t-lg border-b bg-border"> return <dl className="grid grid-cols-2 gap-px overflow-hidden rounded-t-lg border-b bg-border">
{rows.map(([name, value, title]) => <div key={name} title={title} className="flex min-w-0 flex-col gap-0.5 bg-card px-3.5 py-2.5"> {rows.map(([name, value, title]) => <div key={name} title={title} className="flex min-w-0 flex-col gap-0.5 bg-card px-3.5 py-2.5">
@@ -112,11 +134,13 @@ export function NodeHistory({ base, id, refresh, degraded }: { base: string | nu
</> </>
} }
export function ServiceInspector({ service, paths, exits, exitName, country, base, refresh, windowLabel, history, shareOfVisible, flowAt, stale, activePath, onPath, onClose, filtered, onFilter, userId, ix, topology }: { export function ServiceInspector({ service, paths, exits, exitName, country, base, refresh, windowLabel, history, shareOfVisible, shareKnown = true, flowAt, stale, activePath, onPath, onClose, onCategory, filtered, onFilter, userId, ix, topology }: {
service: FlowMapService; paths: FlowMapServicePath[]; exits: FlowMapServiceEdge[]; exitName: (id: string) => string service: FlowMapService; paths: FlowMapServicePath[]; exits: FlowMapServiceEdge[]; exitName: (id: string) => string
country?: string; base: string | null; refresh: number; windowLabel: string; flowAt: string | null; stale: boolean country?: string; base: string | null; refresh: number; windowLabel: string; flowAt: string | null; stale: boolean
history?: {service?: FlowMapService; window: string} history?: {service?: FlowMapService; window: string}
shareOfVisible: boolean shareOfVisible: boolean
shareKnown?: boolean
onCategory?: (category: string) => void
activePath: FlowMapServicePath | null; onPath: (path: FlowMapServicePath) => void activePath: FlowMapServicePath | null; onPath: (path: FlowMapServicePath) => void
onClose: () => void; filtered: boolean; onFilter: () => void onClose: () => void; filtered: boolean; onFilter: () => void
userId?: string; ix?: boolean; topology?: ReadonlySet<string> userId?: string; ix?: boolean; topology?: ReadonlySet<string>
@@ -151,7 +175,7 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
const countryFilter = service.id.startsWith("cc:other|") ? "unknown" : country const countryFilter = service.id.startsWith("cc:other|") ? "unknown" : country
const flows = recent?.data.conversationsList.filter(row => (!topology || topology.has(row.enId || row.serverId)) && matchesMapService(row, service.label, countryFilter)) const flows = recent?.data.conversationsList.filter(row => (!topology || topology.has(row.enId || row.serverId)) && matchesMapService(row, service.label, countryFilter))
.sort((a, b) => b.bps - a.bps).slice(0, 5) ?? [] .sort((a, b) => b.bps - a.bps).slice(0, 5) ?? []
const asns = [...new Set(flows.flatMap(flow => flow.dstAsn ? [flow.dstAsn] : []))] const selectedPath = activePath && paths.find(path => servicePathKey(path) === servicePathKey(activePath))
const rates = [...exits].sort((a, b) => b.bps - a.bps) const rates = [...exits].sort((a, b) => b.bps - a.bps)
const exitIds = [...new Set([...rates.filter(e => !e.observedOnly).map(e => e.fromId), ...paths.map(p => p.enId).filter(Boolean)])] const exitIds = [...new Set([...rates.filter(e => !e.observedOnly).map(e => e.fromId), ...paths.map(p => p.enId).filter(Boolean)])]
const exporterIds = [...new Set([...rates.filter(e => e.observedOnly).map(e => e.fromId), ...paths.filter(p => !p.enId).map(p => p.viaId)])] const exporterIds = [...new Set([...rates.filter(e => e.observedOnly).map(e => e.fromId), ...paths.filter(p => !p.enId).map(p => p.viaId)])]
@@ -163,7 +187,6 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
const averageWindow = history?.window ?? windowLabel const averageWindow = history?.window ?? windowLabel
const volumeBytes = currentVolume ? average?.bytes : volume?.bytes const volumeBytes = currentVolume ? average?.bytes : volume?.bytes
const trafficTypes = service.trafficTypes ?? [] const trafficTypes = service.trafficTypes ?? []
const serviceEvidence = service.serviceEvidence ?? []
const otherTypeBytes = Math.max(0, service.bytes - trafficTypes.reduce((sum, row) => sum + row.bytes, 0)) const otherTypeBytes = Math.max(0, service.bytes - trafficTypes.reduce((sum, row) => sum + row.bytes, 0))
const typeShare = (bytes: number) => percent.format(Math.min(1, bytes / service.bytes)) const typeShare = (bytes: number) => percent.format(Math.min(1, bytes / service.bytes))
const trafficQuery = new URLSearchParams({ view: "flows", service: service.label, serviceId: service.id, from: "map" }) const trafficQuery = new URLSearchParams({ view: "flows", service: service.label, serviceId: service.id, from: "map" })
@@ -180,39 +203,42 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
<header className="flex items-center gap-2 px-3 py-3"> <header className="flex items-center gap-2 px-3 py-3">
<div className="grid size-8 shrink-0 place-items-center rounded-md bg-muted"><ServiceBrandIcon label={service.label} size={18} /></div> <div className="grid size-8 shrink-0 place-items-center rounded-md bg-muted"><ServiceBrandIcon label={service.label} size={18} /></div>
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold" title={service.label}>{service.label}</h2> <div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold" title={service.label}>{service.label}</h2>
<p className="truncate text-[11px] text-muted-foreground" title={flowAt ? new Date(flowAt).toLocaleString("ru-RU") : undefined}>{[service.category, asns.length === 1 ? "AS" + asns[0] : null, country, windowLabel].filter(Boolean).join(" · ")}</p></div> <p className="truncate text-[11px] text-muted-foreground" title={flowAt ? new Date(flowAt).toLocaleString("ru-RU") : undefined}>{[country, "IPFIX", windowLabel].filter(Boolean).join(" · ")}</p></div>
<Badge size="sm" variant={observed ? "success-light" : "secondary"} title="Наличие трафика в окне NetFlow"><span aria-hidden>•</span>{stale ? "Архив" : observed ? "Есть трафик" : "Нет трафика"}</Badge> <Badge size="sm" variant={observed ? "success-light" : "secondary"} title="Наличие трафика в окне NetFlow"><span aria-hidden>•</span>{stale ? "Архив" : observed ? "Есть трафик" : "Нет трафика"}</Badge>
<Button size="icon-xs" variant="ghost" aria-label="Закрыть детали назначения" onClick={onClose}><XIcon /></Button> <Button size="icon-xs" variant="ghost" aria-label="Закрыть детали назначения" onClick={onClose}><XIcon /></Button>
</header> </header>
<div className="mx-0.5 mb-0.5 min-h-0 overflow-y-auto rounded-lg border"> <div className="mx-0.5 mb-0.5 min-h-0 overflow-y-auto rounded-lg border">
<InspectorMetrics rows={[ <InspectorMetrics rows={[
["Средняя за " + averageWindow, average ? formatNetflowRate(average) : "—", "Скорость по сохранённым потокам IPFIX"], ["Средняя за " + averageWindow, average ? formatNetflowRate(average) : "—", "Скорость по сохранённым потокам IPFIX"],
[shareOfVisible ? "Доля показанных сервисов" : country ? "Доля страны" : "Доля трафика", percent.format(service.share), "IPFIX · " + windowLabel], [shareOfVisible ? "Доля показанных сервисов" : country ? "Доля страны" : "Доля трафика", shareKnown ? 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>}</>], ["Объём · " + (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 exitIds.length || !exporterIds.length
? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined] ? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined]
: ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"], : ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"],
]} /> ]} />
{trafficTypes.length > 0 && service.bytes > 0 && <section className="space-y-2 border-b px-3.5 py-3 text-xs" aria-label="Состав трафика IPFIX"> {selectedPath && <section aria-label="Выбранный поток" className="space-y-2 border-b px-3.5 py-3 text-xs">
<h3 className="font-medium">Выбранный поток</h3>
<p className="break-words">{[selectedPath.clientId === "—" ? "Без привязки" : selectedPath.clientName, selectedPath.viaName || selectedPath.viaId, selectedPath.enId !== selectedPath.viaId && (selectedPath.enName || selectedPath.enId), service.label].filter(Boolean).join(" → ")}</p>
<p>{selectedPath.enId ? "Выход подтверждён" : "Наблюдение IPFIX · выход не подтверждён"}</p>
<CategoryEvidence service={service} path={selectedPath} onCategory={onCategory} />
{selectedPath.trafficTypes?.map(row => <p key={JSON.stringify([row.application,row.transport])} className="text-muted-foreground">
{[row.application,row.transport].filter(Boolean).join(" · ")} · {formatBytes(row.bytes)}
</p>)}
<p className="font-mono tabular-nums">IPFIX · среднее за {windowLabel} · {formatNetflowRate(selectedPath)} · {formatBytes(selectedPath.bytes)}</p>
</section>}
<section className="space-y-2 border-b px-3.5 py-3 text-xs" aria-label="Состав трафика IPFIX">
<h3 className="flex justify-between gap-2 font-medium"><span>Состав трафика</span><span className="font-normal text-muted-foreground">IPFIX · {windowLabel}</span></h3> <h3 className="flex justify-between gap-2 font-medium"><span>Состав трафика</span><span className="font-normal text-muted-foreground">IPFIX · {windowLabel}</span></h3>
<dl className="space-y-1"> <CategoryEvidence service={service} onCategory={onCategory} />
{trafficTypes.length > 0 && service.bytes > 0 && <dl className="space-y-1">
{trafficTypes.map(({transport, application, bytes}) => <div key={JSON.stringify([transport, application])} className="flex justify-between gap-2"> {trafficTypes.map(({transport, application, bytes}) => <div key={JSON.stringify([transport, application])} className="flex justify-between gap-2">
<dt>{application ? `${application} · ${transport}` : transport}</dt> <dt>{application ? `${application} · ${transport}` : transport}</dt>
<dd className="shrink-0 font-mono tabular-nums">{typeShare(bytes)}</dd> <dd className="shrink-0 font-mono tabular-nums">{typeShare(bytes)}</dd>
</div>)} </div>)}
{otherTypeBytes > 0 && <div className="flex justify-between gap-2"><dt>Остальные типы</dt><dd className="font-mono tabular-nums">{typeShare(otherTypeBytes)}</dd></div>} {otherTypeBytes > 0 && <div className="flex justify-between gap-2"><dt>Остальные типы</dt><dd className="font-mono tabular-nums">{typeShare(otherTypeBytes)}</dd></div>}
</dl> </dl>}
{trafficTypes.some(row => row.application) && <p className="text-muted-foreground">Приложения определены по портам.</p>} {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>} {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"> </section>
{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} /> <InspectorUsers users={serviceUsers(service, paths)} windowLabel={windowLabel} />
<section className="space-y-2 border-b px-3.5 py-3"><h3 className="text-[11px] text-muted-foreground">Путь трафика</h3> <section className="space-y-2 border-b px-3.5 py-3"><h3 className="text-[11px] text-muted-foreground">Путь трафика</h3>
{paths.map(p => { {paths.map(p => {
@@ -222,26 +248,27 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
const active = activePath && servicePathKey(activePath) === key const active = activePath && servicePathKey(activePath) === key
return <button type="button" key={key} onClick={() => onPath(p)} aria-pressed={Boolean(active)} title={formatNetflowRate(p)} className={cn("flex w-full flex-wrap items-center gap-1 rounded-sm text-left", active && "ring-1 ring-primary")}> return <button type="button" key={key} onClick={() => onPath(p)} aria-pressed={Boolean(active)} title={formatNetflowRate(p)} className={cn("flex w-full flex-wrap items-center gap-1 rounded-sm text-left", active && "ring-1 ring-primary")}>
{parts.map((name, i) => <span key={i} className="inline-flex max-w-full items-center gap-1">{i > 0 && <ChevronRightIcon aria-hidden className="size-3 shrink-0 text-muted-foreground" />}<span className={cn("truncate rounded-md bg-muted px-1.5 py-1 font-mono text-[10px] font-semibold", i === parts.length - 1 && "bg-chart-4/20")}>{name}</span></span>)} {parts.map((name, i) => <span key={i} className="inline-flex max-w-full items-center gap-1">{i > 0 && <ChevronRightIcon aria-hidden className="size-3 shrink-0 text-muted-foreground" />}<span className={cn("truncate rounded-md bg-muted px-1.5 py-1 font-mono text-[10px] font-semibold", i === parts.length - 1 && "bg-chart-4/20")}>{name}</span></span>)}
{!p.enId && <span className="basis-full text-[10px] text-muted-foreground"> <span className="basis-full text-[10px] text-muted-foreground">{p.enId ? "Выход подтверждён" :
Наблюдение IPFIX{p.viaIface ? ` · интерфейс ${p.viaIface}` : ""} · выход не подтверждён `Наблюдение IPFIX${p.viaIface ? ` · интерфейс ${p.viaIface}` : ""} · выход не подтверждён`}</span>
</span>}
</button> </button>
})} })}
{rates.filter(e => !paths.some(p => (p.enId || p.viaId) === e.fromId && Boolean(p.enId) !== Boolean(e.observedOnly))).map(e => <div key={e.fromId} className="flex justify-between gap-2 text-xs"><span>{exitName(e.fromId)} → {service.label}{e.observedOnly && " · наблюдение IPFIX"}</span><span className="shrink-0 font-mono">{formatNetflowRate(e)}</span></div>)} {rates.filter(e => !paths.some(p => (p.enId || p.viaId) === e.fromId && Boolean(p.enId) !== Boolean(e.observedOnly))).map(e => <div key={e.fromId} className="flex justify-between gap-2 text-xs"><span>{exitName(e.fromId)} → {service.label}{e.observedOnly && " · наблюдение IPFIX"}</span><span className="shrink-0 font-mono">{formatNetflowRate(e)}</span></div>)}
{remainder > 0 && <div className="flex justify-between gap-2 text-xs text-muted-foreground"><span>Выход не определён</span><span className="font-mono">{formatNetflowRate({bps:service.bps * remainder / service.bytes})}</span></div>} {remainder > 0 && <div className="flex justify-between gap-2 text-xs text-muted-foreground"><span>Выход не определён</span><span className="font-mono">{formatNetflowRate({bps:service.bps * remainder / service.bytes})}</span></div>}
{!paths.length && !rates.length && !remainder && <p className="text-xs text-muted-foreground">Маршрут не определён</p>} {!paths.length && !rates.length && !remainder && <p className="text-xs text-muted-foreground">Маршрут не определён</p>}
</section> </section>
<section className="space-y-3 border-b px-3.5 py-3"><h3 className="flex items-center justify-between font-mono text-[11px] text-muted-foreground"><span>Крупные потоки · {recent?.data.sourceWindow?.effectiveMinutes ?? 5} мин</span><span title="Наблюдения экспортёров">{recent ? flows.length : "—"}</span></h3> <section className="space-y-3 border-b px-3.5 py-3"><h3 className="flex items-center justify-between font-mono text-[11px] text-muted-foreground"><span>Крупные потоки · IPFIX{recent ? ` · ${recent.data.sourceWindow?.effectiveMinutes ?? 5} мин` : ""}</span><span title="Наблюдения экспортёров">{recent ? flows.length : "—"}</span></h3>
{flows.map((f,i) => { {flows.map((f,i) => {
const port = f.internetPeerPort || f.dstPort const port = f.internetPeerPort ?? (f.direction === "to_client" ? f.srcPort : f.dstPort)
const transport = port ? `${f.protoName}/${port}` : f.protoName const transport = port ? `${f.protoName}/${port}` : f.protoName
return <div key={i} className="flex items-center gap-2 text-xs"> return <div key={i} className="flex items-center gap-2 text-xs">
<span aria-hidden className="size-1.5 shrink-0 rounded-full bg-[var(--status-online)]" /> <span aria-hidden className="size-1.5 shrink-0 rounded-full bg-[var(--status-online)]" />
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="font-medium [overflow-wrap:anywhere]">{f.src} → {f.dst}</p> <p className="font-medium [overflow-wrap:anywhere]">{f.src} → {f.dst}</p>
<p className="truncate text-[11px] text-muted-foreground" title={`Экспортёр: ${f.serverName || f.serverId}`}> <p className="truncate text-[11px] text-muted-foreground" title={`Экспортёр: ${f.serverName || f.serverId}`}>
{transport}{f.application && f.application !== transport && f.application !== f.protoName && ` · ${f.application}`} · {f.serverName || f.serverId} {[transport, f.application !== transport && f.application !== f.protoName && f.application, f.serverName || f.serverId].filter(Boolean).join(" · ")}
</p> </p>
<p className="text-[11px] text-muted-foreground">{[mapTrafficCategory(f), f.serviceBasis ? evidenceLabel[f.serviceBasis] : "Основание не передано", f.dstAsn && "AS" + f.dstAsn].filter(Boolean).join(" · ")}</p>
<p className="text-[11px] text-muted-foreground">{f.enId ? `Выход подтверждён · ${f.enName || f.enId}` : "Наблюдение IPFIX · выход не подтверждён"}</p>
</div> </div>
<span className="font-mono text-[11px] text-muted-foreground">{formatNetflowRate({bps:f.bps})}</span> <span className="font-mono text-[11px] text-muted-foreground">{formatNetflowRate({bps:f.bps})}</span>
</div> </div>
+44 -20
View File
@@ -1,6 +1,6 @@
"use client" "use client"
import { useState, type ReactNode } from "react" import { useMemo, useState, type ReactNode } from "react"
import { ChevronDownIcon, ChevronUpIcon } from "lucide-react" import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"
import { FramePanel } from "@/components/reui/frame" import { FramePanel } from "@/components/reui/frame"
import { Badge } from "@/components/reui/badge" import { Badge } from "@/components/reui/badge"
@@ -8,10 +8,16 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { SectionFrame, ToneBadge, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks" import { SectionFrame, ToneBadge, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { CompactDataGrid, type CompactDataGridColumn } from "@/components/data-grids/compact-data-grid"
import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
import { Flag } from "@/components/flag"
export type MapFlowRow = { id: string; client: string; exit: string; dest: string; rate: string; volume: string; hl: boolean } export type MapFlowRow = { id: string; client: string; exit: string; dest: string; rate: string; volume: string; hl: boolean }
export type MapRttRow = { id: string; name: string; route: string; rtt: string; speed: string; tone: Tone; status: string; hl: boolean } export type MapRttRow = { id: string; name: string; route: string; rtt: string; speed: string; tone: Tone; status: string; hl: boolean }
export type MapDestRow = { id: string; label: string; category: string; rate: string; share: number; hl: boolean } export type MapDestRow = {
id: string; label: string; category: string; rate: string; bps: number; share: number | null; hl: boolean
kind?: "service" | "country" | "category"; countryCode?: string
}
export type MapEventRow = { id: string; ts: number; tone: Tone; label: string; title: string; message: string; serverId?: string } export type MapEventRow = { id: string; ts: number; tone: Tone; label: string; title: string; message: string; serverId?: string }
export type MapBottomTab = "flows" | "rtt" | "dest" | "events" export type MapBottomTab = "flows" | "rtt" | "dest" | "events"
@@ -34,14 +40,43 @@ function Row({ cols, hl, children }: { cols: string; hl?: boolean; children: Rea
const FLOW_COLS = "grid-cols-[minmax(160px,1.4fr)_minmax(120px,1fr)_minmax(140px,1.2fr)_110px_100px]" const FLOW_COLS = "grid-cols-[minmax(160px,1.4fr)_minmax(120px,1fr)_minmax(140px,1.2fr)_110px_100px]"
const RTT_COLS = "grid-cols-[minmax(140px,1fr)_minmax(200px,1.6fr)_90px_minmax(120px,1fr)_110px]" const RTT_COLS = "grid-cols-[minmax(140px,1fr)_minmax(200px,1.6fr)_90px_minmax(120px,1fr)_110px]"
const DEST_COLS = "grid-cols-[minmax(160px,1.4fr)_minmax(120px,1fr)_110px_minmax(140px,1fr)]"
const EVENT_COLS = "grid-cols-[70px_110px_minmax(200px,1.4fr)_minmax(200px,2fr)]" const EVENT_COLS = "grid-cols-[70px_110px_minmax(200px,1.4fr)_minmax(200px,2fr)]"
function Destinations({ rows, onDestination, onCategory }: {
rows: MapDestRow[]
onDestination: (id: string) => void
onCategory?: (category: string) => void
}) {
const columns = useMemo<CompactDataGridColumn<MapDestRow>[]>(() => [
{ id: "label", header: "Назначение", size: 125, cell: row => (
<Button type="button" variant="link" size="xs" className="max-w-full justify-start" title={row.label}
data-map-highlight={row.hl || undefined} onClick={() => onDestination(row.id)}>
{row.countryCode ? <span aria-hidden><Flag code={row.countryCode} size={16} /></span> :
(row.kind ?? "service") === "service" && <ServiceBrandIcon label={row.label} size={16} />}
<span className="truncate">{row.label}</span>
</Button>
) },
{ id: "category", header: "Категория", size: 145, cell: row => onCategory && (row.kind ?? "service") === "service" ?
<Button type="button" variant="link" size="xs" className="max-w-full justify-start" title={row.category}
onClick={() => onCategory(row.category)}><span className="truncate">{row.category}</span></Button> :
<span className="text-muted-foreground">{row.category}</span> },
{ id: "bps", header: "Скорость", size: 124, cell: row => <span className="font-mono tabular-nums">{row.rate}</span> },
{ id: "share", header: "Доля окна", size: 145, cell: row => row.share == null ? "Нет данных" :
<span className="flex items-center gap-2">
<span aria-hidden className="bg-muted h-1.5 w-14 overflow-hidden rounded-full"><i className="block h-full rounded-full bg-chart-4" style={{width: `${Math.round(row.share * 100)}%`}} /></span>
<span className="font-mono text-xs tabular-nums">{Math.round(row.share * 100)}%</span>
</span> },
], [onDestination, onCategory])
return <div className="max-h-[min(34svh,310px)] overflow-y-auto [&_tr:has([data-map-highlight])]:bg-primary/8">
<CompactDataGrid data={rows} columns={columns} horizontalScroll emptyTitle="Назначений за окно нет" />
</div>
}
/** /**
* Рабочая панель под картой (макет v3): потоки NetFlow, RTT каналов, назначения и события. * Рабочая панель под картой (макет v3): потоки NetFlow, RTT каналов, назначения и события.
* Строки выбранного объекта подсвечены. * Строки выбранного объекта подсвечены.
*/ */
export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, destinations, events, onEvent, onFlow, onDestination, eventsError, stat }: { export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, destinations, events, onEvent, onFlow, onDestination, onCategory, eventsError, stat }: {
tab: MapBottomTab tab: MapBottomTab
onTab: (tab: MapBottomTab) => void onTab: (tab: MapBottomTab) => void
open: boolean open: boolean
@@ -53,6 +88,7 @@ export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, des
onEvent: (event: MapEventRow) => void onEvent: (event: MapEventRow) => void
onFlow: (id: string) => void onFlow: (id: string) => void
onDestination: (id: string) => void onDestination: (id: string) => void
onCategory?: (category: string) => void
eventsError: string | null eventsError: string | null
stat: string stat: string
}) { }) {
@@ -77,10 +113,10 @@ export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, des
</TabsTrigger> </TabsTrigger>
))} ))}
</TabsList></div> </TabsList></div>
{open && <span className="hidden text-xs text-muted-foreground xl:inline">{stat}</span>}
<Button type="button" variant="ghost" size="icon-sm" aria-expanded={open} aria-controls="network-map-analysis" aria-label={open ? "Свернуть рабочую панель" : "Открыть рабочую панель"} onClick={() => onOpenChange(!open)}>{open ? <ChevronDownIcon /> : <ChevronUpIcon />}</Button> <Button type="button" variant="ghost" size="icon-sm" aria-expanded={open} aria-controls="network-map-analysis" aria-label={open ? "Свернуть рабочую панель" : "Открыть рабочую панель"} onClick={() => onOpenChange(!open)}>{open ? <ChevronDownIcon /> : <ChevronUpIcon />}</Button>
</div> </div>
<FramePanel id="network-map-analysis" hidden={!open} className="p-0"> <FramePanel id="network-map-analysis" hidden={!open} className="p-0">
{open && <p className="px-3 py-1 text-[11px] text-muted-foreground">{stat}</p>}
<TabsContent value="flows"> <TabsContent value="flows">
<Table head={["Пользователь", "Выход / экспортёр", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}> <Table head={["Пользователь", "Выход / экспортёр", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}>
{flows.map((r) => ( {flows.map((r) => (
@@ -108,19 +144,7 @@ export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, des
</Table> </Table>
</TabsContent> </TabsContent>
<TabsContent value="dest"> <TabsContent value="dest">
<Table head={["Назначение", "Категория", "Скорость", "Доля окна"]} cols={DEST_COLS} empty={destinations.length ? null : "Назначений за окно нет"}> <Destinations rows={destinations} onDestination={onDestination} onCategory={onCategory} />
{destinations.map((r) => (
<Row key={r.id} cols={DEST_COLS} hl={r.hl}>
<Button type="button" variant="link" size="xs" className="min-w-0 justify-start" onClick={() => onDestination(r.id)}><span className="truncate">{r.label}</span></Button>
<span className="text-muted-foreground truncate">{r.category}</span>
<span className="font-mono tabular-nums">{r.rate}</span>
<span className="flex items-center gap-2">
<span className="bg-muted h-1.5 w-20 overflow-hidden rounded-full"><i className="block h-full rounded-full" style={{ width: `${Math.round(Math.min(1, r.share) * 100)}%`, background: "var(--chart-4)" }} /></span>
<span className="font-mono text-xs tabular-nums">{Math.round(r.share * 100)}%</span>
</span>
</Row>
))}
</Table>
</TabsContent> </TabsContent>
<TabsContent value="events"> <TabsContent value="events">
<div className="flex items-center gap-2 border-b px-3 py-1"> <div className="flex items-center gap-2 border-b px-3 py-1">
@@ -149,7 +173,7 @@ export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, des
* «Момент времени» (макет v3): инциденты за 24 часа на шкале и текущий Live-снимок. * «Момент времени» (макет v3): инциденты за 24 часа на шкале и текущий Live-снимок.
* Архив снимков карты не хранится, поэтому прошлые моменты не выбираются. * Архив снимков карты не хранится, поэтому прошлые моменты не выбираются.
*/ */
export function MapTimeline({ events, now, state, onPick }: { events: MapEventRow[]; now: number; state?: string; onPick: (event: MapEventRow) => void }) { export function MapTimeline({ events, now, state, onPick, onJournal }: { events: MapEventRow[]; now: number; state?: string; onPick: (event: MapEventRow) => void; onJournal: () => void }) {
const from = now - 24 * 3_600_000 const from = now - 24 * 3_600_000
const hours = new Map<number, MapEventRow[]>() const hours = new Map<number, MapEventRow[]>()
for (const event of events) { for (const event of events) {
@@ -192,7 +216,7 @@ export function MapTimeline({ events, now, state, onPick }: { events: MapEventRo
<i className="bg-success border-success block size-2.5 rounded-full border-2 shadow-[0_0_0_4px_color-mix(in_oklch,var(--success)_25%,transparent)]" />Live <i className="bg-success border-success block size-2.5 rounded-full border-2 shadow-[0_0_0_4px_color-mix(in_oklch,var(--success)_25%,transparent)]" />Live
</span> </span>
</div> </div>
<small className="text-muted-foreground font-mono text-xs">{new Date(now).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })}</small> <Button type="button" variant="ghost" size="xs" onClick={onJournal}>Журнал</Button>
</div> </div>
) )
} }
@@ -0,0 +1,88 @@
"use client"
import { ChevronRightIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
import { StatusBadge } from "@/components/status-badge"
import type { Server, ServerType } from "@/lib/data"
import type { GreMapEdge } from "@/lib/network-map-layout"
import { channelStatus, countGroupGre } from "@/lib/network-map-group-links"
import { ruPlural } from "./map-kpi-strip"
export function mapSiteName(server: Server) {
const site = server.site?.trim()
return site && site !== "—" ? site : "Без площадки"
}
export function MapChannelList({ edges, selected, onChannel }: {
edges: GreMapEdge[]; selected?: GreMapEdge; onChannel: (edge: GreMapEdge) => void
}) {
return <div className="max-h-56 overflow-y-auto">{edges.map(edge => {
const state = channelStatus(edge)
return <Button type="button" key={JSON.stringify([edge.tunnel.serverId, edge.tunnel.id])} aria-pressed={selected ? edge === selected : undefined}
variant={edge === selected ? "secondary" : "ghost"} className="h-auto min-h-9 w-full justify-between gap-2 whitespace-normal text-left" onClick={() => onChannel(edge)}>
<span className="min-w-0 break-words">{edge.tunnel.name}<small className="block text-muted-foreground">{edge.fromServer.name} ↔ {edge.toServer.name}</small></span>
<StatusBadge status={state === "up" ? "online" : state === "down" ? "offline" : "degraded"} />
</Button>
})}</div>
}
export function MapSiteDirectory({ servers, edges, sites, active, onSite, onServer, onChannel, roleLabels }: {
servers: Server[]
edges: GreMapEdge[]
sites: string[]
active: string | null
onSite: (site: string | null) => void
onServer: (server: Server) => void
onChannel: (edge: GreMapEdge) => void
roleLabels: Record<ServerType, string>
}) {
const members = new Map<string, Server[]>()
for (const server of servers) {
const site = mapSiteName(server)
if (!members.has(site)) members.set(site, [])
members.get(site)!.push(server)
}
const neighbors = new Map<string, GreMapEdge[]>()
for (const edge of edges) {
const a = mapSiteName(edge.fromServer), b = mapSiteName(edge.toServer)
if (a === b || (active !== a && active !== b)) continue
const other = active === a ? b : a
if (!neighbors.has(other)) neighbors.set(other, [])
neighbors.get(other)!.push(edge)
}
if (!sites.length) return null
return <section aria-label="Площадки" className="space-y-2">
<h3 className="text-sm font-semibold">Площадки</h3>
<div className="divide-y rounded-lg border">
{sites.map(site => {
const devices = members.get(site) ?? []
const open = site === active
const problems = devices.filter(s => s.enabled !== false && (s.status === "offline" || s.status === "degraded")).length
return <div key={site}>
<Button type="button" variant="ghost" aria-expanded={open} className="h-auto min-h-10 w-full justify-start gap-2 whitespace-normal px-3 text-left" onClick={() => onSite(open ? null : site)}>
<ChevronRightIcon aria-hidden className={open ? "rotate-90" : ""} />
<span className="min-w-0 flex-1 break-words">{site}</span>
{problems > 0 && <span className="text-xs text-warning">Требуют внимания · {problems}</span>}
<span className="text-xs text-muted-foreground">{devices.length} {ruPlural(devices.length, "узел", "узла", "узлов")}</span>
</Button>
{open && <div className="space-y-2 border-t bg-muted/20 p-2">
{devices.map(server => <Button key={server.id} type="button" variant="ghost" className="h-auto min-h-9 w-full justify-start gap-2 whitespace-normal text-left" onClick={() => onServer(server)}>
<span className="min-w-0 flex-1 break-words">{server.name}{" "}<small className="ml-2 text-muted-foreground">{roleLabels[server.type]}</small></span>
<StatusBadge status={server.status} />
</Button>)}
{Array.from(neighbors, ([neighbor, channels]) => {
const { count, down, degraded } = countGroupGre(channels)
return <details key={neighbor} className="border-t px-2 pt-2">
<summary className="cursor-pointer text-sm">{site} ↔ {neighbor}
{down > 0 && <span className="ml-2 text-warning">Недоступно {down} из {count}</span>}
{degraded > 0 && <span className="ml-2 text-warning">С деградацией · {degraded}</span>}
</summary>
<MapChannelList edges={channels} onChannel={onChannel} />
</details>
})}
</div>}
</div>
})}
</div>
</section>
}
+13
View File
@@ -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
}
+122
View File
@@ -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])
})
+158
View File
@@ -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 }
}
+32
View File
@@ -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), [])
})
+112
View File
@@ -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)
}
+83
View File
@@ -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]
+9 -32
View File
@@ -877,35 +877,6 @@ export function greSourceWanIndexOnMap(
return wanIdx 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-спутника. */ /** GRE на карте только между узлами каталога; у HR конец туннеля — у соответствующего WAN-спутника. */
export interface GreMapEdge { export interface GreMapEdge {
tunnel: GreTunnel tunnel: GreTunnel
@@ -915,6 +886,8 @@ export interface GreMapEdge {
to: { x: number; y: number } to: { x: number; y: number }
fromServer: Server fromServer: Server
toServer: Server toServer: Server
fromWanIndex?: number | null
toWanIndex?: number | null
} }
export function buildGreMapEdges( export function buildGreMapEdges(
@@ -974,9 +947,13 @@ export function buildGreMapEdges(
toServer = a toServer = a
} }
const from = greEndpointAnchor(fromServer, t, "source", nodePos, wanSatPos, resolvedIpv4ByHost) const sourceWan = greSourceWanIndexOnMap(a, t, resolvedIpv4ByHost)
const to = greEndpointAnchor(toServer, t, "peer", nodePos, wanSatPos, resolvedIpv4ByHost) const peerWan = wanIndexMatchingOuterIp(b, t.remoteAddress, resolvedIpv4ByHost)
const edge: GreMapEdge = { tunnel: t, from, to, fromServer, toServer } 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 key = canonicalLinkKey(t, fromServer, toServer)
const group = links.get(key) const group = links.get(key)
if (group) group.push(edge) if (group) group.push(edge)
+15
View File
@@ -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(complete.share, 0.4)
assert.equal(partial.share, 1) 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)
})
+22 -2
View File
@@ -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)) 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( export function scopeMapDestinations(
services: FlowMapService[], edges: FlowMapServiceEdge[], paths: FlowMapServicePath[], services: FlowMapService[], edges: FlowMapServiceEdge[], paths: FlowMapServicePath[],
includes: (id: string) => boolean, userId?: string, retainUnassigned = false, 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) const shareOfVisible = Boolean(userId) || services.some(service => (totals.get(service.id)?.bytes ?? 0) !== service.bytes)
return { return {
shareOfVisible, shareOfVisible,
services: services.flatMap(service => { services: services.flatMap<FlowMapService>(service => {
const total = totals.get(service.id) const total = totals.get(service.id)
if (!total) return [] if (!total) return []
const { trafficTypes, serviceEvidence, lastBucketAt, ...destination } = service const { trafficTypes, serviceEvidence, lastBucketAt, ...destination } = service
const visibleShare = bytes ? total.bytes / bytes : 0 const visibleShare = bytes ? total.bytes / bytes : 0
return [{ ...destination, ...total, share: shareOfVisible ? visibleShare : service.share, 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)), }).sort((a, b) => b.bytes - a.bytes || a.label.localeCompare(b.label)),
edges: visibleEdges, edges: visibleEdges,
paths: visiblePaths, paths: visiblePaths,
+3 -2
View File
@@ -1,5 +1,6 @@
export const networkMapFilters=["all","online","degraded","offline","unknown","jump-host","exit-node","home-router","ix-node"] as const 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 NetworkMapFilter=typeof networkMapFilters[number]
export type MapDestinationMode = "services" | "countries" | "categories"
export function readNetworkMapUrl(params:URLSearchParams){ 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") 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 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(server!==null&&!/^[a-zA-Z0-9_.:-]{1,64}$/.test(server))error="В ссылке указан некорректный сервер карты."
else if(search.length>256)error="Поиск карты в ссылке слишком длинный." else if(search.length>256)error="Поиск карты в ссылке слишком длинный."
else if(!(networkMapFilters as readonly string[]).includes(filter))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="В ссылке указан некорректный аплинк карты." 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>){ export function patchNetworkMapUrl(params:URLSearchParams,values:Record<string,string|null>){
const next=new URLSearchParams(params) const next=new URLSearchParams(params)
+17 -11
View File
@@ -132,6 +132,9 @@ export const trafficFlowOverlayResultSchema = z.object({
hostError: z.string().optional(), hostError: z.string().optional(),
}) })
export const flowServiceBasisSchema = z.enum(["catalog", "network", "heuristic", "port", "unknown"])
export type FlowServiceBasis = z.infer<typeof flowServiceBasisSchema>
export const flowTalkerDtoSchema = z.object({ export const flowTalkerDtoSchema = z.object({
serverId: z.string(), serverId: z.string(),
serverName: z.string(), serverName: z.string(),
@@ -152,6 +155,7 @@ export const flowTalkerDtoSchema = z.object({
application: z.string().optional(), application: z.string().optional(),
category: z.string().optional(), category: z.string().optional(),
service: z.string().optional(), service: z.string().optional(),
serviceBasis: flowServiceBasisSchema.optional(),
dstCountry: z.string().optional(), dstCountry: z.string().optional(),
dstAsn: z.number().int().optional(), dstAsn: z.number().int().optional(),
clientId: z.string().optional(), clientId: z.string().optional(),
@@ -366,17 +370,7 @@ export const flowMapHopDtoSchema = z.object({
bpsRev: z.number().nonnegative(), bpsRev: z.number().nonnegative(),
}) })
export const flowServiceBasisSchema = z.enum(["catalog", "network", "heuristic", "port", "unknown"]) const flowMapClassificationFields = {
export type FlowServiceBasis = z.infer<typeof flowServiceBasisSchema>
export const flowMapServiceDtoSchema = z.object({
id: z.string(),
label: z.string(),
category: z.string(),
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({ trafficTypes: z.array(z.object({
transport: z.string(), transport: z.string(),
application: z.string().nullable(), application: z.string().nullable(),
@@ -386,6 +380,17 @@ export const flowMapServiceDtoSchema = z.object({
basis: flowServiceBasisSchema, basis: flowServiceBasisSchema,
bytes: z.number().positive(), bytes: z.number().positive(),
})).max(flowServiceBasisSchema.options.length).optional(), })).max(flowServiceBasisSchema.options.length).optional(),
}
export const flowMapServiceDtoSchema = z.object({
id: z.string(),
label: z.string(),
category: z.string(),
bytes: z.number().nonnegative(),
bps: z.number().nonnegative(),
share: z.number().min(0).max(1),
lastBucketAt: z.string().datetime().optional(),
...flowMapClassificationFields,
}) })
export const flowMapServiceEdgeDtoSchema = z.object({ export const flowMapServiceEdgeDtoSchema = z.object({
@@ -416,6 +421,7 @@ export const flowMapServicePathDtoSchema = z.object({
serviceId: z.string(), serviceId: z.string(),
bytes: z.number().nonnegative(), bytes: z.number().nonnegative(),
bps: z.number().nonnegative(), bps: z.number().nonnegative(),
...flowMapClassificationFields,
}) })
/** Сервисы внутри одной страны: id вида `cc:us|svc:google`, рёбра от `countryId`. */ /** Сервисы внутри одной страны: id вида `cc:us|svc:google`, рёбра от `countryId`. */
+61
View File
@@ -36,3 +36,64 @@ for(const change of ["backend","mode"])for(const part of ["snapshot","flow","dns
if(change==="backend")await expect(page.getByRole("button",{name:"Устройство Новая карта",exact:true})).toBeVisible() if(change==="backend")await expect(page.getByRole("button",{name:"Устройство Новая карта",exact:true})).toBeVisible()
expect(newReads).toBe(before) expect(newReads).toBe(before)
}) })
test("Карта: плотные группы WAN и узлов раскрывают отказ и найденный объект", async ({page}) => {
const uplinks = Array.from({length: 12}, (_, i) => ({
...wan, id: "wan-" + i, name: "Uplink-" + (i + 1), iface: "ether" + (i + 1), ip: "198.51.100." + (i + 1),
}))
const routers = Array.from({length: 12}, (_, i) => ({
id: i + 2, name: "NSK-JH-" + String(i + 1).padStart(2, "0"), host: "192.0.2." + (i + 2),
type: "jump-host", site: "Новосибирск", country: "RU", enabled: true, status: "online",
}))
const exit = {id: 20, name: "ARN-EXIT", host: "192.0.2.20", type: "exit-node", site: "Стокгольм", country: "SE", enabled: true, status: "online"}
const tunnels = ["up", "down", "up"].map((status, i) => ({
id: "gre-" + i, name: "gre-arn-" + i, serverId: String(routers[0].id), localAddress: routers[0].host, remoteAddress: exit.host,
localInnerIp: `10.60.${i}.1/30`, remoteInnerIp: `10.60.${i}.2/30`, poolId: "pool", ipsec: null, mtu: 1476,
keepaliveInterval: 10, keepaliveRetries: 3, dscp: "inherit", clampTcpMss: true, allowFastPath: true, comment: "", enabled: true, status,
}))
await page.route("**/health", route => route.fulfill({headers, json: {ok: true}}))
await page.route("**/api/**", route => {
const url = new URL(route.request().url())
const replies: Record<string, unknown> = {
"/api/auth/config": {required: false},
"/api/servers": [{...row("NSK-HOME"), site: "Новосибирск", wanUplinks: uplinks}, ...routers, exit],
"/api/filters/gre-tunnels": {tunnels, failures: []},
"/api/uptime/speed-probes": {probes: []},
"/api/traffic/flow/map-hops": emptyMapFlow(url),
}
return route.fulfill({headers, json: replies[url.pathname] ?? {}})
})
await page.goto("/network-map")
const roleGroup = page.locator("[data-map-group]").filter({hasText: "JH ×12"})
const wanGroup = page.locator("[data-map-group]").filter({hasText: "WAN ×12"})
const hiddenServer = page.getByRole("button", {name: "Устройство NSK-JH-12", exact: true})
const hiddenWan = page.getByRole("button", {name: "Аплинк Uplink-12", exact: true})
await expect(roleGroup).toHaveAttribute("aria-expanded", "false")
await expect(roleGroup).toContainText("Проблемы · 1")
await expect(wanGroup).toHaveAttribute("aria-expanded", "false")
await expect(hiddenServer).toHaveCount(0)
await expect(hiddenWan).toHaveCount(0)
const line = page.locator('[data-map-group-link="gre"]')
await expect(line).toHaveAttribute("data-channel-count", "3")
await expect(line).toHaveAttribute("data-channel-down", "1")
const marker = page.locator('[data-map-group-link-label="gre"]')
await expect(marker).toBeVisible()
await marker.click()
await expect(roleGroup).toHaveAttribute("aria-expanded", "true")
await expect(page.getByRole("button", {name: /^Устройство NSK-JH-/})).toHaveCount(12)
await expect(wanGroup).toHaveAttribute("aria-expanded", "false")
await roleGroup.press("Enter")
await expect(hiddenServer).toHaveCount(0)
const search = page.getByRole("textbox", {name: "Поиск узла или назначения"})
const results = page.getByRole("group", {name: "Подсказки поиска"})
await search.fill("NSK-JH-12")
await results.getByRole("button", {name: /NSK-JH-12/}).click()
await expect(hiddenServer).toHaveAttribute("aria-pressed", "true")
await expect(roleGroup).toHaveAttribute("aria-expanded", "true")
await search.fill("Uplink-12")
await results.getByRole("button", {name: /Uplink-12/}).click()
await expect(hiddenWan).toHaveAttribute("aria-pressed", "true")
await expect(wanGroup).toHaveAttribute("aria-expanded", "true")
})
+47 -1
View File
@@ -145,6 +145,43 @@ test("Карта показывает скорость и долю за коро
await expect(dns).toContainText("72 Кбит/с") await expect(dns).toContainText("72 Кбит/с")
}) })
test("На узком экране таблица назначений сортирует категории и открывает их сервисы", async ({page}) => {
await page.setViewportSize({width:320,height:780})
const services = [
{id:"svc:youtube", label:"YouTube", category:"Видео / стриминг", bytes:60, bps:6, share:0.6},
{id:"svc:cloudflare", label:"Cloudflare", category:"CDN", bytes:40, bps:4, share:0.4},
]
await page.route("**/api/**",route => {
const url = new URL(route.request().url())
const responses: Record<string,unknown> = {
"/api/auth/config":{required:false}, "/api/servers":[server], "/api/filters/gre-tunnels":{tunnels:[],failures:[]},
"/api/uptime/speed-probes":{probes:[]},
[flowPath]:{...emptyMapFlow(url),services,totalBytes:100,namedBytes:100},
}
return route.fulfill({json:responses[url.pathname] ?? {}})
})
await page.goto("/network-map")
const analysis = page.getByRole("region", {name:"Рабочая панель карты"})
await analysis.getByRole("tab", {name:/Назначения/}).click()
const grid = analysis.getByRole("table")
const sorter = grid.getByRole("button", {name:"Категория",exact:true})
await expect(sorter).toBeVisible()
const viewport = analysis.locator('[data-slot="scroll-area-viewport"]')
const bounds = await viewport.boundingBox()
const header = await sorter.boundingBox()
expect(header && bounds && header.x + header.width <= bounds.x + bounds.width).toBe(true)
expect(await viewport.evaluate(el => el.scrollWidth > el.clientWidth)).toBe(true)
await sorter.click()
const first = grid.locator("tbody tr").first()
await expect(first).toContainText("Cloudflare")
await sorter.click()
await expect(first).toContainText("YouTube")
await grid.getByRole("button", {name:"CDN",exact:true}).click()
const members = page.getByRole("region", {name:"Сервисы категории"})
await expect(members).toContainText("Cloudflare")
await expect(members).not.toContainText("YouTube")
})
test("Карта не приписывает весь YouTube единственному выходу ARN", async ({page}) => { 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}], trafficTypes: [{transport: "UDP", application: "QUIC", bytes: 900000}],
@@ -191,7 +228,8 @@ test("Карта: DNS виден от экспортёра, пользовате
{clientId: "u1", clientName: "Алиса", bytes: 225000, bps: 6000}, {clientId: "u1", clientName: "Алиса", bytes: 225000, bps: 6000},
{clientId: "—", clientName: "—", bytes: 75000, bps: 2000}, {clientId: "—", clientName: "—", bytes: 75000, bps: 2000},
] ]
const servicePaths = users.map(u => ({...u, viaId: "1", viaName: "MSK", viaIface: "ether1", enId: "", enName: "", serviceId: dns.id})) const servicePaths = users.map(u => ({...u, viaId: "1", viaName: "MSK", viaIface: "ether1", enId: "", enName: "", serviceId: dns.id,
...(u.clientId === "u1" && {serviceEvidence: [{basis: "port", bytes: u.bytes}], trafficTypes: [{transport: "UDP", application: "DNS", bytes: u.bytes}]})}))
await page.route("**/api/**", route => { await page.route("**/api/**", route => {
const url = new URL(route.request().url()) const url = new URL(route.request().url())
const path = url.pathname const path = url.pathname
@@ -229,6 +267,14 @@ test("Карта: DNS виден от экспортёра, пользовате
await expect(panel.getByText(/интерфейс ether1 · выход не подтверждён/i).first()).toBeVisible() await expect(panel.getByText(/интерфейс ether1 · выход не подтверждён/i).first()).toBeVisible()
await panel.getByRole("button").filter({hasText: /Алиса.*Наблюдение IPFIX/}).click() await panel.getByRole("button").filter({hasText: /Алиса.*Наблюдение IPFIX/}).click()
await expect(panel.getByRole("button", {pressed: true}).filter({hasText: "Наблюдение IPFIX"})).toHaveCount(1) await expect(panel.getByRole("button", {pressed: true}).filter({hasText: "Наблюдение IPFIX"})).toHaveCount(1)
const flow = panel.getByRole("region", {name: "Выбранный поток"})
await expect(flow.getByText("По протоколу / порту", {exact: true})).toBeVisible()
await expect(flow).toContainText("DNS · UDP")
await expect(flow).toContainText("выход не подтверждён")
await panel.getByRole("button", {pressed: false}).filter({hasText: "Наблюдение IPFIX"}).click()
await expect(flow).toContainText("Не определена")
await expect(flow).toContainText("Основание классификации в этом снимке не передано")
await expect(flow).not.toContainText("По протоколу / порту")
await page.getByRole("button", {name: "Устройство MSK", exact: true}).press("Enter") await page.getByRole("button", {name: "Устройство MSK", exact: true}).press("Enter")
await expect(breakdown.getByText("Алиса", {exact: true}).locator("..")).toContainText("75%") await expect(breakdown.getByText("Алиса", {exact: true}).locator("..")).toContainText("75%")
}) })
+84
View File
@@ -8,6 +8,71 @@ test.beforeEach(async({page})=>{
await page.route("**/health",r=>r.fulfill({json:{ok:true}})) 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"?emptyMapFlow(r.request().url()):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 [320, 390]) test("Карта: мобильные колонки, выбор отказа и поиск WAN " + width, async ({page}) => {
const uplinks = Array.from({length: 8}, (_, i) => ({...wan, id: "wan-" + i, name: "Провайдер " + (i + 1), iface: "ether" + (i + 1)}))
await page.route("**/api/servers", r => r.fulfill({json: [{...home, wanUplinks: uplinks}, jh]}))
await page.route("**/api/filters/gre-tunnels", r => r.fulfill({json: {tunnels: [{...tunnel, status: "down"}], failures: []}}))
await page.setViewportSize({width, height: 900})
await page.goto("/network-map")
const map = page.getByRole("group", {name: "Интерактивная карта сети"})
const nav = page.getByRole("navigation", {name: "Колонки карты"})
const lane = nav.getByRole("combobox", {name: "Перейти к колонке"})
await expect(lane).toHaveValue("home")
await nav.getByRole("button", {name: "Следующая колонка"}).click()
await expect(lane).toHaveValue("wan")
await nav.getByRole("button", {name: "Предыдущая колонка"}).click()
await expect(lane).toHaveValue("home")
await lane.selectOption("access-nodes")
await expect(nav.getByRole("button", {name: "Следующая колонка"})).toBeDisabled()
await nav.getByRole("button", {name: "К отказу"}).click()
const panel = page.getByRole("complementary", {name: "Детали объекта карты"})
await expect(panel).toContainText(tunnel.name)
await page.keyboard.press("Escape")
await expect(panel).toHaveCount(0)
const search = page.getByRole("textbox", {name: "Поиск узла или назначения"})
await search.fill("ether8")
await page.getByRole("group", {name: "Подсказки поиска"}).getByRole("button", {name: /Провайдер 8/}).click()
await expect(page).toHaveURL(/[?&]wan=7\b/)
await expect(lane).toHaveValue("wan")
const uplink = map.getByRole("button", {name: "Аплинк Провайдер 8"})
await expect(uplink).toHaveAttribute("aria-pressed", "true")
await expect.poll(() => uplink.evaluate(node => {
const r = node.getBoundingClientRect(), view = node.closest("svg")!.getBoundingClientRect()
return r.left >= view.left && r.right <= view.right && r.top >= view.top && r.bottom <= view.bottom
})).toBe(true)
await map.focus()
const before = await map.getAttribute("viewBox")
await map.press("+")
await expect(map).not.toHaveAttribute("viewBox", before!)
const after = await map.getAttribute("viewBox")
await page.waitForResponse(response => response.url().includes("/api/traffic/flow/map-hops") && new URL(response.url()).searchParams.get("range") === "1m")
await expect(map).toHaveAttribute("viewBox", after!)
await expect(uplink).toHaveAttribute("aria-pressed", "true")
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
})
test("Карта: поиск и прямая ссылка показывают устройство из плотной группы рядом с инспектором", async ({page}) => {
const servers = Array.from({length: 12}, (_, i) => ({...jh, id: i + 1, name: "Шлюз " + (i + 1), host: "192.0.2." + (i + 1), site: "Тест"}))
await page.route("**/api/servers", r => r.fulfill({json: servers}))
await page.route("**/api/filters/gre-tunnels", r => r.fulfill({json: {tunnels: [], failures: []}}))
await page.goto("/network-map")
const map = page.getByRole("group", {name: "Интерактивная карта сети"})
const node = map.getByRole("button", {name: "Устройство Шлюз 12", exact: true})
const search = page.getByRole("textbox", {name: "Поиск узла или назначения"})
await search.fill("Шлюз 12")
await page.getByRole("group", {name: "Подсказки поиска"}).getByRole("button", {name: /Шлюз 12/}).click()
await expect(page).toHaveURL(/[?&]server=12\b/)
async function checkFraming() {
await expect(node).toHaveAttribute("aria-pressed", "true")
await expect.poll(() => node.evaluate(el => {
const card = el.getBoundingClientRect(), canvas = el.closest("svg")!.getBoundingClientRect()
const panel = document.querySelector('[aria-label="Детали объекта карты"]')!.getBoundingClientRect()
return card.left >= canvas.left && card.right <= panel.left && card.top >= canvas.top && card.bottom <= canvas.bottom
})).toBe(true)
}
await checkFraming()
await page.reload()
await checkFraming()
})
for(const width of [1440,390,320])test("Карта: доступные детали и адаптивная оболочка "+width,async({page},testInfo)=>{ for(const width of [1440,390,320])test("Карта: доступные детали и адаптивная оболочка "+width,async({page},testInfo)=>{
await page.setViewportSize({width,height:900});await page.goto("/network-map") await page.setViewportSize({width,height:900});await page.goto("/network-map")
await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible() await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
@@ -34,6 +99,25 @@ for(const width of [1440,390,320])test("Карта: доступные дета
await page.getByRole("button",{name:"Слои",exact:true}).click();await expect(page.getByRole("dialog",{name:"Слои карты"})).toBeVisible() await page.getByRole("button",{name:"Слои",exact:true}).click();await expect(page.getByRole("dialog",{name:"Слои карты"})).toBeVisible()
await page.keyboard.press("Escape");await expect(page.getByRole("button",{name:"Слои",exact:true})).toBeFocused();await expect(page).toHaveURL(/server=1/) await page.keyboard.press("Escape");await expect(page.getByRole("button",{name:"Слои",exact:true})).toBeFocused();await expect(page).toHaveURL(/server=1/)
}) })
test("Из площадки в сводке можно открыть соседний канал и устройство без площадки", async ({ page }) => {
await page.route("**/api/servers", route => route.fulfill({ json: [{ ...home, site: "Москва" }, { ...jh, site: "" }] }))
await page.goto("/network-map")
await expect(page.getByRole("button", { name: "Устройство Домашний", exact: true })).toBeVisible()
await page.getByRole("button", { name: "Сводка сети" }).click()
const directory = page.getByRole("region", { name: "Площадки" })
await directory.getByRole("button", { name: /^Москва/ }).click()
await directory.getByText("Москва ↔ Без площадки").click()
await directory.getByRole("button", { name: /gre-home/ }).click()
await expect(page.getByRole("complementary", { name: "Детали объекта карты" })).toContainText("gre-home")
const search = page.getByRole("textbox", { name: "Поиск узла или назначения" })
await search.fill("Без площадки")
await page.getByRole("button", { name: "Без площадки Площадка" }).click()
await directory.getByRole("button", { name: /^Jump JumpHost/ }).click()
await expect(page).toHaveURL(/server=2/)
await page.getByRole("button", { name: "Журнал", exact: true }).click()
await expect(page.getByRole("tab", { name: /События/ })).toHaveAttribute("aria-selected", "true")
})
test("Карта: шкала и рабочая панель фокусируют сбой устройства",async({page})=>{ test("Карта: шкала и рабочая панель фокусируют сбой устройства",async({page})=>{
const now = new Date().toISOString() const now = new Date().toISOString()
await page.route("**/api/events?*", route => route.fulfill({json:{events:[ await page.route("**/api/events?*", route => route.fulfill({json:{events:[
+28
View File
@@ -35,6 +35,34 @@ async function overlaps(page: Page) {
}) })
} }
test("Категория открывает сервисы, фильтрует потоки и сохраняет контекст при возврате", async ({ page }) => {
const services = [
{ id: "svc:video", label: "Видео A", category: "Видео", bytes: 900, bps: 120, share: 0.9 },
{ id: "svc:tiny", label: "Видео B", category: "Видео", bytes: 50, bps: 6, share: 0.05 },
{ id: "svc:dns", label: "DNS", category: "DNS", bytes: 50, bps: 6, share: 0.05 },
]
const paths = services.map(s => ({clientId: "a", clientName: "A", viaId: "1", viaName: "Вход", enId: "", enName: "", serviceId: s.id, bytes: s.bytes, bps: s.bps}))
const edges = services.map(s => ({fromId: "1", toId: s.id, observedOnly: true, bytes: s.bytes, bps: s.bps, bpsFwd: s.bps, bpsRev: 0}))
await serve(page, [srv(1, "Вход", "jump-host")], [], {services, servicePaths: paths, serviceEdges: edges, totalBytes: 1000, namedBytes: 1000})
await page.goto("/network-map")
await page.getByRole("button", {name: "Категории", exact: true}).click()
const map = page.getByRole("group", {name: "Интерактивная карта сети"})
const category = map.getByRole("button", {name: "Категория Видео", exact: true})
await expect(category).toContainText("95%")
await category.press("Enter")
const details = page.getByRole("complementary", {name: "Детали объекта карты"})
await expect(details.getByRole("heading", {name: "Видео", exact: true})).toBeVisible()
await details.getByRole("button", {name: "Потоки категории (2)"}).click()
const panel = page.getByRole("region", {name: "Рабочая панель карты"})
await expect(panel.getByText("Видео A", {exact: true})).toBeVisible()
await expect(panel.getByText("DNS", {exact: true})).toHaveCount(0)
await details.getByRole("button", {name: /Видео B/}).click()
await expect(page).toHaveURL(/service=svc%3Atiny/)
await expect(map.getByRole("button", {name: "Сервис Видео B", exact: true})).toBeVisible()
await page.goBack()
await expect(details.getByRole("heading", {name: "Видео", exact: true})).toBeVisible()
})
test("Карта: 3 JH → Exit + IX, параллельные GRE и 8 сервисов без наложений", async ({ page }) => { test("Карта: 3 JH → Exit + IX, параллельные GRE и 8 сервисов без наложений", async ({ page }) => {
const servers = [ const servers = [
srv(1, "msk-gw01.example.net", "jump-host"), srv(2, "msk-gw02.example.net", "jump-host"), srv(3, "nov-gw01.example.net", "jump-host"), srv(1, "msk-gw01.example.net", "jump-host"), srv(2, "msk-gw02.example.net", "jump-host"), srv(3, "nov-gw01.example.net", "jump-host"),