Compare commits

..
1 Commits
Author SHA1 Message Date
Denozordec ed7b1e0350 fix(map): восстановить учёт трафика сервисов и привязку к выходным узлам
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m50s
Docker images / backend-image (push) Successful in 2m5s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 41s
Docker images / frontend-image (push) Successful in 2m13s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-27 02:34:26 +07:00
12 changed files with 343 additions and 69 deletions

No files matched your search

+11 -11
View File
@@ -1242,7 +1242,7 @@ function NetworkMapContent() {
setFlowLoading(true)
ac?.abort()
ac = new AbortController()
apiFetch<unknown>("/api/traffic/flow/map-hops?range=1m", { signal: ac.signal })
apiFetch<unknown>("/api/traffic/flow/map-hops?range=5m", { signal: ac.signal })
.then((raw) => {
if (cancelled||request!==epoch) return
const res=networkMapFlowSchema.parse(raw)
@@ -1340,7 +1340,7 @@ function NetworkMapContent() {
let timer: ReturnType<typeof setTimeout>
async function refresh() {
try {
const raw = await apiFetch<unknown>(`/api/traffic/flow/map-hops?${new URLSearchParams({range:"1m",userId:scopeUser!})}`, {signal:controller.signal})
const raw = await apiFetch<unknown>(`/api/traffic/flow/map-hops?${new URLSearchParams({range:"5m",userId:scopeUser!})}`, {signal:controller.signal})
const data = networkMapFlowSchema.parse(raw)
if (!controller.signal.aborted) setUserFlow({ key: scopeKey, data, at: new Date().toISOString() })
} catch {
@@ -2179,11 +2179,12 @@ function NetworkMapContent() {
if (!from || !to) return []
const direct = edge.observedOnly || from.type === "jump-host" || from.type === "home-router"
if (direct && !showAuxLinks) return []
const detour = direct ? mapObservationRoute({ x: from.x + MAP_CARD_W / 2, y: from.y }, { x: to.x - destHalfW, y: to.y }, mapObstacles, observationTracks) : null
const link = mapLinkPath(from, MAP_CARD_W / 2, to, destHalfW)
const detour = direct ? mapObservationRoute(link, mapObstacles, observationTracks) : null
if (detour) observationTracks.push(detour.track)
return [{ edge, direct, detour, link: mapLinkPath(from, MAP_CARD_W / 2, to, destHalfW) }]
return [{ edge, direct, detour, link }]
})
const observationMarkers = destRibbons.flatMap(({ edge, detour }) => edge.observedOnly && detour ? [{ x: detour.marker.x - 17, y: detour.marker.y - 7, w: 34, h: 14 }] : [])
const observationMarkers = destRibbons.flatMap(({ edge, detour }) => edge.observedOnly && detour?.marker ? [{ x: detour.marker.x - 17, y: detour.marker.y - 7, w: 34, h: 14 }] : [])
const linkLabels = placeMapLinkLabels([...accessLinks.filter(link => link.texts[0]), ...greLabels, ...wanLabels], [...mapObstacles, ...observationMarkers])
const nestedRibbons = mapRibbons((expandedCountryGroup?.edges ?? []).flatMap((edge) => {
const from = servicePosById[edge.fromId], to = nestedPosById[edge.toId]
@@ -2547,7 +2548,7 @@ function NetworkMapContent() {
const pathHit = Boolean(highlightedPath && (highlightedPath.enId || highlightedPath.viaId) === edge.fromId && selectedDestinationId === edge.toId)
const hl = pathHit || (!highlightedPath && (activeService?.id === edge.toId || selected?.id === edge.fromId || expandedCountryId === edge.toId || filteredServiceId === edge.toId))
const countryDim = !hl && Boolean(expandedCountryGroup) && edge.toId !== expandedCountryId
const d = direct ? detour?.d : link.d
const d = detour?.d ?? link.d
const svc = visibleMapServices.find((s) => s.id === edge.toId)
const enName = mapServers.find((s) => s.id === edge.fromId)?.name ?? edge.fromId
const clientLabel = edge.clients?.map((c) => c.name).filter(Boolean).join(", ") || edge.clientName || "—"
@@ -2560,14 +2561,13 @@ function NetworkMapContent() {
<title>{edge.observedOnly
? `Наблюдение IPFIX · ${enName} → ${destDisplayLabel(svc, destMode, edge.toId)}${rate} · выход не подтверждён`
: `${clientLabel} → ${enName} → ${destDisplayLabel(svc, destMode, edge.toId)}${rate}`}</title>
{d && <path data-map-route={direct ? "observation" : "service"} d={d} fill="none" stroke={direct ? "var(--muted-foreground)" : "var(--chart-4)"} strokeLinejoin="round" strokeWidth={hl ? 2.5 : 1.5} />}
{d && <path d={d} fill="none" stroke="transparent" strokeWidth="12" />}
{edge.observedOnly && detour && <g transform={`translate(${detour.marker.x},${detour.marker.y})`}>
<path data-map-route={direct ? "observation" : "service"} d={d} fill="none" stroke={direct ? "var(--muted-foreground)" : "var(--chart-4)"} strokeLinejoin="round" strokeWidth={hl ? 2.5 : 1.5} />
<path d={d} fill="none" stroke="transparent" strokeWidth="12" />
{edge.observedOnly && detour?.marker && <g transform={`translate(${detour.marker.x},${detour.marker.y})`}>
<rect x="-17" y="-7" width="34" height="14" rx="7" fill="var(--card)" stroke="var(--muted-foreground)" />
<text textAnchor="middle" y="3.5" fill="var(--foreground)" fontSize="9">IPFIX</text>
</g>}
{!d && <circle cx={link.x2 - 5} cy={link.y2} r="4" fill="var(--muted-foreground)" />}
{d && !direct && showAnimDots && !reducedMotion && hl && hopHasRate(hop) && (
{!direct && showAnimDots && !reducedMotion && hl && hopHasRate(hop) && (
<circle r="2.5" fill="var(--foreground)" opacity="0.7" pointerEvents="none">
<animateMotion dur="2.6s" repeatCount="indefinite" path={d} />
</circle>
@@ -12,11 +12,12 @@ import {
uptimeSpeedProbes,
} from "../db/schema.js"
import { listServersRead } from "../modules/servers/service/servers-service.js"
import { rosIdToIfIndex } from "./traffic-flow-ifindex.js"
import { MikrotikClient } from "./mikrotik.js"
import type { InternetPathRunSnapshot } from "../types/scheduler-run-snapshot.js"
import { SCHEDULER_RUN_SNAPSHOT_VERSION } from "../types/scheduler-run-snapshot.js"
import { collectConfirmedInternetPath, readInternetPathRows } from "./internet-path-snapshot.js"
import { collectConfirmedInternetPath, observedGrePeers, readGreEnrichment, readInternetPathRows } from "./internet-path-snapshot.js"
const INTERNET_TARGET = "1.1.1.1"
let collecting = false
@@ -177,12 +178,22 @@ function parseInnerIps(comment: string): { localInnerIp: string; remoteInnerIp:
async function collectGreTunnels() {
const enabled = await db.select().from(servers).where(eq(servers.enabled, true))
const assignedAddresses = new Map<string, Set<string>>()
const all = await Promise.all(enabled.map(async (srv) => {
try {
const client = MikrotikClient.fromServer(srv)
const rows = await client.get<unknown>("/interface/gre").then(raw => readInternetPathRows(raw, "GRE " + srv.id, [".id", "name", "local-address", "remote-address"]))
if (!rows.length) return []
const [addresses, interfaces] = await Promise.all([
readGreEnrichment(() => client.get<unknown>("/ip/address"), "GRE addresses " + srv.id, ["interface", "address"]),
readGreEnrichment(() => client.get<unknown>("/interface"), "interfaces " + srv.id, [".id", "name"]),
])
const activeAddresses = addresses.filter(a => !isTrue(a.disabled) && !isTrue(a.invalid))
assignedAddresses.set(String(srv.id), new Set(activeAddresses.map(a => a.address!.split("/")[0]!)))
return rows.map((g, idx) => {
const keepalive = String(g.keepalive ?? "0,0").split(",")
const identities = interfaces.filter(row => row.name === g.name)
const identity = identities.length === 1 ? identities[0] : undefined
const inner = parseInnerIps(String(g.comment ?? ""))
return {
id: String(g.name ?? g[".id"] ?? `gre-${srv.id}-${idx}`),
@@ -190,6 +201,10 @@ async function collectGreTunnels() {
serverId: String(srv.id),
localAddress: String(g["local-address"] ?? ""),
remoteAddress: String(g["remote-address"] ?? ""),
currentRemoteAddress: String(g["current-remote-address"] ?? ""),
nativeIndex: rosIdToIfIndex(identity?.[".id"]),
ifIndex: /^[1-9][0-9]*$/.test(identity?.ifindex ?? "") ? Number(identity!.ifindex) : null,
observedAddresses: activeAddresses.filter(a => a.interface === g.name).map(a => a.address!),
localInnerIp: inner.localInnerIp,
remoteInnerIp: inner.remoteInnerIp,
poolId: "live",
@@ -212,7 +227,7 @@ async function collectGreTunnels() {
throw new Error(`Internet path: GRE устройства ${srv.id}: ${error instanceof Error ? error.message : String(error)}`)
}
}))
return all.flat()
return observedGrePeers(all.flat(), new Map(enabled.map(server => [String(server.id), server.host])), assignedAddresses)
}
export async function getInternetPathSettings() {
@@ -1,5 +1,5 @@
import assert from "node:assert/strict"
import {collectConfirmedInternetPath, readInternetPathRows, readStoredInternetPathPayload, mapStoredInternetPathResponse} from "./internet-path-snapshot.js"
import {collectConfirmedInternetPath, observedGrePeers, readGreEnrichment, readInternetPathRows, readStoredInternetPathPayload, mapStoredInternetPathResponse} from "./internet-path-snapshot.js"
const servers=[{id:1,type:"home-router",enabled:true},{id:2,type:"home-router",enabled:false},{id:3,type:"exit-node",enabled:true}]
const sampledAt="2026-10-04T00:00:00Z"
const defaults={servers:async()=>servers,gre:async()=>[],filters:async()=>[],speed:async()=>[],route:async(id:number)=>{assert.equal(id,1);return {gateway:null,routingMark:null}},wan:async(id:number)=>{assert.equal(id,1);return {defaultGateway:null,defaultInterface:null,uplinks:[]}}}
@@ -35,3 +35,29 @@ for (const stored of ["2026-10-04 07:00:00+07", "2026-10-04T00:00:00Z"]) {
for (const invalid of ["", "bad", null]) assert.throws(()=>mapStoredInternetPathResponse({payloadJson:good,sampledAt:invalid as string}))
assert.throws(()=>mapStoredInternetPathResponse({payloadJson:"bad",sampledAt}))
console.log("internet path HTTP timestamp: PostgreSQL/ISO instant preserved; invalid metadata rejected")
const jh = { serverId: "7", enabled: true, localAddress: "0.0.0.0", remoteAddress: "198.51.100.9", observedAddresses: ["10.200.100.53/30"] }
const exit = { serverId: "9", enabled: true, localAddress: "198.51.100.9", remoteAddress: "198.51.100.7", observedAddresses: ["10.200.100.54/30"] }
const hosts = new Map([["7", "198.51.100.7"], ["9", "198.51.100.9"]])
assert.deepEqual(observedGrePeers([jh, exit], hosts, new Map()).map(t => t.observedNextHops), [[{ip:"10.200.100.54",serverId:"9"}],[{ip:"10.200.100.53",serverId:"7"}]])
for (const incomplete of [[jh], [jh, exit, {...exit, serverId:"18"}], [jh, {...exit, enabled:false}], [jh, {...exit, remoteAddress:"198.51.100.8"}], [jh, {...exit, observedAddresses:["10.200.100.55/30"]}]]) {
assert.ok(observedGrePeers(incomplete, hosts, new Map()).every(t => !t.observedNextHops.length))
}
const wildcard = observedGrePeers([
{...jh, localAddress:"0.0.0.0",remoteAddress:"exit.example",currentRemoteAddress:"198.51.100.2"},
{...exit,localAddress:"0.0.0.0",remoteAddress:"198.51.100.1"},
], new Map([["7","jump.example"],["9","exit.example"]]), new Map([["7",new Set(["198.51.100.1"])],["9",new Set(["198.51.100.2"])]]))
assert.deepEqual(wildcard[0]?.observedNextHops, [{ip:"10.200.100.54",serverId:"9"}])
for (const read of [async () => { throw Error("forbidden") }, async () => ({ message:"invalid response" })]) {
const observed = await readGreEnrichment(read, "GRE", ["address","interface"])
const [base] = observedGrePeers([{...jh, observedAddresses:observed.map(a => a.address!),localInnerIp:"10.0.0.1/30"}],hosts,new Map())
assert.equal(base?.localInnerIp,"10.0.0.1/30")
assert.deepEqual(base?.observedNextHops,[])
}
const staleDns = observedGrePeers([
{...jh, remoteAddress:"exit.example",currentRemoteAddress:"192.0.2.11"}, exit,
], new Map([["7","198.51.100.7"],["9","exit.example"]]), new Map())
assert.ok(staleDns.every(t => !t.observedNextHops.length))
@@ -1,3 +1,5 @@
import { ipv4ToInt, parseCidrV4 } from "./traffic-flow-ip.js"
// No database or RouterOS imports: this boundary can be checked with injected readers.
type PathServer = {id: number | string; type: string; enabled: boolean}
export async function collectConfirmedInternetPath<S extends PathServer, G, F, P, R extends object, W extends object>(sampledAt: string, readers: {
@@ -36,3 +38,50 @@ export function mapStoredInternetPathResponse(row: { payloadJson: unknown; sampl
if (typeof row.sampledAt !== "string" || !row.sampledAt.trim()) throw new Error("Сохранённая дата Internet path повреждена")
return { snapshot: readStoredInternetPathPayload(row.payloadJson), sampledAt: new Date(row.sampledAt).toISOString() }
}
// Enrichment may be unauthorized on otherwise observable GRE routers.
export async function readGreEnrichment(read: () => Promise<unknown>, source: string, fields: string[]) {
try { return readInternetPathRows(await read(), source, fields) } catch { return [] }
}
// A shared point-to-point subnet and matching outer peers identify the exact next hop on this exporter.
export function observedGrePeers<T extends {serverId: string; enabled: boolean; localAddress: string; remoteAddress: string; currentRemoteAddress?: string; localInnerIp?: string; observedAddresses: string[]}>(
tunnels: T[], hosts: Map<string, string>, assignedAddresses: Map<string, Set<string>>,
) {
const subnets = new Map<string, Array<{ tunnel: T; ip: string }>>()
const peers = new Map<T, Array<{ ip: string; serverId: string }>>()
for (const tunnel of tunnels) {
if (!tunnel.enabled) continue
for (const cidr of tunnel.observedAddresses) {
if (!/^[0-9.]+\/(30|31)$/.test(cidr)) continue
const parsed = parseCidrV4(cidr)
const ip = cidr.split("/")[0]!
if (!parsed || (parsed.prefixLen === 30 && (ipv4ToInt(ip) === parsed.net || ipv4ToInt(ip) === parsed.net + 3))) continue
const key = parsed.net + "/" + parsed.prefixLen
const entries = subnets.get(key) ?? []
entries.push({ tunnel, ip })
subnets.set(key, entries)
}
}
function pointsTo(local: T, peer: T) {
const current = local.currentRemoteAddress?.trim().toLowerCase()
const remote = current && current !== "0.0.0.0" ? current : local.remoteAddress.trim().toLowerCase()
return remote && remote !== "0.0.0.0" && (remote === peer.localAddress.toLowerCase() ||
remote === hosts.get(peer.serverId)?.toLowerCase() || assignedAddresses.get(peer.serverId)?.has(remote))
}
for (const endpoints of subnets.values()) {
if (endpoints.length !== 2) continue
const [a, b] = endpoints as [typeof endpoints[number], typeof endpoints[number]]
if (a.ip === b.ip || a.tunnel.serverId === b.tunnel.serverId || !pointsTo(a.tunnel, b.tunnel) || !pointsTo(b.tunnel, a.tunnel)) continue
for (const [local, peer] of [[a, b], [b, a]] as const) {
const matches = peers.get(local.tunnel) ?? []
matches.push({ ip: peer.ip, serverId: peer.tunnel.serverId })
peers.set(local.tunnel, matches)
}
}
return tunnels.map(tunnel => {
const { observedAddresses, ...rest } = tunnel
return { ...rest, localInnerIp: observedAddresses[0] ?? tunnel.localInnerIp ?? "", observedNextHops: peers.get(tunnel) ?? [] }
})
}
@@ -114,8 +114,9 @@ const { rows: [snapshot] } = await dbQuery<{id: number}>(`
INSERT INTO internet_path_snapshots(sampled_at,payload_json) VALUES (?,?::jsonb) RETURNING id
`, [new Date(bucket).toISOString(), JSON.stringify({ collectionComplete: true, greTunnels: [
{serverId: "7", name: "gre-jh-en", remoteAddress: "198.51.100.1", enabled: true},
{serverId: "7", name: "SWE-VEESP", remoteAddress: "198.51.100.1", enabled: true},
{serverId: "7", name: "gre-second", remoteAddress: "198.51.100.2", enabled: true},
{serverId: "7", name: "SWE-VEESP", remoteAddress: "198.51.100.1", enabled: true, nativeIndex:4, ifIndex:6, observedNextHops:[{ip:"10.200.100.54", serverId:"9"}]},
{serverId:"7", name:"gre-client", remoteAddress:"192.0.2.77", enabled:true,nativeIndex:5,ifIndex:7},
{serverId: "7", name: "gre-second", remoteAddress: "198.51.100.2", enabled: true, nativeIndex:12, ifIndex:4, observedNextHops:[{ip:"10.200.101.54",serverId:"10"}]},
] })])
const topo: FlowTopology = {
@@ -1070,6 +1071,41 @@ try {
ingestParsedFlowsForServerForTests(7, [{ ...flow, bytes: 0, packets: 1, outIface: "ether1" }])
const idle = await buildFlowMapHops({ serverId: 7, minutes: 3, includeCurrentMinute: true, minSharePct: 0 })
assert.equal(idle.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, lastMinute)
resetFlowRingsForTests()
resetFlowMapHopsCacheForTests()
clock.mock.mockImplementation(() => bucket + 90_000)
const forward = { ...flow, src:"10.10.0.1", inIface:"5", outIface:"4", nextHop:"10.200.100.54", bytes:1000 }
const reverse = { ...forward, src:forward.dst, dst:forward.src, srcPort:forward.dstPort, dstPort:forward.srcPort, inIface:"4", outIface:"5", nextHop:"0.0.0.0", bytes:9000 }
ingestClosed(7, [forward, reverse])
rememberServerIfaces(7, [{".id":"*4",name:"ether1"},{".id":"*5",name:"wrong-client"}])
const direct = await buildFlowMapHops({serverId:7, minutes:1, minSharePct:0})
assert.equal(direct.nodeUsers?.["9"]?.find(u => u.clientName === "Alice")?.bytes, 10000)
const own = await buildFlowMapHops({serverId:7, userId:"u1", minutes:1, minSharePct:0})
assert.equal(own.totalBytes, 10000)
assert.deepEqual(direct.serviceEdges?.map(e => [e.fromId,e.bytes]), [["9",10000]])
resetFlowRingsForTests()
resetFlowMapHopsCacheForTests()
ingestClosed(7, [reverse, {...forward, outIface:"ether1", bytes:500}, {...forward, src:"10.10.0.2", outIface:"48", bytes:250}])
const unproven = await buildFlowMapHops({serverId:7, minutes:1, minSharePct:0})
assert.deepEqual(unproven.serviceEdges?.map(e => [e.fromId,e.observedOnly,e.bytes]), [["7",true,9750]])
resetFlowRingsForTests()
resetFlowMapHopsCacheForTests()
ingestClosed(7, [forward, reverse, {...forward, src:"10.10.0.2", nextHop:"10.200.101.54"}])
const ambiguous = await buildFlowMapHops({serverId:7, minutes:1, minSharePct:0})
assert.ok(ambiguous.serviceEdges?.every(e => e.observedOnly), "conflicting paths for one raw index")
const scoped = await buildFlowMapHops({serverId:7,userId:"u1", minutes:1,minSharePct:0})
assert.equal(scoped.totalBytes,0, "a conflicting interface namespace cannot establish client scope")
resetFlowRingsForTests()
resetFlowMapHopsCacheForTests()
clock.mock.mockImplementation(() => bucket + 150_000)
ingestClosed(7, [forward])
ingestClosed(7, [reverse], bucket + 60_000)
const otherMinute = await buildFlowMapHops({serverId:7,minutes:2,minSharePct:0})
assert.equal(otherMinute.serviceEdges?.find(e => e.fromId === "9")?.bytes, 1000)
assert.equal(otherMinute.serviceEdges?.find(e => e.observedOnly)?.bytes, 9000)
} finally { clock.mock.restore() }
} finally {
await dbQuery("DELETE FROM internet_path_snapshots WHERE id=?", [snapshot.id])
@@ -1077,6 +1113,31 @@ try {
seedFlowTopologyForTests(null)
}
// A video download can arrive in an earlier receipt minute than the latest HTTPS traffic.
seedFlowTopologyForTests(topo)
try {
const youtube = (bytes: number) => ({ ...payloadFlow("173.194.151.65", bytes), proto: 17 })
ingestClosed(7, [youtube(224_932_500)], bucket - 120_000)
ingestClosed(7, [youtube(67_500), payloadFlow("104.18.35.51", 69_075_000)], bucket)
const clock = mock.method(Date, "now", () => bucket + 90_000)
try {
const query = { serverId: 7, minSharePct: 0 }
const recent = await buildFlowMapHops({ ...query, minutes: 1, includeCurrentMinute: true })
assert.equal(recent.services?.find(s => s.id === "svc:youtube")?.bps, 6_000)
assert.equal(recent.services?.find(s => s.id === "svc:cloudflare")?.bps, 6_140_000)
const map = await buildFlowMapHops({ ...query, minutes: 5 })
assert.equal(map.windowSec, 300)
const video = map.services?.find(s => s.id === "svc:youtube")
assert.equal(video?.bytes, 225_000_000)
assert.equal(video.bps, 6_000_000)
assert.equal(map.services?.find(s => s.id === "svc:cloudflare")?.bytes, 69_075_000)
} finally { clock.mock.restore() }
} finally {
resetFlowRingsForTests()
seedFlowTopologyForTests(null)
}
// Captured on the test CHR. Three 64-byte UDP packets traversed GRE A -> GRE B.
// RouterOS also exported three 88-byte outer GRE packets on GRE B -> underlay.
const datagram = Buffer.from(
+92 -27
View File
@@ -1,3 +1,4 @@
import { FlowSourceWindowTooLarge, FlowSqlSourceTooLarge } from "./traffic-flow-read-window.js"
import { flowReadDbAll } from "./traffic-flow-read-policy.js"
import { isDeepStrictEqual } from "node:util"
import { readFlowMapSourceLimits } from "./traffic-flow-source-limits.js"
@@ -448,16 +449,49 @@ async function readInterfaceTraffic(serverIds: number[], iface: string, q: FlowM
}
// Interface names are local to the exporter; match them against the GRE inventory for the flow minute.
async function readMapGrePeers(rows: { serverId: number; bucketAt: string; inIface: string; outIface: string }[]) {
async function readMapGrePeers(rows: { serverId: number; bucketAt: string; inIface: string; outIface: string; nextHop: string }[]) {
const peers = new Map<string, Map<string, string>>()
if (!rows.length) return peers
const buckets = new Set<string>(), names = new Set<string>()
const nextHops = new Map<string, { serverId: number; iface: string; native: number | null; explicit: number | null } | null>()
const ingress = new Map<string, { serverId: number; iface: string } | null>()
const names = new Map<string, string>()
const namespace = new Map<string, number>()
const keyFor = (bucket: string, server: number | string) => JSON.stringify([bucket, String(server)])
const ifaceName = (row: typeof rows[number], raw: string) => {
const key = keyFor(row.bucketAt, row.serverId)
const mode = namespace.get(key)
const cached = resolveIfaceName(row.serverId, raw).name
if (!/^[1-9][0-9]*$/.test(raw)) return cached
const native = names.get(JSON.stringify([key, 1, Number(raw)]))
const explicit = names.get(JSON.stringify([key, 2, Number(raw)]))
if (mode === 1 || mode === 2) {
const exact = mode === 1 ? native : explicit
if (exact !== undefined) return exact || "#" + raw
if (native !== undefined || explicit !== undefined) return "#" + raw
}
// The current alias cache cannot resolve conflicting historical interface identities.
if ([native, explicit].some(name => name !== undefined && name !== cached)) return "#" + raw
return cached
}
if (!rows.length) return { peers, nextHops, ingress, ifaceName }
const buckets = new Set<string>()
for (const row of rows) {
buckets.add(row.bucketAt)
for (const iface of [row.inIface, row.outIface]) names.add(row.serverId + "|" + resolveIfaceName(row.serverId, iface).name)
}
const bindings = await flowReadDbAll<{ bucket: string; key: string; remote: string }>(`
SELECT b.bucket, (t->>'serverId') || '|' || (t->>'name') AS key, t->>'remoteAddress' AS remote
const targets = new Set<string>()
const hops = new Set<string>()
for (const row of rows) {
for (const raw of [row.inIface, row.outIface]) {
targets.add(row.serverId + "|" + raw)
targets.add(row.serverId + "|" + resolveIfaceName(row.serverId, raw).name)
}
if (row.nextHop && row.nextHop !== "0.0.0.0" && row.nextHop !== "::") hops.add(row.serverId + "|" + row.nextHop)
}
const bindings = await flowReadDbAll<{ bucket: string; key: string; remote: string; owner: string; iface: string; native: number | null; explicit: number | null; next_hops: Array<{ip: string; serverId: string}> }>(`
SELECT b.bucket, (t->>'serverId') || '|' || (t->>'name') AS key, t->>'remoteAddress' AS remote,
t->>'serverId' AS owner, t->>'name' AS iface, t->'nativeIndex' AS native, t->'ifIndex' AS explicit,
(SELECT COALESCE(jsonb_agg(p), '[]'::jsonb) FROM jsonb_array_elements(CASE WHEN jsonb_typeof(t->'observedNextHops')='array'
THEN t->'observedNextHops' ELSE '[]'::jsonb END) AS p
WHERE p->>'serverId' ~ '^[1-9][0-9]*$' AND p->>'ip' <> '') AS next_hops
FROM unnest(?::text[]) AS b(bucket)
CROSS JOIN LATERAL (
SELECT payload_json FROM internet_path_snapshots
@@ -468,15 +502,43 @@ async function readMapGrePeers(rows: { serverId: number; bucketAt: string; inIfa
CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(payload_json->'greTunnels')='array'
THEN payload_json->'greTunnels' ELSE '[]'::jsonb END) AS t
WHERE payload_json->>'collectionComplete'='true' AND t->>'serverId' ~ '^[1-9][0-9]*$'
AND ((t->>'serverId') || '|' || (t->>'name'))=ANY(?::text[])
AND (EXISTS (SELECT 1 FROM unnest(ARRAY[t->>'name',t->>'nativeIndex',t->>'ifIndex']) AS idx
WHERE (t->>'serverId') || '|' || idx = ANY(?::text[]))
OR EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(t->'observedNextHops')='array'
THEN t->'observedNextHops' ELSE '[]'::jsonb END) AS p WHERE (t->>'serverId') || '|' || (p->>'ip') = ANY(?::text[])))
AND t->>'enabled'='true' AND t->>'name'<>'' AND t->>'remoteAddress'<>''
`, [[...buckets], [...names]])
`, [[...buckets], [...targets], [...hops]]).catch(error => {
if (error instanceof FlowSqlSourceTooLarge) throw new FlowSourceWindowTooLarge()
throw error
})
for (const row of bindings) {
const interfaces = peers.get(row.bucket) ?? new Map<string, string>()
interfaces.set(row.key, interfaces.has(row.key) ? "" : row.remote.trim().toLowerCase())
peers.set(row.bucket, interfaces)
const ownerKey = keyFor(row.bucket, row.owner)
for (const [mode, index] of [[1, row.native], [2, row.explicit]] as const) {
if (!index) continue
const key = JSON.stringify([ownerKey, mode, index])
names.set(key, names.has(key) ? "" : row.iface)
}
for (const peer of row.next_hops) {
const key = JSON.stringify([row.bucket, row.owner, peer.ip])
nextHops.set(key, nextHops.has(key) ? null : { serverId: Number(peer.serverId), iface: row.iface, native: row.native, explicit: row.explicit })
}
}
return peers
// Bind raw IPFIX indexes only to a directly observed next hop for this exporter and minute.
for (const row of rows) {
if (!/^[1-9][0-9]*$/.test(row.outIface)) continue
const peer = nextHops.get(JSON.stringify([row.bucketAt, String(row.serverId), row.nextHop]))
if (peer === undefined) continue
const key = JSON.stringify([row.bucketAt, row.serverId, row.outIface])
const prev = ingress.get(key)
const mode = (peer?.native === Number(row.outIface) ? 1 : 0) | (peer?.explicit === Number(row.outIface) ? 2 : 0)
const ownerKey = keyFor(row.bucketAt, row.serverId)
namespace.set(ownerKey, (namespace.get(ownerKey) ?? 3) & mode)
ingress.set(key, !peer || !mode || prev === null || prev && (prev.serverId !== peer.serverId || prev.iface !== peer.iface) ? null : peer)
}
return { peers, nextHops, ingress, ifaceName }
}
async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number, scope?: ScopedFlowAnalyticsRead): Promise<FlowMapHopsDto> {
@@ -505,33 +567,33 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
const allow = q.userId ? flowClientInterfaces(topo, q.userId) : null
if (scope && allow && !allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
const { peers, nextHops, ingress, ifaceName } = await readMapGrePeers(raw)
function rowClient(r: (typeof raw)[number]) {
return resolveFlowClient(topo, r.serverId, resolveIfaceName(r.serverId, r.inIface).name, resolveIfaceName(r.serverId, r.outIface).name)
return resolveFlowClient(topo, r.serverId, ifaceName(r, r.inIface), ifaceName(r, r.outIface))
}
const matches = (serverId: number, iface: string) =>
flowRowMatchesFilter({ serverId, inIface: iface }, resolveIfaceName(serverId, iface).name, q, allow)
const matches = (r: (typeof raw)[number], iface: string) =>
flowRowMatchesFilter({ serverId: r.serverId, inIface: iface }, ifaceName(r, iface), q, allow)
const selected = raw.filter(r => (!q.userId || rowClient(r)?.userId === q.userId) &&
(matches(r.serverId, r.inIface) || matches(r.serverId, r.outIface)))
(matches(r, r.inIface) || matches(r, r.outIface)))
const { rows } = collapseGreEspRows(selected, r => {
if (ifaceFilter) {
const ingress = matches(r.serverId, r.inIface), egress = matches(r.serverId, r.outIface)
const ingress = matches(r, r.inIface), egress = matches(r, r.outIface)
return ingress === egress ? null : ingress ? "rx" : "tx"
}
return flowRateDirection(r.serverId, r, topo, catalog.byId.get(r.serverId)?.host)
})
const matched = []
for (const r of rows) {
const resolved = resolveIfaceName(r.serverId, r.inIface)
const outResolved = resolveIfaceName(r.serverId, r.outIface)
const plane = classifyFlowPlane({
src: r.src,
dst: r.dst,
proto: r.proto,
srcPort: r.srcPort,
dstPort: r.dstPort,
inIface: resolved.name,
outIface: outResolved.name,
inIface: ifaceName(r, r.inIface),
outIface: ifaceName(r, r.outIface),
}, topo.plane)
if (!shouldKeepPlane(plane, { excludeMesh, excludeOverlay })) continue
matched.push(r)
@@ -549,7 +611,7 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
hostIds.set(key, previous === undefined || previous === node.id ? node.id : null)
}
await authorize()
const peers = await readMapGrePeers(working)
const observed = new Map<(typeof working)[number], {
endpoints: ReturnType<typeof resolveFlowEndpoints>; exitId?: number; viaIface?: string; reverse: boolean
client: ReturnType<typeof rowClient>; nodeBytes: Map<number, number>
@@ -559,10 +621,8 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
let totalBytes = 0
for (const r of working) {
const inRes = resolveIfaceName(r.serverId, r.inIface)
const outRes = resolveIfaceName(r.serverId, r.outIface)
const inName = inRes.name
const outName = outRes.name
const inName = ifaceName(r, r.inIface)
const outName = ifaceName(r, r.outIface)
const fromId = String(r.serverId)
const fromLabel = nameById.get(r.serverId) ?? fromId
const wanSet = topo.wanIfaces.get(r.serverId)
@@ -604,8 +664,13 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
const bindings = peers.get(r.bucketAt)
const outPeer = bindings?.get(fromId + "|" + outName)
const outId = outPeer === undefined ? hostIds.get(r.nextHop) : hostIds.get(outPeer)
const inId = hostIds.get(bindings?.get(fromId + "|" + inName) ?? "")
const nextHop = nextHops.get(JSON.stringify([r.bucketAt, fromId, r.nextHop]))
const verifiedOutput = nextHop && (r.outIface === nextHop.iface || ingress.get(JSON.stringify([r.bucketAt, r.serverId, r.outIface]))?.iface === nextHop.iface)
const outId = nextHop === undefined ? (outPeer === undefined ? hostIds.get(r.nextHop) : hostIds.get(outPeer))
: verifiedOutput && enIds.has(nextHop.serverId) ? nextHop.serverId : undefined
const input = ingress.get(JSON.stringify([r.bucketAt, r.serverId, r.inIface]))
const inId = input === undefined ? hostIds.get(bindings?.get(fromId + "|" + inName) ?? "")
: input && enIds.has(input.serverId) ? input.serverId : undefined
const peerId = outId && inId && outId !== inId ? null : outId ?? inId
const endpoints = resolveFlowEndpoints({
src: r.src,
@@ -621,7 +686,7 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
}),
})
const reverse = !!endpoints.internetPeer && (endpoints.internetPeer === endpoints.packetSrc || endpoints.internetPeer === r.natSrc)
const serviceSide = endpoints.internetPeer ? (reverse ? inId : outId) : peerId
const serviceSide = endpoints.internetPeer ? (reverse ? inId : outId) : undefined
const exitId = enIds.has(r.serverId) ? r.serverId : serviceSide ?? undefined
const serviceIface = reverse ? inName : outName
const otherIface = reverse ? outName : inName
@@ -634,7 +699,7 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
if (peerId && peerId !== r.serverId) {
const toId = String(peerId)
const dir = outId === peerId ? "fwd" : "rev"
const greIface = dir === "fwd" && ifaceUsable(outName) ? outName : (ifaceUsable(inName) ? inName : undefined)
const greIface = dir === "fwd" ? nextHop?.iface ?? (ifaceUsable(outName) ? outName : undefined) : input?.iface ?? (ifaceUsable(inName) ? inName : undefined)
bump(hops, JSON.stringify(["gre", fromId, toId, greIface]), {
fromId,
fromLabel,
+22 -19
View File
@@ -1,27 +1,30 @@
import type { MapBox } from "./network-map-layout"
import type { MapBox, MapLink } from "./network-map-layout"
type Point = { x: number; y: number }
/** Routes IPFIX around cards. A missing route leaves the observation available in service details. */
export function mapObservationRoute(start: Point, end: Point, boxes: readonly MapBox[], usedTracks: readonly number[]) {
if (end.x - start.x < 44) return null
const padding = 8
const obstacles = boxes.filter(box => box.x + box.w > start.x && box.x < end.x)
const first = Math.min(start.x + 20, ...obstacles.map(box => box.x - padding))
const last = Math.max(end.x - 20, ...obstacles.map(box => box.x + box.w + padding))
if (first <= start.x || last >= end.x || last - first < 34) return null
const middle = (start.y + end.y) / 2
const candidates = [middle, start.y, end.y, ...obstacles.flatMap(box => [box.y - 16, box.y + box.h + 16])]
const legal = candidates.flatMap(y => [y, y - 14, y + 14, y - 28, y + 28])
.filter(y => obstacles.every(box => y < box.y - padding || y > box.y + box.h + padding))
/** Find a clear horizontal track between the sides facing the connection after dragging. */
export function mapObservationRoute(link: MapLink, boxes: readonly MapBox[], usedTracks: readonly number[]) {
const { x1, y1, x2, y2, cx } = link
const stub = (x: number) => x + Math.sign(cx - x) * Math.min(20, Math.abs(cx - x))
const first = stub(x1), last = stub(x2)
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 crosses = (a: number, b: number, low: number, size: number) => Math.min(a, b) < low + size && Math.max(a, b) > low
const horizontal = (a: number, b: number, y: number) =>
obstacles.some(box => y > box.y && y < box.y + box.h && crosses(a, b, box.x, box.w))
const vertical = (x: number, a: number, b: number) =>
obstacles.some(box => x > box.x && x < box.x + box.w && crosses(a, b, box.y, box.h))
if (horizontal(x1, first, y1) || horizontal(last, x2, y2)) return null
const candidates = [middle, y1, y2, ...obstacles.flatMap(box => [box.y - 16, box.y + box.h + 16]),
...usedTracks.flatMap(y => [y - 18, y + 18])]
const legal = candidates.filter(y => !vertical(first, y1, y) && !horizontal(first, last, y) && !vertical(last, y, y2))
.sort((a, b) => Math.abs(a - middle) - Math.abs(b - middle) || a - b)
const y = legal.find(candidate => usedTracks.every(track => Math.abs(candidate - track) >= 18))
const markerX = (first + last) / 2
const markerFits = (y: number) => !boxes.some(box => crosses(markerX - 17, markerX + 17, box.x, box.w) && crosses(y - 7, y + 7, box.y, box.h))
const y = legal.find(candidate => markerFits(candidate) && usedTracks.every(track => Math.abs(candidate - track) >= 18)) ?? legal[0]
if (y === undefined) return null
return {
d: `M ${start.x} ${start.y} H ${first} V ${y} H ${last} V ${end.y} H ${end.x}`,
marker: { x: (first + last) / 2, y },
d: `M ${x1} ${y1} H ${first} V ${y} H ${last} V ${y2} H ${x2}`,
marker: markerFits(y) ? { x: markerX, y } : undefined,
track: y,
}
}
+1 -1
View File
@@ -46,7 +46,7 @@ test("map Flow envelope retains zeros and refuses missing metadata and contradic
assert.throws(()=>networkMapFlowSchema.parse({...shorter,rangeMinutes:1,windowSec:60}))
assert.throws(()=>networkMapFlowSchema.parse({...shorter,windowSec:300}))
const recent={...empty,rangeMinutes:1,windowSec:90.125,includesCurrentMinute:true}
assert.equal(networkMapFlowSchema.parse(recent).windowSec,90.125)
assert.throws(()=>networkMapFlowSchema.parse(recent))
assert.throws(()=>networkMapFlowSchema.parse({...recent,windowSec:120}))
assert.throws(()=>networkMapFlowSchema.parse({...recent,includesCurrentMinute:undefined}))
})
+2 -4
View File
@@ -28,11 +28,9 @@ export function validateNetworkMapSnapshot(servers:unknown,gre:unknown,probes:un
import {flowMapHopsDtoSchema} from "@mmapp/contracts/traffic-flow"
import {isIpv4String} from "./gre-endpoint-resolve"
export const networkMapFlowSchema = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true, includesCurrentMinute: true, nodeUsers: true }).refine(data =>
(data.includesCurrentMinute
? !data.sourceWindow && data.rangeMinutes === 1 && data.windowSec >= 60 && data.windowSec < 120
: data.windowSec === data.rangeMinutes * 60 && (data.sourceWindow
!data.includesCurrentMinute && data.windowSec === data.rangeMinutes * 60 && (data.sourceWindow
? data.sourceWindow.requestedMinutes === 5 && data.sourceWindow.effectiveMinutes === data.rangeMinutes
: data.rangeMinutes === 5)) &&
: data.rangeMinutes === 5) &&
data.namedBytes <= data.totalBytes && data.unclassifiedBytes <= data.totalBytes
)
export function validateNetworkMapDns(raw:unknown,hosts:string[]){
+2 -2
View File
@@ -47,7 +47,7 @@ test("Карта и трафик сохраняют пользователя и
await page.getByRole("combobox", {name: "Поиск пользователей"}).fill("Вход")
await expect(page.getByRole("option", {name:/Алиса.*Вход/})).toBeVisible()
await page.getByRole("option", {name: /Алиса/}).click()
await expect.poll(() => requests.some(request => request === `${flowPath}?range=1m&userId=${clientId}`)).toBe(true)
await expect.poll(() => requests.some(request => request === `${flowPath}?range=5m&userId=${clientId}`)).toBe(true)
await expect(panel.getByRole("heading", {name: "Алиса", exact: true})).toBeVisible()
await expect(panel.getByText(/gre-alice · gre, gre-alice-2/)).toBeVisible()
await expect(panel.getByText(/RX 8.*TX 12.*2\/2/)).toBeVisible()
@@ -80,7 +80,7 @@ test("Карта не приписывает весь YouTube единствен
if (path === flowPath && url.searchParams.get("range") === "24h") {
return route.fulfill({ json: { ...empty, rangeMinutes: 1440, windowSec: 86400, totalBytes: service.bytes, namedBytes: service.bytes, services: [service] } })
}
if (path === flowPath) expect(url.searchParams.get("range")).toBe("1m")
if (path === flowPath) expect(url.searchParams.get("range")).toBe("5m")
const responses: Record<string, unknown> = {
"/api/auth/config": {required: false}, "/api/servers": [{...server, type: "exit-node", name: "ARN"}],
"/api/filters/gre-tunnels": {tunnels: [], failures: []}, "/api/uptime/speed-probes": {probes: []},
+45
View File
@@ -105,6 +105,51 @@ test("Карта: группа сервисов сворачивается на
await page.screenshot({path:info.outputPath("карта-сети.png")})
})
test("Связи Cloudflare остаются на гранях экспортёра и подтверждённого выхода при перетаскивании", async ({ page }) => {
const service = { id: "svc:cloudflare", label: "Cloudflare", category: "Cloud", bytes: 10000, bps: 800, share: 1 }
const edge = { toId: service.id, bytes: 5000, bps: 400, bpsFwd: 400, bpsRev: 0 }
await serve(page, [srv(1, "nov-gw01", "jump-host"), srv(2, "ARN", "exit-node")], [], {
services: [service], serviceEdges: [{ ...edge, fromId: "1", observedOnly: true }, { ...edge, fromId: "2" }],
namedBytes: service.bytes, totalBytes: service.bytes,
})
await page.goto("/network-map")
const map = page.getByRole("group", { name: "Интерактивная карта сети" })
const arn = map.getByRole("button", { name: "Устройство ARN" })
const cloudflare = map.getByRole("button", { name: "Сервис Cloudflare" })
const exporter = map.getByRole("button", { name: "Устройство nov-gw01" })
await expect(cloudflare).toBeVisible()
async function attached() {
const connections = await map.evaluate(svg => {
const card = (name: string) => svg.querySelector(`[aria-label="${name}"] [data-map-box]`)!.getBoundingClientRect()
const atSide = (p: DOMPoint, r: DOMRect) =>
Math.min(Math.abs(p.x - r.left), Math.abs(p.x - r.right)) < 1 && Math.abs(p.y - (r.top + r.bottom) / 2) < 1
return [...svg.querySelectorAll<SVGPathElement>("[data-map-route]")].map(path => {
const transform = path.getScreenCTM()!
const start = path.getPointAtLength(0).matrixTransform(transform)
const end = path.getPointAtLength(path.getTotalLength()).matrixTransform(transform)
const source = path.dataset.mapRoute === "observation" ? "Устройство nov-gw01" : "Устройство ARN"
return atSide(start, card(source)) && atSide(end, card("Сервис Cloudflare"))
})
})
expect(connections).toEqual([true, true])
}
await attached()
async function center(node: typeof arn) {
const rect = (await node.boundingBox())!
return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }
}
const a = await center(arn)
await arn.dragTo(map, { targetPosition: { x: a.x - (await map.boundingBox())!.x + 30, y: a.y - (await map.boundingBox())!.y - 65 } })
expect(Math.abs((await center(arn)).y - a.y)).toBeGreaterThan(20)
await attached()
// Same column: before the fix the IPFIX route was replaced by a disconnected dot.
const jh = await center(exporter)
const bounds = (await map.boundingBox())!
await cloudflare.dragTo(map, {targetPosition: {x: jh.x - bounds.x, y: jh.y - bounds.y + 85}})
expect(Math.abs((await center(cloudflare)).x - (await center(exporter)).x)).toBeLessThan(15)
await attached()
})
test("Карта: сетка JH × Exit и аплинки WAN без наложений подписей", async ({ page }) => {
const wan = (i: number) => ({ id: "w" + i, name: "WAN" + i, iface: "ether" + i, isp: "ISP-" + i, ip: `198.51.100.${i}`, maxDl: 100, maxUl: 50 })
const servers = [
+12
View File
@@ -1,6 +1,7 @@
import { test } from "node:test"
import assert from "node:assert/strict"
import { MAP_CARD_H, MAP_CARD_W, MAP_PILL_H, mapLinkPath, mapLinkPoint, mapRibbons, placeMapLinkLabels, type MapBox } from "../../lib/network-map-layout"
import { mapObservationRoute } from "../../lib/network-map-observation-route"
const card = (x: number, y: number): MapBox => ({ x: x - MAP_CARD_W / 2, y: y - MAP_CARD_H / 2, w: MAP_CARD_W, h: MAP_CARD_H })
const hit = (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
@@ -13,6 +14,17 @@ test("кривая связи проходит через концы и сере
assert.deepEqual(mapLinkPoint(l, 0.5), { x: 100, y: 50 })
})
test("наблюдение IPFIX огибает промежуточный узел в обоих направлениях", () => {
const blocker = card(400, 100)
for (const [sourceX, serviceX] of [[100, 800], [800, 100]]) {
const link = mapLinkPath({x: sourceX, y: 100}, 80, {x: serviceX, y: 100}, 140)
const route = mapObservationRoute(link, [blocker], [])
assert.ok(route)
assert.ok(route.d.startsWith(`M ${link.x1} 100 `) && route.d.endsWith(`H ${link.x2}`))
assert.ok(route.track < blocker.y || route.track > blocker.y + blocker.h)
}
})
test("подписи не наезжают на карточки и друг на друга, длинная — укорачивается или пропадает", () => {
// Три JH слева сходятся в один EN справа; у каждой пары — длинный и короткий вариант подписи.
const jh = [100, 180, 260].map((y) => ({ x: 542, y }))