Compare commits

..
3 Commits
Author SHA1 Message Date
Denozordec 01779d7ee6 fix(scheduler): дождаться освобождения блокировки перед сбором метрик
Docker images / prepare-release (push) Successful in 9s
Docker images / updater-image (push) Successful in 3m22s
Docker images / frontend-image (push) Successful in 3m26s
Docker images / netflow-agent-image (push) Successful in 3m21s
Docker images / backend-test (push) Successful in 25m38s
Docker images / backend-image (push) Successful in 20m27s
Docker images / notify-webhook (push) Successful in 1s
Docker images / publish-release (push) Successful in 9s
2026-11-24 22:01:12 +07:00
Denozordec 1b927dcf68 fix(traffic): показывать показатели интерфейсов при неполных замерах
Docker images / prepare-release (push) Successful in 9s
Docker images / backend-test (push) Successful in 2s
Docker images / backend-image (push) Successful in 15s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 1m18s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 29s
Docker images / frontend-image (push) Successful in 6m50s
2026-11-24 16:37:50 +07:00
Denozordec af82497f20 fix(netflow): исправить учёт трафика по выходным узлам на карте сети
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m33s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 2m0s
Docker images / frontend-image (push) Successful in 7m41s
Docker images / publish-release (push) Successful in 33s
Docker images / notify-webhook (push) Successful in 1m55s
2026-11-24 15:41:44 +07:00
14 changed files with 377 additions and 266 deletions

No files matched your search

+22 -95
View File
@@ -356,85 +356,6 @@ function serviceSharePct(share: number): string {
return `${Math.round(share * 100)}%`
}
function exitNodeIdsFromGre(greEdges: GreMapEdge[]): string[] {
const ids = new Set<string>()
for (const g of greEdges) {
if (g.fromServer.type === "exit-node") ids.add(g.fromServer.id)
if (g.toServer.type === "exit-node") ids.add(g.toServer.id)
}
return [...ids]
}
function remapServiceEdgeFromId(
fromId: string,
servers: Server[],
greEdges: GreMapEdge[],
soleEnId: string | null,
): string | null {
const srv = servers.find((s) => s.id === fromId)
if (srv?.type === "exit-node") return fromId
for (const g of greEdges) {
if (g.fromServer.id === fromId && g.toServer.type === "exit-node") return g.toServer.id
if (g.toServer.id === fromId && g.fromServer.type === "exit-node") return g.fromServer.id
}
return soleEnId
}
/** API-рёбра на EN; если hop нет — синтез от единственного EN на карте (GRE / каталог). */
function drawableServiceEdges(
services: FlowMapService[],
edges: FlowMapServiceEdge[],
servers: Server[],
greEdges: GreMapEdge[],
nodePosById: Record<string, { x: number; y: number }>,
): FlowMapServiceEdge[] {
const keep = new Set(services.map((s) => s.id))
const greEn = exitNodeIdsFromGre(greEdges)
const catalogEn = servers.filter((s) => s.type === "exit-node").map((s) => s.id)
const enPool = greEn.length > 0 ? greEn : catalogEn
const soleEnId = enPool.length === 1 ? enPool[0]! : null
const merged = new Map<string, FlowMapServiceEdge>()
function bump(e: FlowMapServiceEdge) {
const key = `${e.fromId}|${e.toId}`
const prev = merged.get(key)
if (!prev) {
merged.set(key, { ...e })
return
}
merged.set(key, {
...prev,
bytes: prev.bytes + e.bytes,
bps: prev.bps + e.bps,
bpsFwd: prev.bpsFwd + e.bpsFwd,
bpsRev: prev.bpsRev + e.bpsRev,
})
}
for (const e of edges) {
if (!keep.has(e.toId)) continue
const fromId = remapServiceEdgeFromId(e.fromId, servers, greEdges, soleEnId)
if (!fromId || !nodePosById[fromId]) continue
bump({ ...e, fromId })
}
const covered = new Set([...merged.values()].map((e) => e.toId))
if (soleEnId && nodePosById[soleEnId]) {
for (const svc of services) {
if (covered.has(svc.id)) continue
bump({
fromId: soleEnId,
toId: svc.id,
bytes: svc.bytes,
bps: svc.bps,
bpsFwd: svc.bps,
bpsRev: 0,
})
}
}
return [...merged.values()]
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
function pingColor(ms: number | null) {
@@ -597,6 +518,11 @@ function GreEdgeMetricBadge({
)
}
// The badge shows download first. Destination edges are oriented from exit to service.
function destinationRate(edge: FlowMapServiceEdge): MatchedNetflowHop {
return { bytes: edge.bytes, bps: edge.bps, bpsFwd: edge.bpsRev, bpsRev: edge.bpsFwd }
}
/** Живой поток NetFlow (не ёмкость канала / не BT). */
function NetflowRateBadge({
mx,
@@ -626,7 +552,7 @@ function NetflowRateBadge({
onClick={(e) => { e.stopPropagation(); onOpen?.(e) }}
>
<title>
{sourceLabel ? sourceLabel + " · RX/TX интерфейса" : "Поток NetFlow между узлами за интервал карты, без overlay/mesh."}
{sourceLabel ? sourceLabel + " · RX/TX интерфейса" : "Средняя скорость по сохранённым потокам NetFlow за завершённые минуты."}
</title>
<rect className="network-map-focus-ring" x={-bw / 2 - 4} y={-bh / 2 - 4} width={bw + 8} height={bh + 8} rx="9" fill="none" stroke="var(--ring)" strokeWidth="2" />
<rect
@@ -1683,9 +1609,14 @@ function NetworkMapContent() {
const visibleMapServices = showServices ? destNodes : []
const visibleServiceEdges = showServices
? drawableServiceEdges(visibleMapServices, destEdges, mapServers, greEdges, nodePosById)
? destEdges.filter(edge => nodePosById[edge.fromId] && visibleMapServices.some(service => service.id === edge.toId))
: []
const selectedExitEdges = destEdges.filter(edge => edge.toId === liveSelectedService?.id)
const unassignedBytes = liveSelectedService
? liveSelectedService.bytes - selectedExitEdges.reduce((sum, edge) => sum + edge.bytes, 0)
: 0
const nodes = mapServers
.map((s) => ({ ...s, ...nodePosById[s.id]! }))
// Визуальный приоритет: HR поверх JH, JH поверх EN.
@@ -2636,12 +2567,7 @@ function NetworkMapContent() {
const from = nodeById[edge.fromId] ?? nodePosById[edge.fromId]
const to = servicePosById[edge.toId]
if (!from || !to) return null
const hop: MatchedNetflowHop = {
bytes: edge.bytes,
bps: edge.bps,
bpsFwd: edge.bpsFwd,
bpsRev: edge.bpsRev,
}
const hop = destinationRate(edge)
const fromR = "type" in from && from.type
? TYPE_STYLE[from.type].r
: TYPE_STYLE["exit-node"].r
@@ -2721,12 +2647,7 @@ function NetworkMapContent() {
const from = servicePosById[edge.fromId]
const to = nestedPosById[edge.toId]
if (!from || !to) return null
const hop: MatchedNetflowHop = {
bytes: edge.bytes,
bps: edge.bps,
bpsFwd: edge.bpsFwd,
bpsRev: edge.bpsRev,
}
const hop = destinationRate(edge)
const clipped = clipSegmentCircleToRect(
from.x,
from.y,
@@ -3207,7 +3128,7 @@ function NetworkMapContent() {
</div>
)}
<div className="flex items-center justify-between py-2 border-b border-border/50">
<span className="text-xs text-muted-foreground">Скорость</span>
<span className="text-xs text-muted-foreground">Скорость по сохранённым потокам</span>
<span className="text-xs font-mono font-medium [overflow-wrap:anywhere] text-right">
{formatNetflowRate({
bytes: liveSelectedService.bytes,
@@ -3244,7 +3165,13 @@ function NetworkMapContent() {
<div>
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2">Выход</p>
<div className="flex flex-col gap-3">
{visibleServiceEdges.filter((e) => e.toId === liveSelectedService.id).map((e) => {
{unassignedBytes > 0 && (
<div className="flex items-center justify-between text-xs">
<span>Выход не определён</span>
<span className="font-mono">{formatNetflowRate({ bps: liveSelectedService.bps * unassignedBytes / liveSelectedService.bytes })}</span>
</div>
)}
{selectedExitEdges.map((e) => {
const src = mapServers.find((s) => s.id === e.fromId)
const enPaths = destPaths
.filter((p) => p.serviceId === liveSelectedService.id && p.enId === e.fromId)
+19 -13
View File
@@ -2,7 +2,7 @@
import { useState, useMemo, useEffect, type ReactNode } from "react"
import { Alert, AlertTitle, AlertDescription } from "@/components/reui/alert"
import { peakOfCombinedTraffic, projectTrafficObservations, type TrafficObservationMeta } from "@/lib/traffic-observations"
import { peakOfCombinedTraffic, projectTrafficObservations, sumObservedTraffic, type TrafficObservationMeta } from "@/lib/traffic-observations"
import { projectTrafficBindingStatus } from "@/lib/traffic-binding-status"
import { TrafficObservationStatus } from "@/components/traffic/traffic-observation-status"
import { TrafficDataTime } from "@/components/traffic/traffic-data-time"
@@ -1143,11 +1143,17 @@ export default function TrafficPage() {
: effectiveMode === "ifaces"
? activeBoundIfaces
: activeServerTraffic
const totalRx = kpiSource.length && kpiSource.every(s => s.rxNow !== null) ? kpiSource.reduce((a, s) => a + (s.rxNow ?? 0), 0) : null
const totalTx = kpiSource.length && kpiSource.every(s => s.txNow !== null) ? kpiSource.reduce((a, s) => a + (s.txNow ?? 0), 0) : null
const allowPartialKpi = effectiveMode === "ifaces"
const totalRx = sumObservedTraffic(kpiSource.map(s => s.rxNow))
const totalTx = sumObservedTraffic(kpiSource.map(s => s.txNow))
const exactPeaks = effectiveMode === "servers" && trafficReady ? trafficState?.peaks : undefined
const peakRx = exactPeaks ? exactPeaks.rx : peakOfCombinedTraffic(kpiSource.map(s => s.rxSeries))
const peakTx = exactPeaks ? exactPeaks.tx : peakOfCombinedTraffic(kpiSource.map(s => s.txSeries))
const peakRx = exactPeaks ? { value: exactPeaks.rx, observed: kpiSource.length } : peakOfCombinedTraffic(kpiSource.map(s => s.rxSeries), allowPartialKpi)
const peakTx = exactPeaks ? { value: exactPeaks.tx, observed: kpiSource.length } : peakOfCombinedTraffic(kpiSource.map(s => s.txSeries), allowPartialKpi)
const coverageHint = (observed: number) => allowPartialKpi && observed > 0 && observed < kpiSource.length
? `${observed} из ${kpiSource.length} интерф.`
: undefined
const totalHint = effectiveMode === "servers" ? "Интерфейсы и туннели" : undefined
const peakHint = exactPeaks ? "По общим замерам" : "По интервалам графика"
const visibleSortFields = SORT_FIELDS.filter(s => !s.modesOnly || s.modesOnly.includes(effectiveMode))
const ingestLine = flowIngestLine(collectorStatus)
@@ -1192,32 +1198,32 @@ export default function TrafficPage() {
{
id: "rx",
label: "Сумма RX",
value: fmtRate(totalRx),
hint: effectiveMode === "servers" ? "Интерфейсы и туннели" : undefined,
value: fmtRate(allowPartialKpi || totalRx.observed === kpiSource.length ? totalRx.value : null),
hint: coverageHint(totalRx.observed) ?? totalHint,
icon: <ArrowDownIcon className="size-4" />,
iconClassName: "text-success",
},
{
id: "tx",
label: "Сумма TX",
value: fmtRate(totalTx),
hint: effectiveMode === "servers" ? "Интерфейсы и туннели" : undefined,
value: fmtRate(allowPartialKpi || totalTx.observed === kpiSource.length ? totalTx.value : null),
hint: coverageHint(totalTx.observed) ?? totalHint,
icon: <ArrowUpIcon className="size-4" />,
iconClassName: "text-info",
},
{
id: "peak-rx",
label: "Пик суммы RX",
value: fmtRate(peakRx),
hint: exactPeaks ? "По общим замерам" : "По интервалам графика",
value: fmtRate(peakRx.value),
hint: coverageHint(peakRx.observed) ?? peakHint,
icon: <TrendingUpIcon className="size-4" />,
iconClassName: "text-warning",
},
{
id: "peak-tx",
label: "Пик суммы TX",
value: fmtRate(peakTx),
hint: exactPeaks ? "По общим замерам" : "По интервалам графика",
value: fmtRate(peakTx.value),
hint: coverageHint(peakTx.observed) ?? peakHint,
icon: <TrendingUpIcon className="size-4" />,
iconClassName: "text-warning",
},
+1 -1
View File
@@ -49,7 +49,7 @@ export function registerFlowMapActions(register: typeof add) {
await authorize()
const output = { serverId: server.id, userId: input.userId ?? null, interface: input.interface ?? null, map: projected, pages, sourceWindow,
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false, listenerBound,
source: "retained flow_buckets plus pending for paths; interfaceTraffic includes private routed traffic in closed minutes before top-N",
source: "closed minutes for all rates; retained flows for services, exit exporter or observed GRE peer/next hop for paths; interfaceTraffic includes private routed traffic before top-N",
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,
referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false,
rowSumIsNetworkTotal: false, historicalOwnershipVerified: false,
+20 -1
View File
@@ -80,10 +80,29 @@ export async function withApplicationMutationLock<T>(work: () => Promise<T>, opt
/** Collectors coexist with each other but exclude configuration mutation for
* the complete native/sample/status operation. This lock grants no authority.
* Verified operations retain their original exact exclusive client protocol. */
export async function withApplicationCollectorLock<T>(work: () => Promise<T>): Promise<T> {
export async function withApplicationCollectorLock<T>(work: () => Promise<T>, { waitMs = 5000 }: { waitMs?: number } = {}): Promise<T> {
assertOperationConfigurationLockScope()
if (applicationLease.getStore()?.active || captureOperationConfigurationLockHandoff()) return withApplicationMutationLock(work)
if (collectorLease.getStore()?.active) return work()
const deadline = performance.now() + waitMs
for (;;) {
let admitted = false
try {
return await tryApplicationCollectorLock(() => {
admitted = true
return work()
})
} catch (error) {
const remaining = deadline - performance.now()
if (admitted || !(error instanceof ConfigurationBusyError) || remaining <= 0) throw error
// Release the failed attempt's connection before waiting for the writer.
await delay(Math.min(250, remaining))
if (performance.now() >= deadline) throw error
}
}
}
async function tryApplicationCollectorLock<T>(work: () => Promise<T>): Promise<T> {
let complete!: () => void
const completed = new Promise<void>(resolve => { complete = resolve })
const client = await pool.connect(), context = { active: true, completed }
@@ -100,6 +100,27 @@ export async function checkCatalogReadContention(serverId: number) {
const load = () => Promise.all([readFilterRulesCatalog([server], { source: "live", persistObserved: true }),
readRecursiveCatalogForServer(server), readRecursiveRoutesForServer(server)])
try {
const jobs = ["uptime_resources", "uptime_ping"]
const startedAt = new Date().toISOString()
const pending = await withApplicationMutationLock(async () => {
const runs = independent.runInAsyncScope(() => Promise.all(jobs.map(runSchedulerJobNow)))
const state = await Promise.race([runs.then(() => "finished", () => "failed"), delay(600, "waiting")])
assert.equal(state, "waiting", "Scheduler must wait for a transient exclusive lock")
await independent.runInAsyncScope(() => assert.rejects(
withApplicationCollectorLock(async () => assert.fail("Collector entered during a write"), { waitMs: 50 }),
ConfigurationBusyError,
))
return { runs }
})
assert.deepEqual((await pending.runs).map(run => run.status), ["ok", "ok"])
const { rows } = await pool.query("SELECT job_key,status FROM scheduler_runs WHERE started_at >= $1 AND job_key=ANY($2::text[]) ORDER BY job_key", [startedAt, jobs])
assert.deepEqual(rows, [{ job_key: "uptime_ping", status: "ok" }, { job_key: "uptime_resources", status: "ok" }])
let executions = 0
await assert.rejects(withApplicationCollectorLock(async () => {
executions++
throw new ConfigurationBusyError("server")
}), ConfigurationBusyError)
assert.equal(executions, 1, "An admitted collector must never be replayed")
const cold = await Promise.all(Array.from({ length: 24 }, load))
assert(cold.every(([filters, catalog, routes]) => filters[0].live && catalog.live && routes.live))
const revisions = () => pool.query("SELECT section,source FROM config_revisions WHERE server_id=$1 ORDER BY section,created_at", [server.id])
@@ -78,7 +78,7 @@ export async function readCatalogWithObservedCache<T extends { current: boolean
let done!: () => void
catalogRefreshes.set(serverId, new Promise(resolve => { done = resolve }))
try {
return await enterCatalogLock(work => withApplicationCollectorLock(() => withConfigMutationLock([serverId], work)), async () => {
return await enterCatalogLock(work => withApplicationCollectorLock(() => withConfigMutationLock([serverId], work), { waitMs: 0 }), async () => {
await assertCatalogSource(server)
const latest = await read(true)
return latest.current ? latest : save(latest)
+7 -6
View File
@@ -476,8 +476,9 @@ export function queueParsedFlows(serverId: number, flows: ParsedFlowInput[]): vo
if (prev) {
prev.bytes += flow.bytes
prev.packets += flow.packets
if (flow.outIface && !prev.flow.outIface) prev.flow.outIface = flow.outIface
if (flow.nextHop && !prev.flow.nextHop) prev.flow.nextHop = flow.nextHop
// This tuple is keyed by ingress. Only retain egress metadata shared by all its bytes.
if (prev.flow.outIface !== flow.outIface) prev.flow.outIface = ""
if (prev.flow.nextHop !== flow.nextHop) prev.flow.nextHop = ""
if (flow.natSrc && !prev.flow.natSrc) prev.flow.natSrc = flow.natSrc
if (flow.natDst && !prev.flow.natDst) prev.flow.natDst = flow.natDst
if (flow.natSrcPort && !prev.flow.natSrcPort) prev.flow.natSrcPort = flow.natSrcPort
@@ -554,8 +555,8 @@ function mergeInto(map: Map<string, PendingFlowRow>, row: PendingFlowRow): void
if (prev) {
prev.bytes += row.bytes
prev.packets += row.packets
if (row.outIface && !prev.outIface) prev.outIface = row.outIface
if (row.nextHop && !prev.nextHop) prev.nextHop = row.nextHop
if (prev.outIface !== row.outIface) prev.outIface = ""
if (prev.nextHop !== row.nextHop) prev.nextHop = ""
if (row.natSrc && !prev.natSrc) prev.natSrc = row.natSrc
if (row.natDst && !prev.natDst) prev.natDst = row.natDst
if (row.natSrcPort && !prev.natSrcPort) prev.natSrcPort = row.natSrcPort
@@ -964,8 +965,8 @@ async function upsertFlowBucketsBatch(rows: PendingFlowRow[]): Promise<void> {
DO UPDATE SET
bytes = flow_buckets.bytes + excluded.bytes,
packets = flow_buckets.packets + excluded.packets,
out_iface = CASE WHEN excluded.out_iface != '' THEN excluded.out_iface ELSE flow_buckets.out_iface END,
next_hop = COALESCE(excluded.next_hop, flow_buckets.next_hop),
out_iface = CASE WHEN flow_buckets.out_iface = excluded.out_iface THEN excluded.out_iface ELSE '' END,
next_hop = CASE WHEN flow_buckets.next_hop = excluded.next_hop THEN excluded.next_hop END,
flow_start_ms = CASE
WHEN excluded.flow_start_ms > 0 AND (flow_buckets.flow_start_ms = 0 OR excluded.flow_start_ms < flow_buckets.flow_start_ms)
THEN excluded.flow_start_ms ELSE flow_buckets.flow_start_ms END,
+2 -2
View File
@@ -429,8 +429,8 @@ function mergeInto(map: Map<string, PendingFlowRow>, row: PendingFlowRow): void
if (prev) {
prev.bytes += row.bytes
prev.packets += row.packets
if (row.outIface && !prev.outIface) prev.outIface = row.outIface
if (row.nextHop && !prev.nextHop) prev.nextHop = row.nextHop
if (prev.outIface !== row.outIface) prev.outIface = ""
if (prev.nextHop !== row.nextHop) prev.nextHop = ""
if (row.natSrc && !prev.natSrc) prev.natSrc = row.natSrc
if (row.natDst && !prev.natDst) prev.natDst = row.natDst
if (row.natSrcPort && !prev.natSrcPort) prev.natSrcPort = row.natSrcPort
@@ -102,6 +102,20 @@ disableRipePersistForTests()
resetRipeCacheForTests()
disableRipeEnqueueForTests()
const bucket = Math.floor(Date.now() / 60000) * 60000 - 60000
function ingestClosed(serverId: number, flows: Parameters<typeof ingestParsedFlowsForServerForTests>[1], at = bucket) {
const clock = mock.method(Date, "now", () => at)
try { ingestParsedFlowsForServerForTests(serverId, flows) } finally { clock.mock.restore() }
}
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},
] })])
const topo: FlowTopology = {
clientIfaces: new Map([[7, new Set(["gre-client"])]]),
clientByIface: new Map([["7|gre-client", {
@@ -134,7 +148,7 @@ rememberServerIfaces(3, [
{ ".id": "*1", name: "ether1-rt" },
])
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
{
src: "10.100.1.17",
dst: "8.8.8.8",
@@ -181,7 +195,7 @@ ingestParsedFlowsForServerForTests(7, [
outIface: "",
},
])
ingestParsedFlowsForServerForTests(3, [
ingestClosed(3, [
{
src: "192.168.1.10",
dst: "8.8.4.4",
@@ -292,7 +306,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" },
])
googleRipe()
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 600),
payloadFlow("11.0.113.50", 9400),
])
@@ -324,7 +338,7 @@ try {
assert.ok(usPath)
assert.equal(usPath.clientName, "Alice")
ingestParsedFlowsForServerForTests(7, [{ ...payloadFlow("8.8.8.8", 2000), proto: 17, dstPort: 51820 }])
ingestClosed(7, [{ ...payloadFlow("8.8.8.8", 2000), proto: 17, dstPort: 51820 }])
const mixedPeer = await buildFlowMapHops({ minutes: 5, serverId: 7, excludeOverlay: false })
assert.equal(mixedPeer.totalBytes, 12_000)
assert.equal(mixedPeer.namedBytes, 600, "WireGuard to the same peer is separate from the HTTPS service")
@@ -344,7 +358,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" },
])
googleRipe()
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 400),
payloadFlow("11.0.113.50", 9600),
])
@@ -378,7 +392,7 @@ rememberServerIfaces(7, [
{ ".id": "*2", name: "gre-client" },
{ ".id": "*3", name: "gre-jh-en" },
])
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 400),
payloadFlow("104.18.35.51", 400),
payloadFlow("11.0.113.50", 9200),
@@ -411,7 +425,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" },
])
seedRipeAsn("162.254.192.71", 32590, "VALVE-CORP")
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("162.254.192.71", 2000),
])
try {
@@ -433,7 +447,7 @@ rememberServerIfaces(7, [
{ ".id": "*2", name: "gre-client" },
{ ".id": "*3", name: "gre-jh-en" },
])
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("64.233.161.1", 10_000),
payloadFlow("11.0.113.50", 20_000),
])
@@ -484,7 +498,7 @@ rememberServerIfaces(7, [
])
googleRipe()
for (const b of smallBrands) seedRipeAsn(b.ip, b.asn, b.holder)
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 5000),
...smallBrands.map((b) => payloadFlow(b.ip, b.bytes)),
])
@@ -512,7 +526,7 @@ rememberServerIfaces(7, [
{ ".id": "*2", name: "gre-client" },
{ ".id": "*3", name: "gre-jh-en" },
])
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
{
src: "203.0.113.10",
dst: "198.51.100.1",
@@ -548,7 +562,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" },
])
googleRipe()
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
{
src: "10.100.1.17",
dst: "8.8.8.8",
@@ -613,7 +627,7 @@ rememberServerIfaces(7, [
{ ".id": "*2", name: "gre-client" },
{ ".id": "*3", name: "gre-jh-en" },
])
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
{
src: "173.194.151.65",
dst: "10.200.100.53",
@@ -622,9 +636,9 @@ ingestParsedFlowsForServerForTests(7, [
dstPort: 57182,
bytes: 9_000,
packets: 90,
inIface: "2",
outIface: "3",
nextHop: "198.51.100.1",
inIface: "3",
outIface: "2",
nextHop: "",
},
{
src: "104.18.35.51",
@@ -634,9 +648,9 @@ ingestParsedFlowsForServerForTests(7, [
dstPort: 53880,
bytes: 1_000,
packets: 10,
inIface: "2",
outIface: "3",
nextHop: "198.51.100.1",
inIface: "3",
outIface: "2",
nextHop: "",
},
])
try {
@@ -663,7 +677,7 @@ rememberServerIfaces(7, [
{ ".id": "*2", name: "gre-client" },
{ ".id": "*3", name: "gre-jh-en" },
])
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 500),
{
src: "173.194.151.65",
@@ -701,9 +715,9 @@ resetRipeCacheForTests()
disableRipeEnqueueForTests()
seedFlowTopologyForTests(topo)
rememberServerIfaces(7, [
{ ".id": "*1", name: "SWE-VEESP" },
{ ".id": "*1", name: "ether1" },
])
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
{
src: "173.194.151.65",
dst: "10.200.100.53",
@@ -720,16 +734,12 @@ ingestParsedFlowsForServerForTests(7, [
try {
resetFlowMapHopsCacheForTests()
const wanOnly = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
const googleEdge = wanOnly.serviceEdges?.find((e) => e.toId === "svc:youtube")
assert.ok(googleEdge, "YouTube WAN без GRE payload")
assert.equal(googleEdge.fromId, "9", "единственный EN, даже без nextHop")
assert.ok(googleEdge.bps > 0, "скорость на hop EN→сервис")
assert.ok(!(wanOnly.serviceEdges ?? []).some((e) => e.fromId === "7"), "нет пунктира с JH")
const googlePath = wanOnly.servicePaths?.find((p) => p.serviceId === "svc:youtube")
assert.ok(googlePath, "путь WAN YouTube")
assert.equal(googlePath.viaId, "7", "via = JH exporter")
assert.equal(googlePath.enId, "9", "якорь EN")
assert.ok(googlePath.bps > 0, "скорость на пути клиента")
assert.equal(wanOnly.services?.find(s => s.id === "svc:youtube")?.bytes, 9000)
assert.deepEqual(wanOnly.serviceEdges, [])
assert.deepEqual(wanOnly.servicePaths, [])
assert.deepEqual(wanOnly.countryEdges, [])
assert.ok(wanOnly.countryServiceGroups?.every(group => !group.edges.length && !group.paths.length))
} finally {
seedFlowTopologyForTests(null)
resetFlowRingsForTests()
@@ -751,8 +761,8 @@ rememberServerIfaces(9, [
{ ".id": "*1", name: "ether1" },
])
googleRipe()
ingestParsedFlowsForServerForTests(7, [payloadFlow("8.8.8.8", 12_000)])
ingestParsedFlowsForServerForTests(9, [{
ingestClosed(7, [payloadFlow("8.8.8.8", 12_000)])
ingestClosed(9, [{
src: "10.100.1.17",
dst: "8.8.8.8",
proto: 6,
@@ -796,7 +806,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" },
])
googleRipe()
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 8_000),
{
src: "8.8.8.8",
@@ -822,6 +832,8 @@ try {
assert.ok(!(bothDir.servicePaths ?? []).some((p) => p.serviceId === "svc:google" && p.clientId === "—"))
const googleEdge = bothDir.serviceEdges?.find((e) => e.toId === "svc:google" && e.fromId === "9")
assert.ok(googleEdge)
assert.equal(googleEdge.bpsFwd, 8000 * 8 / 300)
assert.equal(googleEdge.bpsRev, 4000 * 8 / 300)
assert.equal(googleEdge.bytes, 12_000)
assert.equal(googleEdge.bps, googlePaths[0]?.bps)
} finally {
@@ -852,7 +864,7 @@ seedRipeCacheForTests({
ok: true,
fetchedAt: Date.now(),
})
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 5000),
payloadFlow("185.45.12.10", 5000),
])
@@ -889,7 +901,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" },
])
googleRipe()
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 600),
payloadFlow("11.0.113.50", 9400),
])
@@ -942,7 +954,7 @@ seedRipeCacheForTests({
ok: true,
fetchedAt: Date.now(),
})
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 5000),
payloadFlow("185.45.12.10", 5000),
])
@@ -978,7 +990,7 @@ rememberServerIfaces(7, [
])
googleRipe()
for (const b of smallBrands) seedRipeAsn(b.ip, b.asn, b.holder)
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 5000),
...smallBrands.map((b) => payloadFlow(b.ip, b.bytes)),
])
@@ -1010,6 +1022,27 @@ try {
console.log("traffic-flow-map-hops.test.ts: ok")
// Identical destination/ports on two exits and the local WAN must remain separate.
seedFlowTopologyForTests({ ...topo, enNodes: [...topo.enNodes, {id: 10, name: "FIN", hosts: ["198.51.100.2"]}] })
try {
const flow = { ...payloadFlow("173.194.151.65", 0), nextHop: "", inIface: "gre-client" }
ingestClosed(7, [
{ ...flow, src: "10.0.0.1", bytes: 1000, outIface: "SWE-VEESP" },
{ ...flow, src: "10.0.0.2", bytes: 2000, outIface: "gre-second" },
{ ...flow, src: "10.0.0.3", bytes: 9000, outIface: "ether1" },
])
// This open minute must affect neither the service nor the link rate.
ingestParsedFlowsForServerForTests(7, [{ ...flow, bytes: 90000, outIface: "SWE-VEESP" }])
const map = await buildFlowMapHops({ serverId: 7, minutes: 5, minSharePct: 0 })
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.bytes, 12000)
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes]), [["10", 2000], ["9", 1000]])
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 3000)
} finally {
await dbQuery("DELETE FROM internet_path_snapshots WHERE id=?", [snapshot.id])
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(
@@ -1052,6 +1085,21 @@ try {
assert.deepEqual([b.rxBytes, b.txBytes, b.rxPackets, b.txPackets], [0, 192, 0, 3])
const overlay = await buildFlowMapHops({ serverId: sid, minutes: 5, iface: "gre-b", excludeOverlay: false })
assert.deepEqual(overlay.interfaceTraffic?.map(row => [row.iface, row.rxBytes, row.txBytes]), [["gre-b", 264, 192]])
// One tuple reroutes within a minute, first in memory and then across SQL flushes.
const routed = { ...payloadFlow("173.194.151.65", 1000), inIface: "mixed-lan", outIface: "uplink-a" }
const rerouted = { ...routed, outIface: "uplink-b", nextHop: "198.51.100.2" }
const split = { ...routed, srcPort: 40001 }
ingestClosed(sid, [routed, rerouted, routed, split], bucket - 60000)
await flushEngineNow({ prune: false })
ingestClosed(sid, [{ ...rerouted, srcPort: split.srcPort }], bucket - 60000)
await flushEngineNow({ prune: false })
ingestClosed(sid, [split], bucket - 60000)
const mixed = await buildFlowMapHops({serverId: sid, minutes: 5, iface: "mixed-lan"})
assert.equal(mixed.totalBytes, 6000)
assert.deepEqual(mixed.serviceEdges, [])
await flushEngineNow({ prune: false })
assert.deepEqual((await dbQuery("SELECT out_iface,next_hop FROM flow_buckets WHERE server_id=? AND in_iface='mixed-lan'", [sid])).rows,
[{out_iface: "", next_hop: null}, {out_iface: "", next_hop: null}])
const user = await buildFlowMapHops({serverId: sid, minutes: 5, userId: "no-interface-binding"})
assert.equal(user.interfaceTraffic, undefined)
console.log("CHR NetFlow v5 through PostgreSQL and map: GRE A RX / GRE B TX both 192 B, 3 packets; Top-200 and GRE encapsulation verified")
+109 -95
View File
@@ -10,14 +10,14 @@ import { OTHER_SERVICE, isNamedInternetService, mapCountryNodeId, mapCountryServ
import type { FlowIpMeta } from "./traffic-flow-ripe.js"
import { refreshFlowCatalogInBackground } from "./traffic-flow-classify.js"
import { collapseGreEspRows, dedupFlowRowsAcrossExporters, dedupFlowRowsMaxBytes } from "./traffic-flow-dedup.js"
import { getFlowListenerState, listFlowRowsForWindow } from "./traffic-flow-ingest.js"
import { getFlowListenerState, listStoredFlowRows } from "./traffic-flow-ingest.js"
import { resolveIfaceName } from "./traffic-flow-ifaces.js"
import { classifyFlowPlane, shouldKeepPlane } from "./traffic-flow-planes.js"
import { destCtxForIface, flowRateDirection, mapInternetBrand } from "./traffic-flow-dest.js"
import { resolveFlowEndpoints } from "./traffic-flow-ip.js"
import { geoipReadersStatus, resolveFlowIp } from "./traffic-flow-geoip.js"
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
import { loadFlowTopology, resolveClient, resolveEn, getServerCatalog, type FlowTopology } from "./traffic-flow-topology.js"
import { loadFlowTopology, resolveClient, getServerCatalog, type FlowTopology } from "./traffic-flow-topology.js"
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM } from "./traffic-flow-engine.js"
export const DEFAULT_MAP_SERVICE_MIN_SHARE_PCT = 5
@@ -61,6 +61,9 @@ interface ClientAcc {
}
interface FromAcc {
exporterId: string
enId: string
reverseBytes: number
bytes: number
clients: Map<string, ClientAcc>
}
@@ -111,16 +114,13 @@ function bumpClient(clients: Map<string, ClientAcc>, bytes: number, client: { us
clients.set(id, { name, bytes })
}
function bumpFrom(acc: DstAcc, exporterId: string, bytes: number, client: { userId: string; name: string } | null): void {
const prev = acc.fromBytes.get(exporterId)
if (prev) {
prev.bytes += bytes
bumpClient(prev.clients, bytes, client)
return
}
const clients = new Map<string, ClientAcc>()
bumpClient(clients, bytes, client)
acc.fromBytes.set(exporterId, { bytes, clients })
function bumpFrom(acc: DstAcc, exporterId: string, enId: string, bytes: number, reverse: boolean, client: { userId: string; name: string } | null): void {
const key = exporterId + "|" + enId
const from = acc.fromBytes.get(key) ?? { exporterId, enId, bytes: 0, reverseBytes: 0, clients: new Map<string, ClientAcc>() }
from.bytes += bytes
if (reverse) from.reverseBytes += bytes
bumpClient(from.clients, bytes, client)
acc.fromBytes.set(key, from)
}
let hopsCache: { key: string; at: number; dto: FlowMapHopsDto } | null = null
@@ -180,27 +180,24 @@ function bumpDestFrom(
}
if (prevEdge) {
prevEdge.bytes += from.bytes
prevEdge.bytesFwd += from.bytes
prevEdge.bytesFwd += from.bytes - from.reverseBytes
prevEdge.bytesRev += from.reverseBytes
for (const [id, name] of namedClients) prevEdge.clients.set(id, name)
} else {
edges.set(edgeKey, {
fromId: edgeFromId,
toId,
bytes: from.bytes,
bytesFwd: from.bytes,
bytesRev: 0,
bytesFwd: from.bytes - from.reverseBytes,
bytesRev: from.reverseBytes,
clients: namedClients,
})
}
for (const [clientId, c] of from.clients) {
const pathKey = `${clientId}|${fromId}|${toId}`
const pathKey = `${clientId}|${exporterId}|${fromId}|${toId}`
const prevPath = paths.get(pathKey)
if (prevPath) {
prevPath.bytes += c.bytes
if (exporterId !== fromId && prevPath.viaId === fromId) {
prevPath.viaId = exporterId
prevPath.viaName = viaName
}
if (prevPath.clientName === "—" && c.name !== "—") prevPath.clientName = c.name
} else {
paths.set(pathKey, {
@@ -413,13 +410,12 @@ async function resolveMinSharePct(q: FlowMapHopsQuery): Promise<number> {
}
// Closed minute buckets from every admitted export. Keep an hour of last-seen context for idle links.
async function readInterfaceTraffic(serverIds: number[], iface: string, q: FlowMapHopsQuery, now: number): Promise<FlowMapInterfaceTraffic[]> {
async function readInterfaceTraffic(serverIds: number[], iface: string, q: FlowMapHopsQuery, end: number): Promise<FlowMapInterfaceTraffic[]> {
if (!serverIds.length) return []
const { minutes } = q
// Private site-to-site flows are traffic on the link even when the destination graph hides mesh paths.
const planes = q.excludeOverlay === false ? ["payload", "client_mesh", "overlay"] : ["payload", "client_mesh"]
const dimensions = planes.flatMap(plane => [FLOW_IFACE_RX_DIM + ":" + plane, FLOW_IFACE_TX_DIM + ":" + plane])
const end = Math.floor(now / 60000) * 60000
const start = new Date(end - minutes * 60000).toISOString()
const rows = await flowReadDbAll<{server_id: number; key: string; dim: string; bytes: string; packets: string; last_at: Date | string}>(`
SELECT server_id, key, dim, COALESCE(SUM(bytes) FILTER (WHERE bucket_at >= ?), 0) AS bytes,
@@ -448,6 +444,38 @@ async function readInterfaceTraffic(serverIds: number[], iface: string, q: FlowM
return [...totals.values()].sort((a,b) => a.serverId.localeCompare(b.serverId) || a.iface.localeCompare(b.iface))
}
// 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 }[]) {
const peers = new Map<string, Map<string, string>>()
if (!rows.length) return peers
const buckets = new Set<string>(), names = 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
FROM unnest(?::text[]) AS b(bucket)
CROSS JOIN LATERAL (
SELECT payload_json FROM internet_path_snapshots
WHERE sampled_at < b.bucket::timestamptz + interval '1 minute'
AND sampled_at >= b.bucket::timestamptz - interval '15 minutes'
ORDER BY sampled_at DESC, id DESC LIMIT 1
) snapshot
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 t->>'enabled'='true' AND t->>'name'<>'' AND t->>'remoteAddress'<>''
`, [[...buckets], [...names]])
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)
}
return peers
}
async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number, scope?: ScopedFlowAnalyticsRead): Promise<FlowMapHopsDto> {
const authorize = scope?.authorize ?? (async () => {})
if (!scope) refreshFlowCatalogInBackground()
@@ -455,8 +483,9 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
const limits = scope ? await readFlowMapSourceLimits() : undefined
const windowSec = Math.max(60, q.minutes * 60)
await authorize()
const now = Date.now()
const raw = await listFlowRowsForWindow(q.minutes, q.serverId, { ...(scope ? { maxRows: scope.maxRows } : {}), untilIso: new Date(now).toISOString() })
const end = Math.floor(Date.now() / 60000) * 60000
const start = new Date(end - windowSec * 1000).toISOString()
const raw = await listStoredFlowRows(start, q.serverId, { ...(scope ? { maxRows: scope.maxRows } : {}), untilIso: new Date(end - 1).toISOString() })
if (scope && raw.some(row => row.serverId !== q.serverId)) throw new Error("Строка карты вне выбранного сервера")
await authorize()
const catalog = await getServerCatalog(scope?.serverIds)
@@ -510,7 +539,16 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
if (scope) flowCounterSum(working.map(row => row.bytes))
const hops = new Map<string, HopAcc>()
const dstAcc = new Map<string, DstAcc>()
const jhToEn = new Map<number, number>()
const hostIds = new Map<string, number | null>()
for (const node of topo.enNodes) for (const host of node.hosts) {
const key = host.trim().split("/")[0]!.toLowerCase()
if (!key || key === "0.0.0.0" || key === "::") continue
const previous = hostIds.get(key)
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; reverse: boolean }>()
const enIds = new Set(topo.enNodes.map((n) => n.id))
let totalBytes = 0
@@ -520,15 +558,6 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
return resolveMapClient(topo, r.serverId, inName, outName)
}
const payloadRows = wantDedup
? dedupFlowRowsAcrossExporters(working, (a, b) => {
const aCli = Boolean(rowClient(a))
const bCli = Boolean(rowClient(b))
if (aCli !== bCli) return aCli ? a : b
return a.bytes >= b.bytes ? a : b
})
: working
for (const r of working) {
const inRes = resolveIfaceName(r.serverId, r.inIface)
const outRes = resolveIfaceName(r.serverId, r.outIface)
@@ -573,20 +602,37 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
}
}
const enOut = ifaceUsable(outName) ? resolveEn(topo, r.nextHop, outName) : null
const enIn = ifaceUsable(inName) ? resolveEn(topo, "", inName) : null
const en = (enOut && enOut.id !== r.serverId ? enOut : null)
?? (enIn && enIn.id !== r.serverId ? enIn : null)
if (en) {
jhToEn.set(r.serverId, en.id)
const toId = String(en.id)
const dir: "fwd" | "rev" = enOut && enOut.id === en.id ? "fwd" : "rev"
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 peerId = outId && inId && outId !== inId ? null : outId ?? inId
const endpoints = resolveFlowEndpoints({
src: r.src,
dst: r.dst,
srcPort: r.srcPort,
dstPort: r.dstPort,
ctx: destCtxForIface(topo, r.serverId, inName, {
outIface: outName,
natSrc: r.natSrc,
natDst: r.natDst,
natSrcPort: r.natSrcPort,
natDstPort: r.natDstPort,
}),
})
const reverse = !!endpoints.internetPeer && (endpoints.internetPeer === endpoints.packetSrc || endpoints.internetPeer === r.natSrc)
const serviceSide = endpoints.internetPeer ? (reverse ? inId : outId) : peerId
const exitId = enIds.has(r.serverId) ? r.serverId : serviceSide ?? undefined
observed.set(r, { endpoints, exitId, reverse })
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)
bump(hops, JSON.stringify(["gre", fromId, toId, greIface]), {
fromId,
fromLabel,
toId,
toLabel: en.name,
toLabel: nodeName(toId),
kind: "gre",
iface: greIface,
}, r.bytes, dir)
@@ -616,44 +662,32 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
}
}
const payloadRows = wantDedup
? dedupFlowRowsAcrossExporters(working, (a, b) => {
const aRouted = observed.get(a)?.exitId !== undefined
const bRouted = observed.get(b)?.exitId !== undefined
if (aRouted !== bRouted) return aRouted ? a : b
const aCli = Boolean(rowClient(a))
const bCli = Boolean(rowClient(b))
if (aCli !== bCli) return aCli ? a : b
return a.bytes >= b.bytes ? a : b
})
: working
for (const r of payloadRows) {
const inName = resolveIfaceName(r.serverId, r.inIface).name
const outName = resolveIfaceName(r.serverId, r.outIface).name
totalBytes += r.bytes
const ep = resolveFlowEndpoints({
src: r.src,
dst: r.dst,
srcPort: r.srcPort,
dstPort: r.dstPort,
ctx: destCtxForIface(topo, r.serverId, inName, {
outIface: outName,
natSrc: r.natSrc,
natDst: r.natDst,
natSrcPort: r.natSrcPort,
natDstPort: r.natDstPort,
}),
})
const { endpoints: ep, exitId, reverse } = observed.get(r)!
const dst = ep.internetPeer
const dstPort = ep.peerPort || r.dstPort
const srcPort = ep.otherPort || r.srcPort
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : ""
const client = resolveMapClient(topo, r.serverId, inName, outName)
const prevDst = dstAcc.get(destKey)
if (prevDst) {
prevDst.bytes += r.bytes
bumpFrom(prevDst, String(r.serverId), r.bytes, client)
} else {
const acc: DstAcc = {
dst,
bytes: r.bytes,
proto: r.proto,
dstPort,
srcPort,
fromBytes: new Map(),
}
bumpFrom(acc, String(r.serverId), r.bytes, client)
dstAcc.set(destKey, acc)
}
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, proto: r.proto, dstPort, srcPort, fromBytes: new Map<string, FromAcc>() }
acc.bytes += r.bytes
if (exitId !== undefined) bumpFrom(acc, String(r.serverId), String(exitId), r.bytes, reverse, client)
dstAcc.set(destKey, acc)
}
const svcTotals = new Map<string, DestTotal>()
@@ -666,25 +700,6 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
const nestedEdges = new Map<string, DestEdgeAcc>()
const nestedPaths = new Map<string, DestPathAcc>()
for (const h of hops.values()) {
if (h.kind !== "gre" || !h.toId) continue
const from = Number(h.fromId)
const to = Number(h.toId)
if (!Number.isFinite(from) || !Number.isFinite(to)) continue
if (enIds.has(to) && !enIds.has(from)) jhToEn.set(from, to)
}
const soleEnId = topo.enNodes.length === 1 ? String(topo.enNodes[0]!.id) : null
function anchorEnId(exporterId: string): string | null {
const n = Number(exporterId)
if (enIds.has(n)) return exporterId
const mapped = jhToEn.get(n)
if (mapped != null) return String(mapped)
if (soleEnId) return soleEnId
return null
}
function nodeName(id: string): string {
const n = Number(id)
if (Number.isFinite(n)) {
@@ -708,9 +723,8 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes)
const nestedId = mapCountryServiceNodeId(country.id, svcId)
bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes)
for (const [exporterId, from] of acc.fromBytes) {
const fromId = anchorEnId(exporterId)
if (!fromId) continue
for (const from of acc.fromBytes.values()) {
const { exporterId, enId: fromId } = from
const enName = nodeName(fromId)
const viaName = nodeName(exporterId)
bumpDestFrom(svcEdges, svcPaths, svcId, from, exporterId, fromId, enName, viaName)
@@ -741,7 +755,7 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
if (scope && (!isDeepStrictEqual(topo, await loadFlowTopology(scope.serverIds, authorize)) || !isDeepStrictEqual(limits, await readFlowMapSourceLimits()))) throw new Error("Топология или пределы карты NetFlow изменились во время чтения")
await authorize()
// Whole-interface counters must never be exposed as per-user payload or added to totalBytes.
const interfaceTraffic = q.userId ? undefined : await readInterfaceTraffic(q.serverId ? [q.serverId] : [...catalog.byId.keys()], ifaceFilter, q, now)
const interfaceTraffic = q.userId ? undefined : await readInterfaceTraffic(q.serverId ? [q.serverId] : [...catalog.byId.keys()], ifaceFilter, q, end)
await authorize()
return {
...(interfaceTraffic ? { interfaceTraffic } : {}),
+12 -6
View File
@@ -1,5 +1,5 @@
import assert from "node:assert/strict"
import { peakOfCombinedTraffic, projectTrafficObservations } from "./traffic-observations.js"
import { peakOfCombinedTraffic, projectTrafficObservations, sumObservedTraffic } from "./traffic-observations.js"
const at=Date.parse("2026-10-12T12:00:00Z"),sampledAt=new Date(at).toISOString(),expiresAt=new Date(at+90_000).toISOString()
const row={rxNow:0,txNow:0,rxPeak:0,txPeak:0,rxTotal:0,txTotal:0,rxSeries:[0,0],txSeries:[0,0]}
const obs={rxNow:true,txNow:true,rxSeries:[false,true],txSeries:[false,true],sampledAt,currentState:"current",expiresAt}
@@ -16,8 +16,14 @@ const noPeak=projectTrafficObservations({...row,volumeUnit:"GiB",observations:{.
assert.equal(noPeak.rxPeak,null);assert.equal(noPeak.txPeak,null);assert.equal(noPeak.rxTotal,0)
assert.equal(projectTrafficObservations({...row,observations:{...obs,rxPeak:true,txPeak:true}},at).rxPeak,0)
console.log('aggregate peak confidence overrides bucket confidence; measured zero and volumes retained')
assert.equal(peakOfCombinedTraffic([[10, 3, 20], [4, 15, null]]), 18)
assert.equal(peakOfCombinedTraffic([[0, null], [0, 50]]), 0)
assert.equal(peakOfCombinedTraffic([[null, 10], [4, null]]), null)
assert.equal(peakOfCombinedTraffic([[2], [4, 5]]), null)
assert.equal(peakOfCombinedTraffic([]), null)
assert.equal(peakOfCombinedTraffic([[10, 3, 20], [4, 15, null]]).value, 18)
assert.equal(peakOfCombinedTraffic([[0, null], [0, 50]]).value, 0)
assert.equal(peakOfCombinedTraffic([[null, 10], [4, null]]).value, null)
assert.equal(peakOfCombinedTraffic([[2], [4, 5]]).value, null)
assert.equal(peakOfCombinedTraffic([]).value, null)
assert.deepEqual(sumObservedTraffic([null, 0]), { value: 0, observed: 1 })
assert.deepEqual(sumObservedTraffic([null, null]), { value: null, observed: 0 })
assert.deepEqual(peakOfCombinedTraffic([[10, 3], [4, 15], [null, null]], true), { value: 18, observed: 2 })
assert.deepEqual(peakOfCombinedTraffic([[10, 5], [null, 5]], true), { value: 10, observed: 2 })
assert.deepEqual(peakOfCombinedTraffic([[100, 5], [null, 5]], true), { value: 100, observed: 1 })
assert.deepEqual(peakOfCombinedTraffic([[null], [null]], true), { value: null, observed: 0 })
+19 -8
View File
@@ -7,16 +7,27 @@ const meta = z.object({ rxNow: z.boolean(), txNow: z.boolean(), rxSeries: z.arra
currentState: z.enum(["current", "unknown", "pending", "error", "stale", "disabled"]).optional() })
export type TrafficObservationMeta = z.infer<typeof meta>
/** Sum only intervals with an observation from every series. */
export function peakOfCombinedTraffic(series: readonly (readonly (number | null)[])[]): number | null {
export function sumObservedTraffic(rates: readonly (number | null)[]) {
let sum = 0
let observed = 0
for (const rate of rates) {
if (rate === null) continue
sum += rate
observed++
}
return { value: observed > 0 ? sum : null, observed }
}
export function peakOfCombinedTraffic(series: readonly (readonly (number | null)[])[], allowPartial = false) {
const length = series[0]?.length
if (!length || series.some(values => values.length !== length)) return null
let peak: number | null = null
let peak = { value: null as number | null, observed: 0 }
if (!length || series.some(values => values.length !== length)) return peak
for (let index = 0; index < length; index++) {
const slots = series.map(values => values[index])
if (slots.some(value => value == null)) continue
const sum = slots.reduce<number>((total, value) => total + (value ?? 0), 0)
peak = peak === null ? sum : Math.max(peak, sum)
const bucket = sumObservedTraffic(series.map(values => values[index]))
if (bucket.value === null || (!allowPartial && bucket.observed !== series.length)) continue
if (peak.value === null || bucket.value > peak.value || (bucket.value === peak.value && bucket.observed > peak.observed)) {
peak = bucket
}
}
return peak
}
+27
View File
@@ -4,6 +4,33 @@ const flowPath="/api/traffic/flow/map-hops"
test.beforeEach(async({page})=>{await page.route("**/health",r=>r.fulfill({json:{ok:true}}))})
const server={id:1,name:"Router",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online"}
test("Карта не приписывает весь YouTube единственному выходу ARN", async ({page}) => {
const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1}
const edge = {fromId: "1", toId: service.id, bytes: 300000, bps: 8000, bpsFwd: 2000, bpsRev: 6000}
let known = false
await page.route("**/api/**", route => {
const path = new URL(route.request().url()).pathname
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: []},
[flowPath]: {...empty, totalBytes: service.bytes, namedBytes: service.bytes, services: [service], serviceEdges: known ? [edge] : []},
}
return route.fulfill({json: responses[path] ?? {}})
})
await page.goto("/network-map")
await page.getByRole("button", {name: "Сервис YouTube", exact: true}).press("Enter")
const unknown = page.getByText("Выход не определён", {exact: true}).locator("..")
const badges = page.getByRole("button", {name: "Поток NetFlow между узлами"})
await expect(unknown).toContainText("24 Кбит/с")
await expect(badges).toHaveCount(0)
known = true
await page.getByRole("button", {name: "Обновить", exact: true}).click()
await expect(unknown).toContainText("16 Кбит/с")
await expect(badges).toHaveCount(1)
await expect(badges).toContainText("8 Кбит/с")
await expect(badges).toContainText("↓6 Кбит/с ↑2 Кбит/с")
})
for (const reverse of [false, true]) test(`Карта: малый NetFlow и текущие RX/TX GRE показаны отдельно, reverse=${reverse}`, async ({ page }) => {
const exit = { ...server, name: "ARN", type: "exit-node" }
const jump = { ...server, id: 2, name: "MSK-02", host: "192.0.2.2", type: "jump-host" }
+31
View File
@@ -1,4 +1,5 @@
import {test,expect} from '@playwright/test'
import {observedTrafficFixturePayload} from "./traffic-observation-fixture"
for(const width of [1440,320])test(`Пик трафика: неизвестный интервал, подтверждённый пик и ноль ${width}`,async({page})=>{
await page.setViewportSize({width,height:1000})
let peakKnown=false,peak=100
@@ -23,3 +24,33 @@ for(const width of [1440,320])test(`Пик трафика: неизвестны
await expect(peakCard).toContainText('0')
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1)).toBe(true)
})
test("Интерфейсы: один интерфейс без замеров не очищает суммы и пики", async ({page}) => {
const metrics = {rxNow: 2, txNow: 3, rxPeak: 8, txPeak: 9, rxTotal: 1, txTotal: 2, rxSeries: [8, 2], txSeries: [9, 3]}
const iface = {id: "i1", bindingId: "b1", userId: "u1", userLogin: "test", userName: "Тест",
interfaceName: "gre-a", interfaceType: "gre", comment: "", serverId: "1", serverName: "CHR",
serverSite: "TEST", serverCountry: "RU", status: "online"}
const interfaces = [
{...iface, ...metrics},
{...iface, ...metrics, id: "i2", bindingId: "b2", interfaceName: "gre-b", rxNow: 1, txNow: 2, rxSeries: [1, 7], txSeries: [2, 8]},
{...iface, ...metrics, id: "i3", bindingId: "b3", interfaceName: "gre-c", status: "unknown",
observations: {rxNow: false, txNow: false, rxSeries: [false, false], txSeries: [false, false],
sampledAt: null, currentState: "unknown"}},
]
await page.route("**/health", route => route.fulfill({json: {ok: true}}))
await page.route("**/api/**", route => {
const path = new URL(route.request().url()).pathname
const responses: Record<string, unknown> = {
"/api/auth/config": {required: false}, "/api/traffic/servers": {servers: []},
"/api/traffic/users": {users: []}, "/api/traffic/bound-interfaces": {interfaces}, "/api/servers": [],
}
return route.fulfill({json: observedTrafficFixturePayload(responses[path] ?? {})})
})
await page.goto("/traffic")
await page.getByRole("button", {name: "Интерфейсы", exact: true}).click()
for (const [label, value] of [["Сумма RX", "3"], ["Сумма TX", "5"], ["Пик суммы RX", "9"], ["Пик суммы TX", "11"]]) {
const card = page.locator('[data-slot="frame-panel"]').filter({has: page.getByText(label, {exact: true})})
await expect(card.getByText(new RegExp(`^${value}(?:[.,]0+)? Мбит/с$`))).toBeVisible()
await expect(card.getByText("2 из 3 интерф.", {exact: true}).filter({visible: true})).toBeVisible()
}
})