Files
MikrotikManager/backend/src/services/traffic-flow-analytics.ts
T
Denozordec b896e469a7
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m31s
Docker images / frontend-image (push) Successful in 2m18s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 31s
Docker images / backend-image (push) Successful in 2m11s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
feat(mcp): добавить диагностику инцидентов и проверку отказоустойчивости сети
2026-11-27 17:21:20 +07:00

845 lines
35 KiB
TypeScript

import { flowReadDbAll } from "./traffic-flow-read-policy.js"
import { readFlowWindow } from "./traffic-flow-read-window.js"
import { isDeepStrictEqual } from "node:util"
import { readFlowSourceLimits } from "./traffic-flow-source-limits.js"
import { readFlowExporterInputs, readFlowClientInputs, flowCounter, flowCounterSum } from "./traffic-flow-catalog-read.js"
import type {
FlowAnalyticsDto,
FlowBreakdownRow,
FlowEntityCard,
FlowExportersDto,
FlowMapEdge,
FlowMonthlyDto,
FlowPathRow,
FlowTalkerDto,
} from "@mmapp/contracts/traffic-flow"
import { protoName } from "./traffic-flow-parse.js"
import {
getFlowListenerState,
getFlowRuntimeCounters,
getFlowWorkerHealth,
getRingMbps,
listFlowRowsForWindow,
type PendingFlowRow,
} from "./traffic-flow-ingest.js"
import { ADMITTED_FLOW_DAY_DIM, flowDataEpoch, MAX_PENDING, OBSERVED_FLOW_IFACE_COVERAGE_DIM, OBSERVED_FLOW_IFACE_DIM } from "./traffic-flow-engine.js"
import { resolveIfaceName } from "./traffic-flow-ifaces.js"
import { factIfaceAliases } from "./traffic-flow-ifindex.js"
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
import { applicationName, flowRowMatchesFilter } from "./traffic-flow-apps.js"
import { canonicalIp, ipv6ToInt } from "./traffic-flow-ip.js"
import { collapseGreEspRows, dedupFlowRowsMaxBytes, flowTupleKey } from "./traffic-flow-dedup.js"
import { enqueueRipeMisses } from "./traffic-flow-ripe.js"
import { classifyFlowPlane, flowBps, shouldKeepPlane } from "./traffic-flow-planes.js"
import { flowRateDirection, resolveInternetDest } from "./traffic-flow-dest.js"
import { refreshFlowCatalogInBackground } from "./traffic-flow-classify.js"
import {
enGreIfaceNames,
getServerCatalog,
latestWireBps,
loadFlowTopology,
flowClientInterfaces,
resolveFlowClient,
resolveEn,
} from "./traffic-flow-topology.js"
export const LIVE_ANALYTICS_MINUTES = 5
const LIVE_DEGRADED_PENDING = Math.floor(MAX_PENDING * 0.8)
export interface FlowAnalyticsQuery {
minutes: number
serverId?: number
userId?: string
iface?: string
tuple?: { srcIp?: string; dstIp?: string; srcPort?: number; dstPort?: number; protocol?: number }
/** Default true: один 5-tuple за минуту = max байт по ifaces. */
dedup?: boolean
/** Default true: скрыть GRE/WG между клиентами JH. */
excludeMesh?: boolean
/** Default true: скрыть overlay GRE/ESP JH↔EN из payload KPI. */
excludeOverlay?: boolean
skipHeavy?: boolean
}
function bpsToMbps(bps: number): number {
return bps / 1_000_000
}
function topN(
map: Map<string, { bytes: number; packets: number; label?: string }>,
windowSec: number,
n: number,
): FlowBreakdownRow[] {
const total = [...map.values()].reduce((a, v) => a + v.bytes, 0) || 1
return [...map.entries()]
.sort((a, b) => b[1].bytes - a[1].bytes)
.slice(0, n)
.map(([id, v]) => ({
id,
label: v.label || id,
bytes: v.bytes,
packets: v.packets,
bps: (v.bytes * 8) / windowSec,
percent: (v.bytes / total) * 100,
}))
}
function bump(
map: Map<string, { bytes: number; packets: number; label?: string }>,
id: string,
bytes: number,
packets: number,
label?: string,
) {
const prev = map.get(id) ?? { bytes: 0, packets: 0, label }
prev.bytes += bytes
prev.packets += packets
if (label) prev.label = label
map.set(id, prev)
}
function seriesFromRows(rows: PendingFlowRow[], minutes: number, direction: (row: PendingFlowRow) => "rx" | "tx" | "both" | null, now = Date.now()) {
const slots = Math.min(60, Math.max(5, minutes))
const slotMs = (minutes * 60_000) / slots
const start = now - minutes * 60_000
const rx = Array(slots).fill(0) as number[]
const tx = Array(slots).fill(0) as number[]
let undirectedBytes = 0
for (const r of rows) {
const t = Date.parse(r.bucketAt)
if (!Number.isFinite(t)) continue
const idx = Math.min(slots - 1, Math.max(0, Math.floor((t - start) / slotMs)))
const side = direction(r)
if (side === null) undirectedBytes += r.bytes
if (side === "rx" || side === "both") rx[idx] += r.bytes
if (side === "tx" || side === "both") tx[idx] += r.bytes
}
const slotSec = Math.max(1, slotMs / 1000)
return {
rx: rx.map((b) => bpsToMbps((b * 8) / slotSec)),
tx: tx.map((b) => bpsToMbps((b * 8) / slotSec)),
rxNow: bpsToMbps(rx.reduce((a, b) => a + b, 0) * 8 / (minutes * 60)),
txNow: bpsToMbps(tx.reduce((a, b) => a + b, 0) * 8 / (minutes * 60)),
undirectedBytes,
}
}
function snapshotStatus(serverId: number): FlowEntityCard["status"] {
void serverId
return "online"
}
function topLabel(map: Map<string, { bytes: number; packets: number; label?: string }>, fallback = "—"): string {
let best = fallback
let bestBytes = 0
for (const [id, v] of map) {
if (v.bytes > bestBytes) {
bestBytes = v.bytes
best = v.label || id
}
}
return best
}
export interface ScopedFlowAnalyticsRead { serverIds: readonly number[]; maxRows: number; authorize: () => Promise<unknown> }
export async function buildFlowAnalytics(q: FlowAnalyticsQuery, scope?: ScopedFlowAnalyticsRead): Promise<FlowAnalyticsDto> {
if (scope) {
if (!Number.isSafeInteger(q.serverId) || !scope.serverIds.includes(q.serverId!) || !Number.isSafeInteger(scope.maxRows) || scope.maxRows < 1 || scope.maxRows > 50000 || !Number.isSafeInteger(q.minutes) || q.minutes < 1 || q.minutes > 1440) throw new Error("Некорректная область аналитики NetFlow")
await scope.authorize()
const dto = await buildFlowAnalyticsUncached(q, scope)
await scope.authorize()
return dto
}
const key = analyticsQueryKey(q)
const now = Date.now()
if (analyticsCache && analyticsCache.key === key && now - analyticsCache.at < ANALYTICS_CACHE_TTL_MS) {
return analyticsCache.dto
}
const dto = await buildFlowAnalyticsUncached(q)
analyticsCache = { key, at: now, dto }
return dto
}
export const resetFlowAnalyticsCacheForTests = invalidateFlowAnalyticsCache
export function invalidateFlowAnalyticsCache(): void {
analyticsCache = null
}
function analyticsQueryKey(q: FlowAnalyticsQuery): string {
return JSON.stringify({
epoch: flowDataEpoch(),
minutes: q.minutes,
serverId: q.serverId ?? null,
userId: q.userId ?? null,
iface: q.iface ?? null,
tuple: q.tuple ?? null,
dedup: q.dedup !== false,
excludeMesh: q.excludeMesh !== false,
excludeOverlay: q.excludeOverlay !== false,
skipHeavy: Boolean(q.skipHeavy),
})
}
const ANALYTICS_CACHE_TTL_MS = 2000
let analyticsCache: { key: string; at: number; dto: FlowAnalyticsDto } | null = null
async function readAdmittedFlowTotals(serverId: number, iface: string, minutes: number, now: number): Promise<FlowAnalyticsDto["admittedTotals"]> {
const end = Math.floor(now / 60_000) * 60_000
const from = new Date(end - minutes * 60_000).toISOString(), to = new Date(end).toISOString()
type Totals = { bytes: number | string; packets: number | string; count: number; missing?: number }
const params = [serverId, from, to]
const [totals] = iface
? await flowReadDbAll<Totals>(`
SELECT COALESCE(SUM(observed.bytes), 0) AS bytes, COALESCE(SUM(observed.packets), 0) AS packets,
COUNT(*)::int AS count,
COUNT(*) FILTER (WHERE coverage.bytes IS DISTINCT FROM s.bytes OR coverage.packets IS DISTINCT FROM s.packets)::int AS missing
FROM flow_minute_stats s
LEFT JOIN flow_minute_dims coverage ON coverage.server_id = s.server_id AND coverage.bucket_at = s.bucket_at
AND coverage.dim = ? AND coverage.key = 'all'
LEFT JOIN LATERAL (
SELECT SUM(d.bytes) AS bytes, SUM(d.packets) AS packets
FROM flow_minute_dims d
WHERE d.server_id = s.server_id AND d.bucket_at = s.bucket_at AND d.dim = ? AND d.key = ANY(?::text[])
) observed ON true
WHERE s.server_id = ? AND s.bucket_at >= ? AND s.bucket_at < ?
`, [OBSERVED_FLOW_IFACE_COVERAGE_DIM, OBSERVED_FLOW_IFACE_DIM, factIfaceAliases(iface, serverId), ...params])
: await flowReadDbAll<Totals>(`
SELECT COALESCE(SUM(bytes), 0) AS bytes, COALESCE(SUM(packets), 0) AS packets, COUNT(*)::int AS count
FROM flow_minute_stats WHERE server_id = ? AND bucket_at >= ? AND bucket_at < ?
`, params)
// A minute can contain writes by both old and new collectors after an upgrade.
if (!totals?.count || totals.missing) return undefined
return { bytes: flowCounter(totals.bytes), packets: flowCounter(totals.packets), from, to, minutesWithData: totals.count }
}
async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedFlowAnalyticsRead): Promise<FlowAnalyticsDto> {
const authorize = scope?.authorize ?? (async () => {})
await authorize()
const settings = scope ? await readFlowSourceLimits() : await getTrafficFlowSettingsRow()
const top = Math.min(50, Math.max(10, settings.topN))
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() })
for (const row of raw) if (scope && (!scope.serverIds.includes(row.serverId) || !Number.isSafeInteger(row.bytes) || row.bytes < 0 || !Number.isSafeInteger(row.packets) || row.packets < 0)) throw new Error("Недостоверная строка аналитики NetFlow")
await authorize()
const catalog = await getServerCatalog(scope ? [q.serverId!] : undefined)
const nameById = new Map([...catalog.byId].map(([id, s]) => [id, s.name]))
const countryById = new Map([...catalog.byId].map(([id, s]) => [id, s.country]))
const ifaceFilter = q.iface && q.iface !== "__all__" ? q.iface : ""
const wantDedup = q.dedup !== false && !ifaceFilter
const excludeMesh = q.excludeMesh !== false
const excludeOverlay = q.excludeOverlay !== false
await authorize()
const topo = await loadFlowTopology(scope?.serverIds, authorize)
const allow = q.userId ? flowClientInterfaces(topo, q.userId) : null
if (scope && q.userId && !allow?.size) throw new Error("Пользователь не найден в разрешённой топологии")
if (!scope) refreshFlowCatalogInBackground()
const matchesIngress = (row: PendingFlowRow) => flowRowMatchesFilter(row, resolveIfaceName(row.serverId, row.inIface).name, q, allow)
const matchesEgress = (row: PendingFlowRow) => flowRowMatchesFilter({ serverId: row.serverId, inIface: row.outIface }, resolveIfaceName(row.serverId, row.outIface).name, q, allow)
const serverDirection = (row: PendingFlowRow) => flowRateDirection(row.serverId, row, topo, catalog.byId.get(row.serverId)?.host)
const interfaceDirection = (row: PendingFlowRow) => {
const ingress = matchesIngress(row), egress = matchesEgress(row)
return ingress === egress ? null : ingress ? "rx" : "tx"
}
const visible = ifaceFilter || allow ? raw.filter(row => (matchesIngress(row) || matchesEgress(row)) &&
(!q.userId || resolveFlowClient(topo, row.serverId, resolveIfaceName(row.serverId, row.inIface).name, resolveIfaceName(row.serverId, row.outIface).name)?.userId === q.userId)) : raw
const tuple = q.tuple
const ipKey = (value: string) => {
const ip = canonicalIp(value)
return ip.includes(":") ? ipv6ToInt(ip) ?? ip : ip
}
const src = tuple?.srcIp === undefined ? undefined : ipKey(tuple.srcIp)
const dst = tuple?.dstIp === undefined ? undefined : ipKey(tuple.dstIp)
const selected = tuple ? visible.filter(row =>
(src === undefined || src === ipKey(row.src)) &&
(dst === undefined || dst === ipKey(row.dst)) &&
(tuple.srcPort === undefined || tuple.srcPort === row.srcPort) &&
(tuple.dstPort === undefined || tuple.dstPort === row.dstPort) &&
(tuple.protocol === undefined || tuple.protocol === row.proto)) : visible
const { rows, espDirections } = collapseGreEspRows(selected, ifaceFilter ? interfaceDirection : serverDirection)
const previousMinute = new Date(Math.floor(now / 60_000) * 60_000 - 60_000).toISOString()
const ifacesForWire = new Set<string>()
for (const row of selected) {
ifacesForWire.add(resolveIfaceName(row.serverId, row.inIface).name)
const egress = resolveIfaceName(row.serverId, row.outIface).name
if (egress && egress !== "—") ifacesForWire.add(egress)
}
const applications = new Map<string, { bytes: number; packets: number; label?: string }>()
const protocols = new Map<string, { bytes: number; packets: number; label?: string }>()
const sources = new Map<string, { bytes: number; packets: number; label?: string }>()
const destinations = new Map<string, { bytes: number; packets: number; label?: string }>()
const ifacesMap = new Map<string, { bytes: number; packets: number; index: string }>()
const asns = new Map<string, { bytes: number; packets: number; label?: string }>()
const countries = new Map<string, { bytes: number; packets: number; label?: string }>()
const categories = new Map<string, { bytes: number; packets: number; label?: string }>()
const services = new Map<string, { bytes: number; packets: number; label?: string }>()
const conv = new Map<string, FlowTalkerDto & { rawBytes: number; flowStartMs: number; flowEndMs: number }>()
const edgeAcc = new Map<string, FlowMapEdge & { catBytes: Map<string, number> }>()
const pathAcc = new Map<string, FlowPathRow>()
const srcs = new Set<string>()
const dsts = new Set<string>()
const peers = new Set<string>()
const matched: PendingFlowRow[] = []
const skipHeavy = Boolean(q.skipHeavy)
let bytesPayload = 0
let bytesOverlay = 0
let recentOverlayBytes = 0
let bytesMesh = 0
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,
}, topo.plane)
if (plane === "payload") bytesPayload += r.bytes
else if (plane === "overlay") {
bytesOverlay += r.bytes
if (r.bucketAt === previousMinute) recentOverlayBytes += r.bytes
}
else if (plane === "client_mesh") bytesMesh += r.bytes
if (!shouldKeepPlane(plane, { excludeMesh, excludeOverlay })) continue
matched.push(r)
}
const working = wantDedup ? dedupFlowRowsMaxBytes(matched) : matched
const conversationsRaw = new Set(matched.map((r) => `${flowTupleKey(r)}|${r.inIface}`)).size
const conversations = wantDedup ? new Set(working.map(flowTupleKey)).size : conversationsRaw
let totalBytes = 0
let totalPackets = 0
for (const r of working) {
const resolved = resolveIfaceName(r.serverId, r.inIface)
const outResolved = resolveIfaceName(r.serverId, r.outIface)
const ingressAccounts = ifaceFilter || allow ? matchesIngress(r) : resolved.name !== "—"
const accounted = ingressAccounts ? resolved : outResolved
const ifaceTotal = ifacesMap.get(accounted.name) ?? { bytes: 0, packets: 0, index: accounted.index }
ifaceTotal.bytes += r.bytes
ifaceTotal.packets += r.packets
ifacesMap.set(accounted.name, ifaceTotal)
totalBytes += r.bytes
totalPackets += r.packets
const destMeta = resolveInternetDest({
src: r.src,
dst: r.dst,
proto: r.proto,
srcPort: r.srcPort,
dstPort: r.dstPort,
serverId: r.serverId,
inIface: resolved.name,
outIface: outResolved.name,
topo,
natSrc: r.natSrc,
natDst: r.natDst,
natSrcPort: r.natSrcPort,
natDstPort: r.natDstPort,
})
const ep = destMeta.endpoints
const src = ep.packetSrc || r.src
const dst = ep.packetDst || r.dst
srcs.add(src)
dsts.add(dst)
if (destMeta.dest) peers.add(destMeta.dest)
const app = applicationName(r.proto, ep.peerPort || r.dstPort, ep.otherPort || r.srcPort)
const ripe = destMeta.ripe
const classified = destMeta.classified
bump(applications, app, r.bytes, r.packets)
bump(protocols, protoName(r.proto), r.bytes, r.packets)
bump(sources, src, r.bytes, r.packets)
bump(destinations, dst, r.bytes, r.packets)
bump(categories, classified.category, r.bytes, r.packets)
bump(services, classified.service, r.bytes, r.packets)
const asnId = destMeta.asn ? String(destMeta.asn) : "unknown"
const asnLabel = destMeta.asn ? `AS${destMeta.asn}${ripe?.holder ? ` ${ripe.holder}` : ""}` : "ASN неизвестен"
bump(asns, asnId, r.bytes, r.packets, asnLabel)
const dstCountry = destMeta.country || "unknown"
bump(countries, dstCountry, r.bytes, r.packets, dstCountry === "unknown" ? "Страна неизвестна" : undefined)
if (!skipHeavy) {
const plane = classifyFlowPlane({
src: r.src,
dst: r.dst,
proto: r.proto,
srcPort: r.srcPort,
dstPort: r.dstPort,
inIface: resolved.name,
outIface: outResolved.name,
}, topo.plane)
const client = resolveFlowClient(topo, r.serverId, resolved.name, outResolved.name)
const en = resolveEn(topo, r.nextHop, outResolved.name)
const outIface = outResolved.name === "—" ? "" : outResolved.name
const pathKey = JSON.stringify([client?.userId ?? "unknown", r.serverId, en?.id ?? "", dst, resolved.name, outIface,
classified.service, classified.category, plane])
const ckey = JSON.stringify([flowTupleKey(r), pathKey, accounted.name, app, asnId, dstCountry, ep.internetPeer,
ep.clientIp, ep.peerPort, ep.direction, r.nextHop])
const prev = conv.get(ckey)
if (prev) {
prev.rawBytes += r.bytes
prev.bytes += r.bytes
prev.packets += r.packets
if (r.flowStartMs && (!prev.flowStartMs || r.flowStartMs < prev.flowStartMs)) prev.flowStartMs = r.flowStartMs
if (r.flowEndMs > prev.flowEndMs) prev.flowEndMs = r.flowEndMs
} else {
conv.set(ckey, {
serverId: String(r.serverId),
serverName: nameById.get(r.serverId) ?? String(r.serverId),
src,
dst,
proto: r.proto,
protoName: protoName(r.proto),
srcPort: r.srcPort,
dstPort: r.dstPort,
bytes: r.bytes,
packets: r.packets,
bps: 0,
inIface: resolved.name,
inIfaceIndex: resolved.index,
outIface: outIface || undefined,
accountedIface: accounted.name,
nextHop: r.nextHop || undefined,
application: app,
category: classified.category,
service: classified.service,
dstCountry,
dstAsn: destMeta.asn || undefined,
clientId: client?.userId,
clientName: client?.name,
clientIp: ep.clientIp || undefined,
internetPeer: ep.internetPeer || undefined,
internetPeerPort: ep.peerPort || undefined,
direction: ep.direction,
enId: en ? String(en.id) : undefined,
enName: en?.name,
plane,
rawBytes: r.bytes,
flowStartMs: r.flowStartMs ?? 0,
flowEndMs: r.flowEndMs ?? 0,
})
}
const pathPrev = pathAcc.get(pathKey)
if (pathPrev) {
pathPrev.bytes += r.bytes
pathPrev.packets += r.packets
} else {
pathAcc.set(pathKey, {
id: pathKey,
clientId: client?.userId || "unknown",
clientName: client?.name || "Неизвестный клиент",
ifaces: [...new Set([resolved.name, outIface].filter(name => name && name !== "—"))].join(", ") || "—",
serverId: String(r.serverId),
serverName: nameById.get(r.serverId) ?? String(r.serverId),
inIface: resolved.name,
outIface,
enId: en ? String(en.id) : "",
enName: en?.name || "",
dst,
service: classified.service,
category: classified.category,
plane,
bytes: r.bytes,
packets: r.packets,
bps: 0,
})
}
const ekey = `${r.serverId}|${dstCountry}`
let edge = edgeAcc.get(ekey)
if (!edge) {
edge = {
fromId: String(r.serverId),
fromLabel: nameById.get(r.serverId) ?? String(r.serverId),
fromCountry: countryById.get(r.serverId) || "UN",
toCountry: dstCountry,
toAsn: destMeta.asn,
category: classified.category,
bytes: 0,
bps: 0,
catBytes: new Map(),
}
edgeAcc.set(ekey, edge)
}
edge.bytes += r.bytes
if (edge.toAsn !== destMeta.asn) edge.toAsn = 0
edge.catBytes.set(classified.category, (edge.catBytes.get(classified.category) ?? 0) + r.bytes)
}
}
if (!scope) enqueueRipeMisses(peers)
const conversationsList = [...conv.values()]
.map((t) => {
const { rawBytes, flowStartMs, flowEndMs, ...rest } = t
return { ...rest, bps: flowBps(rawBytes, flowStartMs, flowEndMs, windowSec) }
})
.sort((a, b) => b.bytes - a.bytes)
.slice(0, top)
const paths: FlowPathRow[] = [...pathAcc.values()]
.map((p) => ({ ...p, bps: (p.bytes * 8) / windowSec }))
.sort((a, b) => b.bytes - a.bytes)
.slice(0, top)
const topProto = topLabel(protocols)
const topCategory = topLabel(categories)
const ringServer = q.serverId ?? (matched[0]?.serverId ?? 0)
const ring = ringServer && !ifaceFilter && !allow && !tuple && excludeOverlay ? getRingMbps(ringServer) : null
// The live ring covers about one minute; historical charts must use the requested window.
const fromBuckets = seriesFromRows(working, q.minutes, row => {
if (ifaceFilter || allow) {
const ingress = matchesIngress(row), egress = matchesEgress(row)
if (ingress && egress) {
// A repeated WAN interface in an overlay record does not prove two wire directions.
if (ifaceFilter && (row.proto === 47 || row.proto === 50)) return espDirections.get(row) ?? serverDirection(row)
return "both"
}
// At a client binding, ingress is the client's upload.
return allow && !ifaceFilter ? (ingress ? "tx" : "rx") : (ingress ? "rx" : "tx")
}
return espDirections.get(row) ?? serverDirection(row)
}, now)
const rxSeries = fromBuckets.rx
const txSeries = fromBuckets.tx
const ifaceRows = [...ifacesMap.entries()]
.sort((a, b) => b[1].bytes - a[1].bytes)
.map(([name, v]) => ({
name,
index: v.index,
bps: (v.bytes * 8) / windowSec,
}))
const listener = getFlowListenerState()
const mapEdges: FlowMapEdge[] = [...edgeAcc.values()]
.map((e) => {
let cat = e.category
let catBest = 0
for (const [label, bytes] of e.catBytes) {
if (bytes > catBest) {
catBest = bytes
cat = label
}
}
return {
fromId: e.fromId,
fromLabel: e.fromLabel,
fromCountry: e.fromCountry,
toCountry: e.toCountry,
toAsn: e.toAsn,
category: cat,
bytes: e.bytes,
bps: (e.bytes * 8) / windowSec,
}
})
.sort((a, b) => b.bytes - a.bytes)
.slice(0, top)
// Filtered and overlay-inclusive rates must use the same records as their totals.
const recentBytes = ring ? 0 : working.reduce((sum, row) => sum + (row.bucketAt === previousMinute ? row.bytes : 0), 0)
const bpsNow = ring
? (!fromBuckets.undirectedBytes && (ring.rxNow + ring.txNow) * 1_000_000) || (totalBytes * 8) / windowSec
: (recentBytes * 8) / 60 || (totalBytes * 8) / windowSec
const greNames = ringServer && !q.userId ? enGreIfaceNames(topo, ringServer, [...ifacesForWire]) : []
await authorize()
const wire = ringServer ? await latestWireBps(ringServer, greNames, Boolean(scope)) : { bps: 0, bytes: 0 }
await authorize()
const admittedTotals = q.serverId !== undefined && !q.userId && !tuple
? await readAdmittedFlowTotals(q.serverId, ifaceFilter, q.minutes, now)
: undefined
if (scope && (!Number.isSafeInteger(totalBytes) || !Number.isSafeInteger(totalPackets) || !Number.isSafeInteger(bytesPayload) || !Number.isSafeInteger(bytesOverlay) || !Number.isSafeInteger(bytesMesh))) throw new Error("Переполнение счётчика аналитики NetFlow")
await authorize()
if (scope && (!isDeepStrictEqual(topo, await loadFlowTopology(scope.serverIds, authorize)) || (await readFlowSourceLimits()).topN !== settings.topN)) throw new Error("Топология или предел источника NetFlow изменились во время чтения")
await authorize()
return {
timeBasis: "collector-receipt",
...(admittedTotals ? { admittedTotals } : {}),
bpsNow,
bytes: totalBytes,
packets: totalPackets,
conversations,
conversationsRaw,
uniqueSrc: srcs.size,
uniqueDst: dsts.size,
topProto,
topCategory,
rxSeries,
txSeries,
applications: topN(applications, windowSec, top),
protocols: topN(protocols, windowSec, top),
sources: topN(sources, windowSec, top),
destinations: topN(destinations, windowSec, top),
interfaces: [...ifacesMap.entries()].map(([label, v]) => ({
id: label,
label,
bytes: v.bytes,
packets: v.packets,
bps: (v.bytes * 8) / windowSec,
percent: (v.bytes / (totalBytes || 1)) * 100,
})).sort((a, b) => b.bytes - a.bytes),
asns: topN(asns, windowSec, top),
countries: topN(countries, windowSec, top),
categories: topN(categories, windowSec, top),
services: topN(services, windowSec, top),
mapEdges,
conversationsList,
paths,
ifaces: ifaceRows,
live: listener.bound,
dedupApplied: wantDedup,
degraded: skipHeavy,
bytesPayload,
bytesOverlay,
bytesMesh,
bytesWire: wire.bytes,
bpsOverlay: (recentOverlayBytes * 8) / 60 || (bytesOverlay * 8) / windowSec,
bpsWire: wire.bps,
excludeMeshApplied: excludeMesh,
excludeOverlayApplied: excludeOverlay,
}
}
function groupRowsByServer(rows: PendingFlowRow[]) {
const byServer = new Map<number, PendingFlowRow[]>()
for (const r of rows) {
const group = byServer.get(r.serverId)
if (group) group.push(r)
else byServer.set(r.serverId, [r])
}
return byServer
}
export async function listFlowExporters(minutes: number): Promise<FlowExportersDto> {
const runtime = await getFlowRuntimeCounters()
const inputs = await readFlowExporterInputs(minutes)
const rows = inputs.window.rows
const byServer = groupRowsByServer(rows)
const ids = new Set<number>(byServer.keys())
for (const id of inputs.configuredIds) ids.add(id)
const catalog = inputs.catalog
const topo = await loadFlowTopology()
const exporters = catalog.list
.filter((s) => ids.has(s.id))
.map((s) => {
const ring = getRingMbps(s.id, "__all__")
const records = byServer.get(s.id) ?? []
const rates = ring.rx.some(Boolean) || ring.tx.some(Boolean) ? ring
: seriesFromRows(records, minutes, row => flowRateDirection(s.id, row, topo, s.host))
return {
id: String(s.id),
name: s.name,
subtitle: s.host,
site: s.site,
country: s.country,
status: snapshotStatus(s.id),
rxNow: rates.rxNow,
txNow: rates.txNow,
sessions: records.length,
rxSeries: rates.rx,
txSeries: rates.tx,
bytes: records.reduce((sum, row) => sum + row.bytes, 0),
} satisfies FlowEntityCard
})
.sort((a, b) => b.rxNow - a.rxNow)
const listener = getFlowListenerState()
return {
exporters,
lastExporterIp: runtime.lastExporterIp,
lastError: runtime.lastError,
packetsReceived: runtime.packetsReceived,
lastDatagramAt: runtime.lastDatagramAt,
listenerBound: listener.bound,
listenerAddress: listener.address,
}
}
export async function listFlowClients(minutes: number): Promise<{ clients: FlowEntityCard[] }> {
const [inputs, topo] = await Promise.all([readFlowClientInputs(minutes), loadFlowTopology()])
const byUser = new Map<string, PendingFlowRow[]>()
for (const row of inputs.window.rows) {
const inIface = resolveIfaceName(row.serverId, row.inIface).name
const outIface = resolveIfaceName(row.serverId, row.outIface).name
const client = resolveFlowClient(topo, row.serverId, inIface, outIface)
if (!client || classifyFlowPlane({ ...row, inIface, outIface }, topo.plane) !== "payload") continue
const rows = byUser.get(client.userId) ?? []
rows.push(row)
byUser.set(client.userId, rows)
}
const clients: FlowEntityCard[] = []
for (const u of inputs.users) {
const allow = flowClientInterfaces(topo, u.id)
const namedBindings = u.bindings.filter(binding => allow.get(binding.serverId)?.has(binding.interfaceName)).length
const bound = (id: number, iface: string) => {
return allow.get(id)?.has(resolveIfaceName(id, iface).name)
}
const matched = dedupFlowRowsMaxBytes(byUser.get(u.id) ?? [])
const rates = seriesFromRows(matched, minutes, r => {
if (!bound(r.serverId, r.inIface)) return "rx"
return bound(r.serverId, r.outIface) ? "both" : "tx"
})
clients.push({
id: u.id,
name: u.login,
subtitle: u.name || u.login,
site: namedBindings < u.bindings.length ? `IPFIX: ${namedBindings}/${u.bindings.length} привязок` : `${namedBindings} инт.`,
country: "UN",
status: u.active ? "online" : "offline",
rxNow: matched.length ? rates.rxNow : null,
txNow: matched.length ? rates.txNow : null,
sessions: matched.length,
rxSeries: matched.length ? rates.rx : [],
txSeries: matched.length ? rates.tx : [],
bytes: matched.reduce((sum, row) => sum + row.bytes, 0),
})
}
clients.sort((a, b) => (b.rxNow ?? -1) - (a.rxNow ?? -1))
return { clients }
}
export async function formatLiveSseFromBuilder(
build: () => unknown | Promise<unknown>,
): Promise<{ event: "sample" | "error"; data: unknown }> {
try {
const data = await build()
return { event: "sample", data }
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
return { event: "error", data: { error: message } }
}
}
export function isFlowAnalyticsDegraded(): boolean {
const health = getFlowWorkerHealth()
return health.pendingSize >= LIVE_DEGRADED_PENDING
}
export async function safeBuildLiveFlowSample(q: Omit<FlowAnalyticsQuery, "minutes" | "skipHeavy">, scope?: ScopedFlowAnalyticsRead): Promise<{
event: "sample" | "error"
data: unknown
}> {
return formatLiveSseFromBuilder(async () => {
const skipHeavy = isFlowAnalyticsDegraded()
return readFlowWindow(LIVE_ANALYTICS_MINUTES, minutes => buildFlowAnalytics({ ...q, minutes, skipHeavy }, scope))
})
}
export function flowMonthBounds(month: string): { start: string; end: string } | null {
if (typeof month !== "string" || !/^(?!0000)\d{4}-(0[1-9]|1[0-2])$/.test(month)) return null
const [yearRaw, monthRaw] = month.split("-")
const year = Number(yearRaw)
const monthIdx = Number(monthRaw)
if (!Number.isFinite(year) || monthIdx < 1 || monthIdx > 12) return null
const start = `${month}-01`
// Date.UTC treats years0..99 as1900..1999. Calendar arithmetic also preserves
// the full ISO year at December9999 without truncating an extended date string.
const end = `${String(year + (monthIdx === 12 ? 1 : 0)).padStart(4, "0")}-${String(monthIdx === 12 ? 1 : monthIdx + 1).padStart(2, "0")}-01`
return { start, end }
}
function toBreakdown(
rows: Array<{ key: string; bytes: number; packets: number }>,
totalBytes: number,
windowSec: number,
): FlowBreakdownRow[] {
const denom = totalBytes || 1
return rows
.sort((a, b) => b.bytes - a.bytes || a.key.localeCompare(b.key))
.map((r) => ({
id: r.key,
label: r.key,
bytes: r.bytes,
packets: r.packets,
bps: (r.bytes * 8) / windowSec,
percent: (r.bytes / denom) * 100,
}))
}
export async function getFlowMonthly(month: string, serverId?: number | readonly number[], options?: { maxKeys: number }): Promise<FlowMonthlyDto> {
const bounds = flowMonthBounds(month)
if (!bounds) {
throw Object.assign(new Error("Некорректный месяц отчёта"), { statusCode: 400 })
}
const params: Array<string | number> = [bounds.start, bounds.end, ADMITTED_FLOW_DAY_DIM]
let where = "day >= ? AND day < ? AND dim IN ('country', 'service', 'asn', ?)"
if (Array.isArray(serverId)) {
if (serverId.some(id => !Number.isSafeInteger(id) || id <= 0)) throw new Error("Некорректная область месячного NetFlow")
if (serverId.length === 0) where += " AND false"
else { where += " AND server_id IN (" + serverId.map(() => "?").join(",") + ")"; params.push(...serverId) }
} else if (serverId != null) {
where += " AND server_id = ?"
params.push(serverId as number)
}
if (options && (!Number.isSafeInteger(options.maxKeys) || options.maxKeys < 1 || options.maxKeys > 10000)) throw new Error("Некорректный предел месячных dimension keys")
if (options) params.push(options.maxKeys + 2)
const rows = await flowReadDbAll<{ dim: string; key: string; bytes: number; packets: number }>(`
WITH scoped AS (
SELECT server_id, day, dim, key, bytes, packets FROM flow_daily_dims WHERE ${where}
), daily AS (
SELECT server_id, day, dim, SUM(bytes) AS bytes, SUM(packets) AS packets
FROM scoped GROUP BY server_id, day, dim
), chosen AS (
SELECT DISTINCT ON (server_id, day) dim, bytes, packets
FROM daily
ORDER BY server_id, day, bytes DESC, packets DESC, CASE dim WHEN 'service' THEN 1 WHEN 'asn' THEN 2 WHEN 'country' THEN 3 ELSE 0 END
)
SELECT dim, key, SUM(bytes) AS bytes, SUM(packets) AS packets
FROM scoped WHERE dim IN ('country', 'service', 'asn') GROUP BY dim, key
UNION ALL
SELECT 'total', CASE WHEN BOOL_AND(dim NOT IN ('country','service','asn')) IS FALSE THEN 'legacy-dimensions' ELSE 'admitted-daily' END,
COALESCE(SUM(bytes), 0), COALESCE(SUM(packets), 0)
FROM chosen
${options ? "LIMIT ?" : ""}
`, params)
if (options && rows.length > options.maxKeys + 1) throw new Error("Месячный NetFlow превышает предел dimension keys")
const countries: Array<{ key: string; bytes: number; packets: number }> = []
const services: Array<{ key: string; bytes: number; packets: number }> = []
const asns: Array<{ key: string; bytes: number; packets: number }> = []
const total = rows.find(row => row.dim === "total")
if (!total) throw new Error("Месячный итог NetFlow недоступен")
const bytes = flowCounter(total.bytes)
for (const row of rows) {
const rec = { key: row.key, bytes: flowCounter(row.bytes), packets: flowCounter(row.packets) }
if (row.dim === "country") {
countries.push(rec)
} else if (row.dim === "service") services.push(rec)
else if (row.dim === "asn") asns.push(rec)
}
const countryBytes = flowCounterSum(countries.map(row => row.bytes))
if (countryBytes < bytes) {
const packets = Math.max(0, flowCounter(total.packets) - flowCounterSum(countries.map(row => row.packets)))
const unknown = countries.find(row => row.key === "unknown")
if (unknown) {
unknown.bytes = flowCounter(unknown.bytes + (bytes - countryBytes))
unknown.packets = flowCounter(unknown.packets + packets)
} else {
countries.push({ key: "unknown", bytes: bytes - countryBytes, packets })
}
}
const [year, monthIndex] = month.split("-").map(Number)
const leap = year! % 4 === 0 && (year! % 100 !== 0 || year! % 400 === 0)
const daysInMonth = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][monthIndex! - 1]!
const windowSec = daysInMonth * 86_400
return {
month,
bytes,
totalsSource: total.key === "legacy-dimensions" ? "legacy-dimensions" : "admitted-daily",
countries: toBreakdown(countries, bytes, windowSec),
services: toBreakdown(services, bytes, windowSec),
asns: toBreakdown(asns, bytes, windowSec),
}
}