Compare commits

..
10 Commits
Author SHA1 Message Date
Denozordec 876a61f705 fix(network-map): перенести визуализацию карты из утверждённого прототипа
Docker images / prepare-release (push) Successful in 14s
Docker images / backend-test (push) Successful in 12m24s
Docker images / frontend-image (push) Successful in 2m21s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 1m52s
Docker images / publish-release (push) Successful in 17s
Docker images / notify-webhook (push) Successful in 2s
2026-12-03 11:36:21 +07:00
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
Denozordec 731c19a14d feat(mcp): добавить чтение полной таблицы маршрутов BGP
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 11m50s
Docker images / frontend-image (push) Successful in 4m5s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 35s
Docker images / backend-image (push) Successful in 2m29s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-12-01 21:25:12 +07:00
Denozordec 94c50b9660 fix(mcp): разрешить правила обнаружения отказа по адресу соседа
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m46s
Docker images / backend-image (push) Successful in 2m44s
Docker images / frontend-image (push) Successful in 2m19s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
2026-11-30 23:45:06 +07:00
Denozordec fc39b0da3c fix(mcp): учитывать контекст экземпляра при настройке маршрутизации
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m42s
Docker images / frontend-image (push) Successful in 2m17s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / backend-image (push) Successful in 2m36s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 22:40:29 +07:00
Denozordec 3c06a72349 fix(mcp): снимать свойство встроенного ключа туннеля вместо пустого значения
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 11m44s
Docker images / frontend-image (push) Successful in 5m2s
Docker images / updater-image (push) Successful in 4m40s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 3m30s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 21:32:41 +07:00
Denozordec ea13365f37 fix(mcp): принимать перечень команд при выполнении плана туннеля
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Successful in 11m46s
Docker images / frontend-image (push) Successful in 2m21s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 38s
Docker images / backend-image (push) Successful in 2m25s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 20:00:42 +07:00
60 changed files with 3392 additions and 1021 deletions

No files matched your search

File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -183,7 +183,7 @@
"test:traffic-flow:read-budget": "tsx --test src/services/traffic-flow-read-budget.test.ts src/modules/mcp/flow-read-quality.test.ts && node scripts/test-flow-read-adapters.mjs", "test:traffic-flow:read-budget": "tsx --test src/services/traffic-flow-read-budget.test.ts src/modules/mcp/flow-read-quality.test.ts && node scripts/test-flow-read-adapters.mjs",
"test:traffic-flow:read-http:pg": "node scripts/test-flow-read-http-owned.mjs", "test:traffic-flow:read-http:pg": "node scripts/test-flow-read-http-owned.mjs",
"test:traffic-flow:read-source:pg": "tsx scripts/test-flow-read-sql-owned.mts", "test:traffic-flow:read-source:pg": "tsx scripts/test-flow-read-sql-owned.mts",
"test:mcp:routing-baseline": "tsx --test src/modules/mcp/routing-controller-active-writer.test.ts src/modules/mcp/routing-controller-baseline.test.ts src/modules/mcp/routing-controller-fence.test.ts src/modules/mcp/routing-community-public.test.ts src/modules/mcp/routing-controller-overlap.test.ts", "test:mcp:routing-baseline": "tsx --test src/modules/mcp/routing-controller-active-writer.test.ts src/modules/mcp/routing-controller-baseline.test.ts src/modules/mcp/routing-controller-fence.test.ts src/modules/mcp/routing-community-public.test.ts src/modules/mcp/routing-controller-overlap.test.ts src/services/bgp-rib-observation.test.ts",
"test:mcp:routing-baseline:pg": "node scripts/test-routing-controller-baseline.mjs", "test:mcp:routing-baseline:pg": "node scripts/test-routing-controller-baseline.mjs",
"test:mcp:routing-baseline-inverse:pg": "node scripts/test-routing-controller-baseline.mjs --default-scoped", "test:mcp:routing-baseline-inverse:pg": "node scripts/test-routing-controller-baseline.mjs --default-scoped",
"test:sqlite-import-control:pg": "node scripts/test-sqlite-import-control-postgres.mjs", "test:sqlite-import-control:pg": "node scripts/test-sqlite-import-control-postgres.mjs",
+1 -1
View File
@@ -180,7 +180,7 @@ for (const resource of rosResources) {
: z.object({ serverId, id: rowId.optional(), fields: publicFields.default({}), ...(resource.id === "vrf" ? { productionAdmission: z.literal(true).optional() } : {}) }).strict() : z.object({ serverId, id: rowId.optional(), fields: publicFields.default({}), ...(resource.id === "vrf" ? { productionAdmission: z.literal(true).optional() } : {}) }).strict()
const delegated = resource.id === "wireguard" && action !== "create" || resource.id === "wireguard_peer" || resource.id === "gre" && action !== "create" || resource.id === "ipsec_peer" && action !== "create" || resource.id === "certificate" && action === "delete" || resource.id === "container" && action === "delete" const delegated = resource.id === "wireguard" && action !== "create" || resource.id === "wireguard_peer" || resource.id === "gre" && action !== "create" || resource.id === "ipsec_peer" && action !== "create" || resource.id === "certificate" && action === "delete" || resource.id === "container" && action === "delete"
const guardsOspfInterfaceUse = action !== "create" && !delegated && ospfInterfaceResources.includes(resource.id) const guardsOspfInterfaceUse = action !== "create" && !delegated && ospfInterfaceResources.includes(resource.id)
const previousVersion = action === "create" ? (["ospf_template", "wireguard_peer", "wireguard", "bfd_configuration"].includes(resource.id) ? 3 : 2) : resource.id === "ipsec_peer" || resource.id === "certificate" && action === "delete" ? 2 : resource.id === "wireguard" && action === "update" ? 3 : resource.id === "ospf_template" && action !== "delete" || resource.id === "wireguard_peer" || resource.id === "wireguard" || resource.id === "ip_settings" ? 2 : 1 const previousVersion = action === "create" ? (resource.id === "bfd_configuration" ? 4 : ["ospf_template", "wireguard_peer", "wireguard"].includes(resource.id) ? 3 : 2) : resource.id === "ipsec_peer" || resource.id === "certificate" && action === "delete" ? 2 : resource.id === "wireguard" && action === "update" ? 3 : resource.id === "ospf_template" && action !== "delete" || resource.id === "wireguard_peer" || resource.id === "wireguard" || resource.id === "ip_settings" ? 2 : 1
add(`ros.${resource.id}.${action}`, `mm_${resource.id}_${action}_plan`, `${resource.title}: ${action}`, resource.permission.split(":")[1], resource.id === "certificate" && action === "update" ? ["mm:certificates:write", "mm:network:write"] : resource.permission + ":write", "write", "servers", schema, { add(`ros.${resource.id}.${action}`, `mm_${resource.id}_${action}_plan`, `${resource.title}: ${action}`, resource.permission.split(":")[1], resource.id === "certificate" && action === "update" ? ["mm:certificates:write", "mm:network:write"] : resource.permission + ":write", "write", "servers", schema, {
version: resource.id === "ipsec_peer" ? (action === "create" ? 5 : 3) : resource.id === "certificate" ? (action === "update" ? 4 : 3) : previousVersion + (delegated ? 0 : 1) + (resource.id === "bfd_configuration" ? 4 : resource.id === "ospf_template" ? (action === "update" ? 8 : 7) : 0) + (resource.id === "vrf" ? (action === "delete" ? 3 : 2) : 0) + (resource.id === "ospf_instance" ? 2 : 0) + (["bridge", "bridge_port", "bridge_vlan", "ip_settings", "ipv6_settings"].includes(resource.id) ? 1 : 0) + (guardsOspfInterfaceUse ? 1 : 0), version: resource.id === "ipsec_peer" ? (action === "create" ? 5 : 3) : resource.id === "certificate" ? (action === "update" ? 4 : 3) : previousVersion + (delegated ? 0 : 1) + (resource.id === "bfd_configuration" ? 4 : resource.id === "ospf_template" ? (action === "update" ? 8 : 7) : 0) + (resource.id === "vrf" ? (action === "delete" ? 3 : 2) : 0) + (resource.id === "ospf_instance" ? 2 : 0) + (["bridge", "bridge_port", "bridge_vlan", "ip_settings", "ipv6_settings"].includes(resource.id) ? 1 : 0) + (guardsOspfInterfaceUse ? 1 : 0),
prepare: async (input, context) => { prepare: async (input, context) => {
+15 -5
View File
@@ -1,5 +1,5 @@
import { z } from "zod" import { z } from "zod"
import { readStaticBgpConnection } from "../../services/bgp-connection-read.js" import { readBgpInstanceContext, readStaticBgpConnection } from "../../services/bgp-connection-read.js"
import { bgpExportConnection, bgpExportSources, bgpRedistributionMode, bgpTemplateReferences, nativeBgpExportValue, nativeBgpRows, type BgpExportMode, type NativeBgpRow } from "../../services/bgp-export-model.js" import { bgpExportConnection, bgpExportSources, bgpRedistributionMode, bgpTemplateReferences, nativeBgpExportValue, nativeBgpRows, type BgpExportMode, type NativeBgpRow } from "../../services/bgp-export-model.js"
import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js" import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
import { executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js" import { executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js"
@@ -70,9 +70,18 @@ async function readState(input: Record<string, unknown>) {
return found[0] return found[0]
} }
const instance = unique("bgp_instance", connection.instance), vrf = unique("vrf", connection.vrf), table = unique("routing_table", connection["routing-table"]) const instance = unique("bgp_instance", connection.instance), vrf = unique("vrf", connection.vrf), table = unique("routing_table", connection["routing-table"])
if (instance.vrf !== connection.vrf || instance["routing-table"] !== connection["routing-table"] || vrf.name !== table.name) throw new McpError("STATE_CONFLICT", "Экспорт требует одинаковые явные instance/connection VRF и таблицу", 409) const instanceContext = await readBgpInstanceContext(client, { ...instance, ".id": String(instance[".id"]) })
const [v4, v6] = await Promise.all([client.get<unknown>("/ip/route"), client.get<unknown>("/ipv6/route")]) if (unique("vrf", instanceContext.vrf)[".id"] !== vrf[".id"] || unique("routing_table", instanceContext.table)[".id"] !== table[".id"]) throw new McpError("STATE_CONFLICT", "Контекст VRF и таблицы у BGP instance и connection расходится", 409)
const sources = [...parseState("IPv4 source origins/table/prefixes", () => bgpExportSources(v4, String(table.name), sourceModes, 4)), ...parseState("IPv6 source origins/table/prefixes", () => bgpExportSources(v6, String(table.name), sourceModes, 6))] const tableName = String(table.name)
const sourceGroups = await Promise.all(([4, 6] as const).flatMap(family => sourceModes.filter(kind => kind !== "disabled").map(async kind => {
const params = new URLSearchParams({ "routing-table": tableName, [kind === "connected" ? "connect" : "static"]: "true" })
const rows = nativeBgpRows(await client.get<unknown>(`${family === 4 ? "/ip/route" : "/ipv6/route"}?${params}`))
const candidates = parseState(`IPv${family} source origins/table/prefixes`, () => bgpExportSources(rows, tableName, [kind], family))
if (candidates.length !== rows.length) throw new McpError("STATE_UNAVAILABLE", "Ответ RouterOS не соответствует запросу источников BGP", 409)
return candidates
})))
const sources = sourceGroups.flat().sort((a, b) => a.family - b.family || a.id.localeCompare(b.id))
if (new Set(sources.map(row => `${row.family}:${row.id}`)).size !== sources.length) throw new McpError("STATE_UNAVAILABLE", "Повторяющиеся источники экспорта BGP", 409)
if (sources.length > 500) throw new McpError("LIMIT_EXCEEDED", "Экспорт BGP превышает 500 исходных маршрутов", 409) if (sources.length > 500) throw new McpError("LIMIT_EXCEEDED", "Экспорт BGP превышает 500 исходных маршрутов", 409)
const objects: ChangeEvidence["objects"] = [ const objects: ChangeEvidence["objects"] = [
{ kind: "bgp-export", id, serverId }, { kind: "bgp_connection", id, serverId }, { kind: "bgp-export", id, serverId }, { kind: "bgp_connection", id, serverId },
@@ -87,7 +96,7 @@ async function readState(input: Record<string, unknown>) {
const before = { serverId, serverProof, id, instance: connection.instance, vrf: connection.vrf, table: connection["routing-table"], mode: currentMode, localMode, inheritedMode, const before = { serverId, serverProof, id, instance: connection.instance, vrf: connection.vrf, table: connection["routing-table"], mode: currentMode, localMode, inheritedMode,
templates: templateProof.map(value => ({ id: value.row[".id"], name: value.row.name, mode: value.mode })), templates: templateProof.map(value => ({ id: value.row[".id"], name: value.row.name, mode: value.mode })),
sourceModes, sources: sources.map(({ proof: _proof, ...row }) => row), sourceModes, sources: sources.map(({ proof: _proof, ...row }) => row),
connectionProof: await configurationProof(serverId, id, connection), sourceProof: await privateSecretFingerprint(fingerprint({ serverProof, parentProof, sources, templateProof }), `bgp-export-sources:${serverId}:${id}`) } connectionProof: await configurationProof(serverId, id, connection), sourceProof: await privateSecretFingerprint(fingerprint({ serverProof, parentProof, instanceContext, sources, templateProof }), `bgp-export-sources:${serverId}:${id}`) }
return { server, client, connection, before, objects } return { server, client, connection, before, objects }
} }
async function state(input: Record<string, unknown>) { async function state(input: Record<string, unknown>) {
@@ -117,6 +126,7 @@ export function registerBgpExportActions(register: typeof add) {
}, },
}) })
register("routing.bgp.export", "mm_bgp_export_plan", "Человеческий план перераспределения connected/static в BGP с проверкой источников; disabled отключает только перераспределение", "bgp", ["mm:bgp:write", "mm:network:read", "mm:filters:read"], "write", "servers", schema, { register("routing.bgp.export", "mm_bgp_export_plan", "Человеческий план перераспределения connected/static в BGP с проверкой источников; disabled отключает только перераспределение", "bgp", ["mm:bgp:write", "mm:network:read", "mm:filters:read"], "write", "servers", schema, {
version: 2,
prepare: async input => { prepare: async input => {
const initial = await state(input), before = initial.before, request = { ...input, sourceModes: before.sourceModes, beforeFingerprint: fingerprint(before), expectedServerProof: before.serverProof } const initial = await state(input), before = initial.before, request = { ...input, sourceModes: before.sourceModes, beforeFingerprint: fingerprint(before), expectedServerProof: before.serverProof }
return { target: { scope: "servers", serverIds: [Number(input.serverId)] }, objects: initial.objects, snapshots: [], before, return { target: { scope: "servers", serverIds: [Number(input.serverId)] }, objects: initial.objects, snapshots: [], before,
@@ -1,6 +1,6 @@
import { z } from "zod" import { z } from "zod"
import { pool } from "../../db/index.js" import { pool } from "../../db/index.js"
import { readStaticBgpConnection } from "../../services/bgp-connection-read.js" import { readBgpInstanceContext, readStaticBgpConnection } from "../../services/bgp-connection-read.js"
import { nativeBgpRows, bgpTemplateReferences, type NativeBgpRow } from "../../services/bgp-export-model.js" import { nativeBgpRows, bgpTemplateReferences, type NativeBgpRow } from "../../services/bgp-export-model.js"
import { bgpFilterName, bgpFilterProperty, effectiveBgpFilter, stableBgpPolicyRow, type BgpFilterDirection } from "../../services/bgp-filter-binding-model.js" import { bgpFilterName, bgpFilterProperty, effectiveBgpFilter, stableBgpPolicyRow, type BgpFilterDirection } from "../../services/bgp-filter-binding-model.js"
import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js" import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
@@ -60,12 +60,14 @@ async function readState(input: Record<string, unknown>) {
const [effectiveInstance] = await readOspfEffectiveDisabled<NativeBgpRow & { disabled?: string }>([instance], nativeId => client.post("/routing/bgp/instance/get", { ".id": nativeId, "value-name": "disabled" })) const [effectiveInstance] = await readOspfEffectiveDisabled<NativeBgpRow & { disabled?: string }>([instance], nativeId => client.post("/routing/bgp/instance/get", { ".id": nativeId, "value-name": "disabled" }))
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)
for (const key of ["vrf", "routing-table"]) if (instance[key] === undefined || instance[key] === "") { const instanceContext = await readBgpInstanceContext(client, instance)
const value = bgpFilterName(await client.post("/routing/bgp/instance/get", { ".id": String(instance[".id"]), "value-name": key })) if (unique("vrf", instanceContext.vrf)[".id"] !== vrf[".id"]) throw new Error("BGP instance/connection VRFs disagree")
if (!value) throw new Error("BGP instance effective context not confirmed") const instanceTable = unique("routing_table", instanceContext.table)
instance[key] = value 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")
} }
if (unique("vrf", instance.vrf)[".id"] !== vrf[".id"] || unique("routing_table", instance["routing-table"])[".id"] !== table[".id"] || vrf.name !== table.name) throw new Error("BGP instance/connection contexts disagree")
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)
@@ -75,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), 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,
@@ -112,6 +115,7 @@ export function registerBgpFilterBindingActions(register: typeof add) {
}, },
}) })
register("routing.bgp.filter.bind", "mm_bgp_filter_binding_plan", "Человеческий план локальной input/output привязки BGP к существующей цепочке; пустая chain очищает local binding", "bgp", ["mm:bgp:write", "mm:filters:read", "mm:network:read"], "write", "servers", schema, { register("routing.bgp.filter.bind", "mm_bgp_filter_binding_plan", "Человеческий план локальной input/output привязки BGP к существующей цепочке; пустая chain очищает local binding", "bgp", ["mm:bgp:write", "mm:filters:read", "mm:network:read"], "write", "servers", schema, {
version: 2,
prepare: async input => { prepare: async input => {
const initial = await state(input) const initial = await state(input)
return { target: { scope: "servers", serverIds: [initial.server.id] }, objects: initial.objects, snapshots: [], before: initial.before, requiresHuman: true, verificationScope: "configuration", mutationCost: 1, return { target: { scope: "servers", serverIds: [initial.server.id] }, objects: initial.objects, snapshots: [], before: initial.before, requiresHuman: true, verificationScope: "configuration", mutationCost: 1,
@@ -1,10 +1,12 @@
import { z } from "zod" import { z } from "zod"
import { hasPermission } from "../../lib/permissions.js" import { hasPermission } from "../../lib/permissions.js"
import { bgpPrefixRows } from "../../services/bgp-prefix-model.js" import { bgpPrefixRows } from "../../services/bgp-prefix-model.js"
import { BgpRibChanged, bgpRibSelection, readBgpRib } from "../../services/bgp-rib-observation.js"
import { nativeBgpRows } from "../../services/bgp-export-model.js" import { nativeBgpRows } from "../../services/bgp-export-model.js"
import { getServerRowById } from "../servers/repository/servers-repository.js" import { getServerRowById } from "../servers/repository/servers-repository.js"
import { routerClient } from "./resources.js" import { routerClient } from "./resources.js"
import { effectiveMcpConnection } from "./store.js" import { effectiveMcpConnection } from "./store.js"
import { createRoutingSourceContext, readRoutingEndpoints } from "./routing-observation-source.js"
import { fingerprint, McpError } from "./security.js" import { fingerprint, McpError } from "./security.js"
import type { ActionContext } from "./action-types.js" import type { ActionContext } from "./action-types.js"
import type { add } from "./actions.js" import type { add } from "./actions.js"
@@ -17,6 +19,27 @@ 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.safeExtend({ serverId: z.number().int().positive().safe() })
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)
await access(context)
const source = await createRoutingSourceContext(await readRoutingEndpoints([serverId]))
if (source.expected.length !== 1) throw new McpError("DEVICE_UNAVAILABLE", "Источник RIB недоступен", 409)
const check = async () => { await access(context); await source.assertCurrent() }
try {
await check()
const { client } = await routerClient(serverId)
const startedAt = new Date().toISOString()
const result = await readBgpRib(client, selection, check, context.signal)
await check()
return { serverId, ...result, startedAt, observedAt: new Date().toISOString(), timestampKind: "backend-receipt", forwardingVerified: false }
} catch (error) {
await check()
if (error instanceof McpError) throw error
if (error instanceof BgpRibChanged) throw new McpError("STATE_CONFLICT", "Состояние RIB изменилось; повторите чтение с первой страницы", 409)
throw new McpError("STATE_UNAVAILABLE", "Полнота нативного чтения IPv4 BGP RIB не подтверждена", 409)
}
} })
register("routing.bgp.prefixes.read", "mm_bgp_prefixes_get", "Наблюдаемые BGP-префиксы IPv4/IPv6 в явной таблице; active nullable, без доказательства forwarding или attribution к peer", "bgp", permissions, "read", "servers", z.object({ register("routing.bgp.prefixes.read", "mm_bgp_prefixes_get", "Наблюдаемые BGP-префиксы IPv4/IPv6 в явной таблице; active nullable, без доказательства forwarding или attribution к peer", "bgp", permissions, "read", "servers", z.object({
serverId: z.number().int().positive().safe(), family: z.enum(["ipv4", "ipv6"]).default("ipv4"), serverId: z.number().int().positive().safe(), family: z.enum(["ipv4", "ipv6"]).default("ipv4"),
table: z.string().trim().min(1).max(100).refine(value => !/[\u0000-\u001f\u007f]/.test(value)).default("main"), table: z.string().trim().min(1).max(100).refine(value => !/[\u0000-\u001f\u007f]/.test(value)).default("main"),
@@ -1,7 +1,7 @@
import assert from "node:assert/strict" import assert from "node:assert/strict"
import test from "node:test" import test from "node:test"
import { greIpsecPaths } from "../../services/gre-ipsec-transport.js" import { greIpsecPaths } from "../../services/gre-ipsec-transport.js"
import { greIke2DefaultProposal, greIke2SideCommands, greIke2StableCatalogues, planGreIke2Side, validateGreIke2Defaults, verifyGreIke2Create, verifyGreIke2Update } from "./gre-ikev2-pair-actions.js" import { greIke2DefaultProposal, greIke2SideCommands, greIke2StableCatalogues, greIke2StepInput, greIke2StepSchema, planGreIke2Side, validateGreIke2Defaults, verifyGreIke2Create, verifyGreIke2Update } from "./gre-ikev2-pair-actions.js"
import { redact } from "./security.js" import { redact } from "./security.js"
const pair = { endpoints: [ const pair = { endpoints: [
@@ -74,6 +74,19 @@ test("resumes a partial side and changes only the verified old test policy's pro
assert.equal(verifyGreIke2Update(catalogs, after, patch), false) assert.equal(verifyGreIke2Update(catalogs, after, patch), false)
}) })
test("the runner can parse the prepared plan after its JSON round trip", () => {
const planned = greIke2StepInput(pair, 0, secret, "source-proof", [
{ path: greIpsecPaths.peer, fields: {} },
{ path: greIpsecPaths.policy, id: "*4", fields: { proposal: "default" } },
])
assert.deepEqual(greIke2StepSchema.parse(JSON.parse(JSON.stringify(planned))), planned)
assert.deepEqual(planned.writes, [
{ path: greIpsecPaths.peer, action: "create" },
{ path: greIpsecPaths.policy, id: "*4", action: "update" },
])
assert.throws(() => greIke2StepSchema.parse({ ...planned, writes: [{ path: greIpsecPaths.proposal, id: "*4", action: "update" }] }))
})
test("requires the new plaintext drop to precede existing rules and preserve every prior object", () => { test("requires the new plaintext drop to precede existing rules and preserve every prior object", () => {
const [command] = greIke2SideCommands(pair, 0, secret), before = empty() const [command] = greIke2SideCommands(pair, 0, secret), before = empty()
before[greIpsecPaths.filter] = [{ ".id": "*A", chain: "input", action: "accept", packets: "19" }] before[greIpsecPaths.filter] = [{ ".id": "*A", chain: "input", action: "accept", packets: "19" }]
@@ -22,12 +22,25 @@ const endpoint = z.object({
outerAddress: z.string().refine(value => isIP(value) === 4 && value !== "0.0.0.0", "Требуется фиксированный внешний IPv4"), outerAddress: z.string().refine(value => isIP(value) === 4 && value !== "0.0.0.0", "Требуется фиксированный внешний IPv4"),
}).strict() }).strict()
const schema = z.object({ endpoints: z.array(endpoint).length(2) }).strict() const schema = z.object({ endpoints: z.array(endpoint).length(2) }).strict()
const stepSchema = schema.extend({ side: z.union([z.literal(0), z.literal(1)]), ipsecSecret: z.string().regex(/^[a-f0-9]{64}$/), beforeFingerprint: z.string() }) const writePath = z.enum([greIpsecPaths.filter, greIpsecPaths.profile, greIpsecPaths.peer, greIpsecPaths.identity, greIpsecPaths.policy])
export const greIke2StepSchema = schema.extend({
side: z.union([z.literal(0), z.literal(1)]),
ipsecSecret: z.string().regex(/^[a-f0-9]{64}$/),
beforeFingerprint: z.string(),
writes: z.array(z.discriminatedUnion("action", [
z.object({ path: writePath, action: z.literal("create") }).strict(),
z.object({ path: z.literal(greIpsecPaths.policy), action: z.literal("update"), id: z.string().regex(/^\*[a-z0-9]+$/i) }).strict(),
])).max(6),
})
type Pair = z.infer<typeof schema> type Pair = z.infer<typeof schema>
type Side = 0 | 1 type Side = 0 | 1
type Fields = Record<string, string> type Fields = Record<string, string>
type Catalogue = Record<string, Fields[]> type Catalogue = Record<string, Fields[]>
type RouterWrite = { path: string; fields: Fields; id?: string } type RouterWrite = { path: string; fields: Fields; id?: string }
export function greIke2StepInput(input: Pair, side: Side, ipsecSecret: string, beforeFingerprint: string, commands: RouterWrite[]) {
const writes = commands.map(({ path, id }) => id ? { path, id, action: "update" } : { path, action: "create" })
return greIke2StepSchema.parse({ endpoints: input.endpoints, side, ipsecSecret, beforeFingerprint, writes })
}
const sides = [0, 1] as const const sides = [0, 1] as const
const paths = Object.values(greIpsecPaths) const paths = Object.values(greIpsecPaths)
const runtimeFields: Readonly<Record<string, ReadonlySet<string>>> = { const runtimeFields: Readonly<Record<string, ReadonlySet<string>>> = {
@@ -193,14 +206,16 @@ async function readSide(input: Pair, side: Side) {
export function registerGreIke2PairActions(register: typeof add) { export function registerGreIke2PairActions(register: typeof add) {
registerMcpService(operation, { registerMcpService(operation, {
current: async raw => { current: async raw => {
const input = stepSchema.parse(raw) const input = greIke2StepSchema.parse(raw)
return await Promise.all(sides.map(async side => (await readSide(input, side)).proof)) return await Promise.all(sides.map(async side => (await readSide(input, side)).proof))
}, },
execute: async raw => { execute: async raw => {
const input = stepSchema.parse(raw), side = input.side, state = await readSide(input, side) const input = greIke2StepSchema.parse(raw), side = input.side, state = await readSide(input, side)
if (state.proof !== input.beforeFingerprint) throw new McpError("STATE_CONFLICT", "GRE или IPsec изменился после подготовки", 409) if (state.proof !== input.beforeFingerprint) throw new McpError("STATE_CONFLICT", "GRE или IPsec изменился после подготовки", 409)
const desired = greIke2SideCommands(input, side, input.ipsecSecret) const desired = greIke2SideCommands(input, side, input.ipsecSecret)
const commands = planGreIke2Side(input, side, state.catalogs, desired) const commands = planGreIke2Side(input, side, state.catalogs, desired)
const reviewed = greIke2StepInput(input, side, input.ipsecSecret, state.proof, commands).writes
if (fingerprint(reviewed) !== fingerprint(input.writes)) throw new McpError("STATE_CONFLICT", "Подготовленные команды IKEv2 отличаются от плана", 409)
let before = greIke2StableCatalogues(state.catalogs), confirmed = 0, verified = 0 let before = greIke2StableCatalogues(state.catalogs), confirmed = 0, verified = 0
for (const command of commands) { for (const command of commands) {
let dispatched = false let dispatched = false
@@ -234,14 +249,14 @@ export function registerGreIke2PairActions(register: typeof add) {
return { verified: true, commandCount: commands.length, afterFingerprint, greEnabled: false, forwardingVerified: false } return { verified: true, commandCount: commands.length, afterFingerprint, greEnabled: false, forwardingVerified: false }
}, },
verify: async (raw, result) => { verify: async (raw, result) => {
const input = stepSchema.parse(raw) const input = greIke2StepSchema.parse(raw)
const receipt = result as { verified?: boolean; afterFingerprint?: string } | null const receipt = result as { verified?: boolean; afterFingerprint?: string } | null
return receipt?.verified === true && receipt.afterFingerprint === completedPairProof(input, input.side, return receipt?.verified === true && receipt.afterFingerprint === completedPairProof(input, input.side,
(await readSide(input, input.side)).catalogs, greIke2SideCommands(input, input.side, input.ipsecSecret)) (await readSide(input, input.side)).catalogs, greIke2SideCommands(input, input.side, input.ipsecSecret))
}, },
}) })
register(operation, "mm_gre_ikev2_pair_configure_plan", "План настройки отдельного IKEv2 для двух существующих GRE", "network", "mm:network:write", "write", "servers", schema, { register(operation, "mm_gre_ikev2_pair_configure_plan", "План настройки отдельного IKEv2 для двух существующих GRE", "network", "mm:network:write", "write", "servers", schema, {
version: 2, version: 3,
target: raw => target(schema.parse(raw)), target: raw => target(schema.parse(raw)),
prepare: async raw => { prepare: async raw => {
const input = schema.parse(raw), scope = target(input) const input = schema.parse(raw), scope = target(input)
@@ -250,10 +265,9 @@ export function registerGreIke2PairActions(register: typeof add) {
validateGreIke2Defaults(greIke2DefaultProposal(catalogs[0]), greIke2DefaultProposal(catalogs[1])) validateGreIke2Defaults(greIke2DefaultProposal(catalogs[0]), greIke2DefaultProposal(catalogs[1]))
const ipsecSecret = pairSecret(input, catalogs) const ipsecSecret = pairSecret(input, catalogs)
const changes = sides.map(side => planGreIke2Side(input, side, catalogs[side], greIke2SideCommands(input, side, ipsecSecret))) const changes = sides.map(side => planGreIke2Side(input, side, catalogs[side], greIke2SideCommands(input, side, ipsecSecret)))
const steps = sides.map(side => { const steps = sides.map(side => ({ kind: "service" as const, service: operation,
const writes = changes[side].map(command => ({ path: command.path, id: command.id, action: command.id ? "update" : "create" })) input: greIke2StepInput(input, side, ipsecSecret, before[side].proof, changes[side]),
return { kind: "service" as const, service: operation, input: { ...input, side, ipsecSecret, beforeFingerprint: before[side].proof, writes } } }))
})
const objects = (await Promise.all(before.map(state => greMutationProtectionObjects(Number(state.server.id), state.gre)))).flat() const objects = (await Promise.all(before.map(state => greMutationProtectionObjects(Number(state.server.id), state.gre)))).flat()
return { target: scope, objects, snapshots: [], before: before.map(state => state.proof), steps, mutationCost: Math.max(1, changes.flat().length), requiresHuman: true, return { target: scope, objects, snapshots: [], before: before.map(state => state.proof), steps, mutationCost: Math.max(1, changes.flat().length), requiresHuman: true,
warnings: [ warnings: [
@@ -36,11 +36,15 @@ export function registerGreMutationActions(register: typeof add) {
return receipt?.verified===true && fingerprint(await current(input))===receipt.afterFingerprint return receipt?.verified===true && fingerprint(await current(input))===receipt.afterFingerprint
}}) }})
register(service,"mm_gre_tunnel_"+operation+"_plan","План "+["создания","изменения","удаления"][index]+" GRE и его внутренних адресов", "network","mm:network:write","write","servers",schemas[index],{ register(service,"mm_gre_tunnel_"+operation+"_plan","План "+["создания","изменения","удаления"][index]+" GRE и его внутренних адресов", "network","mm:network:write","write","servers",schemas[index],{
version: operation === "delete" ? 1 : 2,
prepare:async(input,context)=>{ prepare:async(input,context)=>{
const serverId = Number(input.serverId), {server} = await routerClient(serverId) const serverId = Number(input.serverId), {server} = await routerClient(serverId)
let mutation = greMutationSchema.parse({operation,...(operation==="create"?{fields:input.fields}:{...("rosId" in input?{rosId:input.rosId}:{}),...("name" in input?{name:input.name}:{}),...(operation==="update"?{fields:input.fields}:{})})})
const state = await readGreMutationState(server,mutation), target = greTarget(mutation,state)
if (input.ipsecSecretRef && input.clearIpsecSecret) throw new McpError("INVALID_INPUT","Выберите новый PSK или явное удаление",400) if (input.ipsecSecretRef && input.clearIpsecSecret) throw new McpError("INVALID_INPUT","Выберите новый PSK или явное удаление",400)
let mutation = greMutationSchema.parse({operation,...(operation==="create"?{fields:input.fields}:{...("rosId" in input?{rosId:input.rosId}:{}),...("name" in input?{name:input.name}:{}),...(operation==="update"?{fields:input.fields}:{})})})
if (mutation.operation === "update" && (input.ipsecSecretRef || input.clearIpsecSecret)) {
mutation = { ...mutation, fields: { ...mutation.fields, ipsecSecret: "" } }
}
const state = await readGreMutationState(server,mutation), target = greTarget(mutation,state)
if (mutation.operation!=="delete" && (input.ipsecSecretRef || input.clearIpsecSecret)) { if (mutation.operation!=="delete" && (input.ipsecSecretRef || input.clearIpsecSecret)) {
const name = mutation.operation==="create"?mutation.fields.name:target?.name const name = mutation.operation==="create"?mutation.fields.name:target?.name
let value = "" let value = ""
@@ -69,6 +69,7 @@ export function registerGreRevisionActions(register:typeof add){
}, },
}) })
register(service,"mm_gre_revision_restore_plan","Восстановить GRE и все статические адреса из ревизии после подтверждения","network","mm:network:write","write","servers",z.object({serverId:z.number().int().positive().safe(),revisionId:z.string().uuid()}).strict(),{ register(service,"mm_gre_revision_restore_plan","Восстановить GRE и все статические адреса из ревизии после подтверждения","network","mm:network:write","write","servers",z.object({serverId:z.number().int().positive().safe(),revisionId:z.string().uuid()}).strict(),{
version:2,
prepare:async(input,context)=>{ prepare:async(input,context)=>{
const req=request(input,context),source=await read(req,context.signal) const req=request(input,context),source=await read(req,context.signal)
const desired=materializeGreRestore(source.revision.desired,source.state),steps=planGreRevisionRestore(desired,source.state) const desired=materializeGreRestore(source.revision.desired,source.state),steps=planGreRevisionRestore(desired,source.state)
@@ -34,14 +34,19 @@ const native=createServer(async(req,res)=>{
} }
assert.ok(base,"Only typed GRE/address writes allowed") assert.ok(base,"Only typed GRE/address writes allowed")
writes++ writes++
if(base==="/interface/gre"&&data["ipsec-secret"]===""&&["yes","true"].includes(data["allow-fast-path"])){ if(base==="/interface/gre"&&data["ipsec-secret"]===""){
res.statusCode=400;res.end(JSON.stringify({error:400,detail:"failure: cannot enable fastpath together with ipsec yet"}));return res.statusCode=400;res.end(JSON.stringify({error:400,detail:"unexpected empty IPsec secret assignment"}));return
} }
const fields=Object.fromEntries(Object.entries(data).map(([k,v])=>[k,v==="yes"?"true":v==="no"?"false":String(v)])) const fields=Object.fromEntries(Object.entries(data).map(([k,v])=>[k,v==="yes"?"true":v==="no"?"false":String(v)]))
if(!ignored){ if(!ignored){
if(req.method==="PUT"){ if(req.method==="PUT"){
const row=base==="/interface/gre"?{".id":"*G"+(++nextId),"local-address":"0.0.0.0",mtu:"1476",keepalive:"10s,10",dscp:"inherit",disabled:"false",dynamic:"false",running:"false","clamp-tcp-mss":"true","allow-fast-path":"true","ipsec-secret":"",comment:"",...fields}:{".id":"*A"+(++nextId),disabled:"false",dynamic:"false",invalid:"false",advertise:"false","no-dad":"false","eui-64":"false","from-pool":"",comment:"",...fields} const row=base==="/interface/gre"?{".id":"*G"+(++nextId),"local-address":"0.0.0.0",mtu:"1476",keepalive:"10s,10",dscp:"inherit",disabled:"false",dynamic:"false",running:"false","clamp-tcp-mss":"true","allow-fast-path":"true","ipsec-secret":"",comment:"",...fields}:{".id":"*A"+(++nextId),disabled:"false",dynamic:"false",invalid:"false",advertise:"false","no-dad":"false","eui-64":"false","from-pool":"",comment:"",...fields}
;(collections[base]??=[]).push(row) ;(collections[base]??=[]).push(row)
}else if(req.method==="POST"&&path==="/interface/gre/unset"){
assert.equal(data["value-name"],"ipsec-secret")
const row=collections[base].find(r=>r[".id"]===data[".id"])
assert.ok(row)
row["ipsec-secret"]=""
}else if(req.method==="PATCH")Object.assign(collections[base].find(r=>r[".id"]===path.slice(base.length+1))!,fields) }else if(req.method==="PATCH")Object.assign(collections[base].find(r=>r[".id"]===path.slice(base.length+1))!,fields)
else if(req.method==="DELETE")collections[base]=collections[base].filter(r=>r[".id"]!==path.slice(base.length+1)) else if(req.method==="DELETE")collections[base]=collections[base].filter(r=>r[".id"]!==path.slice(base.length+1))
else assert.fail("Unsupported native write") else assert.fail("Unsupported native write")
@@ -11,7 +11,7 @@ const creates = rosResources.filter(resource => !resource.readOnly && resource.c
assert.equal(creates.length, 30) assert.equal(creates.length, 30)
for (const resource of creates) { for (const resource of creates) {
const action = findAction(`mm_${resource.id}_create_plan`) const action = findAction(`mm_${resource.id}_create_plan`)
assert.equal(action.operation.version, resource.id === "bfd_configuration" ? 8 : resource.id === "ospf_template" ? 11 : ["ipsec_peer", "vrf", "ospf_instance"].includes(resource.id) ? 5 : ["wireguard", "bridge", "bridge_port", "bridge_vlan"].includes(resource.id) ? 4 : 3) assert.equal(action.operation.version, resource.id === "bfd_configuration" ? 9 : resource.id === "ospf_template" ? 11 : ["ipsec_peer", "vrf", "ospf_instance"].includes(resource.id) ? 5 : ["wireguard", "bridge", "bridge_port", "bridge_vlan"].includes(resource.id) ? 4 : 3)
assert.equal(action.schema.safeParse({ serverId: 1, fields: {} }).success, true) assert.equal(action.schema.safeParse({ serverId: 1, fields: {} }).success, true)
for (const id of ["*OLD", undefined, null, ""]) { for (const id of ["*OLD", undefined, null, ""]) {
const rejected = action.schema.safeParse({ serverId: 1, fields: {}, id }) const rejected = action.schema.safeParse({ serverId: 1, fields: {}, id })
@@ -27,6 +27,7 @@ assert.throws(() => validateRosStep(bfdConfig, "create", { vrf: "main" }), inval
assert.deepEqual(validateRosStep(bfdConfig, "create", { interfaces: "bridge1", vrf: "main" }), { interfaces: "bridge1", vrf: "main" }) assert.deepEqual(validateRosStep(bfdConfig, "create", { interfaces: "bridge1", vrf: "main" }), { interfaces: "bridge1", vrf: "main" })
for (const interfaces of ["all", "none", "bridge1,all", "bridge1,"]) assert.throws(() => validateRosStep(bfdConfig, "create", { interfaces, vrf: "main" }), invalid) for (const interfaces of ["all", "none", "bridge1,all", "bridge1,"]) assert.throws(() => validateRosStep(bfdConfig, "create", { interfaces, vrf: "main" }), invalid)
for (const [addresses, expected] of [["192.0.2.9/24", "192.0.2.0/24"], ["FD00::20/64", "fd00::/64"], ["192.0.2.9/32", "192.0.2.9/32"], ["fd00::20/128", "fd00::20/128"]]) { for (const [addresses, expected] of [["192.0.2.9/24", "192.0.2.0/24"], ["FD00::20/64", "fd00::/64"], ["192.0.2.9/32", "192.0.2.9/32"], ["fd00::20/128", "fd00::20/128"]]) {
assert.deepEqual(validateRosStep(bfdConfig, "create", { addresses, vrf: "main" }), { addresses: expected, vrf: "main" })
assert.deepEqual(validateRosStep(bfdConfig, "update", { addresses }, "*A"), { addresses: expected }) assert.deepEqual(validateRosStep(bfdConfig, "update", { addresses }, "*A"), { addresses: expected })
} }
for (const addresses of ["0.0.0.0/0", "::/0", "192.0.2.1", "fd00::/129", "192.0.2.1/32/extra", "192.0.2.0/24,192.0.3.0/24", "fe80::%ether1/64"]) assert.equal(bfdConfig.fields.safeParse({ addresses }).success, false) for (const addresses of ["0.0.0.0/0", "::/0", "192.0.2.1", "fd00::/129", "192.0.2.1/32/extra", "192.0.2.0/24,192.0.3.0/24", "fe80::%ether1/64"]) assert.equal(bfdConfig.fields.safeParse({ addresses }).success, false)
+1 -1
View File
@@ -381,7 +381,7 @@ export function validateRosStep(resource: RosResourceSpec, action: RosStep["acti
const parsed = resource.fields.parse(fields ?? {}) as Record<string, unknown> const parsed = resource.fields.parse(fields ?? {}) as Record<string, unknown>
if (action === "create" && resource.requiredOnCreate?.some(field => parsed[field] === undefined)) throw new McpError("INVALID_INPUT", "Не заполнены обязательные поля создания", 400) if (action === "create" && resource.requiredOnCreate?.some(field => parsed[field] === undefined)) throw new McpError("INVALID_INPUT", "Не заполнены обязательные поля создания", 400)
if (resource.id === "bfd_configuration" && action === "create") { if (resource.id === "bfd_configuration" && action === "create") {
if (!parsed.interfaces && !parsed["address-list"]) throw new McpError("INVALID_INPUT", "Для правила BFD укажите интерфейсы или address-list", 400) if (!parsed.interfaces && !parsed.addresses && !parsed["address-list"]) throw new McpError("INVALID_INPUT", "Для правила BFD укажите interfaces, addresses или address-list", 400)
if (parsed.interfaces && parsed.addresses === undefined && String(parsed.interfaces).split(",").some(value => !value.trim() || /^(?:all|none)$/i.test(value.trim()))) { if (parsed.interfaces && parsed.addresses === undefined && String(parsed.interfaces).split(",").some(value => !value.trim() || /^(?:all|none)$/i.test(value.trim()))) {
throw new McpError("INVALID_INPUT", "Для правила BFD без адреса укажите конкретные интерфейсы", 400) throw new McpError("INVALID_INPUT", "Для правила BFD без адреса укажите конкретные интерфейсы", 400)
} }
@@ -1,8 +1,24 @@
import type { MikrotikClient } from "./mikrotik.js" import type { MikrotikClient } from "./mikrotik.js"
import { nativeBgpRows, type NativeBgpRow } from "./bgp-export-model.js" import { nativeBgpRows, type NativeBgpRow } from "./bgp-export-model.js"
import { bgpFilterName } from "./bgp-filter-binding-model.js"
import { readOspfEffectiveDisabled } from "./ospf-effective-disabled.js" import { readOspfEffectiveDisabled } from "./ospf-effective-disabled.js"
import { McpError } from "../modules/mcp/security.js" import { McpError } from "../modules/mcp/security.js"
export async function readBgpInstanceContext(client: Pick<MikrotikClient, "post">, row: NativeBgpRow) {
const read = async (key: "vrf" | "routing-table") => {
const value = row[key]
return value === undefined || value === ""
? bgpFilterName(await client.post("/routing/bgp/instance/get", { ".id": row[".id"], "value-name": key }))
: bgpFilterName({ ret: value })
}
const [observedVrf, observedTable] = await Promise.all([read("vrf"), read("routing-table")])
const vrf = observedVrf || "main"
// Only infer the routing table when the instance uses the built-in VRF.
const table = observedTable || (vrf === "main" ? "main" : null)
if (!table) throw new McpError("STATE_UNAVAILABLE", "Не подтверждена таблица BGP instance", 409)
return { vrf, table }
}
/** Prove a configured peer, including RouterOS releases that omit the D flag. */ /** Prove a configured peer, including RouterOS releases that omit the D flag. */
export async function readStaticBgpConnection(client: Pick<MikrotikClient, "get" | "post">, id: string) { export async function readStaticBgpConnection(client: Pick<MikrotikClient, "get" | "post">, id: string) {
const connections = nativeBgpRows(await client.get("/routing/bgp/connection")), target = connections.find(row => row[".id"] === id) const connections = nativeBgpRows(await client.get("/routing/bgp/connection")), target = connections.find(row => row[".id"] === id)
@@ -0,0 +1,172 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { readBgpRib } from "./bgp-rib-observation.js"
const table = "rtab-antiblock"
const primary = "*B000001"
const standby = "*B000002"
const selection = { table, mode: "page" as const, limit: 500, offset: 0 }
function route(index: number, overrides: Record<string, string> = {}): Record<string, string> {
return {
".id": "*" + (index + 1).toString(16).toUpperCase(),
afi: "ip", bgp: "true", dynamic: "true", "routing-table": table,
"dst-address": `198.18.${Math.floor(index / 256)}.${index % 256}/32`,
contribution: "active", active: "true", "bgp.peer-cache-id": primary,
gateway: "10.255.255.100", "immediate-gw": "10.253.250.1%gre-jh-test-msk",
...overrides,
}
}
function fixture(rows: Record<string, string>[]) {
const reads = { routePages: 0, counts: 0, sessionFilters: new Set<string>() }
const client = {
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")
const { pathname, searchParams } = new URL(path, "http://router.invalid")
if (pathname === "/routing/table") return [{ ".id": "*1", name: table }] as T
assert.equal(pathname, "/routing/route")
assert(!searchParams.has("bgp") && !searchParams.has("afi"), "Independent RIB read must include unclassified rows")
assert.equal(searchParams.get("routing-table"), table)
reads.routePages++
const properties = searchParams.get(".proplist")?.split(",")
assert(properties)
return rows.filter(row => row["routing-table"] === table)
.map(row => Object.fromEntries(Object.entries(row).filter(([key]) => properties.includes(key)))) as T
},
async post<T>(path: string, body: Record<string, string | string[]>) {
assert.equal(path, "/routing/route/print")
assert.equal(body["count-only"], "")
const query = body[".query"]
assert(Array.isArray(query))
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, [
"routing-table=" + table, "bgp=true", "afi=ip", "afi=ip4", "#|",
...(peer ? ["bgp.peer-cache-id=" + peer] : []),
...(session ? ["bgp.session=" + session] : []),
])
reads.counts++
if (session !== undefined) reads.sessionFilters.add(session)
const count = rows.filter(row =>
row["routing-table"] === table && row.bgp === "true" && (row.afi === "ip" || row.afi === "ip4") &&
(!peer || row["bgp.peer-cache-id"] === peer) && (!session || row["bgp.session"] === session),
).length
return { ret: String(count) } as T
},
}
return { client, reads }
}
test("positive native count is cheap; a verified zero independently reads the target table", async () => {
const nonempty = fixture([route(0)])
assert.equal((await readBgpRib(nonempty.client, { ...selection, mode: "count" })).total, 1)
assert.equal(nonempty.reads.routePages, 0)
const { client, reads } = fixture([route(0, { "routing-table": "main" }), route(1, { afi: "ip6", "dst-address": "2001:db8::/32" })])
const result = await readBgpRib(client, { ...selection, mode: "count" })
assert.equal(result.total, 0)
assert(reads.counts > 0)
assert.equal(reads.routePages, 1)
for (const invalid of [[], {}, { ret: "" }, { ret: "0oops" }, { ret: "-1" }]) {
const broken = { ...client, post: async <T>() => invalid as T }
await assert.rejects(readBgpRib(broken, { ...selection, mode: "count" }))
}
})
test("zero fails closed on a missed IPv4 BGP route or ambiguous native BGP evidence", async () => {
const staticRow = { ".id": "*70", afi: "ip", static: "true", "routing-table": table, "dst-address": "198.18.250.1/32", contribution: "active", active: "true" }
const justStatic = fixture([staticRow])
assert.equal((await readBgpRib(justStatic.client, { ...selection, mode: "count" })).total, 0)
assert.equal(justStatic.reads.routePages, 1)
for (const ambiguous of [route(0), { ...staticRow, "bgp.peer-cache-id": primary }, { ...staticRow, "belongs-to": "BGP IP routes from 192.0.2.1" }]) {
const { client } = fixture([ambiguous])
const wrongZero = { ...client, post: async <T>() => ({ ret: "0" }) as T }
await assert.rejects(readBgpRib(wrongZero, { ...selection, mode: "count" }))
}
})
test("matching peer paths include filtered and inactive alternatives with distinct IDs", async () => {
const filtered = route(1, { "dst-address": "198.18.0.0/32", contribution: "filtered", filtered: "true", active: "false", "bgp.peer-cache-id": standby })
const candidate = route(2, { afi: "ip4", contribution: "candidate", active: "false" })
const { client } = fixture([route(0), filtered, candidate, route(3, { afi: "ip6", "dst-address": "2001:db8::/32" })])
const result = await readBgpRib(client, selection)
assert.equal(result.total, 3)
assert(result.items)
const samePrefix = result.items.filter(item => item.prefix === "198.18.0.0/32")
assert.equal(samePrefix.length, 2)
assert.equal(new Set(samePrefix.map(item => item.id)).size, 2)
assert.equal(samePrefix.find(item => item.peerCacheId === standby)?.filtered, true)
assert.equal(result.items.find(item => item.id === candidate[".id"])?.active, false)
const otherPeer = await readBgpRib(client, { ...selection, peerCacheId: standby })
assert.equal(otherPeer.total, 1)
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 () => {
const { client } = fixture([])
const missingTable = { ...client, get: async <T>() => [] as T }
await assert.rejects(readBgpRib(missingTable, { ...selection, mode: "count" }), /table/i)
const unknownPeer = route(0)
delete unknownPeer["bgp.peer-cache-id"]
const result = await readBgpRib(fixture([unknownPeer]).client, selection)
assert.equal(result.items?.[0].peerCacheId, null)
await assert.rejects(readBgpRib(fixture([unknownPeer]).client, { ...selection, mode: "count", peerCacheId: standby }), /peer/i)
})
test("pages beyond 13,000 preserve snapshot identity and reject a changed next page", async () => {
const rows = Array.from({ length: 13_705 }, (_, i) => route(i))
const { client } = fixture(rows)
const first = await readBgpRib(client, selection)
assert.equal(first.total, rows.length)
assert.equal(first.items?.length, selection.limit)
assert.equal(first.nextOffset, selection.limit)
assert(first.fingerprint)
rows.reverse()
const tailSelection = { ...selection, offset: 13_700, expectedFingerprint: first.fingerprint }
const tail = await readBgpRib(client, tailSelection)
assert.equal(tail.items?.length, 5)
assert.equal(tail.nextOffset, null)
assert.equal(tail.fingerprint, first.fingerprint)
rows[0] = { ...rows[0], gateway: "10.255.255.101" }
await assert.rejects(readBgpRib(client, tailSelection))
})
+122
View File
@@ -0,0 +1,122 @@
import { createHash } from "node:crypto"
import { isIP } from "node:net"
import { z } from "zod"
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
import type { MikrotikClient } from "./mikrotik.js"
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({
table: exactName.max(100),
peerCacheId: rosId.optional(),
sessionName: sessionIdentity.optional(),
mode: z.enum(["count", "page"]).default("count"),
offset: z.number().int().min(0).max(100_000).default(0),
limit: z.number().int().min(1).max(500).default(100),
expectedFingerprint: z.string().regex(/^[a-f0-9]{64}$/).optional(),
}).strict().refine(input => !(input.peerCacheId && input.sessionName), { message: "Choose only one BGP peer selector" })
const nativeRow = z.record(z.string(), z.unknown())
const otherProtocols = ["static", "connect", "ospf", "dhcp", "rip", "isis", "modem", "slaac", "vpn", "fantasy"]
const properties = [".id", "afi", "dst-address", "routing-table", "bgp", "bgp.peer-cache-id", "bgp.session", "belongs-to", "contribution", "active", "filtered", "gateway", "immediate-gw", ...otherProtocols].join(",")
const otherFamilies = new Set(["ip6", "ipv6", "link", "vpnv4", "vpnv6", "l2vpn", "l2vpn-cisco", "l2vpn-link", "evpn", "mip4", "mip6"])
type Selection = z.infer<typeof bgpRibSelection>
const text = z.string().max(512)
export class BgpRibChanged extends Error {}
const contributions = new Set(["active", "filtered", "candidate", "best-candidate", "unreachable"])
function optionalFlag(value: unknown) {
if (value === undefined) return null
if (value === true || value === "true" || value === "yes") return true
if (value === false || value === "false" || value === "no") return false
throw new Error("Unrecognized RouterOS flag")
}
function ipv4Row(row: Record<string, unknown>, table: string) {
if (row["routing-table"] !== table) throw new Error("Unexpected native route table")
if (otherFamilies.has(String(row.afi))) return null
const bgp = optionalFlag(row.bgp)
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) {
// 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")
return null
}
if (other) throw new Error("Conflicting native route origins")
const dst = text.parse(row["dst-address"])
const prefix = isIP(dst) === 4 ? dst + "/32" : dst
if (isIP(prefix.split("/")[0]) !== 4 || canonicalBgpPolicyPrefix(prefix) !== prefix) throw new Error("Invalid IPv4 destination")
const id = rosId.parse(row[".id"])
const peerCacheId = row["bgp.peer-cache-id"] === undefined ? null : rosId.parse(row["bgp.peer-cache-id"])
const contribution = text.nullable().parse(row.contribution ?? null)
const activeFlag = optionalFlag(row.active), filteredFlag = optionalFlag(row.filtered)
const known = contribution !== null && contributions.has(contribution)
if (known && (activeFlag !== null && activeFlag !== (contribution === "active") ||
filteredFlag !== null && filteredFlag !== (contribution === "filtered"))) throw new Error("Conflicting native route flags")
return {
id, prefix, table, peerCacheId, contribution,
active: activeFlag ?? (known ? contribution === "active" : null),
filtered: filteredFlag ?? (known ? contribution === "filtered" : null),
session: sessionIdentity.nullable().parse(row["bgp.session"] ?? null),
gateway: text.nullable().parse(row.gateway ?? null), immediateGateway: text.nullable().parse(row["immediate-gw"] ?? null),
}
}
/** 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,
beforeRead: () => Promise<unknown> = async () => {}, signal?: AbortSignal) {
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")
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 tableIdentity = async () => {
const raw = await client.get<unknown>(tablePath, 10_000, signal, 16_384, beforeRead)
if (!Array.isArray(raw) || raw.length !== 1) throw new Error("Missing or ambiguous routing table")
const row = nativeRow.parse(raw[0])
if (row.name !== table || optionalFlag(row.disabled) || optionalFlag(row.invalid)) throw new Error("Routing table unavailable")
return rosId.parse(row[".id"])
}
const nativeCount = async (scoped = false) => {
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 { ret } = z.object({ ret: z.string().regex(/^(?:0|[1-9]\d{0,14})$/) }).strict().parse(raw)
return Number(ret)
}
const identity = await tableIdentity()
const allCount = await nativeCount()
type Item = NonNullable<ReturnType<typeof ipv4Row>>
let items: Item[] = [], fingerprint: string | null = null, total = allCount, nextOffset: number | null = null
if (mode === "page" || peer || allCount === 0) {
if (allCount > 100_000) throw new Error("RIB row limit exceeded")
const path = "/routing/route?.proplist=" + properties + "&routing-table=" + encodeURIComponent(table)
const raw = await client.get<unknown>(path, 30_000, signal, 8 * 1024 * 1024, beforeRead)
if (!Array.isArray(raw) || raw.length > 100_000) throw new Error("Invalid or oversized RIB view")
const ids = new Set<string>(), selected: Item[] = []
for (const rawRow of raw) {
const observed = ipv4Row(nativeRow.parse(rawRow), table)
if (!observed) continue
if (ids.has(observed.id)) throw new Error("Duplicate native RIB identity")
ids.add(observed.id)
if (peer && !observed[peer.field]) throw new Error("Native peer identity unavailable")
if (!peer || observed[peer.field] === peer.value) selected.push(observed)
}
if (allCount !== ids.size || selected.length !== await nativeCount(true)) throw new BgpRibChanged("Native RIB count changed or view incomplete")
total = selected.length
if (mode === "page") {
selected.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
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")
items = selected.slice(offset, offset + limit)
nextOffset = offset + items.length < total ? offset + items.length : null
}
}
if (identity !== await tableIdentity()) throw new BgpRibChanged("Routing table changed during observation")
return { family: "ipv4", table, peerCacheId: peerCacheId ?? null, sessionName: sessionName ?? null, mode, total, items, nextOffset, fingerprint, source: "/routing/route", atomicSnapshot: false }
}
+1 -1
View File
@@ -907,7 +907,7 @@ export function greInterfaceBody(t: GreSnapshotTunnel): Record<string, string> {
"allow-fast-path": t.allowFastPath ? "yes" : "no", "allow-fast-path": t.allowFastPath ? "yes" : "no",
comment: writeGreComment(t.comment, peer), comment: writeGreComment(t.comment, peer),
disabled: rosYesNo(t.disabled), disabled: rosYesNo(t.disabled),
"ipsec-secret": isHiddenSecret(t.ipsecSecret) ? undefined : t.ipsecSecret, "ipsec-secret": !t.ipsecSecret || isHiddenSecret(t.ipsecSecret) ? undefined : t.ipsecSecret,
}) })
} }
+18 -1
View File
@@ -27,6 +27,7 @@ function apply(state:GreMutationState,op:RosWriteOp) {
next[key].push(row) next[key].push(row)
if (key==="gre") next.dependencies["/interface"].push({".id":"*C",name:row.name,type:"gre"}) if (key==="gre") next.dependencies["/interface"].push({".id":"*C",name:row.name,type:"gre"})
} else if (op.op === "patch") Object.assign(next[key].find(row=>row[".id"]===id)!,body) } else if (op.op === "patch") Object.assign(next[key].find(row=>row[".id"]===id)!,body)
else if (op.op === "post" && op.path === "/interface/gre/unset") next.gre.find(row=>row[".id"]===body[".id"])!["ipsec-secret"] = ""
else if (op.op === "delete") { else if (op.op === "delete") {
next[key]=next[key].filter(row=>row[".id"]!==id) next[key]=next[key].filter(row=>row[".id"]!==id)
if (key==="gre") next.dependencies["/interface"]=next.dependencies["/interface"].filter(row=>row[".id"]!==id) if (key==="gre") next.dependencies["/interface"]=next.dependencies["/interface"].filter(row=>row[".id"]!==id)
@@ -40,6 +41,10 @@ let state = empty(), commands = 0
const ops = planGreMutation(server,create,state) const ops = planGreMutation(server,create,state)
assert.equal(ops.length,3); assert.equal(ops[0].op,"put"); assert.equal("body" in ops[0]&&ops[0].body.disabled,"yes"); assert.equal(ops[2].path,"/interface/gre/@created") assert.equal(ops.length,3); assert.equal(ops[0].op,"put"); assert.equal("body" in ops[0]&&ops[0].body.disabled,"yes"); assert.equal(ops[2].path,"/interface/gre/@created")
assert.equal("body" in ops[0] && ops[0].body.mtu, "1476") assert.equal("body" in ops[0] && ops[0].body.mtu, "1476")
assert.ok("body" in ops[0] && !("ipsec-secret" in ops[0].body))
const createWithClear = greMutationSchema.parse({operation:"create",fields:{name:"clear-gre",remoteAddress:"192.0.2.2",ipsecSecret:""}})
const createWithClearOp = planGreMutation(server,createWithClear,state)[0]
assert.ok("body" in createWithClearOp && !("ipsec-secret" in createWithClearOp.body))
const autoCreate = greMutationSchema.parse({operation:"create",fields:{name:"own-gre",remoteAddress:"192.0.2.2",mtu:"auto"}}) const autoCreate = greMutationSchema.parse({operation:"create",fields:{name:"own-gre",remoteAddress:"192.0.2.2",mtu:"auto"}})
const autoPut = planGreMutation(server,autoCreate,state)[0] const autoPut = planGreMutation(server,autoCreate,state)[0]
assert.equal("body" in autoPut && autoPut.body.mtu, "auto") assert.equal("body" in autoPut && autoPut.body.mtu, "auto")
@@ -62,7 +67,19 @@ assert.equal(verifyGreMutationOp(autoState, autoAfter, autoPatch), false)
const commentPlan = planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{mtu:1400}}),preserve) const commentPlan = planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{mtu:1400}}),preserve)
assert.equal(commentPlan[0].op,"patch"); assert.equal("body" in commentPlan[0]&&commentPlan[0].body.keepalive,"1m,3"); assert.equal("body" in commentPlan[0]&&commentPlan[0].body.comment,native.comment); assert.ok(!("body" in commentPlan[0]&&"ipsec-secret" in commentPlan[0].body)) assert.equal(commentPlan[0].op,"patch"); assert.equal("body" in commentPlan[0]&&commentPlan[0].body.keepalive,"1m,3"); assert.equal("body" in commentPlan[0]&&commentPlan[0].body.comment,native.comment); assert.ok(!("body" in commentPlan[0]&&"ipsec-secret" in commentPlan[0].body))
const clear = planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{comment:"",remoteInnerIp:"",localAddress:"",ipsecSecret:""}}),preserve) const clear = planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{comment:"",remoteInnerIp:"",localAddress:"",ipsecSecret:""}}),preserve)
assert.equal(clear[0].op,"patch"); assert.equal("body" in clear[0]&&clear[0].body.comment,""); assert.equal("body" in clear[0]&&clear[0].body["ipsec-secret"],"") assert.deepEqual(clear[0],{op:"post",path:"/interface/gre/unset",body:{".id":"*G","value-name":"ipsec-secret"}})
assert.equal(clear[1].op,"patch"); assert.equal("body" in clear[1]&&clear[1].body.comment,""); assert.ok("body" in clear[1]&&!("ipsec-secret" in clear[1].body))
const runningWithKey = structuredClone(preserve)
Object.assign(runningWithKey.gre[0], {disabled:"false","ipsec-secret":"fixture-key","allow-fast-path":"false"})
const clearRunning = greMutationSchema.parse({operation:"update",rosId:"*G",fields:{ipsecSecret:"",allowFastPath:true}})
const clearRunningOps = planGreMutation(server,clearRunning,runningWithKey)
assert.deepEqual(clearRunningOps.map(op=>op.op),["patch","post","patch","patch"])
assert.equal(verifyGreMutationOp(runningWithKey,runningWithKey,clearRunningOps[1]),false)
let afterClear = runningWithKey
const cleared = await executeGreMutationOps(clearRunning,runningWithKey,clearRunningOps,{read:async()=>afterClear,command:async op=>{afterClear=apply(afterClear,op)}})
assert.equal(cleared.verified,true)
assert.equal(afterClear.gre[0]["ipsec-secret"],"")
assert.equal(afterClear.gre[0].disabled,"false")
const collision = empty(); collision.dependencies["/interface"]=[{".id":"*E",name:"own-gre",type:"ether"}] const collision = empty(); collision.dependencies["/interface"]=[{".id":"*E",name:"own-gre",type:"ether"}]
assert.throws(()=>planGreMutation(server,create,collision),/используется/) assert.throws(()=>planGreMutation(server,create,collision),/используется/)
assert.throws(()=>planGreMutation(server,greMutationSchema.parse({operation:"delete",rosId:"*G",name:"different"}),preserve),/разные/) assert.throws(()=>planGreMutation(server,greMutationSchema.parse({operation:"delete",rosId:"*G",name:"different"}),preserve),/разные/)
+25 -4
View File
@@ -12,6 +12,11 @@ import { greMutationSchema, greTunnelFromBody, type GreMutation } from "./gre-mu
import { assertGreDeleteDependencies, greMutationProblem, greMutationProof, greNativeValue, greStableRows, greTarget, readGreMutationState, type GreMutationState } from "./gre-mutation-state.js" import { assertGreDeleteDependencies, greMutationProblem, greMutationProof, greNativeValue, greStableRows, greTarget, readGreMutationState, type GreMutationState } from "./gre-mutation-state.js"
const same = (a: unknown,b: unknown) => fingerprint(a) === fingerprint(b) const same = (a: unknown,b: unknown) => fingerprint(a) === fingerprint(b)
export function greSecretUnsetOp(id: string): RosWriteOp {
return { op: "post", path: "/interface/gre/unset", body: { ".id": id, "value-name": "ipsec-secret" } }
}
export async function recordGreMutationRevision(server:ServerRow){ export async function recordGreMutationRevision(server:ServerRow){
try{ try{
const revisionRecorded=(await captureAndAppendRevision({serverId:server.id,section:"gre",source:"apply",capture:async()=>{ const revisionRecorded=(await captureAndAppendRevision({serverId:server.id,section:"gre",source:"apply",capture:async()=>{
@@ -61,17 +66,29 @@ export function planGreMutation(server: ServerRow, input: GreMutation, before: G
const ops = planGreRestore({tunnels:[desired]},selected) const ops = planGreRestore({tunnels:[desired]},selected)
if (ops[0]?.op !== "patch") throw greMutationProblem("Не подготовлено изменение GRE") if (ops[0]?.op !== "patch") throw greMutationProblem("Не подготовлено изменение GRE")
const body = ops[0].body const body = ops[0].body
if (fields.ipsecSecret === undefined) delete body["ipsec-secret"] const clearSecret = fields.ipsecSecret === ""
if (!fields.ipsecSecret) delete body["ipsec-secret"]
else body["ipsec-secret"] = fields.ipsecSecret else body["ipsec-secret"] = fields.ipsecSecret
if (fields.localAddress !== undefined) body["local-address"] = fields.localAddress || "0.0.0.0" if (fields.localAddress !== undefined) body["local-address"] = fields.localAddress || "0.0.0.0"
body.comment = fields.comment !== undefined || fields.remoteInnerIp !== undefined ? desired.comment : target.comment ?? "" body.comment = fields.comment !== undefined || fields.remoteInnerIp !== undefined ? desired.comment : target.comment ?? ""
if (ops.length === 1 && Object.entries(body).every(([key,value])=>same(greNativeValue(key,target[key]),greNativeValue(key,value)))) throw greMutationProblem("GRE уже имеет запрошенную конфигурацию") if (!clearSecret && ops.length === 1 && Object.entries(body).every(([key,value])=>same(greNativeValue(key,target[key]),greNativeValue(key,value)))) throw greMutationProblem("GRE уже имеет запрошенную конфигурацию")
body.disabled = "yes" body.disabled = "yes"
if (clearSecret) {
// Clear even a configured empty value. RouterOS can create dynamic IKEv1 objects for it.
const path = ops[0].path
ops.unshift(greSecretUnsetOp(live.rosId))
if (!live.disabled) ops.unshift({ op: "patch", path, body: { disabled: "yes" } })
}
if (!desired.disabled) ops.push({op:"patch",path:"/interface/gre/"+live.rosId,body:{disabled:"no"}}) if (!desired.disabled) ops.push({op:"patch",path:"/interface/gre/"+live.rosId,body:{disabled:"no"}})
return ops return ops
} }
export function verifyGreMutationOp(before: GreMutationState, after: GreMutationState, op: RosWriteOp) { export function verifyGreMutationOp(before: GreMutationState, after: GreMutationState, op: RosWriteOp) {
if (op.op === "post" && op.path === "/interface/gre/unset" && op.body["value-name"] === "ipsec-secret") {
const id = op.body[".id"]
if (after.gre.find(row => row[".id"] === id)?.["ipsec-secret"] !== "") return false
return verifyGreMutationOp(before, after, { op: "patch", path: "/interface/gre/" + id, body: { "ipsec-secret": "" } })
}
const paths = {"/interface/gre":"gre","/ip/address":"ipv4","/ipv6/address":"ipv6"} as const const paths = {"/interface/gre":"gre","/ip/address":"ipv4","/ipv6/address":"ipv6"} as const
const path = Object.keys(paths).find(path=>op.path===path||op.path.startsWith(path+"/")) as keyof typeof paths|undefined const path = Object.keys(paths).find(path=>op.path===path||op.path.startsWith(path+"/")) as keyof typeof paths|undefined
if (!path || !["put","patch","delete"].includes(op.op)) return false if (!path || !["put","patch","delete"].includes(op.op)) return false
@@ -79,8 +96,11 @@ export function verifyGreMutationOp(before: GreMutationState, after: GreMutation
const id = op.path === path ? undefined : decodeURIComponent(op.path.slice(path.length+1)) const id = op.path === path ? undefined : decodeURIComponent(op.path.slice(path.length+1))
if (op.op === "put") { if (op.op === "put") {
const added = next[key].filter(row=>!prior[key].some(previous=>previous[".id"]===row[".id"])) const added = next[key].filter(row=>!prior[key].some(previous=>previous[".id"]===row[".id"]))
if (added.length !== 1 || !same(next[key].filter(row=>row!==added[0]),prior[key]) || !Object.entries(op.body).every(([field,value])=>same(greNativeValue(field,after[key].find(row=>row[".id"]===added[0][".id"])?.[field]),greNativeValue(field,value)))) return false if (added.length !== 1 || !same(next[key].filter(row=>row!==added[0]),prior[key])) return false
if (key!=="gre"&&observedBoolean(after[key].find(row=>row[".id"]===added[0][".id"])?.dynamic)!==false) return false const created = after[key].find(row => row[".id"] === added[0][".id"])
const expected = key === "gre" ? { "ipsec-secret": "", ...op.body } : op.body
if (!created || !Object.entries(expected).every(([field,value])=>same(greNativeValue(field,created[field]),greNativeValue(field,value)))) return false
if (key!=="gre"&&observedBoolean(created.dynamic)!==false) return false
// An address on our deliberately disabled GRE can legitimately be invalid. // An address on our deliberately disabled GRE can legitimately be invalid.
// This proof confirms configuration, not link/DAD/forwarding readiness. // This proof confirms configuration, not link/DAD/forwarding readiness.
} else { } else {
@@ -124,6 +144,7 @@ export async function mutateGreTunnel(server: ServerRow, raw: GreMutation, expec
const client = MikrotikClient.fromServer(fresh) const client = MikrotikClient.fromServer(fresh)
const receipt = await executeGreMutationOps(input,before,ops,{read:()=>readGreMutationState(fresh,input),...(input.operation==="delete"?{validate:(state:GreMutationState)=>{planGreMutation(fresh,input,state)}}:{}),command:op=>{ const receipt = await executeGreMutationOps(input,before,ops,{read:()=>readGreMutationState(fresh,input),...(input.operation==="delete"?{validate:(state:GreMutationState)=>{planGreMutation(fresh,input,state)}}:{}),command:op=>{
if (op.op === "put") return client.put(op.path,op.body) if (op.op === "put") return client.put(op.path,op.body)
if (op.op === "post") return client.post(op.path,op.body)
const slash = op.path.lastIndexOf("/"), path = op.path.slice(0,slash+1)+encodeURIComponent(op.path.slice(slash+1)) const slash = op.path.lastIndexOf("/"), path = op.path.slice(0,slash+1)+encodeURIComponent(op.path.slice(slash+1))
if (op.op === "delete") return client.delete(path) if (op.op === "delete") return client.delete(path)
if (op.op === "patch") return client.patch(path,op.body) if (op.op === "patch") return client.patch(path,op.body)
@@ -1,5 +1,5 @@
import assert from "node:assert/strict" import assert from "node:assert/strict"
import {validateGreRestoreSnapshot,materializeGreRestore,planGreRevisionRestore,executeGreRevisionSteps,readGreRestoreState,greRestoreWireOp} from "./gre-revision-restore.js" import {validateGreRestoreSnapshot,materializeGreRestore,planGreRevisionRestore,executeGreRevisionSteps,readGreRestoreState} from "./gre-revision-restore.js"
import {canonicalGreSnapshot,type GreSnapshot,type RosWriteOp} from "./entity-snapshots.js" import {canonicalGreSnapshot,type GreSnapshot,type RosWriteOp} from "./entity-snapshots.js"
import {greDependencyPaths,type GreMutationState} from "./gre-mutation-state.js" import {greDependencyPaths,type GreMutationState} from "./gre-mutation-state.js"
import {mapGreLive} from "./gre-live.js" import {mapGreLive} from "./gre-live.js"
@@ -12,13 +12,6 @@ assert.equal(expiredAccess,0)
const empty=():GreMutationState=>({serverConfiguration:"source",restoreProtectionProof:"protections",gre:[],ipv4:[],ipv6:[],dependencies:Object.fromEntries(greDependencyPaths.map(p=>[p,[]])),bindings:[],filters:[]}) const empty=():GreMutationState=>({serverConfiguration:"source",restoreProtectionProof:"protections",gre:[],ipv4:[],ipv6:[],dependencies:Object.fromEntries(greDependencyPaths.map(p=>[p,[]])),bindings:[],filters:[]})
const native={".id":"*G",name:"old","local-address":"192.0.2.1","remote-address":"192.0.2.2",mtu:"1476",keepalive:"1m,3",dscp:"inherit",disabled:"false",dynamic:"false",running:"true","clamp-tcp-mss":"true","allow-fast-path":"false","ipsec-secret":" key ",comment:"old-comment","dont-fragment":"yes"} const native={".id":"*G",name:"old","local-address":"192.0.2.1","remote-address":"192.0.2.2",mtu:"1476",keepalive:"1m,3",dscp:"inherit",disabled:"false",dynamic:"false",running:"true","clamp-tcp-mss":"true","allow-fast-path":"false","ipsec-secret":" key ",comment:"old-comment","dont-fragment":"yes"}
const wanted=(name:string)=>({name,localAddress:"",remoteAddress:"192.0.2.2",localInnerIp:"",remoteInnerIp:"",innerAddresses:[],comment:"",disabled:false,mtu:1400,keepalive:"0",dscp:"inherit",clampTcpMss:true,allowFastPath:false,ipsecSecret:""}) const wanted=(name:string)=>({name,localAddress:"",remoteAddress:"192.0.2.2",localInnerIp:"",remoteInnerIp:"",innerAddresses:[],comment:"",disabled:false,mtu:1400,keepalive:"0",dscp:"inherit",clampTcpMss:true,allowFastPath:false,ipsecSecret:""})
const defaultCreate:RosWriteOp={op:"put",path:"/interface/gre",body:{name:"gre","ipsec-secret":"","allow-fast-path":"yes"}}
const defaultWire=greRestoreWireOp(defaultCreate,empty())
assert.ok("body"in defaultWire&&!("ipsec-secret"in defaultWire.body));assert.equal(defaultCreate.body["ipsec-secret"],"")
const keyState=empty();keyState.gre=[{...native}]
const clearKey:RosWriteOp={op:"patch",path:"/interface/gre/*G",body:{"ipsec-secret":"","allow-fast-path":"no"}}
assert.equal(greRestoreWireOp(clearKey,keyState),clearKey,"A real key removal must not be silently omitted")
keyState.gre[0]["ipsec-secret"]="";assert.ok("body"in greRestoreWireOp(clearKey,keyState)&&!("ipsec-secret"in(greRestoreWireOp(clearKey,keyState)as{body:Record<string,string>}).body))
const snapshot=(...names:string[])=>canonicalGreSnapshot({tunnels:names.map(wanted)}) const snapshot=(...names:string[])=>canonicalGreSnapshot({tunnels:names.map(wanted)})
let sequence=0 let sequence=0
function apply(state:GreMutationState,op:RosWriteOp){ function apply(state:GreMutationState,op:RosWriteOp){
@@ -26,10 +19,11 @@ function apply(state:GreMutationState,op:RosWriteOp){
const key=path==="/interface/gre"?"gre":path==="/ip/address"?"ipv4":"ipv6",id=op.path.slice(path.length+1) const key=path==="/interface/gre"?"gre":path==="/ip/address"?"ipv4":"ipv6",id=op.path.slice(path.length+1)
const body="body"in op?Object.fromEntries(Object.entries(op.body).map(([k,v])=>[k,v==="yes"?"true":v==="no"?"false":v])):{} const body="body"in op?Object.fromEntries(Object.entries(op.body).map(([k,v])=>[k,v==="yes"?"true":v==="no"?"false":v])):{}
if(op.op==="put"){ if(op.op==="put"){
const added={...(key==="gre"?native:{dynamic:"false",invalid:"false","no-dad":"false","eui-64":"false","from-pool":""}),...body,".id":"*N"+(++sequence)} const added={...(key==="gre"?{...native,"ipsec-secret":""}:{dynamic:"false",invalid:"false","no-dad":"false","eui-64":"false","from-pool":""}),...body,".id":"*N"+(++sequence)}
next[key].push(added) next[key].push(added)
if(key==="gre")next.dependencies["/interface"].push({".id":added[".id"],name:added.name,type:"gre"}) if(key==="gre")next.dependencies["/interface"].push({".id":added[".id"],name:added.name,type:"gre"})
}else if(op.op==="patch")Object.assign(next[key].find(r=>r[".id"]===id)!,body) }else if(op.op==="patch")Object.assign(next[key].find(r=>r[".id"]===id)!,body)
else if(op.op==="post"&&op.path==="/interface/gre/unset")next.gre.find(r=>r[".id"]===body[".id"])!["ipsec-secret"]=""
else if(op.op==="delete"){ else if(op.op==="delete"){
next[key]=next[key].filter(r=>r[".id"]!==id) next[key]=next[key].filter(r=>r[".id"]!==id)
if(key==="gre")next.dependencies["/interface"]=next.dependencies["/interface"].filter(r=>r[".id"]!==id) if(key==="gre")next.dependencies["/interface"]=next.dependencies["/interface"].filter(r=>r[".id"]!==id)
@@ -74,6 +68,13 @@ assert.deepEqual(state.ipv6.find(r=>r.interface==="ether1"),original.ipv6[0]);as
const firstAddress=commands.findIndex(op=>!op.path.startsWith("/interface/gre")),oldDisable=commands.findIndex(op=>op.path==="/interface/gre/*G"&&"body"in op&&op.body.disabled==="yes") const firstAddress=commands.findIndex(op=>!op.path.startsWith("/interface/gre")),oldDisable=commands.findIndex(op=>op.path==="/interface/gre/*G"&&"body"in op&&op.body.disabled==="yes")
assert.ok(oldDisable>=0&&oldDisable<firstAddress);assert.ok(commands.slice(-2).every(op=>"body"in op&&op.body.disabled==="no")) assert.ok(oldDisable>=0&&oldDisable<firstAddress);assert.ok(commands.slice(-2).every(op=>"body"in op&&op.body.disabled==="no"))
assert.deepEqual(planGreRevisionRestore(fixed,state),[]) assert.deepEqual(planGreRevisionRestore(fixed,state),[])
assert.ok(commands.every(op=>!("body" in op)||op.body["ipsec-secret"]!==""))
const clearRevision=structuredClone(fixed)
clearRevision.tunnels.find(row=>row.name==="old")!.ipsecSecret=""
commands=[]
assert.equal((await execute(clearRevision)).verified,true)
assert.deepEqual(commands.find(op=>op.op==="post"),{op:"post",path:"/interface/gre/unset",body:{".id":"*G","value-name":"ipsec-secret"}})
assert.ok(commands.every(op=>!("body" in op)||!("ipsec-secret" in op.body)))
const deletion=planGreRevisionRestore({tunnels:[]},original) const deletion=planGreRevisionRestore({tunnels:[]},original)
assert.deepEqual(deletion[0],{kind:"native",op:{op:"patch",path:"/interface/gre/*G",body:{disabled:"yes"}}}) assert.deepEqual(deletion[0],{kind:"native",op:{op:"patch",path:"/interface/gre/*G",body:{disabled:"yes"}}})
assert.equal(deletion.at(-1)?.kind,"native");state=structuredClone(original);commands=[] assert.equal(deletion.at(-1)?.kind,"native");state=structuredClone(original);commands=[]
+11 -17
View File
@@ -9,7 +9,7 @@ import { canonicalGreSnapshot,greAddressKey,greAddressPath,greInterfaceBody,isHi
import { mapGreLive } from "./gre-live.js" import { mapGreLive } from "./gre-live.js"
import { greMtuSchema } from "./gre-mutation-input.js" import { greMtuSchema } from "./gre-mutation-input.js"
import { assertGreDeleteDependencies,greMutationProblem,greMutationProof,greNativeValue,readGreMutationState,type GreMutationState } from "./gre-mutation-state.js" import { assertGreDeleteDependencies,greMutationProblem,greMutationProof,greNativeValue,readGreMutationState,type GreMutationState } from "./gre-mutation-state.js"
import { verifyGreMutationOp } from "./gre-mutation.js" import { greSecretUnsetOp, verifyGreMutationOp } from "./gre-mutation.js"
import { observedBoolean } from "./ospf-observed-values.js" import { observedBoolean } from "./ospf-observed-values.js"
import { MikrotikClient } from "./mikrotik.js" import { MikrotikClient } from "./mikrotik.js"
import { withApplicationMutationLock,withConfigMutationLock } from "./config-mutation-lock.js" import { withApplicationMutationLock,withConfigMutationLock } from "./config-mutation-lock.js"
@@ -69,17 +69,6 @@ export function materializeGreRestore(desired:GreSnapshot,before:GreMutationStat
})}) })})
} }
export type GreRestoreStep={kind:"native";op:RosWriteOp}|{kind:"enable";name:string} export type GreRestoreStep={kind:"native";op:RosWriteOp}|{kind:"enable";name:string}
/** RouterOS treats presence of an empty ipsec-secret as an IPsec write and
* rejects it together with FastPath. Omit a redundant empty assignment on the
* wire only; per-command verification still uses the original expected body. */
export function greRestoreWireOp(op:RosWriteOp,before:GreMutationState):RosWriteOp{
if((op.op!=="put"&&op.op!=="patch")||op.body["ipsec-secret"]!=="")return op
const creating=op.op==="put"&&op.path==="/interface/gre"
const live=op.op==="patch"&&op.path.startsWith("/interface/gre/")?before.gre.find(row=>row[".id"]===decodeURIComponent(op.path.slice("/interface/gre/".length))):undefined
if(!creating&&live?.["ipsec-secret"]!=="")return op
const body={...op.body};delete body["ipsec-secret"]
return{...op,body}
}
export function planGreRevisionRestore(desired:GreSnapshot,before:GreMutationState):GreRestoreStep[]{ export function planGreRevisionRestore(desired:GreSnapshot,before:GreMutationState):GreRestoreStep[]{
const wanted=new Set(desired.tunnels.map(row=>row.name)) const wanted=new Set(desired.tunnels.map(row=>row.name))
for(const live of before.gre){ for(const live of before.gre){
@@ -95,10 +84,15 @@ export function planGreRevisionRestore(desired:GreSnapshot,before:GreMutationSta
let op=item let op=item
if((op.op==="put"&&op.path==="/interface/gre")||(op.op==="patch"&&op.path.startsWith("/interface/gre/"))){ if((op.op==="put"&&op.path==="/interface/gre")||(op.op==="patch"&&op.path.startsWith("/interface/gre/"))){
const want=desired.tunnels.find(row=>row.name===("body"in op?op.body.name:undefined))! const want=desired.tunnels.find(row=>row.name===("body"in op?op.body.name:undefined))!
const body:Record<string,string>={...op.body,"local-address":want.localAddress||"0.0.0.0",comment:greInterfaceBody(want).comment??"","ipsec-secret":want.ipsecSecret} const body:Record<string,string>={...op.body,"local-address":want.localAddress||"0.0.0.0",comment:greInterfaceBody(want).comment??""}
const live=before.gre.find(row=>row.name===want.name) const live=before.gre.find(row=>row.name===want.name)
const clearSecret=live&&Boolean(live["ipsec-secret"])&&!want.ipsecSecret
const addressChanges=legacy.some(row=>!row.path.startsWith("/interface/gre")&&("body"in row?row.body.interface===want.name:mapped.addrs.some(a=>a.interfaceName===want.name&&row.path===greAddressPath(a.address)+"/"+a.rosId))) const addressChanges=legacy.some(row=>!row.path.startsWith("/interface/gre")&&("body"in row?row.body.interface===want.name:mapped.addrs.some(a=>a.interfaceName===want.name&&row.path===greAddressPath(a.address)+"/"+a.rosId)))
if(live&&Object.entries(body).every(([key,value])=>same(greNativeValue(key,live[key]),greNativeValue(key,value)))&&!addressChanges)continue if(live&&!clearSecret&&Object.entries(body).every(([key,value])=>same(greNativeValue(key,live[key]),greNativeValue(key,value)))&&!addressChanges)continue
if(live&&clearSecret){
if(observedBoolean(live.disabled)===false)staging.push({kind:"native",op:{op:"patch",path:op.path,body:{disabled:"yes"}}})
staging.push({kind:"native",op:greSecretUnsetOp(live[".id"])})
}
body.disabled="yes";op={...op,body};if(!want.disabled)enable.add(want.name) body.disabled="yes";op={...op,body};if(!want.disabled)enable.add(want.name)
staging.push({kind:"native",op});continue staging.push({kind:"native",op});continue
} }
@@ -132,12 +126,12 @@ export async function restoreGreRevision(server:ServerRow,id:string,options:{bef
const desired=options.desired?validateGreRestoreSnapshot(options.desired):materializeGreRestore(revision.desired,before),steps=planGreRevisionRestore(desired,before),client=MikrotikClient.fromServer(server) const desired=options.desired?validateGreRestoreSnapshot(options.desired):materializeGreRestore(revision.desired,before),steps=planGreRevisionRestore(desired,before),client=MikrotikClient.fromServer(server)
const checkRevision=async()=>{if((await readGreRestoreRevision(server.id,id,authorize)).revisionProof!==revision.revisionProof)throw problem("Ревизия изменилась во время GRE restore")} const checkRevision=async()=>{if((await readGreRestoreRevision(server.id,id,authorize)).revisionProof!==revision.revisionProof)throw problem("Ревизия изменилась во время GRE restore")}
const receipt=await executeGreRevisionSteps(before,steps,{read:()=>readGreRestoreState(server,authorize,undefined,deadlineAt),authorizeRevision:checkRevision,validate:state=>{planGreRevisionRestore(desired,state)},command:(op,gate)=>{ const receipt=await executeGreRevisionSteps(before,steps,{read:()=>readGreRestoreState(server,authorize,undefined,deadlineAt),authorizeRevision:checkRevision,validate:state=>{planGreRevisionRestore(desired,state)},command:(op,gate)=>{
const wire=greRestoreWireOp(op,before)
const slash=op.path.lastIndexOf("/"),path=op.path.slice(0,slash+1)+encodeURIComponent(op.path.slice(slash+1)) const slash=op.path.lastIndexOf("/"),path=op.path.slice(0,slash+1)+encodeURIComponent(op.path.slice(slash+1))
const timeout=Math.max(1,Math.min(op.op==="delete"?10000:15000,deadlineAt-Date.now())) const timeout=Math.max(1,Math.min(op.op==="delete"?10000:15000,deadlineAt-Date.now()))
if(wire.op==="put")return client.put(wire.path,wire.body,timeout,gate) if(op.op==="put")return client.put(op.path,op.body,timeout,gate)
if(op.op==="post")return client.post(op.path,op.body,timeout,undefined,gate)
if(op.op==="delete")return client.delete(path,timeout,gate) if(op.op==="delete")return client.delete(path,timeout,gate)
if(wire.op==="patch")return client.patch(path,wire.body,timeout,gate) if(op.op==="patch")return client.patch(path,op.body,timeout,gate)
throw problem("Недопустимая команда GRE restore") throw problem("Недопустимая команда GRE restore")
}}) }})
const verified=receipt.verified&&planGreRevisionRestore(desired,receipt.after).length===0 const verified=receipt.verified&&planGreRevisionRestore(desired,receipt.after).length===0
@@ -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)
} }
} }
+23 -4
View File
@@ -9,10 +9,10 @@ import { createMcpConnection, authenticateMcpToken } from "../modules/mcp/store.
import { approvePlan, applyPlan, invokeMcpTool } from "../modules/mcp/runtime.js" import { approvePlan, applyPlan, invokeMcpTool } from "../modules/mcp/runtime.js"
export async function verifyMcpBgpExport(actor: AuthUser) { export async function verifyMcpBgpExport(actor: AuthUser) {
let mode = "", templateMode = "", writes = 0, reads = 0, ignored = false, unexpected = false, lost = false let mode = "", templateMode = "", writes = 0, reads = 0, ignored = false, unexpected = false, lost = false, ignoreRouteQuery = false
let staticQueryReply: unknown = [{ ".id": "*peer" }] let staticQueryReply: unknown = [{ ".id": "*peer" }]
const connection: Record<string, string> = { ".id": "*peer", name: "export-peer", disabled: "false", instance: "lab", vrf: "lab", "routing-table": "lab", templates: "default", "remote.address": "192.0.2.2", "remote.as": "64513", "tcp-md5-key": "NEVER_BGP_EXPORT_MD5" } const connection: Record<string, string> = { ".id": "*peer", name: "export-peer", disabled: "false", instance: "lab", vrf: "lab", "routing-table": "lab", templates: "default", "remote.address": "192.0.2.2", "remote.as": "64513", "tcp-md5-key": "NEVER_BGP_EXPORT_MD5" }
const routes: Record<string, unknown[]> = { const routes: Record<string, Record<string, unknown>[]> = {
"/ip/route": [{ ".id": "*c4", "routing-table": "lab", "dst-address": "192.0.2.0/30", connect: "true", dynamic: "true", active: "true", comment: "NEVER_BGP_EXPORT_ROUTE_NOTE" }, "/ip/route": [{ ".id": "*c4", "routing-table": "lab", "dst-address": "192.0.2.0/30", connect: "true", dynamic: "true", active: "true", comment: "NEVER_BGP_EXPORT_ROUTE_NOTE" },
{ ".id": "*s4", "routing-table": "lab", "dst-address": "198.18.0.1/32", static: "true", dynamic: "false", active: "true" }, { ".id": "*s4", "routing-table": "lab", "dst-address": "198.18.0.1/32", static: "true", dynamic: "false", active: "true" },
{ ".id": "*b4", "routing-table": "lab", "dst-address": "198.18.1.1/32", bgp: "true", dynamic: "true", active: "true" }], { ".id": "*b4", "routing-table": "lab", "dst-address": "198.18.1.1/32", bgp: "true", dynamic: "true", active: "true" }],
@@ -29,10 +29,17 @@ export async function verifyMcpBgpExport(actor: AuthUser) {
"/routing/filter/rule": [{ ".id": "*f", chain: "export-out", rule: "NEVER_BGP_EXPORT_FILTER_SECRET", disabled: "false" }], "/routing/filter/rule": [{ ".id": "*f", chain: "export-out", rule: "NEVER_BGP_EXPORT_FILTER_SECRET", disabled: "false" }],
} }
const mock = createServer(async (req, res) => { const mock = createServer(async (req, res) => {
const path = (req.url ?? "").replace(/^\/rest/, "") const url = new URL(req.url ?? "/", "http://127.0.0.1")
const path = url.pathname.replace(/^\/rest/, "")
if (req.method === "GET") { if (req.method === "GET") {
reads++; res.setHeader("content-type", "application/json") reads++; res.setHeader("content-type", "application/json")
res.end(JSON.stringify(path === "/routing/bgp/connection" ? [connection] : collections[path] ?? routes[path] ?? [])); return const candidates = routes[path]
if (candidates) {
const table = url.searchParams.get("routing-table"), kind = url.searchParams.has("connect") ? "connect" : "static"
assert.ok(table); assert.equal(url.searchParams.get(kind), "true")
res.end(JSON.stringify(ignoreRouteQuery ? candidates : candidates.filter(row => row["routing-table"] === table && row[kind] === "true"))); return
}
res.end(JSON.stringify(path === "/routing/bgp/connection" ? [connection] : collections[path] ?? [])); return
} }
let raw = ""; for await (const data of req) raw += data let raw = ""; for await (const data of req) raw += data
const body = raw ? JSON.parse(raw) as Record<string, string> : {} const body = raw ? JSON.parse(raw) as Record<string, string> : {}
@@ -49,6 +56,7 @@ export async function verifyMcpBgpExport(actor: AuthUser) {
const property = body["value-name"] const property = body["value-name"]
res.end(JSON.stringify(property === "output.redistribute" ? templateMode ? { ret: templateMode } : [] : property === "templates" ? { ret: collections["/routing/bgp/template"][0].templates ?? "" } : { ret: "false" })); return res.end(JSON.stringify(property === "output.redistribute" ? templateMode ? { ret: templateMode } : [] : property === "templates" ? { ret: collections["/routing/bgp/template"][0].templates ?? "" } : { ret: "false" })); return
} }
if (path === "/routing/bgp/instance/get") { res.end(JSON.stringify([])); return }
if (req.method === "PATCH" && path === "/routing/bgp/connection/*peer") { if (req.method === "PATCH" && path === "/routing/bgp/connection/*peer") {
writes++ writes++
assert.deepEqual(Object.keys(body), ["output.redistribute"]) assert.deepEqual(Object.keys(body), ["output.redistribute"])
@@ -100,6 +108,7 @@ export async function verifyMcpBgpExport(actor: AuthUser) {
staticQueryReply = invalid; await assert.rejects(plan("connected")); assert.equal(writes, 0) staticQueryReply = invalid; await assert.rejects(plan("connected")); assert.equal(writes, 0)
} }
staticQueryReply = [{ ".id": "*peer" }] staticQueryReply = [{ ".id": "*peer" }]
ignoreRouteQuery = true; await assert.rejects(plan("connected"), /не соответствует запросу источников/); ignoreRouteQuery = false
let prepared = await plan("connected") let prepared = await plan("connected")
assert.equal(prepared.state, "awaiting-approval"); assert.equal(prepared.changes.before.mode, "disabled"); assert.equal(prepared.changes.before.sources.length, 2) assert.equal(prepared.state, "awaiting-approval"); assert.equal(prepared.changes.before.mode, "disabled"); assert.equal(prepared.changes.before.sources.length, 2)
assert(prepared.changes.objects.some(row => row.kind === "ipv4_route" && row.id === "*c4")); assert(!prepared.changes.objects.some(row => row.kind === "ipv4_route" && row.id === "*b4")) assert(prepared.changes.objects.some(row => row.kind === "ipv4_route" && row.id === "*c4")); assert(!prepared.changes.objects.some(row => row.kind === "ipv4_route" && row.id === "*b4"))
@@ -146,6 +155,16 @@ export async function verifyMcpBgpExport(actor: AuthUser) {
const lostPlan = await plan("disabled"), lostOperation = await apply(lostPlan.planId) const lostPlan = await plan("disabled"), lostOperation = await apply(lostPlan.planId)
assert.equal(lostOperation.state, "unknown"); assert.equal(writes, beforeLost + 1); lost = false assert.equal(lostOperation.state, "unknown"); assert.equal(writes, beforeLost + 1); lost = false
assert.equal((await applyPlan(principal, lostPlan.planId, randomUUID())).id, lostOperation.id); assert.equal(writes, beforeLost + 1) assert.equal((await applyPlan(principal, lostPlan.planId, randomUUID())).id, lostOperation.id); assert.equal(writes, beforeLost + 1)
const instance = collections["/routing/bgp/instance"][0]
delete instance.vrf; delete instance["routing-table"]
Object.assign(connection, { vrf: "main", "routing-table": "main" }); mode = ""
collections["/ip/vrf"].push({ ".id": "*mainVrf", name: "main", interfaces: "all" })
collections["/routing/table"].push({ ".id": "*mainTable", name: "main", fib: "" })
const baseRoute = routes["/ip/route"][0]
routes["/ip/route"].push({ ...baseRoute, ".id": "*mainRoute", "routing-table": "main" })
const defaultContextPlan = await plan("connected")
assert.equal(defaultContextPlan.changes.before.sources.length, 1)
assert.equal((await apply(defaultContextPlan.planId)).state, "applied")
const requests = (await pool.query("SELECT input,result FROM mcp_requests WHERE connection_id=ANY($1::uuid[])", [connections])).rows const requests = (await pool.query("SELECT input,result FROM mcp_requests WHERE connection_id=ANY($1::uuid[])", [connections])).rows
const audit = (await pool.query("SELECT payload FROM mcp_audit WHERE connection_id=ANY($1::uuid[])", [connections])).rows const audit = (await pool.query("SELECT payload FROM mcp_audit WHERE connection_id=ANY($1::uuid[])", [connections])).rows
assert.equal(JSON.stringify({ requests, audit }).includes("NEVER_BGP_EXPORT_"), false) assert.equal(JSON.stringify({ requests, audit }).includes("NEVER_BGP_EXPORT_"), false)
+36 -3
View File
@@ -9,7 +9,7 @@ import { createMcpConnection, authenticateMcpToken } from "../modules/mcp/store.
import { approvePlan, applyPlan, invokeMcpTool } from "../modules/mcp/runtime.js" import { approvePlan, applyPlan, invokeMcpTool } from "../modules/mcp/runtime.js"
export async function verifyMcpBgpFilterBinding(actor: AuthUser) { export async function verifyMcpBgpFilterBinding(actor: AuthUser) {
let reads = 0, writes = 0, ignored = false, corrupt = false, lost = false, lateDrift = false, lateFenceReached = false, intentBaseline = 0 let reads = 0, writes = 0, ignored = false, corrupt = false, lost = false, lateDrift = false, lateFenceReached = false, intentBaseline = 0, unsetInstanceContext = false
const peer: Record<string, string> = { ".id": "*peer", name: "binding-peer", disabled: "false", instance: "lab", vrf: "lab", "routing-table": "lab", templates: "default", "tcp-md5-key": "NEVER_BIND_PEER_SECRET", "output.redistribute": "connected,static,ospf" } const peer: Record<string, string> = { ".id": "*peer", name: "binding-peer", disabled: "false", instance: "lab", vrf: "lab", "routing-table": "lab", templates: "default", "tcp-md5-key": "NEVER_BIND_PEER_SECRET", "output.redistribute": "connected,static,ospf" }
const local: Record<string, string | null> = { "input.filter": null, "output.filter-chain": null }, inherited: Record<string, string | null> = { "input.filter": null, "output.filter-chain": null } const local: Record<string, string | null> = { "input.filter": null, "output.filter-chain": null }, inherited: Record<string, string | null> = { "input.filter": null, "output.filter-chain": null }
const context: Record<string, string> = { instance: "lab", vrf: "lab", "routing-table": "lab" } const context: Record<string, string> = { instance: "lab", vrf: "lab", "routing-table": "lab" }
@@ -29,7 +29,7 @@ export async function verifyMcpBgpFilterBinding(actor: AuthUser) {
if (path === "/routing/bgp/connection/get") { const value = property === "dynamic" ? null : property === "templates" ? peer.templates : property in local ? local[property] : property in peer ? peer[property] : context[property] ?? "false"; res.end(JSON.stringify(value === null ? [] : { ret: value })); return } if (path === "/routing/bgp/connection/get") { const value = property === "dynamic" ? null : property === "templates" ? peer.templates : property in local ? local[property] : property in peer ? peer[property] : context[property] ?? "false"; res.end(JSON.stringify(value === null ? [] : { ret: value })); return }
if (path === "/routing/bgp/connection/print") { assert.deepEqual(body[".query"], [".id=*peer", "-dynamic", "#&"]); res.end(JSON.stringify([{ ".id": "*peer" }])); return } if (path === "/routing/bgp/connection/print") { assert.deepEqual(body[".query"], [".id=*peer", "-dynamic", "#&"]); res.end(JSON.stringify([{ ".id": "*peer" }])); return }
if (path === "/routing/bgp/template/get") { const value = property in inherited ? inherited[property] : property === "templates" ? collections["/routing/bgp/template"][0].templates ?? "" : "false"; res.end(JSON.stringify(value === null ? [] : { ret: value })); return } if (path === "/routing/bgp/template/get") { const value = property in inherited ? inherited[property] : property === "templates" ? collections["/routing/bgp/template"][0].templates ?? "" : "false"; res.end(JSON.stringify(value === null ? [] : { ret: value })); return }
if (path === "/routing/bgp/instance/get") { res.end(JSON.stringify({ ret: context[property] ?? "false" })); return } if (path === "/routing/bgp/instance/get") { res.end(JSON.stringify(unsetInstanceContext && ["vrf", "routing-table"].includes(property) ? [] : { ret: context[property] ?? "false" })); return }
if (path === "/routing/filter/rule/get") { res.end(JSON.stringify({ ret: "false" })); return } if (path === "/routing/filter/rule/get") { res.end(JSON.stringify({ ret: "false" })); return }
if (req.method === "PATCH" && path === "/routing/bgp/connection/*peer") { if (req.method === "PATCH" && path === "/routing/bgp/connection/*peer") {
writes++; assert.equal(Object.keys(body).length, 1); const key = Object.keys(body)[0]; assert.ok(key in local) writes++; assert.equal(Object.keys(body).length, 1); const key = Object.keys(body)[0]; assert.ok(key in local)
@@ -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) }
@@ -69,6 +69,39 @@ export async function verifyMcpBgpFilterBinding(actor: AuthUser) {
assert.equal((await apply((await prepare()).planId)).state, "applied", "Effective default context comes from native /get, not guessed main") assert.equal((await apply((await prepare()).planId)).state, "applied", "Effective default context comes from native /get, not guessed main")
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" })
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]
delete instance.vrf; delete instance["routing-table"]
Object.assign(peer, { vrf: "main", "routing-table": "main" }); unsetInstanceContext = true
assert.equal((await apply((await prepare()).planId)).state, "applied")
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" })
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
collections["/routing/bgp/template"][0].templates = "default"; await assert.rejects(prepare()); delete collections["/routing/bgp/template"][0].templates collections["/routing/bgp/template"][0].templates = "default"; await assert.rejects(prepare()); delete collections["/routing/bgp/template"][0].templates
await assert.rejects(prepare("In")); await assert.rejects(prepare("missing")) await assert.rejects(prepare("In")); await assert.rejects(prepare("missing"))
const beforeInvalid = reads; await assert.rejects(invokeMcpTool(principal, "mm_bgp_filter_binding_plan", { serverId: 79, id: "all", chain: "in", direction: "input" })); assert.equal(reads, beforeInvalid) const beforeInvalid = reads; await assert.rejects(invokeMcpTool(principal, "mm_bgp_filter_binding_plan", { serverId: 79, id: "all", chain: "in", direction: "input" })); assert.equal(reads, beforeInvalid)
+6 -5
View File
@@ -13,8 +13,8 @@ export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
const head = "text-muted-foreground mt-1 text-[11px] font-semibold tracking-wider uppercase" const head = "text-muted-foreground mt-1 text-[11px] font-semibold tracking-wider uppercase"
return ( return (
<Popover key={compact ? "compact" : "overview"}> <Popover key={compact ? "compact" : "overview"}>
<PopoverTrigger render={<Button type="button" variant="outline" className="text-[13px]" />}> <PopoverTrigger render={<Button type="button" variant="outline" size="sm" aria-label="Легенда" title="Легенда" />}>
<InfoIcon aria-hidden="true" className="size-4" />Легенда <InfoIcon aria-hidden="true" className="size-4" /><span className="@max-[430px]/network-map:hidden">Легенда</span>
</PopoverTrigger> </PopoverTrigger>
<PopoverContent align="end" role="region" aria-label="Легенда карты" className="max-h-[min(60vh,var(--available-height))] w-[310px] max-w-[calc(100vw-2rem)] gap-2 overflow-y-auto border p-3 text-xs"> <PopoverContent align="end" role="region" aria-label="Легенда карты" className="max-h-[min(60vh,var(--available-height))] w-[310px] max-w-[calc(100vw-2rem)] gap-2 overflow-y-auto border p-3 text-xs">
<p className={head}>Статус</p> <p className={head}>Статус</p>
@@ -38,11 +38,12 @@ export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--success)" strokeWidth="3" /></svg>GRE-туннель</span> <span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--success)" strokeWidth="3" /></svg>GRE-туннель</span>
<span className="flex items-center gap-2"><LockIcon aria-hidden className="mx-2 size-4" />GRE + IPsec</span> <span className="flex items-center gap-2"><LockIcon aria-hidden className="mx-2 size-4" />GRE + IPsec</span>
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--destructive)" strokeWidth="3" /></svg>GRE · нет связи</span> <span className="flex items-center gap-2"><svg aria-hidden width="32" height="10"><path d="M0 5H32" stroke="var(--status-degraded)" strokeWidth="3" strokeDasharray="6 3" /></svg>Каналы · частичный отказ или деградация</span>
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10"><path d="M0 5H32" stroke="var(--status-offline)" strokeWidth="3" strokeDasharray="2 3" /></svg>GRE · нет связи</span>
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeWidth="2" /></svg>Home Router → аплинк</span> <span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeWidth="2" /></svg>Home Router → аплинк</span>
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeOpacity=".5" strokeWidth="2" /></svg>WAN → JH · модель связности</span> <span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeOpacity=".5" strokeWidth="2" /></svg>WAN → JH · модель связности</span>
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="12" viewBox="0 0 32 12"><path d="M0 3 C16 3 16 9 32 9" fill="none" stroke="var(--chart-4)" strokeWidth="2" /></svg>Связь с сервисом</span> <span className="flex items-center gap-2"><svg aria-hidden width="32" height="12"><path d="M0 3H12Q16 3 16 6T20 9H32" fill="none" stroke="var(--chart-4)" strokeWidth="2" /></svg>Связь с сервисом · выход подтверждён</span>
<span className="flex items-center gap-2"><Badge variant="outline" size="xs">IPFIX</Badge>Наблюдение экспортёра · выход не подтверждён</span> <span className="flex items-center gap-2"><svg aria-hidden width="32" height="10"><path d="M0 5H32" stroke="var(--muted-foreground)" strokeWidth="2" strokeDasharray="4 3" /></svg><Badge variant="outline" size="xs">IPFIX</Badge>Наблюдение экспортёра · выход не подтверждён</span>
</div> </div>
<p className="text-muted-foreground leading-snug">Подпись линии GRE показывает последний замер RX/TX интерфейса RouterOS. Скорость сервиса и знак «≈» показывают среднюю скорость по принятым записям IPFIX. RTT — задержка пробы, «—» означает, что нет измерения.</p> <p className="text-muted-foreground leading-snug">Подпись линии GRE показывает последний замер RX/TX интерфейса RouterOS. Скорость сервиса и знак «≈» показывают среднюю скорость по принятым записям IPFIX. RTT — задержка пробы, «—» означает, что нет измерения.</p>
</PopoverContent> </PopoverContent>
+29
View File
@@ -0,0 +1,29 @@
"use client"
import { UsersIcon } from "lucide-react"
import { mapCardMeta, mapCardMetrics } from "@/lib/network-map-card-metrics"
export function MapAccessMark({ x, y, name, meta, selected, ariaLabel, onPick, width = 150 }: {
x: number; y: number; name: string; meta: string; selected: boolean; ariaLabel: string; onPick: () => void; width?: number
}) {
const kind = selected ? "user" : "access"
const { height, lines } = mapCardMetrics(name, kind, width)
const iconX = selected ? 19 : 15, nameX = selected ? 35 : 29
return <g transform={`translate(${x - width / 2},${y - height / 2})`} data-node-kind={kind}
role="button" aria-label={ariaLabel} tabIndex={0} className="network-map-focusable cursor-pointer"
onPointerDown={event => event.stopPropagation()}
onClick={event => { event.stopPropagation(); onPick() }}
onKeyDown={event => {
if (event.key === "Enter" || event.key === " ") { event.preventDefault(); event.stopPropagation(); onPick() }
}}>
<title>{[name, meta].filter(Boolean).join(" · ")}</title>
<rect className="network-map-focus-ring" x="-3" y="-3" width={width + 6} height={height + 6} rx="11" fill="none" stroke="var(--ring)" strokeWidth="2" />
<rect data-map-box="access" width={width} height={height} rx="9" fill="var(--card)" stroke={selected ? "var(--foreground)" : "var(--border)"} strokeWidth={selected ? 2 : 1.5} />
<circle cx={iconX} cy="21" r="12" fill="var(--muted)" />
<UsersIcon x={iconX - 8} y="13" width="16" height="16" color="var(--chart-2)" aria-hidden="true" />
{lines.map((line, i) => <text key={i} x={nameX} y={18 + i * 14} fill="var(--foreground)" fontSize="13" fontWeight="600">{line}</text>)}
<text x={nameX} y={33 + (lines.length - 1) * 14} fill="var(--muted-foreground)" fontFamily="var(--font-mono,Geist Mono,monospace)" fontSize="10.5">
{mapCardMeta(meta, width - nameX - 7)}
</text>
</g>
}
@@ -2,7 +2,19 @@
import { flagCdnUrl } from "@/components/flag" import { flagCdnUrl } from "@/components/flag"
const flags = {
RU: {w:4.5,h:3,art:<><rect width="4.5" height="3" fill="#fff"/><path d="M0 1h4.5v1H0z" fill="#0039a6"/><path d="M0 2h4.5v1H0z" fill="#d52b1e"/></>},
DE: {w:5,h:3,art:<><rect width="5" height="3" fill="#000"/><path d="M0 1h5v1H0z" fill="#d00"/><path d="M0 2h5v1H0z" fill="#ffce00"/></>},
SE: {w:16,h:10,art:<><rect width="16" height="10" fill="#006aa7"/><path d="M5 0h2v10H5zM0 4h16v2H0z" fill="#fecc02"/></>},
FI: {w:18,h:11,art:<><rect width="18" height="11" fill="#fff"/><path d="M5 0h3v11H5zM0 4h18v3H0z" fill="#002f6c"/></>},
}
export function CountryFlagSvg({ iso, size = 22 }: { iso: string; size?: number }) { export function CountryFlagSvg({ iso, size = 22 }: { iso: string; size?: number }) {
const code = iso.trim().toUpperCase()
if (Object.hasOwn(flags,code)) {
const {w,h,art} = flags[code as keyof typeof flags]
return <svg aria-hidden="true" width={size} height={size*h/w} viewBox={`0 0 ${w} ${h}`}>{art}</svg>
}
const url = flagCdnUrl(iso, size) const url = flagCdnUrl(iso, size)
if (!url) return null if (!url) return null
const h = Math.round(size * 0.75) const h = Math.round(size * 0.75)
+94
View File
@@ -0,0 +1,94 @@
"use client"
import { ChevronsUpDownIcon } from "lucide-react"
import type { KeyboardEvent } from "react"
import { mapCardMeta, mapCardMetrics } from "@/lib/network-map-card-metrics"
import { MapFaultBadge } from "./wire-badge"
import { 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, width = code === "WAN" ? 155 : 157 }: {
id: string; x: number; y: number; name: string; code: string; count: number; expanded: boolean
problems?: number; unknownCount?: number; onToggle: () => void; visible?: boolean; width?: number
}) {
const {height, lines} = mapCardMetrics(name, "group", width)
const color = roleColors[code] ?? "var(--muted-foreground)"
const health = problems ? `Проблемы · ${problems}` : unknownCount ? `Нет данных · ${unknownCount}` : ""
const label = [name, `${code} × ${count}`, health, problems && unknownCount ? `Нет данных · ${unknownCount}` : ""].filter(Boolean).join(" · ")
const meta = `${code === "WAN" ? "WAN" : "Устройств"} · ${count}`
return <g transform={`translate(${x - width / 2},${y - height / 2})`} data-map-group={id} data-node-kind="group"
role="button" tabIndex={visible ? 0 : -1} aria-expanded={expanded} aria-label={`${expanded ? "Свернуть" : "Раскрыть"} группу · ${label}`}
className="network-map-focusable cursor-pointer" opacity={visible ? 1 : 0.38}
onPointerDown={event => event.stopPropagation()} onClick={event => { event.stopPropagation(); onToggle() }}
onKeyDown={event => activate(event, onToggle)}>
<title>{[name, `${code} ×${count}`, health].filter(Boolean).join(" · ")}</title>
<rect className="network-map-focus-ring" x="-3" y="-3" width={width + 6} height={height + 6} rx="11" fill="none" stroke="var(--ring)" strokeWidth="2" />
<rect data-map-box="group" width={width} height={height} rx="9" fill="var(--card)" stroke={problems ? "color-mix(in oklch,var(--warning) 50%,transparent)" : "var(--border)"} strokeWidth="1.5" strokeDasharray="4 2" />
<rect data-role-tile={code} x="7" y="7" width="24" height="24" rx="7" fill={color} fillOpacity=".18" />
<text x="19" y="23" textAnchor="middle" fill={color} fontFamily="var(--font-mono,Geist Mono,monospace)" fontSize="11.5" fontWeight="700">{code}</text>
<ChevronsUpDownIcon x={width - 21} y="6" width="16" height="16" color="var(--muted-foreground)" aria-hidden="true" />
{lines.map((line, i) => <text key={i} x="37" y={18 + i * 14} fill="var(--foreground)" fontSize="13" fontWeight="600">{line}</text>)}
<text x="37" y={33 + (lines.length - 1) * 14} fill="var(--muted-foreground)" fontFamily="var(--font-mono,Geist Mono,monospace)" fontSize="10.5">{mapCardMeta(meta, width - 44) === meta ? meta : `×${count}`}</text>
{health && <text x="8" y={height - 5} fill={problems ? "var(--status-degraded-fg)" : "var(--muted-foreground)"} fontFamily={problems ? undefined : "var(--font-mono,Geist Mono,monospace)"}
fontSize={problems ? 11 : 10.5} fontWeight={problems ? 500 : 400}>{mapCardMeta(health, width - 18)}</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 ? [`${type} · Недоступно ${row.down} из ${row.count}`, `Недоступно ${row.down} из ${row.count}`, `↓ ${row.down}/${row.count}`] :
row.degraded ? [`${type} · Деградация ${row.degraded} из ${row.count}`, `! ${row.degraded}/${row.count}`] : []
return { ...row, color, texts, fault:Boolean(row.down || row.degraded), 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.fault ? 2.8 : row.type === "gre" ? 2.4 : 1.6} opacity={row.fault ? 1 : row.type === "observation" ? .56 : .76}
strokeDasharray={row.down === row.count ? "2 3" : row.fault ? "6 3" : row.type === "observation" ? "4 3" : undefined} strokeLinejoin="round" 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>
<MapFaultBadge width={row.w} text={row.text} down={row.down === row.count} />
</g>
))}
</>
}
+105 -51
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,11 +28,32 @@ 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">
{path && <span className="text-muted-foreground">Категория потока</span>}
{onCategory ? <Button type="button" size="xs" variant="link" className="h-auto max-w-full justify-start whitespace-normal p-0 text-left text-[13px] font-semibold" onClick={() => onCategory(category)}>{category}<ChevronRightIcon aria-hidden className="size-3 text-muted-foreground" /></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="px-3">
{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 flex-wrap items-baseline justify-between gap-x-3 gap-y-1 border-b py-2">
<dt className="text-[11px] text-muted-foreground">{name}</dt> <dt className="text-[13px] text-muted-foreground">{name}</dt>
<dd className="font-mono text-sm font-semibold leading-tight [overflow-wrap:anywhere]">{value}</dd> <dd className="min-w-0 text-right font-mono text-[13px] font-semibold tabular-nums [overflow-wrap:anywhere]">{value}</dd>
</div>)} </div>)}
</dl> </dl>
} }
@@ -112,11 +134,16 @@ 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({ back, onNode, onUser, service, paths, exits, exitName, country, base, refresh, windowLabel, history, shareOfVisible, shareKnown = true, flowAt, stale, activePath, onPath, onClose, onCategory, filtered, onFilter, userId, ix, topology }: {
back?: ReactNode
onNode: (id: string) => (() => void) | undefined
onUser: (id: string) => (() => void) | undefined
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 +178,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 +190,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" })
@@ -177,71 +203,99 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
} }
if (countryFilter) trafficQuery.set("country", countryFilter) if (countryFilter) trafficQuery.set("country", countryFilter)
return <> return <>
<header className="flex items-center gap-2 px-3 py-3"> <header className="flex shrink-0 items-center gap-1 border-b 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="min-w-0 flex-1">
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold" title={service.label}>{service.label}</h2> <p className="mb-1 text-xs text-muted-foreground">Сервис</p>
<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> <h2 className="flex items-center gap-2 break-words text-[15px] font-semibold"><ServiceBrandIcon label={service.label} size={16} />{service.label}</h2>
<Badge size="sm" variant={observed ? "success-light" : "secondary"} title="Наличие трафика в окне NetFlow"><span aria-hidden>•</span>{stale ? "Архив" : observed ? "Есть трафик" : "Нет трафика"}</Badge> </div>
<Button size="icon-xs" variant="ghost" aria-label="Закрыть детали назначения" onClick={onClose}><XIcon /></Button> {back}<Button size="icon-sm" variant="outline" 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="min-h-0 flex-1 overflow-y-auto overscroll-contain">
<InspectorMetrics rows={[ {selectedPath && <section aria-label="Выбранный поток" className="space-y-2 border-b px-3.5 py-3 text-xs">
["Средняя за " + averageWindow, average ? formatNetflowRate(average) : "—", "Скорость по сохранённым потокам IPFIX"], <h3 className="font-medium">Выбранный поток</h3>
[shareOfVisible ? "Доля показанных сервисов" : country ? "Доля страны" : "Доля трафика", percent.format(service.share), "IPFIX · " + windowLabel], <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>
["Объём · " + (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>}</>], <p>{selectedPath.enId ? "Выход подтверждён" : "Наблюдение IPFIX · выход не подтверждён"}</p>
exitIds.length || !exporterIds.length <CategoryEvidence service={service} path={selectedPath} onCategory={onCategory} />
? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined] {selectedPath.trafficTypes?.map(row => <p key={JSON.stringify([row.application,row.transport])} className="text-muted-foreground">
: ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"], {[row.application,row.transport].filter(Boolean).join(" · ")} · {formatBytes(row.bytes)}
]} /> </p>)}
{trafficTypes.length > 0 && service.bytes > 0 && <section className="space-y-2 border-b px-3.5 py-3 text-xs" aria-label="Состав трафика IPFIX"> <p className="font-mono tabular-nums">IPFIX · среднее за {windowLabel} · {formatNetflowRate(selectedPath)} · {formatBytes(selectedPath.bytes)}</p>
<h3 className="flex justify-between gap-2 font-medium"><span>Состав трафика</span><span className="font-normal text-muted-foreground">IPFIX · {windowLabel}</span></h3> </section>}
<dl className="space-y-1"> <section className="space-y-2 border-b px-3.5 py-3 text-xs" aria-label="Состав трафика IPFIX">
<div className="flex flex-wrap items-center justify-between gap-1">
<h3 className="text-sm font-semibold">Категория трафика</h3>
<Badge size="sm" variant={observed ? "success-light" : "secondary"} title={flowAt ? new Date(flowAt).toLocaleString("ru-RU") : undefined}>{stale ? "Архив" : observed ? "Есть трафик" : "Нет трафика"}</Badge>
</div>
<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}> <section className="space-y-2 border-b px-3 py-3"><h3 className="flex items-baseline gap-2 text-sm font-semibold">Пути по данным IPFIX <span className="font-mono text-xs font-normal text-muted-foreground">{paths.length}</span></h3>
<Badge size="sm" variant={row.basis === "heuristic" ? "info-light" : "secondary"} {paths.map((path, index) => {
title={row.basis === "heuristic" ? "Сервис предполагается по сети назначения и порту 443" : undefined}> const key = servicePathKey(path)
{evidenceLabel[row.basis]}{serviceEvidence.length > 1 && ` · ${typeShare(row.bytes)}`} const active = selectedPath && servicePathKey(selectedPath) === key
</Badge> const expanded = active || (!selectedPath && index === 0)
</li>)} const user = path.clientId === "—" ? "Без привязки" : path.clientName
</ul> : null} const hops = [
</section>} {role:"Пользователь", name:user, go:onUser(path.clientId)},
<InspectorUsers users={serviceUsers(service, paths)} windowLabel={windowLabel} /> ...(path.viaId !== path.enId ? [{role:path.enId ? "Узел доступа" : "Экспортёр IPFIX", name:path.viaName || path.viaId, go:onNode(path.viaId)}] : []),
<section className="space-y-2 border-b px-3.5 py-3"><h3 className="text-[11px] text-muted-foreground">Путь трафика</h3> ...(path.enId ? [{role:"Подтверждённый выход", name:path.enName || path.enId, go:onNode(path.enId)}] : []),
{paths.map(p => { {role:path.enId ? "Назначение" : "Назначение записи", name:service.label, go:undefined},
const parts = [p.clientName !== "—" ? p.clientName : "", p.viaId !== p.enId ? p.viaName : "", ]
p.enName, service.label].filter(Boolean) return <div key={key} className="border-t py-1 text-xs">
const key = servicePathKey(p) <button type="button" onClick={() => onPath(path)} aria-pressed={Boolean(active)} className="grid w-full gap-1 rounded-sm py-1.5 text-left hover:bg-muted/50">
const active = activePath && servicePathKey(activePath) === key <span className="flex items-baseline gap-1.5"><ChevronRightIcon aria-hidden className={cn("size-3 shrink-0", expanded && "rotate-90")} />
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")}> <b className="min-w-0 break-words">{user} → {service.label}</b><span className="ml-auto shrink-0 font-mono text-muted-foreground">{formatNetflowRate(path)}</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>)} </span>
{!p.enId && <span className="basis-full text-[10px] text-muted-foreground"> <span className="flex items-center gap-1 text-[11px] text-muted-foreground">
Наблюдение IPFIX{p.viaIface ? ` · интерфейс ${p.viaIface}` : ""} · выход не подтверждён <i aria-hidden className={cn("w-4 border-t-2", path.enId ? "border-chart-4" : "border-dashed")} />
</span>} {path.enId ? "Выход подтверждён" : `Наблюдение IPFIX${path.viaIface ? ` · интерфейс ${path.viaIface}` : ""} · выход не подтверждён`}
</button> </span>
</button>
{expanded && <ol className="ml-1.5 py-2" aria-label="Путь потока">
{hops.map(({role,name,go},i) => <li key={role} className={cn("relative border-l pl-4 pb-2 last:border-transparent last:pb-0",
i === 0 ? "border-chart-2" : i === hops.length - 2 ? path.enId ? "border-chart-4" : "border-dashed border-muted-foreground" : "border-border")}>
<i aria-hidden className={cn("absolute top-0 left-[-4px] size-[7px] rounded-full border bg-card", i === 0 ? "border-chart-2" : i === hops.length-1 && path.enId ? "border-chart-4" : "border-muted-foreground")} />
<small className="block text-[11px] leading-none text-muted-foreground">{role}</small>
{go ? <button type="button" onClick={go} className="mt-1 flex min-h-7 w-full items-center justify-between gap-2 rounded px-1 text-left font-semibold hover:bg-muted">
{name}<ChevronRightIcon aria-hidden className="size-3 text-muted-foreground" /></button> : <strong className="mt-1 block py-1">{name}</strong>}
</li>)}
</ol>}
</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>)} {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> <InspectorMetrics rows={[
["Средняя за " + averageWindow, average ? formatNetflowRate(average) : "—", "Скорость по сохранённым потокам IPFIX"],
[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>}</>],
exitIds.length || !exporterIds.length
? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined]
: ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"],
]} />
<InspectorUsers users={serviceUsers(service, paths)} windowLabel={windowLabel} />
<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>
+4 -3
View File
@@ -1,6 +1,6 @@
"use client" "use client"
import { useEffect, useState } from "react" import { useEffect, useState, type ReactNode } from "react"
import Link from "next/link" import Link from "next/link"
import { UsersIcon, XIcon } from "lucide-react" import { UsersIcon, XIcon } from "lucide-react"
import type { IxLinuxBinding, IxSegment } from "@mmapp/contracts/internet-exchange" import type { IxLinuxBinding, IxSegment } from "@mmapp/contracts/internet-exchange"
@@ -168,7 +168,8 @@ export function MapUserPicker({ open, onOpenChange, users, pending, unavailable,
</CommandDialog> </CommandDialog>
} }
export function MapUserDetails({ user, groups, paths, services, rates, userRate, windowLabel, onClose, onService, nodeName, trafficHref }: { export function MapUserDetails({ back, user, groups, paths, services, rates, userRate, windowLabel, onClose, onService, nodeName, trafficHref }: {
back?: ReactNode
user: MapAccessUser; groups: Map<string, AccessBinding[]>; paths: FlowMapServicePath[]; services: FlowMapService[]; rates?: Map<string, AccessRate>; windowLabel: string user: MapAccessUser; groups: Map<string, AccessBinding[]>; paths: FlowMapServicePath[]; services: FlowMapService[]; rates?: Map<string, AccessRate>; windowLabel: string
userRate?: ReturnType<typeof projectTrafficObservations> userRate?: ReturnType<typeof projectTrafficObservations>
onClose: () => void; onService: (service: FlowMapService) => void; nodeName: (id: string) => string; trafficHref?: string onClose: () => void; onService: (service: FlowMapService) => void; nodeName: (id: string) => string; trafficHref?: string
@@ -177,7 +178,7 @@ export function MapUserDetails({ user, groups, paths, services, rates, userRate,
<header className="flex items-center gap-2 border-b p-3"> <header className="flex items-center gap-2 border-b p-3">
<UsersIcon className="size-4 shrink-0" aria-hidden /> <UsersIcon className="size-4 shrink-0" aria-hidden />
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold">{user.name}</h2><p className="text-xs text-muted-foreground">{user.linux ? "Linux-клиент IX" : user.login}</p></div> <div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold">{user.name}</h2><p className="text-xs text-muted-foreground">{user.linux ? "Linux-клиент IX" : user.login}</p></div>
<Button size="icon-xs" variant="ghost" onClick={onClose} aria-label="Закрыть детали пользователя"><XIcon /></Button> {back}<Button size="icon-sm" variant="outline" onClick={onClose} aria-label="Закрыть детали пользователя"><XIcon /></Button>
</header> </header>
<div className="flex flex-col gap-3 overflow-y-auto p-3"> <div className="flex flex-col gap-3 overflow-y-auto p-3">
{!user.linux && <section className="grid gap-1 text-xs" aria-label="Трафик пользователя"> {!user.linux && <section className="grid gap-1 text-xs" aria-label="Трафик пользователя">
+112 -114
View File
@@ -1,47 +1,66 @@
"use client" "use client"
import { useState, type ReactNode } from "react" import { useMemo, useState } from "react"
import { ChevronDownIcon, ChevronUpIcon } from "lucide-react" import { ArrowUpRightIcon, ChevronDownIcon, ChevronUpIcon, HistoryIcon } 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"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { SectionFrame, ToneBadge, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks" import { ToneBadge, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
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; confirmed: boolean; dest: string; bps: number; bytes: number; 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; rttMs: number | null; 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"
function Table({ head, cols, empty, children }: { head: string[]; cols: string; empty: string | null; children: ReactNode }) { function AnalysisGrid<T extends {id:string}>({rows, columns, empty}: {
return ( rows:T[]; columns:CompactDataGridColumn<T>[]; empty:string
<div className="max-h-[min(34svh,310px)] overflow-auto"> }) {
<div className="min-w-[720px]"> return <div className="max-h-[min(34svh,310px)] overflow-y-auto [&_tr:has([data-map-highlight])]:bg-primary/8">
<div aria-hidden="true" className={cn("bg-muted/55 text-muted-foreground sticky top-0 z-[1] grid h-10 items-center gap-x-3 border-b px-4 text-xs font-medium", cols)}> <CompactDataGrid data={rows} columns={columns} horizontalScroll emptyTitle={empty} />
{head.map((h) => <span key={h}>{h}</span>)} </div>
</div>
{empty ? <p className="text-muted-foreground px-4 py-8 text-center text-sm">{empty}</p> : children}
</div>
</div>
)
} }
function Row({ cols, hl, children }: { cols: string; hl?: boolean; children: ReactNode }) { function Destinations({ rows, onDestination, onCategory }: {
return <div className={cn("grid min-h-11 items-center gap-x-3 border-b px-4 py-1.5 text-[13px] last:border-b-0", cols, hl && "bg-primary/8")}>{children}</div> 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 <AnalysisGrid rows={rows} columns={columns} empty="Назначений за окно нет" />
} }
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 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)]"
/** /**
* Рабочая панель под картой (макет 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, onTunnel, onDestination, onCategory, eventsError, stat }: {
tab: MapBottomTab tab: MapBottomTab
onTab: (tab: MapBottomTab) => void onTab: (tab: MapBottomTab) => void
open: boolean open: boolean
@@ -52,11 +71,33 @@ export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, des
events: MapEventRow[] events: MapEventRow[]
onEvent: (event: MapEventRow) => void onEvent: (event: MapEventRow) => void
onFlow: (id: string) => void onFlow: (id: string) => void
onTunnel: (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
}) { }) {
const [showRoutineEvents, setShowRoutineEvents] = useState(false) const [showRoutineEvents, setShowRoutineEvents] = useState(false)
const flowColumns: CompactDataGridColumn<MapFlowRow>[] = [
{id:"dest",header:"Поток к назначению",size:156,cell:r=><Button variant="link" size="xs" data-map-highlight={r.hl || undefined} onClick={() => onFlow(r.id)}>{r.dest}</Button>},
{id:"client",header:"Пользователь",size:142},
{id:"exit",header:"Выход / экспортёр",size:178,cell:r=><div><span>{r.exit}</span><small className="block text-muted-foreground">{r.confirmed ? "Выход подтверждён" : "Выход не подтверждён"}</small></div>},
{id:"bps",header:"Скорость",size:125,cell:r=><span className="tabular-nums">{r.rate}</span>},
{id:"bytes",header:"Объём",size:120,cell:r=><span className="tabular-nums">{r.volume}</span>},
]
const rttColumns: CompactDataGridColumn<MapRttRow>[] = [
{id:"name",header:"Канал",size:160,cell:r=><Button variant="link" size="xs" data-map-highlight={r.hl || undefined} onClick={() => onTunnel(r.id)}>{r.name}</Button>},
{id:"route",header:"Участок",size:180},
{id:"rttMs",header:"RTT",size:90,cell:r=>r.rtt},
{id:"speed",header:"Скорость ↓/↑",size:152,enableSorting:false},
{id:"status",header:"Состояние",size:125,cell:r=><ToneBadge tone={r.tone}>{r.status}</ToneBadge>},
]
const eventColumns: CompactDataGridColumn<MapEventRow>[] = [
{id:"ts",header:"Время",size:84,cell:r=><time dateTime={new Date(r.ts).toISOString()}>{new Date(r.ts).toLocaleTimeString("ru-RU", {hour:"2-digit",minute:"2-digit"})}</time>},
{id:"title",header:"Событие",size:225,cell:r=><Button variant="link" size="xs" onClick={()=>onEvent(r)}>{r.title}</Button>},
{id:"label",header:"Тип",size:112,cell:r=><ToneBadge tone={r.tone} mark={false}>{r.label}</ToneBadge>},
{id:"message",header:"Подробности",size:255},
]
const incidentEvents = events.filter(event => event.tone === "er" || event.tone === "wn") const incidentEvents = events.filter(event => event.tone === "er" || event.tone === "wn")
const visibleEvents = showRoutineEvents ? events : incidentEvents const visibleEvents = showRoutineEvents ? events : incidentEvents
const tabs: Array<{ id: MapBottomTab; label: string; count: number }> = [ const tabs: Array<{ id: MapBottomTab; label: string; count: number }> = [
@@ -66,61 +107,32 @@ export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, des
{ id: "events", label: "События", count: visibleEvents.length }, { id: "events", label: "События", count: visibleEvents.length },
] ]
return ( return (
<SectionFrame aria-label="Рабочая панель карты" bare className="min-w-0 shrink-0"> <section aria-label="Рабочая панель карты" className="@container/workbench min-w-0 shrink-0 rounded-xl border bg-card">
<Tabs value={tab} onValueChange={(value) => { onTab(value as MapBottomTab); onOpenChange(true) }} className="gap-1"> <Tabs value={tab} onValueChange={(value) => { onTab(value as MapBottomTab); onOpenChange(true) }} className="gap-0">
<div className="flex min-w-0 items-center gap-2 px-2 py-1"> <div className="flex min-w-0 items-center gap-1.5 p-1.5">
<div className="min-w-0 flex-1 overflow-x-auto"><TabsList aria-label="Рабочая панель"> <div className="min-w-0 flex-1"><TabsList aria-label="Рабочая панель" className="max-w-full flex-wrap justify-start gap-y-1" style={{height:"auto"}}>
{tabs.map((t) => ( {tabs.map((t) => (
<TabsTrigger key={t.id} value={t.id} className="px-2.5" onClick={() => onOpenChange(true)}> <TabsTrigger key={t.id} value={t.id} className="h-7 flex-none px-2.5" onClick={() => onOpenChange(true)}>
{t.label} {t.label}
<Badge variant="secondary" size="sm" className="font-mono">{t.count}</Badge> <Badge variant="secondary" size="sm" className="font-mono">{t.count}</Badge>
</TabsTrigger> </TabsTrigger>
))} ))}
</TabsList></div> </TabsList></div>
{open && <span className="hidden text-xs text-muted-foreground xl:inline">{stat}</span>} <Button type="button" variant="outline" 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="min-w-0 rounded-none border-0 border-t p-3">
{open && <header className="mb-2 flex flex-wrap items-baseline gap-x-3 gap-y-1">
<h2 className="text-base font-semibold">{tabs.find(item => item.id === tab)?.label}</h2>
<span className="text-[11px] text-muted-foreground">{stat}</span>
</header>}
<TabsContent value="flows"> <TabsContent value="flows">
<Table head={["Пользователь", "Выход / экспортёр", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}> <AnalysisGrid rows={flows} columns={flowColumns} empty="NetFlow за окно не прислал потоков к назначениям" />
{flows.map((r) => (
<Row key={r.id} cols={FLOW_COLS} hl={r.hl}>
<span className="truncate font-mono">{r.client}</span>
<span className="truncate font-mono">{r.exit}</span>
<Button type="button" variant="link" size="xs" className="min-w-0 justify-start" onClick={() => onFlow(r.id)}><span className="truncate">{r.dest}</span></Button>
<span className="font-mono tabular-nums">{r.rate}</span>
<span className="text-muted-foreground font-mono tabular-nums">{r.volume}</span>
</Row>
))}
</Table>
</TabsContent> </TabsContent>
<TabsContent value="rtt"> <TabsContent value="rtt">
<Table head={["Туннель", "Участок", "RTT", "Скорость ↓/↑", "Статус"]} cols={RTT_COLS} empty={rtt.length ? null : "GRE-туннелей на карте нет"}> <AnalysisGrid rows={rtt} columns={rttColumns} empty="GRE-туннелей на карте нет" />
{rtt.map((r) => (
<Row key={r.id} cols={RTT_COLS} hl={r.hl}>
<span className="truncate font-mono">{r.name}</span>
<span className="truncate font-mono">{r.route}</span>
<span className="font-mono tabular-nums">{r.rtt}</span>
<span className="font-mono tabular-nums">{r.speed}</span>
<span><ToneBadge tone={r.tone}>{r.status}</ToneBadge></span>
</Row>
))}
</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">
@@ -128,20 +140,11 @@ export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, des
<Button type="button" size="xs" variant={showRoutineEvents ? "secondary" : "outline"} aria-pressed={showRoutineEvents} onClick={() => setShowRoutineEvents(true)}>Все события</Button> <Button type="button" size="xs" variant={showRoutineEvents ? "secondary" : "outline"} aria-pressed={showRoutineEvents} onClick={() => setShowRoutineEvents(true)}>Все события</Button>
</div> </div>
{eventsError && <p role="status" className="px-3 py-1 text-xs text-muted-foreground">{eventsError}</p>} {eventsError && <p role="status" className="px-3 py-1 text-xs text-muted-foreground">{eventsError}</p>}
<Table head={["Время", "Тип", "Событие", "Подробности"]} cols={EVENT_COLS} empty={visibleEvents.length ? null : eventsError ? "Нет подтверждённых событий" : showRoutineEvents ? "Событий пока нет" : "В полученных событиях нет сбоев и предупреждений"}> <AnalysisGrid rows={visibleEvents} columns={eventColumns} empty={eventsError ? "Нет подтверждённых событий" : showRoutineEvents ? "Событий пока нет" : "В полученных событиях нет сбоев и предупреждений"} />
{visibleEvents.map((r) => (
<Row key={r.id} cols={EVENT_COLS}>
<time dateTime={new Date(r.ts).toISOString()} className="text-muted-foreground font-mono text-xs">{new Date(r.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })}</time>
<span><ToneBadge tone={r.tone} mark={false}>{r.label}</ToneBadge></span>
<Button type="button" variant="link" size="xs" className="min-w-0 justify-start" onClick={() => onEvent(r)}><span className="truncate">{r.title}</span></Button>
<span className="text-muted-foreground truncate text-xs">{r.message}</span>
</Row>
))}
</Table>
</TabsContent> </TabsContent>
</FramePanel> </FramePanel>
</Tabs> </Tabs>
</SectionFrame> </section>
) )
} }
@@ -149,7 +152,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) {
@@ -159,40 +162,35 @@ export function MapTimeline({ events, now, state, onPick }: { events: MapEventRo
group.push(event) group.push(event)
hours.set(hour, group) hours.set(hour, group)
} }
const at = (t: number) => `calc(10px + (100% - 20px) * ${t.toFixed(4)})` const yesterday = new Date(from).toLocaleTimeString("ru-RU", {hour:"2-digit", minute:"2-digit"})
// Шкала макета v3: остановки (кружок и подпись под ним), инциденты — цветные засечки над линией.
const stop = "absolute top-[7px] flex -translate-x-1/2 flex-col items-center gap-1 text-[11px] leading-none whitespace-nowrap"
return ( return (
<div className="flex shrink-0 items-center gap-3 border-t px-3 pt-1.5 pb-1"> <section aria-label="Лента инцидентов" className="@container/incidents min-w-0 shrink-0 rounded-xl border bg-card">
<small className="flex flex-col text-xs text-muted-foreground" title={state}>Инциденты{state ? <span role="status" className="hidden sm:inline">{state}</span> : null}</small> <div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-2 gap-y-1 px-3 py-1.5 @min-[590px]/incidents:grid-cols-[auto_minmax(0,1fr)_auto] @min-[590px]/incidents:gap-x-5">
<div role="group" aria-label="Инциденты карты за 24 часа" className="relative mx-3.5 h-9 min-w-0 flex-1"> <div className="flex items-center gap-2">
<span aria-hidden="true" className="bg-border absolute inset-x-2.5 top-[11px] h-0.5 rounded-full" /> <HistoryIcon aria-hidden className="size-4 shrink-0 text-muted-foreground" />
{[["−24 ч", 0], ["−6 ч", 0.75], ["−1 ч", 0.9583]].map(([label, t]) => ( <div className="flex flex-wrap items-baseline gap-x-2 @min-[590px]/incidents:block">
<span key={label} aria-hidden="true" className={cn(stop, "text-muted-foreground")} style={{ left: at(Number(t)) }}> <strong className="block text-[13px] font-semibold">Инциденты</strong>
<i className="bg-card border-muted-foreground block size-2.5 rounded-full border-2" />{label === "−1 ч" ? <span className="hidden xl:inline">{label}</span> : label} <small className="block text-[11px] text-muted-foreground">24 ч · Вся сеть{state && <span role="status"> · {state}</span>}</small>
</span> </div>
))} </div>
{[...hours].map(([hour, group]) => { <div role="group" aria-label="Инциденты карты за 24 часа" className="col-span-2 row-start-2 min-w-0 px-1.5 @min-[590px]/incidents:col-span-1 @min-[590px]/incidents:col-start-2 @min-[590px]/incidents:row-start-1">
const e = group.find(event => event.tone === "er") ?? group[0] <div className="relative h-6 before:absolute before:inset-x-0 before:top-1/2 before:border-t">
const label = `${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}${group.length > 1 ? ` · ещё ${group.length - 1}` : ""}` {[...hours.values()].map(group => {
return ( const event = group.find(item => item.tone === "er") ?? group[0]
<button const label = `${new Date(event.ts).toLocaleTimeString("ru-RU", {hour:"2-digit",minute:"2-digit"})} · ${event.title}${group.length > 1 ? ` · ещё ${group.length - 1}` : ""}`
key={e.id} return <button key={event.id} type="button" onClick={() => onPick(event)} aria-label={label} title={label}
type="button" className="absolute top-1/2 grid size-6 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => onPick(e)} style={{left:`${(event.ts-from)/86_400_000*100}%`}}>
aria-label={label} <span aria-hidden className="h-2.5 w-2 rounded-[2px]" style={{background:TONE_COLOR[event.tone]}} />
title={label} </button>
className="focus-visible:ring-ring absolute top-1 flex h-4 w-3 -translate-x-1/2 justify-center rounded-sm outline-none focus-visible:ring-2" })}
style={{ left: at((hour + 0.5) / 24) }} </div>
> <div aria-hidden className="flex justify-between font-mono text-[10px] tabular-nums text-muted-foreground">
<span aria-hidden="true" className="block h-full w-1.5 rounded-sm" style={{ background: TONE_COLOR[e.tone] }} /> <span>Вчера, {yesterday}</span><span>−12 ч</span><span>Сейчас</span>
</button> </div>
)})} </div>
<span className={cn(stop, "text-foreground font-semibold")} style={{ left: at(1) }}> <Button type="button" variant="ghost" size="xs" className="col-start-2 row-start-1 @min-[590px]/incidents:col-start-3" onClick={onJournal}>Журнал <ArrowUpRightIcon aria-hidden /></Button>
<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>
</div> </div>
<small className="text-muted-foreground font-mono text-xs">{new Date(now).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })}</small> </section>
</div>
) )
} }
+163
View File
@@ -0,0 +1,163 @@
"use client"
import type { KeyboardEvent, MouseEvent, PointerEvent } from "react"
import { ArrowDownLeftIcon, ArrowUpRightIcon, ChevronDownIcon, ChevronUpIcon, GlobeIcon, LayersIcon } from "lucide-react"
import type { Server, WanUplink } from "@/lib/data"
import { fmtRate } from "@/lib/fmt-rate"
import { mapCardMeta, mapCardMetrics } from "@/lib/network-map-card-metrics"
import type { MapDestinationMode } from "@/lib/network-map-url-state"
import { CountryFlagSvg } from "./country-flag-svg"
import { ServiceBrandIcon } from "./service-brand-icon"
const mono = "var(--font-mono,Geist Mono,monospace)"
const sans = "var(--font-sans,Geist,sans-serif)"
const muted = "var(--muted-foreground)"
const ink = "var(--foreground)"
const role = {
"home-router": {code:"HR",color:"var(--chart-2)"}, "jump-host": {code:"JH",color:"var(--chart-1)"},
"exit-node": {code:"EN",color:"var(--chart-3)"}, "ix-node": {code:"IX",color:"var(--chart-4)"},
}
const statusColor = { online:"var(--success)",degraded:"var(--warning)",offline:"var(--destructive)",unknown:muted }
function keys(event: KeyboardEvent<SVGGElement>, open: () => void) {
if (event.key === "Enter" || event.key === " ") { event.preventDefault(); event.stopPropagation(); open() }
}
function NameLines({ x, y, lines }: { x:number;y:number;lines:string[] }) {
return <g fontFamily={sans} fill={ink} fontSize={13} fontWeight={600} pointerEvents="none">
{lines.map((part,i) => <text key={i} x={x} y={y+i*14}>{part}</text>)}
</g>
}
function FocusRing({width,height,radius}: {width:number;height:number;radius:number}) {
return <rect className="network-map-focus-ring" x={-width/2-4} y={-height/2-4} width={width+8} height={height+8}
rx={radius+3} fill="none" stroke="var(--ring)" strokeWidth={2}/>
}
function Frame({width,height,kind,radius,stroke,selected,halo,fill="var(--card)"}: {
width:number;height:number;kind:"wan"|"card"|"dest";radius:number;stroke:string;selected:boolean;halo?:boolean;fill?:string
}) {
return <>
{selected && halo && <rect x={-3} y={-3} width={width+6} height={height+6} rx={radius+3} fill="none" stroke={stroke} strokeWidth={1.3} strokeDasharray="4 3"/>}
<rect data-map-box={kind} width={width} height={height} rx={radius} fill={fill} stroke={stroke} strokeWidth={selected?2:1.5}/>
</>
}
function Signal({x,y,status}:{x:number;y:number;status:Server["status"]}) {
return <circle data-node-status={status} cx={x} cy={y} r={4.3} fill={statusColor[status]} stroke="var(--card)" strokeWidth={1.7}/>
}
function shortRate(rate: string) {
return rate.replace(/(\d+(?:[.,]\d+)?) ([ГМК]?)бит\/с/g, (_, value: string, unit: string) => {
const reading = Number(value.replace(",","."))
return reading === 0 ? "0" : reading.toLocaleString("ru-RU",{maximumFractionDigits:2})+(unit||"б/с")
})
}
type PointerDown = (e: PointerEvent<SVGGElement>)=>void
export function ServerNode({ n,width,isSel,isVis,isDragged,hideCatalogLatency,channelProblem,rates,onClick,onDblClick,onHoverChange,onContextMenu,onPointerDown }: {
n:Server & {x:number;y:number};width:number;isSel:boolean;isVis:boolean;isDragged:boolean
hideCatalogLatency?:boolean;channelProblem?:"down"|"degraded";rates?:{rxMbps:number|null;txMbps:number|null}
onClick:()=>void;onDblClick:()=>void;onHoverChange:(hover:boolean)=>void;onContextMenu:(e:MouseEvent)=>void;onPointerDown:PointerDown
}) {
const {height,lines} = mapCardMetrics(n.name,"device",width)
const {code,color} = role[n.type]
const status = n.status !== "offline" && channelProblem ? "degraded" : n.status
const offline = status === "offline", warn = status === "degraded"
const border = isSel ? ink : warn ? "color-mix(in oklch,var(--warning) 50%,transparent)" : offline ? "var(--destructive)" : "var(--border)"
const iso = /^[A-Za-z]{2}$/.test(n.country?.trim() || "") ? n.country.trim() : ""
const metaY = 34 + (lines.length-1)*14, metaX = iso?60:42
const site = n.site?.trim() && n.site.trim() !== "—" ? n.site.trim() : "Без площадки"
const reading = offline ? "Нет ответа" : channelProblem === "down" ? "Отказ канала" : channelProblem ? "Деградация канала" :
!hideCatalogLatency && n.latency != null ? `RTT · ${n.latency} мс` : "Нет данных"
return <g role="button" className="network-map-focusable" aria-label={"Устройство "+n.name} aria-pressed={isSel} tabIndex={isVis?0:-1}
transform={`translate(${n.x},${n.y})`} data-node-kind="device" data-node-id={n.id} style={{cursor:isDragged?"grabbing":"grab"}} opacity={isVis?1:.38}
onKeyDown={e=>keys(e,onClick)} onClick={e=>{e.stopPropagation();onClick()}}
onDoubleClick={e=>{e.stopPropagation();onDblClick()}} onContextMenu={e=>{e.preventDefault();e.stopPropagation();onContextMenu(e)}}
onPointerDown={e=>{e.stopPropagation();onPointerDown(e)}} onMouseEnter={()=>onHoverChange(true)} onMouseLeave={()=>onHoverChange(false)}>
<title>{[n.name,site,rates?`RouterOS · RX ${fmtRate(rates.rxMbps)} · TX ${fmtRate(rates.txMbps)}`:reading].join(" · ")}</title>
<FocusRing width={width} height={height} radius={12}/>
<g transform={`translate(${-width/2},${-height/2})`}>
<Frame width={width} height={height} kind="card" radius={12} selected={isSel} stroke={border} fill={offline?"color-mix(in oklch,var(--destructive) 10%,var(--card))":"var(--card)"}/>
<rect data-role-tile={code} x={7} y={7} width={29} height={29} rx={7} fill={color} fillOpacity={.18}/>
<text x={21.5} y={25.5} textAnchor="middle" fill={color} fontSize={11.5} fontWeight={700} fontFamily={mono}>{code}</text>
<Signal x={35} y={8} status={status}/>
<NameLines x={42} y={19} lines={lines}/>
{iso && <g data-country-flag={iso.toUpperCase()} transform={`translate(42,${metaY-8})`}><CountryFlagSvg iso={iso} size={14}/></g>}
<text x={metaX} y={metaY} fill={muted} fontFamily={mono} fontSize={10.5}>{mapCardMeta(site,width-metaX-7)}</text>
{rates ? (["rx","tx"] as const).map((dir,i)=>{
const x=i?width/2+1:8
const RxTx=dir==="rx"?ArrowDownLeftIcon:ArrowUpRightIcon
const rate=dir==="rx"?rates.rxMbps:rates.txMbps
return <g key={dir} data-rate-dir={dir}>
<title>{`RouterOS ${dir.toUpperCase()} · ${fmtRate(rate)}`}</title>
<RxTx x={x} y={height-19} width={12} height={12} color={dir==="rx"?"var(--chart-rx)":"var(--chart-tx)"}/>
<text x={x+14} y={height-9} fill={ink} fontFamily={mono} fontSize={11} fontWeight={500}>{shortRate(fmtRate(rate))}</text>
</g>
}) : <text x={8} y={height-9} fill={warn?"var(--status-degraded-fg)":ink} fontSize={11} fontWeight={500} fontFamily={warn?sans:mono}>{mapCardMeta(reading,width-15)}</text>}
</g>
</g>
}
export function WanSatNode({x,y,wan,width,color,index,active,isSel,isDragged,traffic,onSelect,onPointerDown}: {
x:number;y:number;wan:WanUplink;width:number;color:string;index:number;active:boolean;isSel:boolean;isDragged:boolean;traffic?:string
onSelect:()=>void;onPointerDown:PointerDown
}) {
const name=wan.isp||wan.name
const {height,lines}=mapCardMetrics(name,"wan",width)
const status = active || traffic?.startsWith("Live ") ? "online" : "unknown"
return <g data-node-kind="wan" data-wan-index={index} role="button" aria-label={"Аплинк "+wan.name} aria-pressed={isSel} tabIndex={0} className="network-map-focusable"
transform={`translate(${x},${y})`} style={{cursor:isDragged?"grabbing":"grab"}} onKeyDown={e=>keys(e,onSelect)}
onPointerDown={e=>{e.stopPropagation();onPointerDown(e)}} onClick={e=>{e.stopPropagation();onSelect()}}>
<title>{[name,wan.name,wan.iface,traffic||"Нет данных"].filter(Boolean).join(" · ")}</title>
<FocusRing width={width} height={height} radius={24}/>
<g transform={`translate(${-width/2},${-height/2})`}>
<Frame width={width} height={height} kind="wan" radius={24} stroke={color} halo selected={isSel}/>
<circle cx={19} cy={21} r={12} fill="var(--muted)"/>
<GlobeIcon x={11} y={13} width={16} height={16} color={muted}/>
<Signal x={29} y={11} status={status}/>
<NameLines x={35} y={18} lines={lines}/>
<text x={35} y={33+(lines.length-1)*14} fill={muted} fontFamily={mono} fontSize={10.5}>{mapCardMeta(traffic?shortRate(traffic):"Нет данных",width-42)}</text>
</g>
</g>
}
export function ServiceNode({label,share,x,y,width,isSel,isVis,isDragged,destMode,iso,dim,shareLabel,category,rate,expanded,onClick,onPointerDown}: {
label:string;share:number|null;x:number;y:number;width:number;isSel:boolean;isVis:boolean;isDragged:boolean;destMode:MapDestinationMode
iso?:string;dim?:boolean;shareLabel?:string;category?:string;rate?:string;expanded?:boolean;onClick:()=>void;onPointerDown:PointerDown
}) {
const {height,lines} = mapCardMetrics(label,"destination",width)
const kind=expanded!==undefined?"minor-services":destMode==="categories"?"category":destMode==="countries"?"country":"service"
const aria=kind==="minor-services"?label:(kind==="service"?"Сервис ":kind==="country"?"Страна ":"Категория ")+label
const percent=share!=null?`${Math.round(share*100)}%`:"—"
const speed = rate?.replace(/\d+(?:[.,]\d+)?(?= [ГМК]?бит\/с)/g,
value => Number(value.replace(",",".")).toLocaleString("ru-RU",{maximumFractionDigits:2}))
const attrs=kind==="service"?{"data-service-brand":label}:kind==="country"?{"data-country-flag":iso}:kind==="category"?{"data-traffic-category":label}:{}
const Chevron=expanded?ChevronUpIcon:ChevronDownIcon
const subtitle=category||(kind==="country"?"Страна":"Сервис")
return <g data-node-kind={kind} role="button" aria-label={aria} aria-pressed={expanded===undefined?isSel:undefined} aria-expanded={expanded} tabIndex={isVis?0:-1} className="network-map-focusable"
transform={`translate(${x},${y})`} style={{cursor:expanded!==undefined?"pointer":isDragged?"grabbing":"grab"}} opacity={!isVis||dim ? .38 : 1}
onKeyDown={e=>keys(e,onClick)} onClick={e=>{e.stopPropagation();onClick()}} onPointerDown={e=>{e.stopPropagation();onPointerDown(e)}}>
<title>{[label,subtitle,speed,share===null?"Доля неизвестна":percent+" "+(shareLabel??"трафика окна")].filter(Boolean).join(" · ")}</title>
<FocusRing width={width} height={height} radius={9}/>
<g transform={`translate(${-width/2},${-height/2})`}>
<Frame width={width} height={height} kind="dest" radius={9} stroke={isSel?"var(--chart-4)":"var(--border)"} selected={isSel} halo/>
<circle cx={22} cy={21} r={14.5} fill="var(--muted)"/>
<g {...attrs} aria-hidden="true">
{kind==="minor-services"?<Chevron x={14} y={13} width={16} height={16} color={muted}/>:
kind==="category"?<LayersIcon x={14} y={13} width={16} height={16} color="var(--chart-4)"/>:
kind==="country"&&iso&&/^[a-z]{2}$/i.test(iso)?<g transform="translate(11,13)"><CountryFlagSvg iso={iso} size={22}/></g>:
kind==="country"?<GlobeIcon x={14} y={13} width={16} height={16} color={muted}/>:
<g transform="translate(11,10)"><ServiceBrandIcon label={label} size={22}/></g>}
</g>
<NameLines x={42} y={18} lines={lines}/>
<text x={kind==="minor-services" && width<150 ? 8 : 42} y={33+(lines.length-1)*14} fill={muted} fontFamily={sans} fontSize={11}>
{kind==="minor-services"&&!expanded?subtitle:mapCardMeta(subtitle,width-49)}</text>
<text x={8} y={height-12} fill={ink} fontFamily={mono} fontSize={11} fontWeight={500}>{mapCardMeta(speed||"Нет данных",width-46)}</text>
<text x={width-7} y={height-12} textAnchor="end" fill={muted} fontFamily={mono} fontSize={10.5}>{percent}</text>
{share!==null && <><rect x={8} y={height-7} width={width-16} height={2.5} rx={1.25} fill="var(--muted)"/>
<rect data-service-share={share*100} x={8} y={height-7} width={(width-16)*Math.max(0,Math.min(1,share))} height={2.5} rx={1.25} fill="var(--chart-4)"/></>}
</g>
</g>
}
@@ -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>
}
+19
View File
@@ -0,0 +1,19 @@
import { TriangleAlertIcon } from "lucide-react"
import { Badge } from "@/components/reui/badge"
export function MapFaultBadge({ width, text, down }: { width: number; text: string; down: boolean }) {
const tone = down ? "var(--status-offline-fg)" : "var(--status-degraded-fg)"
return <>
<rect data-map-box="pill" x={-width/2} y="-11" width={width} height="22" rx="5" fill="var(--card)" />
<foreignObject data-map-runtime-badge x={-width/2} y="-11" width={width} height="22" pointerEvents="none">
<div className="flex h-full items-center justify-center dark:[--destructive-foreground:var(--status-offline-fg)] dark:[--warning-foreground:var(--status-degraded-fg)]">
<Badge size="lg" variant={down ? "destructive-light" : "warning-light"}><TriangleAlertIcon aria-hidden="true" />{text}</Badge>
</div>
</foreignObject>
<g data-map-export-badge display="none" aria-hidden="true">
<rect x={-width/2} y="-11" width={width} height="22" rx="5" fill={down ? "var(--destructive)" : "var(--warning)"} fillOpacity=".14" />
<TriangleAlertIcon x={-width/2+6} y="-6" width="12" height="12" color={tone} />
<text x="7" y="4" textAnchor="middle" fill={tone} fontSize="12" fontWeight="500" fontFamily="Geist,sans-serif">{text}</text>
</g>
</>
}
+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
}
+54
View File
@@ -0,0 +1,54 @@
type CardKind = "device" | "wan" | "destination" | "access" | "user" | "group"
const cards: Record<CardKind, {height:number; inset:number}> = {
device: {height:63, inset:48}, wan: {height:51, inset:41}, destination: {height:64, inset:46},
access: {height:47, inset:33}, user: {height:47, inset:41}, group: {height:53, inset:62},
}
let measuringContext: CanvasRenderingContext2D | null = null
function textWidth(text: string) {
if (!measuringContext && typeof document !== "undefined") {
measuringContext = document.createElement("canvas").getContext("2d")
if (measuringContext) measuringContext.font = "600 13px " + getComputedStyle(document.body).fontFamily
}
if (measuringContext) return measuringContext.measureText(text).width
return [...text].reduce((w, ch) => w + (/[il1.,:'!|-]/.test(ch) ? 4.3 : /[mwMWШЩЖМЮ]/.test(ch) ? 11 : /[A-ZА-ЯЁ0-9]/.test(ch) ? 8.5 : 7.3), 0)
}
/** SVG marks, row placement and link routing share the same wrapped title and physical bounds. */
export function mapCardMetrics(name: string, kind: CardKind, width: number) {
const {height,inset} = cards[kind]
const room = Math.max(12,width-inset)
if (textWidth(name) <= room) return {width,height,lines:[name || "—"]}
const lines: string[] = []
let line = ""
function flush() {
if (line.trim()) lines.push(line.trim())
line = ""
}
function word(part: string) {
if (textWidth((line+part).trim()) <= room) { line += part; return }
if (line.trim()) flush()
if (textWidth(part.trim()) <= room) { line = part; return }
for (const char of part) {
if (line.trim() && textWidth((line+char).trim()) > room) flush()
line += char
}
}
const nameParts = (text: string) => text.match(/[^\s-]+-?|\s+|-/gu) ?? []
const host = kind === "device" && /^[\w-]+(?:\.[\w-]+){2,}$/.test(name)
if (host) {
const dot = name.indexOf(".")
nameParts(name.slice(0,dot)).forEach(word)
flush()
word(name.slice(dot))
} else nameParts(name).forEach(word)
flush()
if (!lines.length) lines.push("—")
return {width, lines, height:height+(lines.length-1)*14}
}
export function mapCardMeta(text: string, room: number) {
const max = Math.max(7,Math.floor(room/6.2))
return text.length > max ? text.slice(0,max-1)+"…" : text
}
+117
View File
@@ -0,0 +1,117 @@
import type { Server } from "./data"
import type { projectNetworkMapDensity, MapPoint } from "./network-map-density"
import { densityWanKey } from "./network-map-density"
import { mapCardMetrics } from "./network-map-card-metrics"
export type MapLane = "access" | "home" | "wan" | "jh" | "en" | "dest" | "nested"
export const deviceLane = (type: Server["type"]) => type === "home-router" ? "home" : type === "jump-host" ? "jh" : "en"
const minimum = {access:147, home:158, wan:147, jh:157, en:162, dest:167, nested:167}
const preferredCard = {access:150, home:157, wan:155, jh:157, en:157, dest:174, nested:174}
const laneOrder: MapLane[] = ["access", "home", "wan", "jh", "en", "dest", "nested"]
type Row = {
name: string
kind: Parameters<typeof mapCardMetrics>[1]
order: number
place: (point: MapPoint) => void
}
/** Place the visible rows at their real text size; retain the projected anchors for all folded members. */
export function layoutNetworkMapColumns(
viewWidth: number,
servers: readonly Server[],
projection: ReturnType<typeof projectNetworkMapDensity>,
access: {name:string; individual:boolean} | null,
destinations: ReadonlyArray<{id:string; name:string}>,
nested: ReadonlyArray<{id:string; name:string}>,
) {
const rows: Record<MapLane, Row[]> = {access:[], home:[], wan:[], jh:[], en:[], dest:[], nested:[]}
const nodePos = {...projection.nodePos}
const wanSatPos = Object.fromEntries(Object.entries(projection.wanSatPos).map(([id, points]) => [id, [...points]]))
const groups = projection.groups.map(group => ({...group}))
let accessPosition: MapPoint = {x:0, y:0}
const destPos: Record<string, MapPoint> = {}
const nestedPos: Record<string, MapPoint> = {}
if (access) {
rows.access.push({
name: access.name, kind: access.individual ? "user" : "access", order: 0,
place: point => { accessPosition = point },
})
}
const routers = servers.filter(server => server.type === "home-router")
.sort((a, b) => nodePos[a.id].y - nodePos[b.id].y || a.id.localeCompare(b.id))
const routerOrder = new Map(routers.map((server, index) => [server.id, index]))
for (const server of servers) {
if (!projection.hiddenServers.has(server.id)) {
rows[deviceLane(server.type)].push({
name: server.name, kind: "device", order: nodePos[server.id].y,
place: point => { nodePos[server.id] = point },
})
}
if (server.type !== "home-router") continue
const uplinks = server.wanUplinks ?? []
for (const [index, wan] of uplinks.entries()) {
if (projection.hiddenWans.has(densityWanKey(server.id, index))) continue
rows.wan.push({
name: wan.isp || wan.name, kind: "wan",
// The group header sorts first, followed by its uplinks in router interface order.
order: routerOrder.get(server.id)! + (index + 1) / (uplinks.length + 1),
place: point => { wanSatPos[server.id][index] = point },
})
}
}
for (const group of groups) {
const lane = group.kind === "wan" ? "wan" : deviceLane(group.type)
rows[lane].push({
name: group.label, kind: "group", order: group.routerId ? routerOrder.get(group.routerId)! : group.y,
place: point => Object.assign(group, point),
})
}
destinations.forEach((item, index) => {
rows.dest.push({name:item.name, kind:"destination", order:index, place:point => { destPos[item.id] = point }})
})
nested.forEach((item, index) => {
rows.nested.push({name:item.name, kind:"destination", order:index, place:point => { nestedPos[item.id] = point }})
})
const active = laneOrder.filter(lane => rows[lane].length)
const minimumWidth = active.reduce((sum,id) => sum + minimum[id], 0)
const worldWidth = Math.max(viewWidth,minimumWidth)
const extra = active.length ? (worldWidth-minimumWidth)/active.length : 0
const cardWidths = {...preferredCard}
let left = 0
const columns = active.map(id => {
const width = minimum[id] + extra
const x0 = left
left += width
cardWidths[id] = Math.min(preferredCard[id], width - 17)
const items = rows[id].sort((a, b) => a.order - b.order).map(row => ({
row, height: mapCardMetrics(row.name, row.kind, cardWidths[id]).height,
}))
return {id, x0, x1:left, cx:x0+width/2, items}
})
const gap = 15, top = 86
const tallest = Math.max(0, ...columns.map(({items}) => items.slice(0,5).reduce((sum,item) => sum+item.height+gap,0)))
const bodyHeight = Math.max(225,Math.min(390,tallest))
let worldHeight = Math.max(340, top+bodyHeight+24)
for (const {cx,items} of columns) {
const stack = items.reduce((sum,item) => sum+item.height+gap,-gap)
let y = top + Math.max(0,(bodyHeight-stack)/2)
for (const {row,height} of items) {
row.place({x:cx,y:y+height/2})
y += height+gap
}
worldHeight = Math.max(worldHeight,y-gap+26)
}
const groupById = new Map(groups.map(g => [g.id,g]))
for (const [id, parent] of projection.hiddenServers) {
const {x, y} = groupById.get(parent)!
nodePos[id] = {x, y}
}
for (const server of servers) for (const [i] of (server.wanUplinks ?? []).entries()) {
const parent = projection.hiddenWans.get(densityWanKey(server.id, i))
if (parent) {
const {x, y} = groupById.get(parent)!
wanSatPos[server.id][i] = {x, y}
}
}
return {groups, nodePos, wanSatPos, accessPosition, destPos, nestedPos, columns, cardWidths, worldWidth, worldHeight}
}
+141
View File
@@ -0,0 +1,141 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { greTunnels, type GreTunnel, type Server } from "./data"
import { densityWanKey, projectNetworkMapDensity } from "./network-map-density"
import { collectGroupLinks, countGroupGre } 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])
})
test("отказ между двумя узлами доступа одной группы учитывается свёрнутым и ведёт к обоим узлам после раскрытия", () => {
const servers = Array.from({length:12},(_,i) => ({...server("nsk-jh-"+(i+1),"jump-host","NSK"),host:`192.0.2.${i+1}`}))
const [first] = servers, last = servers.at(-1)!
const tunnel: GreTunnel = {...greTunnels[0],id:"nsk-internal",serverId:last.id,localAddress:last.host,remoteAddress:first.host,status:"down"}
const base = computeNetworkMapLayout(servers,[tunnel])
const edges = buildGreMapEdges([tunnel],servers,base.nodePos,base.wanSatPos)
const closed = projectNetworkMapDensity(servers,base.nodePos,base.wanSatPos,new Set())
const [group] = closed.groups
assert.equal(closed.hiddenServers.get(first.id),group.id)
assert.equal(closed.hiddenServers.get(last.id),group.id)
assert.deepEqual(countGroupGre(edges.filter(e=>group.serverIds.includes(e.fromServer.id)||group.serverIds.includes(e.toServer.id))),
{count:1,down:1,degraded:0})
const open = projectNetworkMapDensity(servers,base.nodePos,base.wanSatPos,new Set([group.id]))
const [channel] = buildGreMapEdges([tunnel],servers,open.nodePos,open.wanSatPos)
assert.deepEqual(new Set([channel.fromServer.id,channel.toServer.id]),new Set([first.id,last.id]))
assert.equal(channel.from.x,channel.to.x)
assert.notEqual(channel.from.y,channel.to.y)
})
+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, type MapBox } 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>, obstacles?: MapBox[], nextFaultTrack?: () => number) {
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, {obstacles, faultY:totals.down || totals.degraded ? nextFaultTrack?.() : undefined}),
}
})
}
export type MapGroupLink = ReturnType<typeof collectGroupLinks>[number]
+69 -59
View File
@@ -66,30 +66,61 @@ const NESTED_SERVICE_X = 1160
const MIN_NODE_Y = 80 const MIN_NODE_Y = 80
const MAX_NODE_Y = H - 44 const MAX_NODE_Y = H - 44
/** type MapPoint = { x: number; y: number }
* Плавная связь между боковыми гранями двух карточек: горизонтальная кривая Безье, как в макете. export interface MapLink { d: string; x1: number; y1: number; x2: number; y2: number; cx: number; points: MapPoint[] }
* Если карточки в одной полосе — дуга справа от обеих.
*/ /** Ортогональные участки соединяются закруглениями до 7 единиц, как на карте раздела. */
export function mapLinkPath( export function roundedMapPath(points: MapPoint[]) {
a: { x: number; y: number }, aHalfW: number, const clean = points.filter((p, i) => !i || p.x !== points[i-1].x || p.y !== points[i-1].y)
b: { x: number; y: number }, bHalfW: number, let d = `M ${clean[0].x} ${clean[0].y}`
): MapLink { for (let i = 1; i < clean.length - 1; i++) {
if (Math.abs(b.x - a.x) < aHalfW + bHalfW) { const a = clean[i-1], p = clean[i], b = clean[i+1]
const x1 = a.x + aHalfW, x2 = b.x + bHalfW, bend = Math.max(x1, x2) + 48 const before = Math.hypot(a.x - p.x, a.y - p.y), after = Math.hypot(b.x - p.x, b.y - p.y)
return { d: `M ${x1} ${a.y} C ${bend} ${a.y} ${bend} ${b.y} ${x2} ${b.y}`, x1, y1: a.y, x2, y2: b.y, cx: bend } const r = Math.min(7, before/2, after/2)
d += ` L ${p.x + (a.x-p.x)*r/before} ${p.y + (a.y-p.y)*r/before} Q ${p.x} ${p.y} ${p.x + (b.x-p.x)*r/after} ${p.y + (b.y-p.y)*r/after}`
} }
const dir = b.x > a.x ? 1 : -1 const end = clean.at(-1)!
const x1 = a.x + dir * aHalfW, x2 = b.x - dir * bHalfW, mx = (x1 + x2) / 2 return clean.length > 1 ? d + ` L ${end.x} ${end.y}` : d
return { d: `M ${x1} ${a.y} C ${mx} ${a.y} ${mx} ${b.y} ${x2} ${b.y}`, x1, y1: a.y, x2, y2: b.y, cx: mx }
} }
/** Связь карты: путь и опорные точки кривой (cx — x обеих управляющих точек). */ export function mapLinkPath(
export interface MapLink { d: string; x1: number; y1: number; x2: number; y2: number; cx: number } a: MapPoint, aHalfW: number, b: MapPoint, bHalfW: number,
options?: { faultY?: number; obstacles?: readonly MapBox[] },
): MapLink {
const sameLane = Math.abs(b.x - a.x) < aHalfW + bHalfW || a.x === b.x
const dir = b.x >= a.x ? 1 : -1
const fault = options?.faultY !== undefined
const startSide = sameLane ? 1 : fault ? -dir : dir
const endSide = sameLane ? 1 : fault ? dir : -dir
const x1 = a.x + startSide * aHalfW, x2 = b.x + endSide * bHalfW
const cx = sameLane ? Math.max(x1, x2) + 6 : (x1 + x2) / 2
const inner = (options?.obstacles ?? []).filter(box => box.x > Math.min(a.x, b.x) && box.x + box.w < Math.max(a.x, b.x))
const middle = (a.y + b.y) / 2
const intersectsRow = (y: number) => inner.some(box => y > box.y - 5 && y < box.y + box.h + 5)
let rail = options?.faultY
if (!fault && inner.length) {
const rows = [middle, ...inner.flatMap(box => [box.y - 6, box.y + box.h + 6])]
rail = rows.filter(y => !intersectsRow(y)).sort((l, r) => Math.abs(l-middle) - Math.abs(r-middle))[0]
}
const start = {x:x1, y:a.y}, end = {x:x2, y:b.y}
const first = x1 + startSide * 5, last = x2 + endSide * 6
const points = rail === undefined
? [start, {x:cx, y:a.y}, {x:cx, y:b.y}, end]
: [start, {x:first,y:a.y}, {x:first,y:rail}, {x:last,y:rail}, {x:last,y:b.y}, end]
return { d: roundedMapPath(points), x1, y1:a.y, x2, y2:b.y, cx, points }
}
/** Точка кривой связи при параметре t ∈ [0, 1]. */
export function mapLinkPoint(l: MapLink, t: number): { x: number; y: number } { export function mapLinkPoint(l: MapLink, t: number): { x: number; y: number } {
const u = 1 - t, a = u * u * u, b = 3 * u * u * t, c = 3 * u * t * t, d = t * t * t const lengths = l.points.slice(1).map((b, i) => Math.hypot(b.x - l.points[i].x, b.y - l.points[i].y))
return { x: a * l.x1 + (b + c) * l.cx + d * l.x2, y: (a + b) * l.y1 + (c + d) * l.y2 } let remaining = Math.max(0, Math.min(1, t)) * lengths.reduce((sum, n) => sum + n, 0)
for (const [i, length] of lengths.entries()) {
if (length && remaining <= length) {
const a = l.points[i], b = l.points[i+1], ratio = remaining / length
return { x:a.x + ratio*(b.x-a.x), y:a.y + ratio*(b.y-a.y) }
}
remaining -= length
}
return { x:l.x2, y:l.y2 }
} }
/** Прямоугольник на холсте (левый верхний угол и размеры). */ /** Прямоугольник на холсте (левый верхний угол и размеры). */
@@ -101,14 +132,14 @@ export const mapPillWidth = (text: string) => Math.round(text.length * 6.6 + 16)
const boxesHit = (a: MapBox, b: MapBox) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h const boxesHit = (a: MapBox, b: MapBox) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
/** Сначала середина кривой (как в макете), затем ближе к концам. */ /** Сначала середина кривой (как в макете), затем ближе к концам. */
const LABEL_T = [0.5, 0.42, 0.58, 0.34, 0.66, 0.27, 0.73] const LABEL_T = [0.5, 0.32, 0.68, 0.18, 0.82]
/** /**
* Раскладка подписей связей без наложений: каждая подпись ставится на свою кривую в первое свободное место — * Раскладка подписей связей без наложений: каждая подпись ставится на свою кривую в первое свободное место —
* не поверх карточек и других подписей. `texts` — варианты от полного к короткому; если не влезает ни один, * не поверх карточек и других подписей. `texts` — варианты от полного к короткому; если не влезает ни один,
* подпись не рисуется (значение остаётся в aria-label связи и в панели деталей). * подпись не рисуется (значение остаётся в aria-label связи и в панели деталей).
*/ */
export function placeMapLinkLabels<T extends { id: string; link: MapLink; texts: string[] }>( export function placeMapLinkLabels<T extends { id: string; link: MapLink; texts: string[]; fault?: boolean }>(
labels: T[], labels: T[],
obstacles: MapBox[], obstacles: MapBox[],
gap = 4, gap = 4,
@@ -116,10 +147,13 @@ export function placeMapLinkLabels<T extends { id: string; link: MapLink; texts:
const taken = obstacles.map((o) => ({ x: o.x - gap, y: o.y - gap, w: o.w + gap * 2, h: o.h + gap * 2 })) const taken = obstacles.map((o) => ({ x: o.x - gap, y: o.y - gap, w: o.w + gap * 2, h: o.h + gap * 2 }))
const out: Array<T & { x: number; y: number; w: number; text: string }> = [] const out: Array<T & { x: number; y: number; w: number; text: string }> = []
for (const label of labels) { for (const label of labels) {
const segments = label.link.points.slice(1).map((b, i) => ({ a:label.link.points[i], b, i,
length:Math.hypot(b.x-label.link.points[i].x, b.y-label.link.points[i].y) })).filter(s => s.length)
segments.sort((a,b) => (label.fault ? Number(b.i===2)-Number(a.i===2) : 0) || b.length-a.length)
search: for (const text of label.texts) { search: for (const text of label.texts) {
const w = mapPillWidth(text) const w = mapPillWidth(text) + (label.fault ? 16 : 0)
for (const t of LABEL_T) { for (const {a,b} of segments) for (const t of LABEL_T) {
const p = mapLinkPoint(label.link, t) const p = { x:a.x+t*(b.x-a.x), y:a.y+t*(b.y-a.y) }
const box = { x: p.x - w / 2, y: p.y - MAP_PILL_H / 2, w, h: MAP_PILL_H } const box = { x: p.x - w / 2, y: p.y - MAP_PILL_H / 2, w, h: MAP_PILL_H }
if (taken.some((o) => boxesHit(box, o))) continue if (taken.some((o) => boxesHit(box, o))) continue
taken.push({ x: box.x - gap, y: box.y - gap, w: w + gap * 2, h: MAP_PILL_H + gap * 2 }) taken.push({ x: box.x - gap, y: box.y - gap, w: w + gap * 2, h: MAP_PILL_H + gap * 2 })
@@ -877,35 +911,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 +920,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(
@@ -963,10 +970,9 @@ export function buildGreMapEdges(
const aIsIx = a.type === "ix-node", bIsIx = b.type === "ix-node" const aIsIx = a.type === "ix-node", bIsIx = b.type === "ix-node"
const la = aIsIx ? roleLayer("EN") : layerOfServer(a) const la = aIsIx ? roleLayer("EN") : layerOfServer(a)
const lb = bIsIx ? roleLayer("EN") : layerOfServer(b) const lb = bIsIx ? roleLayer("EN") : layerOfServer(b)
if (la == null || lb == null || la === lb && !aIsIx && !bIsIx) continue if (la == null || lb == null) continue
// Строгий поток слева направо: HR → JH → EN. // Keep an undirected channel in the same position for reports from either end.
// Если направление туннеля против иерархии — переворачиваем визуальное ребро.
let fromServer = a let fromServer = a
let toServer = b let toServer = b
if (la > lb || la === lb && a.id > b.id) { if (la > lb || la === lb && a.id > b.id) {
@@ -974,9 +980,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)
})
+3 -3
View File
@@ -1,9 +1,9 @@
import type { MapBox, MapLink } from "./network-map-layout" import { roundedMapPath, type MapBox, type MapLink } from "./network-map-layout"
/** Find a clear horizontal track between the sides facing the connection after dragging. */ /** Find a clear horizontal track between the sides facing the connection after dragging. */
export function mapObservationRoute(link: MapLink, boxes: readonly MapBox[], usedTracks: readonly number[]) { export function mapObservationRoute(link: MapLink, boxes: readonly MapBox[], usedTracks: readonly number[]) {
const { x1, y1, x2, y2, cx } = link const { x1, y1, x2, y2, cx } = link
const stub = (x: number) => x + Math.sign(cx - x) * Math.min(20, Math.abs(cx - x)) const stub = (x: number) => x + Math.sign(cx - x) * Math.min(6, Math.abs(cx - x))
const first = stub(x1), last = stub(x2) const first = stub(x1), last = stub(x2)
const middle = (y1 + y2) / 2 const middle = (y1 + y2) / 2
const obstacles = boxes.filter(box => box.x < Math.max(x1, first, last, x2) && box.x + box.w > Math.min(x1, first, last, x2)) const obstacles = boxes.filter(box => box.x < Math.max(x1, first, last, x2) && box.x + box.w > Math.min(x1, first, last, x2))
@@ -23,7 +23,7 @@ export function mapObservationRoute(link: MapLink, boxes: readonly MapBox[], use
if (y === undefined) return null if (y === undefined) return null
return { return {
d: `M ${x1} ${y1} H ${first} V ${y} H ${last} V ${y2} H ${x2}`, d: roundedMapPath([{x:x1,y:y1},{x:first,y:y1},{x:first,y},{x:last,y},{x:last,y:y2},{x:x2,y:y2}]),
marker: markerFits(y) ? { x: markerX, y } : undefined, marker: markerFits(y) ? { x: markerX, y } : undefined,
track: y, track: y,
} }
+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`. */
+125
View File
@@ -0,0 +1,125 @@
import type { Page } from "@playwright/test"
import { emptyMapFlow } from "./map-flow"
import { observedTrafficFixturePayload } from "../traffic-observation-fixture"
const ip = (id: number) => "192.0.2." + id
const server = (id: number, name: string, type: string, site: string, providers: string[] = []) => ({
id, name, type, site, host: ip(id), country: site === "ARN" ? "SE" : site ? "RU" : "", enabled: true,
status: id === 7 ? null : "online", latency: id === 7 ? null : id + 2,
wanUplinks: providers.map((provider, i) => ({ id: id + "-wan" + (i + 1), name: provider, iface: "ether" + (i + 1),
isp: provider, ip: `198.51.100.${id * 16 + i + 1}`, maxDl: 100, maxUl: 100 })),
})
const destinations = [
{label:"YouTube", country:"SE", category:"Видео / стриминг", mbps:24.8, user:"north", via:3, exit:8},
{label:"Cloudflare", country:"SE", category:"CDN", mbps:13.2, user:"north", via:4, exit:9},
{label:"Instagram", country:"DE", category:"Видео / стриминг", mbps:8.4, user:"east", via:5, exit:0},
{label:"Telegram", country:"FI", category:"Мессенджеры", mbps:10.4, user:"baltic", via:6, exit:8},
{label:"Microsoft", country:"SE", category:"CDN", mbps:2.4, user:"baltic", via:6, exit:8},
{label:"AWS", country:"DE", category:"CDN", mbps:0.6, user:"baltic", via:6, exit:8},
]
export async function serveMapVisual(page: Page, dense = false) {
const nskProviders = ["Обь Телеком", "Сибирская линия", "Городская сеть"]
const servers = [
server(1,"msk-home01","home-router","MSK",["Северная сеть","Городская линия"]),
server(2,"nsk-home01","home-router","NSK",Array.from({length:dense ? 12 : 2},(_,i) =>
i < 3 ? nskProviders[i] : nskProviders[i % 3] + " " + (i + 1))),
server(3,"msk-gw01","jump-host","MSK"), server(4,"msk-gw02","jump-host","MSK"),
server(5,"nsk-gw01","jump-host","NSK"), server(6,"spb-gw01","jump-host","SPB"),
server(7,"spare-gw01","jump-host",""), server(8,"arn-exit01","exit-node","ARN"),
server(9,"arn-exit02","exit-node","ARN"), server(10,"spb-ix01","ix-node","SPB"), server(11,"lab-ix01","ix-node","IX-LAB"),
...Array.from({length:dense ? 11 : 0},(_,i)=>server(22+i,"nsk-gw"+String(i+2).padStart(2,"0"),"jump-host","NSK")),
]
const gre = (name:string, from:number, to:number, failed = false) => ({
id:name, name, serverId:String(from), localAddress:ip(from), remoteAddress:ip(to), localInnerIp:"", remoteInnerIp:"",
poolId:"", ipsec:null, mtu:1476, keepaliveInterval:10, keepaliveRetries:3, dscp:"inherit",
clampTcpMss:true, allowFastPath:false, comment:"", enabled:true, status:failed ? "down" : "up",
})
const tunnels = [gre("gre-arn-main",3,8),gre("gre-arn-backup",3,8),gre("gre-arn-reserve",3,8,true),
gre("gre-msk-nsk",3,5),gre("gre-nsk-spb",5,6),gre("gre-msk02-arn02",4,9),
...Array.from({length:dense ? 11 : 0},(_,i)=>gre("gre-nsk-"+String(i+2).padStart(2,"0"),22+i,5,i===10))]
const links = [[1,3],[1,4],[2,5],[6,8],[6,10]].map(([from,to])=>({from,to,segment:"wg-"+from+"-"+to}))
const timestamp = new Date().toISOString()
const users = [
{id:"north",name:"Северный офис",via:1}, {id:"east",name:"Восточный офис",via:2}, {id:"baltic",name:"Балтийский офис",via:6},
].map(u=>{
const node=servers.find(s=>s.id===u.via)!
return {id:u.id,name:u.name,login:u.id,email:u.id+"@example.test",active:true,role:"viewer",avatar:u.name[0],
createdAt:timestamp,updatedAt:timestamp,lastSeen:null,sections:[],servers:[],bindings:[
{id:"binding-"+u.id,userId:u.id,serverId:node.id,serverName:node.name,serverSite:node.site,serverCountry:node.country,
interfaceName:"gre-"+u.id,interfaceType:"gre",comment:"",createdAt:timestamp,updatedAt:timestamp},
]}
})
const readings = [[1,48.8,12.6],[2,51.2,22.9],[3,132.1,86.3],[4,24.5,17.5],[5,20.4,30.8],[6,18.1,15.1],[8,78.3,95.3],[9,22.9,19.1],[10,10.4,5.2]]
const interfaceRates = new Map<string,number>([
["3/gre-arn-main",126.4],["3/gre-arn-backup",42],["3/gre-arn-reserve",0],
["3/gre-msk-nsk",28.6],["5/gre-nsk-spb",22.6],["4/gre-msk02-arn02",29.4],
])
for (const router of servers.filter(s=>s.wanUplinks.length)) {
router.wanUplinks.forEach((wan,i)=>{
if(i!==11) interfaceRates.set(router.id+"/"+wan.iface,i===0 ? (router.id===1?48.8:51.2) : 0)
})
}
const routerTraffic = observedTrafficFixturePayload(readings.map(([id,rxNow,txNow])=>({
id, rxNow, txNow, rxPeak:rxNow, txPeak:txNow, rxTotal:0, txTotal:0, rxSeries:[rxNow], txSeries:[txNow],
})))
function mapFlow(url:URL) {
const window=emptyMapFlow(url)
if(window.includesCurrentMinute) window.windowSec=60
const selectedUser=url.searchParams.get("userId")
const rows=destinations.filter(p=>!selectedUser || p.user===selectedUser)
const totalBps=rows.reduce((sum,p)=>sum+Math.round(p.mbps*1e6),0)
const services=rows.map(p=>{
const bps=Math.round(p.mbps*1e6), bytes=bps*window.windowSec/8
return {id:"svc:"+p.label.toLowerCase(),label:p.label,category:p.category,bytes,bps,share:bps/totalBps,
trafficTypes:[{transport:p.label==="Instagram"?"UDP/443":"TCP/443",application:p.label==="Instagram"?"QUIC":"HTTPS",bytes}],
serviceEvidence:[{basis:p.category==="Видео / стриминг"?"heuristic":"network",bytes}]}
})
const servicePaths=rows.map((p,i)=>({clientId:p.user,clientName:users.find(u=>u.id===p.user)!.name,
viaId:String(p.via),viaName:servers.find(s=>s.id===p.via)!.name,enId:p.exit ? String(p.exit) : "",enName:servers.find(s=>s.id===p.exit)?.name ?? "",
serviceId:services[i].id,bps:services[i].bps,bytes:services[i].bytes,serviceEvidence:services[i].serviceEvidence,trafficTypes:services[i].trafficTypes}))
const serviceEdges=servicePaths.map(p=>({fromId:p.enId || p.viaId,toId:p.serviceId,...(!p.enId ? {observedOnly:true} : {}),
bytes:p.bytes,bps:p.bps,bpsFwd:p.bps,bpsRev:0,clientId:p.clientId,clientName:p.clientName}))
const countries=[...new Set(rows.map(s=>s.country))].map(code=>{
const bps=rows.reduce((sum,p)=>sum+(p.country===code?Math.round(p.mbps*1e6):0),0)
return {id:"cc:"+code.toLowerCase(),label:code,category:"Страна",bps,bytes:bps*window.windowSec/8,share:bps/totalBps}
})
const countryId=(i:number)=>"cc:"+rows[i].country.toLowerCase()
return {...window,live:true,totalBytes:totalBps*window.windowSec/8,namedBytes:totalBps*window.windowSec/8,asnLoaded:true,countryLoaded:true,
mapServiceMinSharePct:0,services,servicePaths,serviceEdges,countries,
countryPaths:servicePaths.map((p,i)=>({...p,serviceId:countryId(i)})),countryEdges:serviceEdges.map((e,i)=>({...e,toId:countryId(i)})),
countryServiceGroups:countries.map(c=>{
const indexes=rows.flatMap((_,i)=>countryId(i)===c.id?[i]:[])
return {countryId:c.id,services:indexes.map(i=>({...services[i],id:c.id+"|"+services[i].id,share:services[i].bytes/c.bytes})),
edges:indexes.map(i=>({...serviceEdges[i],fromId:c.id,toId:c.id+"|"+services[i].id})),
paths:indexes.map(i=>({...servicePaths[i],serviceId:c.id+"|"+services[i].id}))}
})}
}
await page.route("**/health",route=>route.fulfill({json:{ok:true}}))
await page.route("**/api/**",route=>{
const url=new URL(route.request().url()), pathname=url.pathname
if(pathname==="/api/traffic/flow/map-hops") return route.fulfill({json:mapFlow(url)})
const live=pathname.match(/^\/api\/traffic\/servers\/(\d+)\/live$/)
if(live && url.searchParams.get("once")==="1") {
const sample=(iface:string)=>{
const mbps=interfaceRates.get(live[1]+"/"+iface)
return mbps==null ? null : {rxMbps:mbps,txMbps:0,at:new Date().toISOString(),timestampKind:"backend-receipt"}
}
const iface=url.searchParams.get("iface")
return route.fulfill({json:iface ? sample(iface) : {
interfaces:Object.fromEntries((url.searchParams.get("ifaces")??"").split(",").map(key=>[key,sample(key)])),
}})
}
const endpoints:Record<string,unknown>={
"/api/auth/config":{required:false}, "/api/servers":servers, "/api/users":{users}, "/api/filters/gre-tunnels":{tunnels,failures:[]},
"/api/uptime/speed-probes":{probes:[]}, "/api/traffic/servers":{servers:routerTraffic}, "/api/ix/topology":{links},
"/api/ix/segments":{items:[{id:"lab",appliedRevision:1}]}, "/api/ix/segments/lab/linux":{items:[
{serverId:11,interfaceName:"wg-lab-a",kind:"wireguard",name:"Linux-клиент Альфа",enabled:true},
{serverId:11,interfaceName:"gre-lab-b",kind:"gre",name:"Linux-клиент Бета",enabled:true}]},
"/api/events":{events:[{id:"gre-arn-reserve-down",createdAt:new Date(Date.parse(timestamp)-8*60_000).toISOString(),
level:"warning",eventType:"monitor",sourceModule:"alerts",title:"Недоступен gre-arn-reserve",message:"Не отвечает резервный GRE в ARN",entityType:"server",entityId:"3"}]},
}
return route.fulfill({json:endpoints[pathname] ?? {}})
})
}
+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")
})
+6 -2
View File
@@ -33,7 +33,9 @@ test("Карта: выбранный GRE обновляется и неизве
let changed=false let changed=false
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[{...tunnel,name:changed?"gre-new":"gre-home",status:changed?"down":"up"}],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?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,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[{...tunnel,name:changed?"gre-new":"gre-home",status:changed?"down":"up"}],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})})
await page.goto("/network-map") await page.goto("/network-map")
await page.locator("g").filter({has:page.locator("title",{hasText:"RTT неизвестен."})}).last().click() const link=page.getByRole("button",{name:/^Связь Домашний → Jump:/})
await expect(link.locator("title")).toContainText("RTT неизвестен.")
await link.press("Enter")
await expect(page.getByText("gre-home",{exact:true}).last()).toBeVisible();await expect(page.getByText("Ping неизвестен",{exact:true})).toBeVisible() await expect(page.getByText("gre-home",{exact:true}).last()).toBeVisible();await expect(page.getByText("Ping неизвестен",{exact:true})).toBeVisible()
changed=true;await page.getByRole("button",{name:"Обновить",exact:true}).click() changed=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
await expect(page.getByText("gre-new",{exact:true}).last()).toBeVisible();await expect(page.getByText("Недоступен",{exact:true})).toBeVisible() await expect(page.getByText("gre-new",{exact:true}).last()).toBeVisible();await expect(page.getByText("Недоступен",{exact:true})).toBeVisible()
@@ -44,7 +46,9 @@ test("Карта: GRE сохраняет частичное измерение,
const probe={id:"measured-probe",srcServerId:"1",dstServerId:"2",srcInterface:"gre-home",dstInterface:"",enabled:true,lastPingRttMs:0,lastPingLossPct:0,lastTxAvgMbps:0.125,lastRxAvgMbps:null,lastPingAt:"2020-01-01T00:00:00Z"} const probe={id:"measured-probe",srcServerId:"1",dstServerId:"2",srcInterface:"gre-home",dstInterface:"",enabled:true,lastPingRttMs:0,lastPingLossPct:0,lastTxAvgMbps:0.125,lastRxAvgMbps:null,lastPingAt:"2020-01-01T00:00:00Z"}
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[probe]}:p==="/api/traffic/flow/map-hops"?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,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[probe]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})})
await page.goto("/network-map") await page.goto("/network-map")
await page.locator("g").filter({has:page.locator("title",{hasText:"Проба measured-probe"})}).last().click() const link=page.getByRole("button",{name:/^Связь /})
await expect(link.locator("title")).toContainText("Проба measured-probe")
await link.press("Enter")
await expect(page.getByText("0 мс",{exact:true}).last()).toBeVisible() await expect(page.getByText("0 мс",{exact:true}).last()).toBeVisible()
await expect(page.getByText("↓0.125 ↑—",{exact:true}).last()).toBeVisible() await expect(page.getByText("↓0.125 ↑—",{exact:true}).last()).toBeVisible()
await expect(page.getByText("Проба measured-probe",{exact:false}).last()).toContainText("2020") await expect(page.getByText("Проба measured-probe",{exact:false}).last()).toContainText("2020")
+52 -5
View File
@@ -56,7 +56,7 @@ test("Карта и трафик сохраняют пользователя и
await expect(panel.getByText(/gre-alice · gre, gre-alice-2/)).toBeVisible() await expect(panel.getByText(/gre-alice · gre, gre-alice-2/)).toBeVisible()
await expect(panel.getByText(/RX 8.*TX 12.*2\/2/)).toBeVisible() await expect(panel.getByText(/RX 8.*TX 12.*2\/2/)).toBeVisible()
await expect(panel.getByRole("region", {name: "Трафик пользователя"})).toContainText("RX 8.00 Мбит/с · TX 12.0 Мбит/с") await expect(panel.getByRole("region", {name: "Трафик пользователя"})).toContainText("RX 8.00 Мбит/с · TX 12.0 Мбит/с")
await expect(map.getByRole("button", {name: "Пользователь Алиса"}).locator('rect[fill="var(--card)"]')).toHaveAttribute("stroke", "var(--border)") await expect(map.getByRole("button", {name: "Пользователь Алиса"}).locator('[data-map-box="access"]')).toHaveAttribute("stroke", "var(--foreground)")
await panel.getByRole("button", {name: /DNS/}).click() await panel.getByRole("button", {name: /DNS/}).click()
await panel.getByRole("link", {name: "Открыть в «Трафике»"}).click() await panel.getByRole("link", {name: "Открыть в «Трафике»"}).click()
await expect(page).toHaveURL(/\/traffic\?.*user=alice/) await expect(page).toHaveURL(/\/traffic\?.*user=alice/)
@@ -129,7 +129,7 @@ test("Карта показывает скорость и долю за коро
const url = new URL(response.url()) const url = new URL(response.url())
return url.pathname === flowPath && url.searchParams.get("range") === "1m" && url.searchParams.get("userId") === "boris" && response.status() === status return url.pathname === flowPath && url.searchParams.get("range") === "1m" && url.searchParams.get("userId") === "boris" && response.status() === status
}) })
await page.getByRole("button", {name: "Алиса", exact: true}).click() await page.getByRole("button", {name: "Алиса", exact: true}).and(page.locator('[aria-haspopup="dialog"]')).click()
await Promise.all([borisResponse(503), page.getByRole("option", {name: /Борис/}).click()]) await Promise.all([borisResponse(503), page.getByRole("option", {name: /Борис/}).click()])
await expect(card.getByRole("heading", {name: "Борис", exact: true})).toBeVisible() await expect(card.getByRole("heading", {name: "Борис", exact: true})).toBeVisible()
await expect(page.getByRole("status").filter({hasText: "Скорости сервисов пока недоступны"})).toBeVisible() await expect(page.getByRole("status").filter({hasText: "Скорости сервисов пока недоступны"})).toBeVisible()
@@ -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%")
}) })
@@ -279,9 +325,10 @@ for (const reverse of [false, true]) test(`Карта: малый NetFlow и т
}) })
await page.goto("/network-map") await page.goto("/network-map")
const badge = page.getByRole("button", { name: /^Связь / }) const badge = page.getByRole("button", { name: /^Связь / })
await expect(badge.locator("text")).toHaveText("—") await expect(badge).toHaveAccessibleName(/^Связь .*: GRE(?: ×2)?$/)
await expect(badge.locator("text")).toHaveCount(0)
await expect.poll(() => liveReads).toBeGreaterThan(0) await expect.poll(() => liveReads).toBeGreaterThan(0)
await badge.click() await badge.press("Enter")
const panel = page.getByRole("complementary", { name: "Детали объекта карты" }) const panel = page.getByRole("complementary", { name: "Детали объекта карты" })
await expect(panel.getByText("Нет записей", { exact: true })).toBeVisible() await expect(panel.getByText("Нет записей", { exact: true })).toBeVisible()
const live = page.getByText("Live GRE · RX/TX сейчас", {exact: true}).locator("..") const live = page.getByText("Live GRE · RX/TX сейчас", {exact: true}).locator("..")
+110 -6
View File
@@ -8,6 +8,79 @@ 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")
const scroller = page.locator("[data-map-scroll]")
expect(await scroller.evaluate(el => el.scrollWidth > el.clientWidth)).toBe(true)
await expect(page.getByRole("group", {name:"Масштаб карты"})).toContainText("100%")
await nav.getByRole("button", {name: "Следующая колонка"}).click()
await expect(lane).toHaveValue("wan")
await expect.poll(() => scroller.evaluate(el => el.scrollLeft)).toBeGreaterThan(0)
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 expect.poll(() => map.locator("[data-map-runtime-badge]").first().evaluate(element => {
const badge = element.getBoundingClientRect(), viewport = element.closest("svg")!.getBoundingClientRect()
return badge.left >= viewport.left && badge.right <= viewport.right && badge.top >= viewport.top && badge.bottom <= viewport.bottom
})).toBe(true)
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()
@@ -18,8 +91,10 @@ for(const width of [1440,390,320])test("Карта: доступные дета
await expect(panel).toBeVisible();await expect(panel.getByText("Ресурсы",{exact:true})).toBeVisible() await expect(panel).toBeVisible();await expect(panel.getByText("Ресурсы",{exact:true})).toBeVisible()
const bounds=await panel.boundingBox(),map=await page.getByRole("group",{name:"Интерактивная карта сети"}).boundingBox() const bounds=await panel.boundingBox(),map=await page.getByRole("group",{name:"Интерактивная карта сети"}).boundingBox()
expect(bounds!.width).toBeGreaterThan(250);expect(bounds!.height).toBeGreaterThan(350) expect(bounds!.width).toBeGreaterThan(250);expect(bounds!.height).toBeGreaterThan(350)
expect(map!.height).toBeGreaterThanOrEqual(390) expect(map!.height).toBeGreaterThanOrEqual(320)
if(width>=1024)expect(bounds!.x).toBeGreaterThan(map!.x+map!.width/2) expect(map!.height).toBeLessThanOrEqual(490)
if(width>=1024)expect(bounds!.x).toBeGreaterThanOrEqual(map!.x+map!.width-2)
else expect(bounds!.y).toBeGreaterThanOrEqual(map!.y+map!.height-2)
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true) expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true)
await page.screenshot({path:testInfo.outputPath("network-map-detail.png")}) await page.screenshot({path:testInfo.outputPath("network-map-detail.png")})
await panel.getByRole("button",{name:"Закрыть детали устройства"}).click() await panel.getByRole("button",{name:"Закрыть детали устройства"}).click()
@@ -34,6 +109,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:[
@@ -72,6 +166,11 @@ test("Карта: пропорции камеры, ручной масштаб
await expect.poll(async()=>Number((await map.getAttribute("viewBox"))!.split(" ")[2])).toBeLessThan(1240) await expect.poll(async()=>Number((await map.getAttribute("viewBox"))!.split(" ")[2])).toBeLessThan(1240)
const camera=await map.evaluate((element:SVGSVGElement)=>{const rect=element.getBoundingClientRect(),box=element.viewBox.baseVal;return {ratio:box.width/box.height,screenRatio:rect.width/rect.height}}) const camera=await map.evaluate((element:SVGSVGElement)=>{const rect=element.getBoundingClientRect(),box=element.viewBox.baseVal;return {ratio:box.width/box.height,screenRatio:rect.width/rect.height}})
expect(camera.ratio).toBeCloseTo(camera.screenRatio,3) expect(camera.ratio).toBeCloseTo(camera.screenRatio,3)
await map.hover()
await page.mouse.wheel(65,0)
const scroller=page.locator("[data-map-scroll]")
await expect.poll(()=>scroller.evaluate(el=>el.scrollLeft)).toBeGreaterThan(40)
await expect.poll(()=>map.evaluate((svg:SVGSVGElement)=>svg.viewBox.baseVal.x)).toBeGreaterThan(40)
await page.getByRole("button",{name:"Увеличить карту",exact:true}).click() await page.getByRole("button",{name:"Увеличить карту",exact:true}).click()
const manual=await map.getAttribute("viewBox") const manual=await map.getAttribute("viewBox")
await page.getByRole("button",{name:"Обновить",exact:true}).click() await page.getByRole("button",{name:"Обновить",exact:true}).click()
@@ -86,9 +185,10 @@ test("Карта: пропорции камеры, ручной масштаб
test("Карта: pointer capture, клавиатурный pan и возврат фокуса",async({page})=>{ test("Карта: pointer capture, клавиатурный pan и возврат фокуса",async({page})=>{
await page.goto("/network-map");const map=page.getByRole("group",{name:"Интерактивная карта сети"}),node=page.getByRole("button",{name:/^Устройство Домашний/}) await page.goto("/network-map");const map=page.getByRole("group",{name:"Интерактивная карта сети"}),node=page.getByRole("button",{name:/^Устройство Домашний/})
await expect(node).toBeVisible();await map.focus();const before=await map.getAttribute("viewBox");await map.press("ArrowDown");expect(await map.getAttribute("viewBox")).not.toBe(before) await expect(node).toBeVisible();await page.getByRole("button",{name:"Увеличить карту"}).click()
await map.focus();const before=await map.getAttribute("viewBox");await map.press("ArrowDown");await expect(map).not.toHaveAttribute("viewBox",before!)
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click() await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click()
const transform=await node.getAttribute("transform"),point=await node.evaluate((g:SVGGElement)=>{const matrix=g.getScreenCTM()!;return {x:matrix.e,y:matrix.f}}) const transform=await node.getAttribute("transform"),point=await node.evaluate(g=>{const box=g.getBoundingClientRect();return {x:box.x+box.width/2,y:box.y+box.height/2}})
await page.mouse.move(point.x,point.y);await page.mouse.down();await page.mouse.move(point.x+80,point.y+25,{steps:5});await page.mouse.up() await page.mouse.move(point.x,point.y);await page.mouse.down();await page.mouse.move(point.x+80,point.y+25,{steps:5});await page.mouse.up()
expect(await node.getAttribute("transform")).not.toBe(transform);await expect(page).toHaveURL(/server=1/) expect(await node.getAttribute("transform")).not.toBe(transform);await expect(page).toHaveURL(/server=1/)
await page.getByRole("button",{name:"Закрыть детали устройства"}).click();await expect(page.getByRole("textbox",{name:"Поиск узла или назначения"})).toBeFocused() await page.getByRole("button",{name:"Закрыть детали устройства"}).click();await expect(page.getByRole("textbox",{name:"Поиск узла или назначения"})).toBeFocused()
@@ -101,9 +201,13 @@ test("Карта: touch pan и отмена жеста без залипания
await page.setViewportSize({width:390,height:900});await page.goto("/network-map") await page.setViewportSize({width:390,height:900});await page.goto("/network-map")
const map=page.getByRole("group",{name:"Интерактивная карта сети"});await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible() const map=page.getByRole("group",{name:"Интерактивная карта сети"});await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
expect(await map.evaluate(e=>getComputedStyle(e).touchAction)).toBe("none") expect(await map.evaluate(e=>getComputedStyle(e).touchAction)).toBe("none")
await map.scrollIntoViewIfNeeded()
const box=(await map.boundingBox())!,before=await map.getAttribute("viewBox"),session=await page.context().newCDPSession(page) const box=(await map.boundingBox())!,before=await map.getAttribute("viewBox"),session=await page.context().newCDPSession(page)
await session.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{x:box.x+20,y:box.y+box.height-70,id:1}]}) const x=box.x+110,y=box.y+box.height-12
await session.send("Input.dispatchTouchEvent",{type:"touchMove",touchPoints:[{x:box.x+70,y:box.y+box.height-100,id:1}]}) expect(await page.evaluate(({x,y})=>document.elementFromPoint(x,y)?.hasAttribute("data-map-background"),{x,y})).toBe(true)
await session.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{x,y,id:1}]})
await session.send("Input.dispatchTouchEvent",{type:"touchMove",touchPoints:[{x:x-60,y:y-30,id:1}]})
await expect.poll(()=>page.locator("[data-map-scroll]").evaluate(el=>el.scrollLeft)).toBeGreaterThan(30)
await session.send("Input.dispatchTouchEvent",{type:"touchCancel",touchPoints:[]}) await session.send("Input.dispatchTouchEvent",{type:"touchCancel",touchPoints:[]})
expect(await map.getAttribute("viewBox")).not.toBe(before) expect(await map.getAttribute("viewBox")).not.toBe(before)
const stopped=await map.getAttribute("viewBox");await page.mouse.move(box.x+150,box.y+50);expect(await map.getAttribute("viewBox")).toBe(stopped) const stopped=await map.getAttribute("viewBox");await page.mouse.move(box.x+150,box.y+50);expect(await map.getAttribute("viewBox")).toBe(stopped)
+1 -1
View File
@@ -28,7 +28,7 @@ test("Карта: раскрытая легенда объясняет стат
const hit = document.elementFromPoint(x + width / 2, y + height / 2) const hit = document.elementFromPoint(x + width / 2, y + height / 2)
return hit !== null && element.contains(hit) return hit !== null && element.contains(hit)
})).toBe(true) })).toBe(true)
for (const text of ["Онлайн", "Внимание", "Оффлайн", "Неизвестно", "JumpHost", "Exit Node", "Home Router", "GRE + IPsec", "Связь с сервисом"]) await expect(legend.getByText(text, { exact: true })).toBeVisible() for (const text of ["Онлайн", "Внимание", "Оффлайн", "Неизвестно", "JumpHost", "Exit Node", "Home Router", "GRE + IPsec", "Связь с сервисом · выход подтверждён", "Каналы · частичный отказ или деградация"]) await expect(legend.getByText(text, { exact: true })).toBeVisible()
await expect(legend).toContainText("нет измерения") await expect(legend).toContainText("нет измерения")
await expect(legend).toContainText("последний замер RX/TX интерфейса RouterOS") await expect(legend).toContainText("последний замер RX/TX интерфейса RouterOS")
await expect(legend).toContainText("среднюю скорость по принятым записям IPFIX") await expect(legend).toContainText("среднюю скорость по принятым записям IPFIX")
+71 -3
View File
@@ -2,6 +2,7 @@ import { test, expect, type Page } from "@playwright/test"
// Подписи и карточки холста не наезжают друг на друга: проверяем видимые тела (data-map-box), а не фоновые полосы. // Подписи и карточки холста не наезжают друг на друга: проверяем видимые тела (data-map-box), а не фоновые полосы.
import { emptyMapFlow } from "./fixtures/map-flow" import { emptyMapFlow } from "./fixtures/map-flow"
import { serveMapVisual } from "./fixtures/network-map-visual"
const srv = (id: number, name: string, type: string, country = "RU", status = "online") => const srv = (id: number, name: string, type: string, country = "RU", status = "online") =>
({ id, name, host: `192.0.2.${id}`, type, country, enabled: true, status, latency: 10 + id }) ({ id, name, host: `192.0.2.${id}`, type, country, enabled: true, status, latency: 10 + id })
const gre = (id: string, owner: number, peer: number, status = "up") => ({ const gre = (id: string, owner: number, peer: number, status = "up") => ({
@@ -23,7 +24,7 @@ async function serve(page: Page, servers: unknown[], tunnels: ReturnType<typeof
async function overlaps(page: Page) { async function overlaps(page: Page) {
return page.getByRole("group", { name: "Интерактивная карта сети" }).evaluate((svg) => { return page.getByRole("group", { name: "Интерактивная карта сети" }).evaluate((svg) => {
const boxes = [...svg.querySelectorAll("[data-map-box]")].map((el) => ({ kind: el.getAttribute("data-map-box")!, label: el.closest("[aria-label]")?.getAttribute("aria-label") ?? el.parentElement?.textContent ?? "", text: el.parentElement?.querySelector(":scope > text")?.textContent ?? "", r: el.getBoundingClientRect() })) const boxes = [...svg.querySelectorAll("[data-map-box]")].map((el) => ({ kind: el.getAttribute("data-map-box")!, label: el.closest("[aria-label]")?.getAttribute("aria-label") ?? el.parentElement?.textContent ?? "", text: el.parentElement?.querySelector(":scope > text")?.textContent ?? "", r: el.getBoundingClientRect() }))
// Панель масштаба и миникарта лежат поверх холста — они тоже не должны закрывать карточки и подписи. // Учитываем включённые наложения, например миникарту.
const overlays = [...document.querySelectorAll("[data-map-overlay]")].map((el) => ({ kind: el.getAttribute("data-map-overlay")!, label: "", r: el.getBoundingClientRect() })) const overlays = [...document.querySelectorAll("[data-map-overlay]")].map((el) => ({ kind: el.getAttribute("data-map-overlay")!, label: "", r: el.getBoundingClientRect() }))
const hits: string[] = [] const hits: string[] = []
const pairs = [...boxes.flatMap((a, i) => boxes.slice(i + 1).map((b) => [a, b] as const)), ...overlays.flatMap((o) => boxes.map((b) => [o, b] as const))] const pairs = [...boxes.flatMap((a, i) => boxes.slice(i + 1).map((b) => [a, b] as const)), ...overlays.flatMap((o) => boxes.map((b) => [o, b] as const))]
@@ -31,10 +32,38 @@ async function overlaps(page: Page) {
const ix = Math.min(a.r.right, b.r.right) - Math.max(a.r.left, b.r.left), iy = Math.min(a.r.bottom, b.r.bottom) - Math.max(a.r.top, b.r.top) const ix = Math.min(a.r.right, b.r.right) - Math.max(a.r.left, b.r.left), iy = Math.min(a.r.bottom, b.r.bottom) - Math.max(a.r.top, b.r.top)
if (ix > 1 && iy > 1) hits.push(`${a.kind} «${a.label}» × ${b.kind} «${b.label}»`) if (ix > 1 && iy > 1) hits.push(`${a.kind} «${a.label}» × ${b.kind} «${b.label}»`)
} }
return { overlays: overlays.length, rates: boxes.filter((b) => b.kind === "pill" && /бит\/с/.test(b.text)).length, pills: boxes.filter((b) => b.kind === "pill").length, cards: boxes.filter((b) => b.kind === "card").length, hits } return { rates: boxes.filter((b) => b.kind === "pill" && /бит\/с/.test(b.text)).length, pills: boxes.filter((b) => b.kind === "pill").length, cards: boxes.filter((b) => b.kind === "card").length, hits }
}) })
} }
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"),
@@ -54,8 +83,13 @@ test("Карта: 3 JH → Exit + IX, параллельные GRE и 8 серв
await expect.poll(async () => (await overlaps(page)).cards).toBe(5) await expect.poll(async () => (await overlaps(page)).cards).toBe(5)
const result = await overlaps(page) const result = await overlaps(page)
expect(result.cards).toBe(5) expect(result.cards).toBe(5)
expect(result.overlays).toBe(2)
expect(result.hits).toEqual([]) expect(result.hits).toEqual([])
const map = page.getByRole("group", { name: "Интерактивная карта сети" })
const controls = page.getByRole("group", {name: "Масштаб карты"})
const [canvas, footer] = await Promise.all([map.boundingBox(), controls.boundingBox()])
expect(footer!.y).toBeGreaterThanOrEqual(canvas!.y + canvas!.height - 1)
const openMini = controls.getByRole("button", {name: "Показать миникарту"})
await expect(openMini).toHaveAttribute("aria-pressed", "false")
// Скорость NetFlow пары не теряется: она на подписи или, если не влезла между карточками, — в title линии. // Скорость NetFlow пары не теряется: она на подписи или, если не влезла между карточками, — в title линии.
expect(result.rates + await page.locator("path > title", { hasText: /^Связь .*бит\/с/ }).count()).toBeGreaterThan(0) expect(result.rates + await page.locator("path > title", { hasText: /^Связь .*бит\/с/ }).count()).toBeGreaterThan(0)
// Имя хоста без домена, параллельные туннели — одной подписью. // Имя хоста без домена, параллельные туннели — одной подписью.
@@ -63,6 +97,10 @@ test("Карта: 3 JH → Exit + IX, параллельные GRE и 8 серв
const pair = /^Связь msk-gw01\.example\.net → arn-gw01\.example\.net: .*GRE ×2/ const pair = /^Связь msk-gw01\.example\.net → arn-gw01\.example\.net: .*GRE ×2/
expect(await page.getByRole("button", { name: pair }).count()).toBeLessThanOrEqual(1) expect(await page.getByRole("button", { name: pair }).count()).toBeLessThanOrEqual(1)
expect(await page.locator("path > title", { hasText: pair }).count()).toBeGreaterThan(0) expect(await page.locator("path > title", { hasText: pair }).count()).toBeGreaterThan(0)
await openMini.click()
await expect(page.getByRole("button", {name: "Закрыть миникарту"})).toBeVisible()
await controls.getByRole("button", {name: "Вписать карту"}).click()
await expect.poll(async () => (await overlaps(page)).hits).toEqual([])
}) })
test("Карта: группа сервисов сворачивается на холсте, IPFIX огибает карточки", async ({ page }, info) => { test("Карта: группа сервисов сворачивается на холсте, IPFIX огибает карточки", async ({ page }, info) => {
@@ -164,3 +202,33 @@ test("Карта: сетка JH × Exit и аплинки WAN без налож
await expect.poll(async () => (await overlaps(page)).pills).toBeGreaterThan(2) await expect.poll(async () => (await overlaps(page)).pills).toBeGreaterThan(2)
expect((await overlaps(page)).hits).toEqual([]) expect((await overlaps(page)).hits).toEqual([])
}) })
test("Скрытый GRE в NSK остаётся в RTT и после раскрытия соединяет две карточки JH", async ({page}) => {
await serveMapVisual(page, true)
await page.goto("/network-map")
const map = page.getByRole("group", {name: "Интерактивная карта сети"})
const group = map.getByRole("button", {name: /^Раскрыть группу.*NSK.*Узлы доступа/i})
const count = page.getByText(/\d+ уз(?:ел|ла|лов) · 17 туннелей GRE$/)
await expect(count).toBeVisible()
await expect(group).toHaveAttribute("aria-expanded", "false")
await expect(group).toContainText("Проблемы · 1")
await expect(map.getByRole("button", {name: "Устройство nsk-gw12", exact: true})).toHaveCount(0)
await page.getByRole("tab", {name: /^RTT каналов/}).click()
await expect(page.getByRole("row").filter({has: page.getByRole("button", {name: "gre-nsk-12", exact: true})})).toContainText("Недоступен")
await group.press("Enter")
await expect(count).toBeVisible()
const broken = map.locator('[data-gre-status="down"] > path[stroke="var(--status-offline)"]')
await expect(broken).toHaveAttribute("stroke-dasharray", "2 3")
const error = await broken.evaluate(path => {
const wire = path as SVGPathElement
const project = (length: number) => wire.getPointAtLength(length).matrixTransform(wire.getScreenCTM()!)
const ends = [project(0), project(wire.getTotalLength())].sort((a,b) => a.y-b.y)
const cards = ["nsk-gw01", "nsk-gw12"].map(name => {
const card = wire.ownerSVGElement!.querySelector(`[aria-label="Устройство ${name}"] [data-map-box="card"]`)!.getBoundingClientRect()
return {x: card.right, y: card.top + card.height / 2}
}).sort((a,b) => a.y-b.y)
return Math.max(Math.abs(cards[0].x-cards[1].x), ...ends.map((p,i) => Math.hypot(p.x-cards[i].x, p.y-cards[i].y)))
})
expect(error, "Оба конца на правых гранях карточек одной колонки").toBeLessThan(1)
})
+151
View File
@@ -0,0 +1,151 @@
import { mkdir, writeFile } from "node:fs/promises"
import path from "node:path"
import { expect, test } from "@playwright/test"
import { serveMapVisual } from "./fixtures/network-map-visual"
// The approved atlas has 63px device cards, 13px names and 15px row gutters.
// Measure screen coordinates: inspecting SVG attributes alone misses a compressed viewBox.
for (const width of [998, 1320, 320, 390]) {
for (const dense of [false, true]) {
const theme = (width === 998 || width === 390) === !dense ? "dark" : "light"
const size = dense ? "dense" : "ordinary"
test(`Карта сети: физический масштаб и подписи ${width} · ${size} · ${theme}`, async ({ page }, info) => {
await page.setViewportSize({ width, height: width < 500 ? 1040 : 915 })
await page.emulateMedia({ colorScheme: theme, reducedMotion: "reduce" })
await page.addInitScript(scheme => localStorage.setItem("rl-theme", scheme), theme)
await serveMapVisual(page, dense)
await page.goto("/network-map")
const map = page.getByRole("group", { name: "Интерактивная карта сети" })
await expect(map.getByRole("button", { name: "Устройство msk-gw01", exact: true })).toBeVisible()
await expect(map.getByRole("button", { name: "Сервис YouTube", exact: true })).toBeVisible()
await expect(map.getByRole("button", { name: /^Остальные сервисы \(2\)/ })).toBeVisible()
await expect(page.locator("html")).toHaveClass(new RegExp(theme))
await page.evaluate(() => document.fonts.ready)
if (width < 500) {
const lane = page.getByRole("combobox", { name: "Перейти к колонке" })
await lane.selectOption("access-nodes")
await expect(lane).toHaveValue("access-nodes")
await lane.blur()
} else {
await expect(page.getByRole("button", { name: "Боковое меню" })).toHaveAttribute("aria-expanded", "true")
}
const sizes = await map.evaluate(svg => {
const position = (element: Element) => {
const r = element.getBoundingClientRect()
return { x:r.x,y:r.y,w:r.width,h:r.height }
}
const buttons = Array.from(svg.querySelectorAll("g[role=button]"))
const measure = (label: string, word: string, box: string) => {
const node = buttons.find(n => n.getAttribute("aria-label") === label)
const plate = node?.querySelector('[data-map-box="'+box+'"]')
const name = Array.from(node?.querySelectorAll<SVGTextElement>("text") ?? []).find(n => n.textContent?.includes(word))
if (!plate || !name) throw Error("Нет подписанной карточки " + label)
const matrix = name.getScreenCTM()!
return {...position(plate), font:parseFloat(getComputedStyle(name).fontSize)*Math.hypot(matrix.a,matrix.b)}
}
const host = position(svg)
const gateway = measure("Устройство msk-gw01", "msk-gw01","card")
const otherGateway = measure("Устройство msk-gw02", "msk-gw02","card")
const service = measure("Сервис YouTube","YouTube","dest")
const visibleDevice = Array.from(svg.querySelectorAll('[data-map-box="card"]')).map(position)
.filter(card=>card.x+card.w>host.x && card.x<host.x+host.w && card.y+card.h>host.y && card.y<host.y+host.h)
const span = visibleDevice.length ? Math.max(...visibleDevice.map(c=>c.y+c.h))-Math.min(...visibleDevice.map(c=>c.y)) : 0
return {host,gateway,service,span,rowPitch:Math.abs(otherGateway.y-gateway.y), overflow:document.documentElement.scrollWidth-innerWidth}
})
const stage = process.env.MAP_VISUAL_STAGE
if (stage === "before" || stage === "after") {
const folder = path.resolve("work/map-release-preview",stage)
const name = [width,size,theme].join("-")
await mkdir(folder,{recursive:true})
await page.screenshot({path:path.join(folder,name+".png"),animations:"disabled",style:"nextjs-portal { visibility:hidden !important }"})
await writeFile(info.outputPath("geometry.json"),JSON.stringify(sizes,null,2))
}
expect(sizes.overflow, "Горизонтальный скролл принадлежит полотну").toBeLessThanOrEqual(1)
// The reference uses 938px for its six minimum column widths. Surplus space is shared evenly.
const expectedGatewayWidth=Math.min(157,140+Math.max(0,sizes.host.w-938)/6)
expect(Math.abs(sizes.gateway.w-expectedGatewayWidth),"Физическая ширина карточки JH из эталона").toBeLessThanOrEqual(3)
expect(Math.abs(sizes.gateway.h-63),"Физическая высота карточки JH из эталона").toBeLessThanOrEqual(2)
expect(Math.abs(sizes.gateway.font-13),"Размер имени при открытии").toBeLessThanOrEqual(.5)
expect(Math.abs(sizes.service.font-13),"Размер имени сервиса при открытии").toBeLessThanOrEqual(.5)
expect(sizes.service.w/sizes.gateway.w,"Пропорция ширины сервиса и устройства").toBeGreaterThan(0.9)
expect(sizes.service.w/sizes.gateway.w).toBeLessThan(1.35)
expect(sizes.service.h/sizes.gateway.h,"Сервис рисуется полноценной карточкой").toBeGreaterThan(0.85)
expect(sizes.rowPitch,"Между московскими JH остаётся зазор").toBeGreaterThanOrEqual(sizes.gateway.h+8)
const gateway=map.getByRole("button",{name:"Устройство msk-gw01",exact:true})
const roleTile=gateway.locator('[data-role-tile="JH"]')
await expect(roleTile).toHaveAttribute("width","29")
await expect(gateway.locator('[data-country-flag="RU"]')).toHaveCount(1)
await expect(gateway.locator('[data-rate-dir="rx"]')).toContainText("132")
await expect(gateway.locator('[data-rate-dir="tx"]')).toContainText("86")
const youtube=map.getByRole("button",{name:"Сервис YouTube",exact:true})
await expect(youtube.locator('[data-service-brand="YouTube"]')).toHaveCount(1)
await expect(youtube.locator('[data-service-share]')).toHaveCount(1)
await expect(map.locator('[data-map-lane]')).toHaveCount(6)
const nodes=map.locator('g[data-node-kind=device]')
await expect(nodes).toHaveCount(dense ? 9 : 10)
if (dense) {
const hiddenJhs=map.getByRole("button",{name:/^Раскрыть группу.*NSK.*Узлы доступа/i})
await expect(hiddenJhs).toHaveAttribute("aria-expanded","false")
await expect(hiddenJhs).toContainText(/(?:отказ|проблем)\S*\s*·?\s*1/i)
}
const intersections=await map.evaluate(root=>{
const nodes=[...root.querySelectorAll('[data-map-box="card"],[data-map-box="group"],[data-map-box="dest"],[data-map-box="wan"],[data-map-box="access"]')].map(e=>({
name:e.closest('[role=button]')?.getAttribute("aria-label") ?? e.getAttribute("data-map-box"),box:e.getBoundingClientRect()
}))
return nodes.flatMap(({name,box:a},i)=>nodes.slice(i+1).filter(({box:b})=>
Math.min(a.right,b.right)-Math.max(a.left,b.left)>2 && Math.min(a.bottom,b.bottom)-Math.max(a.top,b.top)>2
).map(n=>[name,n.name]))
})
expect(intersections,"Карточки и заголовки групп имеют непересекающиеся области нажатия").toEqual([])
if (width >= 998) {
expect(sizes.span,"Узлы занимают по высоте минимум три ряда карточек").toBeGreaterThan(260)
}
})
}
}
for (const width of [320,1320]) {
test(`Карта сети: расположение карточки назначения и возврат к категории · ${width}`, async ({page})=>{
await page.setViewportSize({width,height:width===320 ? 1040 : 915})
await serveMapVisual(page)
await page.goto("/network-map")
const map=page.getByRole("group",{name:"Интерактивная карта сети"})
const details=page.getByRole("complementary",{name:"Детали объекта карты"})
await page.getByRole("button",{name:"Категории",exact:true}).click()
const category=map.getByRole("button",{name:"Категория CDN",exact:true})
if(width===320)await page.getByRole("combobox",{name:"Перейти к колонке"}).selectOption("destinations")
await category.press("Enter")
await expect(details.getByRole("heading",{name:"CDN",exact:true})).toBeVisible()
await details.getByRole("button",{name:/^Cloudflare/}).click()
await expect(details.getByRole("heading",{name:"Cloudflare",exact:true})).toBeVisible()
const bounds=await details.boundingBox(),canvas=await map.boundingBox()
if (!bounds || !canvas) throw Error("Нет карты или карточки выбранного сервиса")
if (width===320) expect(bounds.y).toBeGreaterThanOrEqual(canvas.y+canvas.height-2)
else expect(bounds.x).toBeGreaterThanOrEqual(canvas.x+canvas.width-2)
expect(bounds.height,"Панель не схлопнулась после включения contain:size").toBeGreaterThan(220)
const scroll=await details.evaluate(aside=>{
const body=Array.from(aside.querySelectorAll<HTMLElement>("div")).find(el=>el.classList.contains("flex-1") && getComputedStyle(el).overflowY==="auto")
if (!body) return null
const max=body.scrollHeight-body.clientHeight
body.scrollTop=max
const reached=body.scrollTop
body.scrollTop=0
return {client:body.clientHeight,max,reached}
})
expect(scroll).not.toBeNull()
expect(scroll!.client).toBeGreaterThan(70)
expect(scroll!.reached).toBeGreaterThanOrEqual(scroll!.max-1)
if(width===1320 && process.env.MAP_VISUAL_STAGE==="after"){
await page.screenshot({path:path.resolve("work/map-release-preview/after/1320-service-inspector.png"),animations:"disabled",style:"nextjs-portal { visibility:hidden !important }"})
}
expect(await page.evaluate(()=>document.documentElement.scrollWidth-innerWidth)).toBeLessThanOrEqual(1)
await details.getByRole("button",{name:"Назад к предыдущему объекту"}).click()
await expect(details.getByRole("heading",{name:"CDN",exact:true})).toBeVisible()
const workbench=page.getByRole("region",{name:"Рабочая панель карты"})
await workbench.getByRole("tab",{name:/^Назначения/}).click()
await expect(workbench.locator("table")).toBeVisible()
expect((await map.boundingBox())!.height,"Раскрытая диагностика не обрезает холст").toBeGreaterThanOrEqual(canvas.height-2)
})
}
+27 -1
View File
@@ -20,11 +20,37 @@ test("наблюдение IPFIX огибает промежуточный уз
const link = mapLinkPath({x: sourceX, y: 100}, 80, {x: serviceX, y: 100}, 140) const link = mapLinkPath({x: sourceX, y: 100}, 80, {x: serviceX, y: 100}, 140)
const route = mapObservationRoute(link, [blocker], []) const route = mapObservationRoute(link, [blocker], [])
assert.ok(route) assert.ok(route)
assert.ok(route.d.startsWith(`M ${link.x1} 100 `) && route.d.endsWith(`H ${link.x2}`)) assert.ok(route.d.startsWith(`M ${link.x1} 100 `) && route.d.endsWith(`L ${link.x2} 100`))
assert.ok(route.track < blocker.y || route.track > blocker.y + blocker.h) assert.ok(route.track < blocker.y || route.track > blocker.y + blocker.h)
} }
}) })
test("неисправная связь выходит на отдельную верхнюю полку, обычная обходит промежуточную колонку", () => {
const a = {x: 100, y: 170}, b = {x: 680, y: 230}
const issue = mapLinkPath(a, 70, b, 75, {faultY: 49})
assert.equal(issue.x1, 30)
assert.equal(issue.x2, 755)
assert.deepEqual(issue.points.slice(2, 4), [{x:25,y:49}, {x:761,y:49}])
assert.match(issue.d, / Q /)
const normal = mapLinkPath(a, 70, b, 75, {obstacles:[{x:340,y:140,w:120,h:125}]})
assert.equal(normal.x1, 170)
assert.equal(normal.x2, 605)
assert.ok(normal.points[2].y < 140 || normal.points[2].y > 265)
})
test("GRE одной колонки остаётся снаружи правых граней обеих карточек при любом состоянии", () => {
const top = {x: 400, y: 120}, bottom = {x: 400, y: 320}
for (const [a,b] of [[top,bottom],[bottom,top]]) {
for (const faultY of [undefined,64]) {
const link = mapLinkPath(a, 70, b, 70, {faultY})
assert.deepEqual(mapLinkPoint(link,0), {x:470,y:a.y})
assert.deepEqual(mapLinkPoint(link,1), {x:470,y:b.y})
assert.ok(link.points.slice(1,-1).every(p => p.x > 470))
if (faultY != null) assert.ok(link.points.some(p => p.y === faultY))
}
}
})
test("подписи не наезжают на карточки и друг на друга, длинная — укорачивается или пропадает", () => { test("подписи не наезжают на карточки и друг на друга, длинная — укорачивается или пропадает", () => {
// Три JH слева сходятся в один EN справа; у каждой пары — длинный и короткий вариант подписи. // Три JH слева сходятся в один EN справа; у каждой пары — длинный и короткий вариант подписи.
const jh = [100, 180, 260].map((y) => ({ x: 542, y })) const jh = [100, 180, 260].map((y) => ({ x: 542, y }))