Compare commits

...
4 Commits
Author SHA1 Message Date
Denozordec 1337325697 fix(ix): исправить цепочку ограничения размера сегмента
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m57s
Docker images / frontend-image (push) Successful in 2m58s
Docker images / updater-image (push) Successful in 1m26s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / backend-image (push) Successful in 3m33s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-12-04 23:31:36 +07:00
Denozordec f9b742b730 fix(ix): учесть включённые правила блокировки открытых туннелей
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 11m35s
Docker images / backend-image (push) Successful in 4m31s
Docker images / frontend-image (push) Successful in 4m57s
Docker images / updater-image (push) Successful in 2m9s
Docker images / netflow-agent-image (push) Successful in 37s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
2026-12-04 22:53:04 +07:00
Denozordec b395c06ffb fix(ix): исправить проверку и продолжение настройки туннелей
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Successful in 11m9s
Docker images / frontend-image (push) Successful in 5m7s
Docker images / updater-image (push) Successful in 3m58s
Docker images / netflow-agent-image (push) Successful in 36s
Docker images / backend-image (push) Successful in 6m53s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
2026-12-04 22:16:10 +07:00
DenozordecandClaude Opus 5.5 2da1b17b65 fix(network-map): разгрузить отрисовку карты сети
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m43s
Docker images / frontend-image (push) Successful in 2m18s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 1m51s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
- отказ GRE рисуется на своём маршруте, без верхней полки над картой; короткая метка на линии, полная формулировка у выбранного канала
- метка отказа не пропадает: без свободного места встаёт на середину участка
- исправные каналы, доступ пользователей и WAN нейтральные, цвет только у проблем
- подписи скорости только от 1 Мбит/с, у выбранного объекта или при слое RTT; «0К» не показывается
- при выборе устройства приглушаются узлы, WAN и сервисы вне его GRE-связей
- имя хоста на карточке в одну строку; рамка карточки показывает состояние узла, а не канала
- легенда описывает новые обозначения

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-03 14:16:33 +07:00
12 changed files with 259 additions and 107 deletions

No files matched your search

+27 -17
View File
@@ -1924,8 +1924,6 @@ function NetworkMapContent() {
// ── Связи макета v3: линия + одна «таблетка» на связь; подписи раскладываются без наложений.
const rttLabel = (ms: number | null) => (ms == null ? "—" : `${ms} мс`)
const groupedConnections: MapGroupConnection[] = []
let faultRow = 0
const nextFaultTrack = () => 49 + Math.min(faultRow++, 2) * 15
function endpoint(id: string, index?: number | null): GroupLinkEnd {
const server = nodeById[id]
const wan = index != null ? server.wanUplinks?.[index] : undefined
@@ -1942,6 +1940,9 @@ function NetworkMapContent() {
return true
}
const scopedGreEdges = greEdges.filter(e => onMap(e.fromServer.id) && onMap(e.toServer.id))
// Выбрано устройство: в фокусе оно и соседи по GRE, остальное приглушено.
const focusIds = selected && selWanIdx === null ? new Set([selected.id, ...scopedGreEdges.flatMap(e =>
e.fromServer.id === selected.id ? [e.toServer.id] : e.toServer.id === selected.id ? [e.fromServer.id] : [])]) : null
const greLinks = scopedGreEdges.flatMap((e, i) => {
const from = endpoint(e.fromServer.id,e.fromWanIndex), to = endpoint(e.toServer.id,e.toWanIndex)
if (groupedConnection({from,to,type:"gre",gre:e})) return []
@@ -1980,7 +1981,7 @@ function NetworkMapContent() {
?? group.find(({e}) => channelStatus(e) === "degraded")
?? group.find(g => greTunnelIdsWithMapBadge.has(g.id)) ?? group[0]
const {from,to} = lead.e
const link = mapLinkPath(from, from.halfWidth, to, to.halfWidth, {obstacles:mapObstacles, faultY:health === "up" ? undefined : nextFaultTrack()})
const link = mapLinkPath(from, from.halfWidth, to, to.halfWidth, {obstacles:mapObstacles})
return {group,counts,health,lead,link}
})
// Полная подпись связи — в title линии: короткая «таблетка» может не влезть между карточками.
@@ -2017,8 +2018,13 @@ function NetworkMapContent() {
const many = count > 1 ? `GRE ×${count}` : ""
const issue = down ? count === 1 ? "Канал недоступен" : `Недоступно каналов · ${count} из ${count}` : counts.down ? `${counts.down} из ${count} каналов ${ruPlural(counts.down,"недоступен","недоступны","недоступны")}` : counts.degraded ? `Деградация ${counts.degraded} из ${count}` : ""
const focused = group.some(({e,id}) => selectedGreEdge && greEdgeKey(selectedGreEdge) === id || selected?.id === e.fromServer.id || selected?.id === e.toServer.id || highlightedPath && greMatchesPath(e,highlightedPath))
const texts = issue ? ["GRE · " + issue,issue,`${counts.down || counts.degraded}/${count}`] : [
[many || "GRE", compactMapRate(rate), rtt].filter(Boolean).join(" · "), compactMapRate(rate) || rtt,
const bps = liveBps ?? flowBps ?? 0
const ratio = `${counts.down || counts.degraded}/${count}`
// Без выбора отказ подписан коротко; полная формулировка — у выбранного канала, в title и панели справа.
const brief = down ? count === 1 ? "Нет связи" : `Нет связи ${ratio}` : counts.down ? `Отказ ${ratio}` : count === 1 ? "Деградация" : `Деградация ${ratio}`
const shownRate = bps > 0 ? compactMapRate(rate) : ""
const texts = issue ? focused ? ["GRE · " + issue,issue,ratio] : [brief,ratio] : [
[many || "GRE", shownRate, rtt].filter(Boolean).join(" · "), shownRate || rtt,
].filter(Boolean)
const fullText = [health !== "up" ? texts[0] : rate || rtt, many].filter(Boolean).join(" · ") || "GRE"
const outer = greOuterSummaryLine(lead.e.tunnel, nodeById[lead.e.fromServer.id], nodeById[lead.e.toServer.id], greResolvedMap)
@@ -2032,10 +2038,12 @@ function NetworkMapContent() {
"Клик — панель справа."
greLinkTitle.set(lead.id, `Связь ${lead.e.fromServer.name} → ${lead.e.toServer.name}: ${fullText}`)
greLinkHint.set(lead.id, hint)
if (health === "up" && (!rtt && !rate && !focused || lead.opacity < 1)) return []
// Исправный канал подписан только у выбранного объекта, при слое RTT или от 1 Мбит/с — остальное в title.
if (health === "up" && (!rtt && !focused && bps < 1_000_000 || lead.opacity < 1)) return []
return [{
id: "gre:" + lead.id, link, texts, hint, open: lead.open, fullText, fault: Boolean(issue),
opacity: Math.max(...group.map((g) => g.opacity)),
// Линия отказа не приглушается при выборе другого узла — её метка тоже.
opacity: issue ? 1 : Math.max(...group.map((g) => g.opacity)),
tone: down ? "er" as const : health === "degraded" ? "wn" as const : !rtt && !rate ? "mu" as const : "fg" as const,
name: `${lead.e.fromServer.name} → ${lead.e.toServer.name}`,
}]
@@ -2071,7 +2079,8 @@ function NetworkMapContent() {
const rate = accessRate(bindings, access.rates)
const text = pickedUser && showNetflow && rate.measured ? rate.label : ""
const link = mapLinkPath(accessPosition, cardWidths.access / 2, target, widthForServer(target.type) / 2, {obstacles:mapObstacles})
return [{ id: `access:${id}`, link, texts: [text], name: `${pickedUser?.name ?? "Пользователи"} → ${target.name}`, opacity: bindings.length && bindings.every(binding => binding.enabled === false) ? 0.48 : 1,
return [{ id: `access:${id}`, link, texts: [text], name: `${pickedUser?.name ?? "Пользователи"} → ${target.name}`,
opacity: (bindings.length && bindings.every(binding => binding.enabled === false) ? 0.48 : 1) * (focusIds && !focusIds.has(id) ? 0.3 : 1),
tone: "fg" as const, hint: pickedUser ? `RouterOS · RX ${fmtRate(rate.measured ? rate.rx : null)} · TX ${fmtRate(rate.measured ? rate.tx : null)} · ${rate.measured}/${rate.total} замеров` : "Привязки из каталога пользователей",
open: () => { if (pickedUser) { setSelected(null); setSelectedGreEdge(null); setSelectedService(null); setInspectUser(true) } else setUserPicker(true) },
}]
@@ -2135,7 +2144,7 @@ function NetworkMapContent() {
if (groupedConnection({from,to,type:"wan"})) return []
return [{key:densityWanKey(router.id,i),link:mapLinkPath(from,from.halfWidth,to,to.halfWidth,{obstacles:mapObstacles})}]
}))
const groupLinks = collectGroupLinks(groupedConnections, mapObstacles, nextFaultTrack)
const groupLinks = collectGroupLinks(groupedConnections, mapObstacles)
const groupProblems = new Map(density.groups.map(g => {
const ids = new Set(g.serverIds)
const channels = scopedGreEdges.filter(e =>
@@ -2600,7 +2609,7 @@ function NetworkMapContent() {
))}
<g id="network-map-wires">
{accessLinks.map(({ id, link, name, open, opacity }) => <path key={id} d={link.d} fill="none" stroke="var(--chart-2)" strokeWidth={pickedUser ? 2.2 : 1.5} opacity={opacity * (pickedUser ? 1 : .75)} pointerEvents="stroke" onPointerDown={e => e.stopPropagation()} onClick={open}><title>{name}</title></path>)}
{accessLinks.map(({ id, link, name, open, opacity }) => <path key={id} d={link.d} fill="none" stroke={pickedUser ? "var(--foreground)" : "var(--muted-foreground)"} strokeWidth={pickedUser ? 2.2 : 1.5} opacity={opacity * (pickedUser ? .8 : .55)} pointerEvents="stroke" onPointerDown={e => e.stopPropagation()} onClick={open}><title>{name}</title></path>)}
{/* Наблюдаемые пути от выходов и экспортёров к сервисам. */}
{destRibbons.map(({ edge, direct, detour, link }) => {
const hop = destinationRate(edge)
@@ -2668,9 +2677,10 @@ function NetworkMapContent() {
className="network-map-focusable cursor-pointer" onPointerDown={ev => ev.stopPropagation()} onClick={open}
onKeyDown={ev => {if(ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); open(ev) }}}>
<path className="network-map-focus-ring" d={link.d} fill="none" stroke="var(--ring)" strokeWidth="6" />
<path d={link.d} fill="none" stroke={ts.stroke}
strokeWidth={focused ? 3.5 : health === "up" ? 2.4 : 2.8}
strokeDasharray={health === "down" ? "2 3" : health === "degraded" ? "6 3" : undefined} strokeLinejoin="round" strokeLinecap="round" opacity={health === "up" && !focused ? .76 : 1} />
{/* Цвет только у проблем: исправный канал серый, у выбранного объекта — контрастный. */}
<path d={link.d} fill="none" stroke={health !== "up" ? ts.stroke : focused ? "var(--foreground)" : "var(--muted-foreground)"}
strokeWidth={focused ? 2.6 : health === "up" ? 1.6 : 2.2}
strokeDasharray={health === "down" ? "2 3" : health === "degraded" ? "6 3" : undefined} strokeLinejoin="round" strokeLinecap="round" opacity={health !== "up" ? 1 : focused ? .8 : .6} />
<path d={link.d} fill="none" stroke="transparent" strokeWidth={16} strokeLinecap="round">
<title>{greLinkTitle.get(id)}. {greLinkHint.get(id)}</title>
</path>
@@ -2730,6 +2740,7 @@ function NetworkMapContent() {
key={n.id} n={n} width={widthForServer(n.type)} channelProblem={channelProblemByDevice.get(n.id)}
isSel={selected?.id === n.id}
isVis={isVisible(n)}
dim={focusIds ? !focusIds.has(n.id) : false}
isDragged={draggedNodeId === n.id}
rates={showNetflow && n.status !== "offline" ? (n.id === selected?.id ? selectedNodeRate : undefined) ?? (nodeTraffic?.base === backendUrl ? nodeTraffic.current.get(n.id) : undefined) : undefined}
hideCatalogLatency={hideCatalogLatencyByNodeId.has(n.id)}
@@ -2750,16 +2761,15 @@ function NetworkMapContent() {
return (router.wanUplinks ?? []).map((wan, wIdx) => {
const sat = effectiveSatPos[router.id]?.[wIdx]
if (!sat || density.hiddenWans.has(densityWanKey(router.id,wIdx))) return null
const color = WAN_COLORS[wIdx % WAN_COLORS.length]
const isActive = wanJhEdges.filter(e => e.homeId === router.id && e.wanIdx === wIdx).some(e => e.active)
const isSatSel = selected?.id === router.id && selWanIdx === wIdx
const satKey = `${router.id}-${wIdx}`
const live = showNetflow ? getInterfaceLiveRate(`wan:${router.id}:${wIdx}`) : undefined
const flow = netflowByWanKey.get(`${router.id}\t${wIdx}`)
return (
<g key={`${router.id}-wan-${wIdx}`} opacity={vis ? 1 : 0.06} style={{ transition: "opacity 0.3s" }}>
<g key={`${router.id}-wan-${wIdx}`} opacity={!vis ? 0.06 : focusIds && !focusIds.has(router.id) ? 0.38 : 1} style={{ transition: "opacity 0.3s" }}>
<WanSatNode
x={sat.x} y={sat.y} wan={wan} color={color} index={wIdx} width={cardWidths.wan}
x={sat.x} y={sat.y} wan={wan} index={wIdx} width={cardWidths.wan}
active={isActive} isSel={isSatSel}
traffic={live ? `Live ${formatNetflowRate(live)}` : flow ? `≈${formatNetflowRate(flow)}` : undefined}
isDragged={draggedSatKey === satKey}
@@ -2794,7 +2804,7 @@ function NetworkMapContent() {
y={pos.y}
isSel={activeService?.id === svc.id}
isVis
dim={Boolean(expandedCountryGroup) && svc.id !== expandedCountryId}
dim={Boolean(expandedCountryGroup) && svc.id !== expandedCountryId || Boolean(focusIds) && !visibleServiceEdges.some(e => e.fromId === selected?.id && e.toId === svc.id)}
isDragged={draggedSvcId === svc.id}
destMode={destMode}
iso={svc.label}
@@ -1,8 +1,8 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import type { IxRouterObject } from "@mmapp/contracts/internet-exchange"
import { ixSegmentConfigurationSchema, type IxRouterObject } from "@mmapp/contracts/internet-exchange"
import { planIxNative } from "./internet-exchange-execution.js"
import { ixNamespace } from "./internet-exchange-plan.js"
import { compileIxConfiguration, ixNamespace } from "./internet-exchange-plan.js"
const id = "aaaaaaaa-1111-4222-8333-123456789abc"
const name = ixNamespace(id)
@@ -17,7 +17,7 @@ const device = (rows: Record<string, Array<Record<string, string>>>) => [{ serve
test("managed MSS rules are backfilled and removed without adopting a hand-written rule", () => {
const path = "/ip/firewall/mangle"
const from = { serverId: 17, path, fields: { comment: name + ":linux-mss-from-il-wg", action: "change-mss",
chain: "prerouting", "in-interface": "il-wg", "new-mss": "1380", "tcp-mss": "1381-65535" } }
chain: "forward", "in-interface": name, "new-mss": "1380", "tcp-mss": "1381-65535" } }
const to = { serverId: 17, path, fields: { comment: name + ":linux-mss-to-il-wg", action: "change-mss",
chain: "postrouting", "out-interface": "il-wg", "new-mss": "1380", "tcp-mss": "1381-65535" } }
const manual = { ...to.fields, comment: "manual MSS", ".id": "*A" }
@@ -34,6 +34,22 @@ test("managed MSS rules are backfilled and removed without adopting a hand-writt
assert.throws(() => planIxNative(id, desired, desired, live([{ ...fromRow, "new-mss": "1460" }, toRow])), /изменён вне операции/)
})
test("IX migrates an exact disabled legacy ingress MSS rule", () => {
const path = "/ip/firewall/mangle"
const fields = { comment: name + ":linux-mss-from-il-vps", chain: "forward", "in-interface": name,
action: "change-mss", "new-mss": "1380", disabled: "true" }
const previous = { serverId: 17, path, fields }
const next = { ...previous, fields: { ...fields, disabled: "false" } }
const legacy = { ...fields, ".id": "*C", chain: "prerouting", "in-interface": "il-vps" }
const [update] = planIxNative(id, [next], [previous], device({ [path]: [legacy] }))
assert.equal(update.rosId, "*C")
assert.deepEqual(update.fields, { chain: "forward", "in-interface": name, disabled: "false" })
const [resumed] = planIxNative(id, [previous], [], device({ [path]: [legacy] }), true)
assert.deepEqual(resumed.fields, { chain: "forward", "in-interface": name })
assert.throws(() => planIxNative(id, [next], [previous], device({ [path]: [{ ...legacy, "new-mss": "1400" }] })), /изменён вне операции/)
})
test("a new VRF is inserted before main and no foreign route is altered", () => {
const changes = planIxNative(id, [vrf, route], [], device({
"/ip/vrf": [{ ".id": "*A", name: "main", interfaces: "all", builtin: "true" }],
@@ -96,6 +112,67 @@ test("RouterOS REST host matches allow only the equivalent explicit host length"
}
})
test("another Linux VPS can be planned while a managed GRE/IPsec peer has no SA", () => {
const binding = (client: string, endpoint: string, localAddress: string, peerAddress: string) => ({
name: "il-gre-" + client, kind: "gre-ipsec", endpoint, localEndpoint: "192.0.2.17",
provisionGre: { localAddress, peerAddress, credentialId: id }, linux: { name: client, enabled: true, destinations: [] },
})
const existing = binding("old", "192.0.2.20", "10.254.0.1/30", "10.254.0.2")
const next = binding("new", "192.0.2.21", "10.254.0.5/30", "10.254.0.6")
const compile = (...interfaces: ReturnType<typeof binding>[]) => compileIxConfiguration(id, ixSegmentConfigurationSchema.parse({
name: "compute", sites: [{ serverId: 17, autonomousSystem: 64512, routerId: "192.0.2.17", interfaces }],
}))
const previous = compile(existing)
const desired = compile(existing, next)
const policyPath = "/ip/ipsec/policy", peerPath = "/ip/ipsec/peer"
const rows: Record<string, Array<Record<string, string>>> = {}
for (const [index, { path, fields }] of previous.entries()) {
const catalogue = rows[path] ??= []
catalogue.push({ ...fields, ".id": "*" + (index + 1).toString(16) })
}
const [policy] = rows[policyPath]
Object.assign(policy, { "src-address": "::/0", "dst-address": "::/0", invalid: "true" })
delete policy.template
delete policy["ipsec-protocols"]
const tasks = planIxNative(id, desired, previous, device(rows))
const policyTasks = tasks.filter(task => task.path === policyPath)
assert.equal(policyTasks.length, 1)
const [create] = policyTasks
assert.equal(create.rosId, undefined)
assert.equal(create.fields?.peer, name + "-" + next.name)
assert.equal(create.fields?.["src-address"], undefined)
assert.equal(create.fields?.["dst-address"], undefined)
policy.level = "use"
assert.throws(() => planIxNative(id, desired, previous, device(rows)), /изменён вне операции/)
policy.level = "require"
policy.template = "true"
assert.throws(() => planIxNative(id, desired, previous, device(rows)), /изменён вне операции/)
delete policy.template
rows[peerPath][0].address = "192.0.2.99/32"
assert.throws(() => planIxNative(id, desired, previous, device(rows)), /изменён вне операции/)
})
test("an omitted enabled-by-default flag on a GRE plaintext drop does not block IX", () => {
const path = "/ip/firewall/filter"
const object = (chain: string, policy: string) => ({ serverId: 17, path, fields: {
comment: name + ":gre-" + chain + "-il-vps", chain, action: "drop", protocol: "gre", "ipsec-policy": policy, disabled: "false",
} })
const inbound = object("input", "in,none"), outbound = object("output", "out,none")
const rows = [inbound, outbound].map(({ fields }, index) => {
const { disabled: _disabled, ...observed } = fields
return { ...observed, ".id": "*" + (index + 1), invalid: "false" }
})
assert.deepEqual(planIxNative(id, [inbound], [inbound], device({ [path]: [rows[0]] })), [])
assert.deepEqual(planIxNative(id, [inbound, outbound], [inbound], device({ [path]: rows }), true), [])
const disabled = { ...rows[0], disabled: "true" }
assert.throws(() => planIxNative(id, [inbound], [inbound], device({ [path]: [disabled] }), true), /изменён вне операции.*gre-input-il-vps.*disabled/)
const otherRule = { ...inbound, fields: { ...inbound.fields, protocol: "tcp" } }
const observedOtherRule = { ...rows[0], protocol: "tcp" }
assert.throws(() => planIxNative(id, [otherRule], [otherRule], device({ [path]: [observedOtherRule] })), /изменён вне операции.*disabled/)
})
test("RouterOS REST encodes an enabled blackhole route as a present empty flag", () => {
const fields = { comment: name + ":default-discard-4", "routing-table": name, "dst-address": "0.0.0.0/0", blackhole: "yes" }
const discard = { ...route, fields }
@@ -8,7 +8,8 @@ import { audit } from "../modules/mcp/store.js"
import { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js"
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
import { assertVerifiedConfigurationAccess } from "./config-mutation-policy.js"
import { compileIxConfiguration, inIxNetwork, IxConflict, ixClientRoutingTable, ixDeviceIds, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
import { compileIxConfiguration, inIxNetwork, IxConflict, ixClientRoutingTable, ixDeviceIds, ixDiscardInterface, ixEgressList, ixManagedGreFields, ixNamespace } from "./internet-exchange-plan.js"
import { greIpsecPaths } from "./gre-ipsec-transport.js"
import { archiveIxSegment, assertIxBondClientAssignments, assertIxName, assertIxRevision, assertIxRouterIds, assertIxSites, assertIxSegmentWithoutBonds, ixBondClientId, ixKnownVpsClient, ixReservedLinuxPoolBlocks, ixReservedRouterIds, ixReservedTunnelBindings, nextIxRouterId, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js"
import { MikrotikClient } from "./mikrotik.js"
import { ixGreClientTemplate, ixLegacyWireguardRoutes, ixLinuxBindingKind, ixLinuxInterfaceName, ixWireguardClientTemplate } from "./internet-exchange-client.js"
@@ -59,6 +60,8 @@ const ipsecPolicyColumns = [".id", "action", "level", "tunnel", "protocol", "src
function normalize(field: string, value: string | undefined) {
if (["blackhole", "fib"].includes(field) && value === "") return "yes"
if (field === "ipsec-protocols") return value ?? "esp"
if (field === "template") return isTrue(value) ? "yes" : "no"
if (["disabled", "advertise", "blackhole", "multihop", "fib", "passive", "tunnel", "allow-fast-path", "passthrough"].includes(field)) {
return value === undefined ? null : isTrue(value) ? "yes" : "no"
}
@@ -75,8 +78,17 @@ function normalize(field: string, value: string | undefined) {
return value
}
function fieldMatches(row: NativeRow, fields: Record<string, string>, field: string) {
// RouterOS can omit disabled=no on GRE plaintext drops created without an explicit flag.
if (field === "disabled" && row.disabled === undefined && fields.disabled === "false" &&
fields.action === "drop" && fields.protocol === "gre" &&
((fields.chain === "input" && fields["ipsec-policy"] === "in,none") ||
(fields.chain === "output" && fields["ipsec-policy"] === "out,none"))) return true
return normalize(field, row[field]) === normalize(field, fields[field])
}
function matches(row: NativeRow, fields: Record<string, string>) {
return Object.entries(fields).every(([field, value]) => normalize(field, row[field]) === normalize(field, value))
return Object.keys(fields).every(field => fieldMatches(row, fields, field))
}
function rowsFor(device: NativeDevice, path: string) { return device.rows[path] ?? [] }
@@ -94,6 +106,11 @@ function verifyNativeId(row: NativeRow) {
export function planIxNative(id: string, desired: IxRouterObject[], previous: IxRouterObject[], devices: NativeDevice[], resume = false): Task[] {
const namespace = ixNamespace(id)
const egressObject = (comment = "") => comment.startsWith(namespace + ":egress-")
const legacyMssIngress = (row: NativeRow, fields: Record<string, string>) => {
const prefix = namespace + ":linux-mss-from-"
return fields.disabled === "true" && fields.action === "change-mss" && fields.comment?.startsWith(prefix) &&
matches(row, { ...fields, chain: "prerouting", "in-interface": fields.comment.slice(prefix.length) })
}
const withEgressList = new Set(devices.filter(device => Object.values(device.rows).some(rows =>
rows.some(row => egressObject(row.comment)))).map(device => device.serverId))
// An older applied revision had no egress list. A partial set still needs reconciliation.
@@ -115,7 +132,9 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
const tunnel = ["/interface/wireguard", "/interface/gre"].includes(object.path)
const managedTunnel = tunnel && [":wg-il-", ":gre-il-", ":transit-it-"].some(sign => object.fields.comment?.includes(sign))
const alreadyStopped = managedTunnel && resume && row && matches(row, { ...object.fields, disabled: "true" })
if (!row || !alreadyStopped && !matches(row, object.fields)) throw new IxConflict("Объект предыдущей ревизии IX изменён вне операции")
if (!row || !alreadyStopped && !matches(row, object.fields) && !legacyMssIngress(row, object.fields)) {
throw new IxConflict("Объект предыдущей ревизии IX изменён вне операции")
}
const task = { serverId: object.serverId, path: object.path, rosId: verifyNativeId(row), before: row }
if (managedTunnel && !isTrue(row.disabled)) shutdown.push({ ...task, fields: { disabled: "true" } })
const steps = tunnel ? interfaceCleanup : result
@@ -129,21 +148,24 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
throw new IxConflict("Служебный next hop BGP уже занят в таблице main")
}
if (resume && row && !isTrue(row.invalid) && matches(row, object.fields)) { verifyNativeId(row); continue }
if (row && !previousByKey.has(deviceMarker(object))) {
const before = previousByKey.get(deviceMarker(object)) ??
(resume && row && legacyMssIngress(row, object.fields) ? object : undefined)
if (row && !before) {
throw new IxConflict(object.fields.comment ? "Найден объект незавершённой операции IX. Сначала выполните сверку" :
"Имя объекта IX уже занято. Сначала выполните сверку")
}
if (row) {
const before = previousByKey.get(deviceMarker(object))!
if (!matches(row, before.fields)) throw new IxConflict("Объект IX изменён вне операции")
if (row && before) {
const differences = Object.keys(before.fields).filter(field => !fieldMatches(row, before.fields, field))
if (differences.length && !legacyMssIngress(row, before.fields)) throw new IxConflict("Объект IX изменён вне операции · узел " + object.serverId + " · " + path +
" · " + (object.fields.comment ?? object.fields.name) + " · " + differences.join(", "))
if (Object.keys(before.fields).some(field => !(field in object.fields))) {
throw new IxConflict("Поле RouterOS нельзя неявно сбросить. Замените объект с новым идентификатором")
}
const fields = Object.fromEntries(Object.entries(object.fields).filter(([field, value]) => normalize(field, row[field]) !== normalize(field, value)))
const fields = Object.fromEntries(Object.entries(object.fields).filter(([field]) => !fieldMatches(row, object.fields, field)))
if (Object.keys(fields).length) result.push({ serverId: object.serverId, path, rosId: verifyNativeId(row), fields, before: row })
continue
}
if (previousByKey.has(deviceMarker(object))) throw new IxConflict("Объект предыдущей ревизии IX исчез. Сначала выполните сверку")
if (before) throw new IxConflict("Объект предыдущей ревизии IX исчез. Сначала выполните сверку")
const foreign = rowsFor(device, path).some(entry => !entry.comment?.startsWith(namespace + ":") &&
(object.fields.name && entry.name === object.fields.name || object.fields.chain && entry.chain === object.fields.chain && path === "/routing/filter/rule" ||
object.fields["routing-table"] && entry["routing-table"] === namespace && !isTrue(entry.dynamic)))
@@ -448,7 +470,7 @@ export async function configureIxTransit(segment: IxSegment, input: IxTransitReq
return configuration
}
async function readDevice(server: ServerRow, objects: IxRouterObject[], removing = false): Promise<NativeDevice> {
async function readDevice(server: ServerRow, objects: IxRouterObject[], removing = false, verifyExternalGre = false): Promise<NativeDevice> {
const client = MikrotikClient.fromServer(server)
const fieldsByPath = new Map<string, string[]>([["/interface", columns], ["/interface/bridge/port", [".id", "bridge", "interface"]],
["/ip/vrf", columns], ["/ip/route", columns], ["/ipv6/route", columns]])
@@ -461,7 +483,7 @@ async function readDevice(server: ServerRow, objects: IxRouterObject[], removing
...(filterPath(object.path) ? ["invalid"] : []), ...Object.keys(object.fields)])])
}
if (fieldsByPath.has("/interface/list")) fieldsByPath.get("/interface/list")!.push("include", "exclude")
if (objects.some(object => object.fields["ipsec-policy"])) {
if (verifyExternalGre) {
fieldsByPath.set("/interface/gre", [...new Set([...greColumns, ...(fieldsByPath.get("/interface/gre") ?? [])])])
fieldsByPath.set("/ip/ipsec/policy", [...new Set([...ipsecPolicyColumns, ...(fieldsByPath.get("/ip/ipsec/policy") ?? [])])])
}
@@ -474,14 +496,10 @@ async function readDevice(server: ServerRow, objects: IxRouterObject[], removing
return { serverId: server.id, source: fingerprint(server), rows }
}
function verifyGreBinding(binding: IxSite["interfaces"][number], interfaces: NativeRow[], policies: NativeRow[]) {
function verifyGreInterface(binding: IxSite["interfaces"][number], interfaces: NativeRow[]) {
const gre = interfaces.find(row => row.name === binding.name)
const policy = policies.some(row =>
!isTrue(row.disabled) && !isTrue(row.template) && !isTrue(row.tunnel) &&
row.action === "encrypt" && ["require", "unique"].includes(row.level) && ["gre", "47"].includes(row.protocol) &&
row["src-address"] === binding.localEndpoint + "/32" && row["dst-address"] === binding.endpoint + "/32")
if (!gre || gre["local-address"] !== binding.localEndpoint || gre["remote-address"] !== binding.endpoint || !policy) {
throw new IxConflict("Для " + binding.name + " не подтверждены адреса и обязательная политика GRE/IPsec")
if (!gre || gre["local-address"] !== binding.localEndpoint || gre["remote-address"] !== binding.endpoint) {
throw new IxConflict("Для " + binding.name + " не подтверждены внешние адреса GRE")
}
if (!["false", "no"].includes(gre["allow-fast-path"])) {
throw new IxConflict("Отключите FastPath на интерфейсе GRE/IPsec " + binding.name)
@@ -489,6 +507,14 @@ function verifyGreBinding(binding: IxSite["interfaces"][number], interfaces: Nat
return gre
}
function verifyGrePolicy(binding: IxSite["interfaces"][number], policies: NativeRow[]) {
const policy = policies.some(row =>
!isTrue(row.disabled) && !isTrue(row.template) && !isTrue(row.tunnel) &&
row.action === "encrypt" && ["require", "unique"].includes(row.level) && ["gre", "47"].includes(row.protocol) &&
row["src-address"] === binding.localEndpoint + "/32" && row["dst-address"] === binding.endpoint + "/32")
if (!policy) throw new IxConflict("Для " + binding.name + " не подтверждена обязательная политика GRE/IPsec")
}
/** Inspect operator-owned transports without running the provisioning or VRF planner. */
export async function verifyIxExistingTransport(segmentId: string, serverId: number, name: string, path: IxExistingTransport) {
const client = await requiredIxNode(serverId)
@@ -517,7 +543,9 @@ export async function verifyIxExistingTransport(segmentId: string, serverId: num
if (path.kind === "gre-ipsec") {
const [interfaces, policies] = await Promise.all([readRows(client, "/interface/gre", [...greColumns, "disabled"]),
readRows(client, "/ip/ipsec/policy", ipsecPolicyColumns)])
const gre = verifyGreBinding({ name, kind: path.kind, localEndpoint: path.endpoint, endpoint: path.remoteEndpoint, prefixes: [] }, interfaces, policies)
const binding = { name, kind: path.kind, localEndpoint: path.endpoint, endpoint: path.remoteEndpoint, prefixes: [] }
const gre = verifyGreInterface(binding, interfaces)
verifyGrePolicy(binding, policies)
if (isTrue(gre.disabled)) throw new IxConflict("Интерфейс отключён: " + name)
if (!sameIP(local.network, path.address) && !inIxNetwork(local.address, path.address)) {
const routes = await readRows(client, isIP(path.address) === 4 ? "/ip/route" : "/ipv6/route", ["dst-address", "gateway", "immediate-gw", "disabled"])
@@ -582,8 +610,9 @@ function validateBindings(configuration: IxConfiguration, id: string, devices: N
gateway.trim().split("@")[0].split("%").at(-1) === binding.name))) {
throw new IxConflict("Интерфейс " + binding.name + " уже используется другой маршрутизацией")
}
if (binding.kind === "gre-ipsec") {
verifyGreBinding(binding, rowsFor(device, "/interface/gre"), rowsFor(device, "/ip/ipsec/policy"))
if (binding.kind === "gre-ipsec" && !binding.provisionGre) {
verifyGreInterface(binding, rowsFor(device, "/interface/gre"))
verifyGrePolicy(binding, rowsFor(device, "/ip/ipsec/policy"))
}
}
}
@@ -648,7 +677,8 @@ async function prepareNative(id: string, configuration: IxConfiguration | null,
if (site?.autoRouterId && (await observedIxRouterIds(MikrotikClient.fromServer(server), id)).has(site.routerId)) {
throw new IxConflict("Router ID " + site.routerId + " уже используется на CHR")
}
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId), !configuration))
const verifyExternalGre = site?.interfaces.some(binding => binding.kind === "gre-ipsec" && !binding.provisionGre)
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId), !configuration, verifyExternalGre))
verifyIxMainGateways(before.at(-1)!, objects.filter(object => object.serverId === serverId))
}
if (configuration) validateBindings(configuration, id, before, resume ? objects.concat(previous) : previous)
@@ -673,10 +703,19 @@ async function prepareNative(id: string, configuration: IxConfiguration | null,
async function assertIxResume(id: string, revision: number, native: IxNativeChange) {
const { rows: [attempt] } = await pool.query<{ sources: unknown }>(`
SELECT payload->'sources' AS sources FROM mcp_audit
WHERE action='ix.web.apply_started' AND payload->>'segmentId'=$1 AND payload->>'revision'=$2
ORDER BY id DESC LIMIT 1
`, [id, String(revision)])
WITH last_attempt AS (
SELECT payload FROM mcp_audit
WHERE action='ix.web.apply_started' AND payload->>'segmentId'=$1::uuid::text
ORDER BY id DESC LIMIT 1
)
SELECT last_attempt.payload->'sources' AS sources
FROM last_attempt
JOIN ix_segments s ON s.id=$1
JOIN ix_segment_revisions draft ON draft.segment_id=s.id AND draft.revision=s.revision
JOIN ix_segment_revisions started ON started.segment_id=s.id AND started.revision::text=last_attempt.payload->>'revision'
WHERE draft.revision=$2 AND started.revision>COALESCE(s.applied_revision,0)
AND started.revision<=draft.revision AND started.configuration=draft.configuration
`, [id, revision])
const sources = native.before.map(device => [device.serverId, device.source])
if (!attempt || fingerprint(attempt.sources) !== fingerprint(sources)) {
throw new IxConflict("Нет подтверждённой попытки применения этой ревизии к этим устройствам")
@@ -889,11 +928,24 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
}
const client = MikrotikClient.fromServer(server)
if (binding.kind === "gre-ipsec") {
const [interfaces, policies] = await Promise.all([
readRows(client, "/interface/gre", [...greColumns, "disabled"]),
readRows(client, "/ip/ipsec/policy", ipsecPolicyColumns),
])
if (isTrue(verifyGreBinding(binding, interfaces, policies).disabled)) throw new IxConflict("Интерфейс GRE/IPsec отключён")
const interfaces = await readRows(client, "/interface/gre", [...greColumns, "disabled"])
const gre = verifyGreInterface(binding, interfaces)
if (isTrue(gre.disabled)) throw new IxConflict("Интерфейс GRE/IPsec отключён")
if (binding.provisionGre) {
const { peer, policy } = ixManagedGreFields(ixNamespace(segment.id), binding)
const [peers, policies] = await Promise.all([
readRows(client, greIpsecPaths.peer, [".id", "dynamic", ...Object.keys(peer)]),
readRows(client, greIpsecPaths.policy, [".id", "dynamic", ...Object.keys(policy)]),
])
const device = { serverId, source: "", rows: { [greIpsecPaths.peer]: peers, [greIpsecPaths.policy]: policies } }
for (const [path, fields] of [[greIpsecPaths.peer, peer], [greIpsecPaths.policy, policy]] as const) {
const row = managedRow(device, { serverId, path, fields })
if (!row || !matches(row, fields)) throw new IxConflict("Пир или политика GRE/IPsec изменены на узле · " + name)
verifyNativeId(row)
}
} else {
verifyGrePolicy(binding, await readRows(client, greIpsecPaths.policy, ipsecPolicyColumns))
}
if (includeCredential && !binding.provisionGre) throw new IxConflict("IX не выдавал этот IKEv2 PSK", 404)
const credential = includeCredential && binding.provisionGre
? (await privateFingerprinterExisting("ix-gre-client-credential-v1"))(segment.id + ":" + serverId + ":ix-credential:" + binding.provisionGre.credentialId)
@@ -974,7 +1026,7 @@ async function applyNativeTasks(native: IxNativeChange, authorize: () => Promise
if (!returnedId || !routerId.test(returnedId)) throw new IxConflict("RouterOS не подтвердил ID объекта IX")
const row = (await readRows(client, task.path, [".id", ...Object.keys(task.fields)])).find(entry => entry[".id"] === returnedId)
if (!row || !matches(row, task.fields)) {
const fields = row ? Object.keys(task.fields).filter(field => normalize(field, row[field]) !== normalize(field, task.fields![field])) : []
const fields = row ? Object.keys(task.fields).filter(field => !fieldMatches(row, task.fields!, field)) : []
throw new IxConflict("Перечитанный объект IX не совпал с планом · " + task.path + (fields.length ? " · " + fields.join(", ") : ""))
}
const vrfName = task.path === "/ip/vrf" ? task.fields.name : undefined
@@ -32,8 +32,7 @@ test("managed clients get their own return path and fail closed if both exit pro
provisionWireguard: { peerPublicKey: "A".repeat(43) + "=", listenPort: 51900,
localAddress: "10.254.1.1/30", peerAddress: "10.254.1.2", hubEndpoint: "192.0.2.10" } })
const objects = compileIxConfiguration(id, value)
const clamp = objects.findIndex(object => object.fields.comment === table + ":linux-mss-from-linux-wg")
assert.ok(clamp >= 0 && clamp < objects.findIndex(object => object.fields.comment === table + ":linux-linux-wg-route"))
assert.equal(objects.find(object => object.fields.comment === table + ":linux-linux-wg-route")?.fields.chain, "prerouting")
const clientTable = ixClientRoutingTable(table, "linux-wg")
const defaults = objects.filter(object => object.fields["routing-table"] === clientTable)
assert.deepEqual(defaults.map(object => object.fields.distance), ["10", "11", "254"])
@@ -47,7 +46,7 @@ test("managed clients get their own return path and fail closed if both exit pro
assert.ok(objects.every(object => object.path !== "/ip/vrf" || !object.fields.interfaces.includes("ether1")))
})
test("managed Linux tunnels clamp TCP SYN in both directions before routing marks can end prerouting", () => {
test("managed Linux tunnels clamp TCP SYN in forward from IX and postrouting to the tunnel", () => {
const value = fixture(), site = value.sites[0]
site.interfaces.push(
{ name: "linux-wg", kind: "wireguard", prefixes: [], linux: { name: "vps", enabled: true, destinations: [] },
@@ -69,7 +68,7 @@ test("managed Linux tunnels clamp TCP SYN in both directions before routing mark
action: "change-mss", "new-mss": String(mss), passthrough: "true", disabled }
assert.deepEqual(rules.filter(object => object.fields.comment.endsWith("-" + binding)), [
{ serverId: site.serverId, path: "/" + family + "/firewall/mangle",
fields: { ...shared, chain: "prerouting", "in-interface": binding, "src-address-list": list, comment: table + ":linux-mss-from-" + binding } },
fields: { ...shared, chain: "forward", "in-interface": table, "src-address-list": list, comment: table + ":linux-mss-from-" + binding } },
{ serverId: site.serverId, path: "/" + family + "/firewall/mangle",
fields: { ...shared, chain: "postrouting", "out-interface": binding, "dst-address-list": list, comment: table + ":linux-mss-to-" + binding } },
])
+15 -8
View File
@@ -28,6 +28,15 @@ const forbiddenPublic = {
}
export function ixNamespace(id: string) { return "ix-" + id.replace(/-/g, "").slice(0, 18) }
export function ixManagedGreFields(namespace: string, binding: IxSite["interfaces"][number]) {
const name = namespace + "-" + binding.name
const fields = greIke2TransportFields(name, binding.localEndpoint!, binding.endpoint!, true,
"ix-credential:" + binding.provisionGre!.credentialId, !binding.linux!.enabled)
// RouterOS derives transport-mode selectors from the active SA.
const { "src-address": _source, "dst-address": _destination, ...policy } = fields.policy
return { ...fields, peer: { ...fields.peer, disabled: "false" },
policy: { ...policy, disabled: "false", template: "false", "ipsec-protocols": "esp", comment: namespace + ":gre-policy-" + binding.name } }
}
// RouterOS accepts unambiguous prefixes for interface names before the VRF interface appears.
export function ixDiscardInterface(id: string) { return "ix-drop-" + ixNamespace(id).slice(3) }
export function ixEgressList(id: string) { return "ix-out-" + ixNamespace(id).slice(3) }
@@ -120,9 +129,9 @@ function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["in
add(filter, key + "-allow-inbound", { ...inbound, "src-address-list": permitted, "in-interface": namespace,
action: "accept", disabled: String(!policy.enabled) })
add(filter, key + "-deny-inbound", { ...inbound, action: "drop" })
// The real VRF member is visible before routing and after routing, respectively.
// RouterOS allows MSS changes in forward, where ingress is the virtual VRF interface.
add(mangle, "linux-mss-from-" + binding.name, {
...clamp, ...ingress, "src-address-list": sources,
...clamp, chain: "forward", "in-interface": namespace, "src-address-list": sources,
})
add(mangle, "linux-mss-to-" + binding.name, {
...clamp, chain: "postrouting", "out-interface": binding.name, "dst-address-list": sources,
@@ -284,8 +293,8 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
}
const protectGre = (binding: IxSite["interfaces"][number], key: string) => {
const [inbound, outbound] = greIpsecPlaintextDrops(binding.localEndpoint!, binding.endpoint!)
add(greIpsecPaths.filter, "gre-in-" + key, inbound)
add(greIpsecPaths.filter, "gre-out-" + key, outbound)
add(greIpsecPaths.filter, "gre-in-" + key, { ...inbound, disabled: "false" })
add(greIpsecPaths.filter, "gre-out-" + key, { ...outbound, disabled: "false" })
}
const dropInterface = ixDiscardInterface(id)
for (const [index, binding] of site.interfaces.entries()) {
@@ -294,11 +303,9 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
if (binding.provisionTransit) compileIxTransit(namespace, site, binding, object => result.push(object))
if (wireguard) add("/interface/wireguard", "wg-" + key, { name: binding.name, "listen-port": String(wireguard.listenPort),
...(binding.linux && { disabled: String(!binding.linux.enabled) }) })
const gre = binding.provisionGre
if (gre) {
const transport = namespace + "-" + key
if (binding.provisionGre) {
protectGre(binding, key)
const fields = greIke2TransportFields(transport, binding.localEndpoint!, binding.endpoint!, true, "ix-credential:" + gre.credentialId, !binding.linux!.enabled)
const fields = ixManagedGreFields(namespace, binding)
for (const kind of ["profile", "proposal", "peer"] as const) add(greIpsecPaths[kind], key, fields[kind])
add(greIpsecPaths.identity, "gre-identity-" + key, fields.identity)
add(greIpsecPaths.policy, "gre-policy-" + key, fields.policy)
+2 -1
View File
@@ -36,7 +36,7 @@ export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
</div>
<p className={head}>Связи</p>
<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(--muted-foreground)" strokeWidth="2" /></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"><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>
@@ -46,6 +46,7 @@ export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
<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>
<p className="text-muted-foreground leading-snug">Подпись линии GRE показывает последний замер RX/TX интерфейса RouterOS. Скорость сервиса и знак «≈» показывают среднюю скорость по принятым записям IPFIX. RTT — задержка пробы, «—» означает, что нет измерения.</p>
<p className="text-muted-foreground leading-snug">Цвет на линии — только у проблем. Скорость подписана от 1 Мбит/с и у выбранного объекта; остальное — в подсказке и панели справа.</p>
</PopoverContent>
</Popover>
)
+4 -5
View File
@@ -52,8 +52,6 @@ const linkNames: Record<MapGroupLink["type"], string> = {
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)"
}
@@ -65,8 +63,9 @@ export function MapGroupLinks({ links, obstacles, onExpand, layer = "all" }: {
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}`] : []
// Коротко на линии; полная сводка — в title.
const texts = row.down ? [`${row.down === row.count ? "Нет связи" : "Отказ"} ${row.down}/${row.count}`, `${row.down}/${row.count}`] :
row.degraded ? [`Деградация ${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)
@@ -78,7 +77,7 @@ export function MapGroupLinks({ links, obstacles, onExpand, layer = "all" }: {
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}
<path d={row.link.d} fill="none" stroke={row.color} strokeWidth={row.fault ? 2.2 : 1.6} opacity={row.fault ? 1 : row.type === "observation" ? .56 : .6}
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>
+10 -9
View File
@@ -56,23 +56,24 @@ function shortRate(rate: string) {
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
export function ServerNode({ n,width,isSel,isVis,dim,isDragged,hideCatalogLatency,channelProblem,rates,onClick,onDblClick,onHoverChange,onContextMenu,onPointerDown }: {
n:Server & {x:number;y:number};width:number;isSel:boolean;isVis:boolean;dim?: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 status = n.status
const offline = status === "offline", warn = status === "degraded" || Boolean(channelProblem && !offline)
const border = isSel ? ink : status === "degraded" ? "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}
transform={`translate(${n.x},${n.y})`} data-node-kind="device" data-node-id={n.id} style={{cursor:isDragged?"grabbing":"grab",transition:"opacity .3s"}} opacity={isVis&&!dim?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)}>
@@ -100,8 +101,8 @@ export function ServerNode({ n,width,isSel,isVis,isDragged,hideCatalogLatency,ch
</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
export function WanSatNode({x,y,wan,width,index,active,isSel,isDragged,traffic,onSelect,onPointerDown}: {
x:number;y:number;wan:WanUplink;width:number;index:number;active:boolean;isSel:boolean;isDragged:boolean;traffic?:string
onSelect:()=>void;onPointerDown:PointerDown
}) {
const name=wan.isp||wan.name
@@ -113,7 +114,7 @@ export function WanSatNode({x,y,wan,width,color,index,active,isSel,isDragged,tra
<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}/>
<Frame width={width} height={height} kind="wan" radius={24} stroke={isSel?ink:"var(--border)"} 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}/>
+3 -6
View File
@@ -37,12 +37,9 @@ export function mapCardMetrics(name: string, kind: CardKind, width: number) {
}
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)
// Домен хоста — в подсказке и панели справа; на карточке только короткое имя в одну строку.
if (host) nameParts(name.slice(0,name.indexOf("."))).forEach(word)
else nameParts(name).forEach(word)
flush()
if (!lines.length) lines.push("—")
return {width, lines, height:height+(lines.length-1)*14}
+3 -2
View File
@@ -54,7 +54,7 @@ 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) {
export function collectGroupLinks(rows: Iterable<MapGroupConnection>, obstacles?: MapBox[]) {
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
@@ -75,7 +75,8 @@ export function collectGroupLinks(rows: Iterable<MapGroupConnection>, obstacles?
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}),
// Отказ рисуется на своём обычном маршруте: цвет и значок, без отдельной полки над картой.
link: mapLinkPath(from, from.halfWidth, to, to.halfWidth, {obstacles}),
}
})
}
+14 -6
View File
@@ -85,20 +85,19 @@ export function roundedMapPath(points: MapPoint[]) {
export function mapLinkPath(
a: MapPoint, aHalfW: number, b: MapPoint, bHalfW: number,
options?: { faultY?: number; obstacles?: readonly MapBox[] },
options?: { 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 startSide = sameLane ? 1 : dir
const endSide = sameLane ? 1 : -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) {
let rail: number | undefined
if (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]
}
@@ -150,6 +149,7 @@ export function placeMapLinkLabels<T extends { id: string; link: MapLink; texts:
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)
let placed = false
search: for (const text of label.texts) {
const w = mapPillWidth(text) + (label.fault ? 16 : 0)
for (const {a,b} of segments) for (const t of LABEL_T) {
@@ -158,9 +158,17 @@ export function placeMapLinkLabels<T extends { id: string; link: MapLink; texts:
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 })
out.push({ ...label, x: Math.round(p.x), y: Math.round(p.y), w, text })
placed = true
break search
}
}
// Отказ не пропадает с карты: без свободного места короткая метка встаёт на середину самого длинного участка.
if (!placed && label.fault && segments.length && label.texts.length) {
const {a,b} = segments.reduce((best, s) => s.length > best.length ? s : best)
const text = label.texts.at(-1)!, w = mapPillWidth(text) + 16, p = { x:(a.x+b.x)/2, y:(a.y+b.y)/2 }
taken.push({ x: p.x - w / 2 - gap, y: p.y - MAP_PILL_H / 2 - gap, w: w + gap * 2, h: MAP_PILL_H + gap * 2 })
out.push({ ...label, x: Math.round(p.x), y: Math.round(p.y), w, text })
}
}
return out
}
+14 -14
View File
@@ -25,29 +25,22 @@ test("наблюдение IPFIX огибает промежуточный уз
}
})
test("неисправная связь выходит на отдельную верхнюю полку, обычная обходит промежуточную колонку", () => {
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.match(normal.d, / Q /)
assert.equal(normal.x1, 170)
assert.equal(normal.x2, 605)
assert.ok(normal.points[2].y < 140 || normal.points[2].y > 265)
})
test("GRE одной колонки остаётся снаружи правых граней обеих карточек при любом состоянии", () => {
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))
}
const link = mapLinkPath(a, 70, b, 70)
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))
}
})
@@ -73,6 +66,13 @@ test("подписи не наезжают на карточки и друг н
}
})
test("метка отказа остаётся на линии, даже если свободного места нет", () => {
const link = mapLinkPath({ x: 542, y: 400 }, MAP_CARD_W / 2, { x: 780, y: 400 }, MAP_CARD_W / 2)
const [placed] = placeMapLinkLabels([{ id: "down", link, texts: ["GRE · Канал недоступен"], fault: true }], [card(542, 400), card(780, 400)])
assert.equal(placed?.text, "GRE · Канал недоступен")
assert.equal(placed.y, 400)
})
test("ленты NetFlow уложены стопкой у узла и толще у большей скорости", () => {
const exit = { x: 780, y: 300 }
const flows = [