37 lines
2.7 KiB
TypeScript
37 lines
2.7 KiB
TypeScript
import type { FlowTalkerDto } from "@mmapp/contracts/traffic-flow"
|
|
import type { PendingFlowRow } from "./traffic-flow-engine.js"
|
|
import { protoName } from "./traffic-flow-parse.js"
|
|
import { applicationName } from "./traffic-flow-apps.js"
|
|
import { flowCounter, flowCounterSum } from "./traffic-flow-observed-values.js"
|
|
|
|
/** Shared REST/MCP projection. The caller must scope and bound rows before this
|
|
* function; retained exporter rows are not a deduplicated network total. */
|
|
export function projectFlowTalkers(rows: readonly PendingFlowRow[], minutes: number, topN: number,
|
|
names: ReadonlyMap<number, string>, resolve: (serverId: number, value: string) => { name: string; index: string }) {
|
|
if (!Number.isSafeInteger(minutes) || minutes < 1 || minutes > 1440 || !Number.isSafeInteger(topN) || topN < 1 || topN > 1000) throw new Error("Некорректное окно или предел NetFlow")
|
|
const agg = new Map<string, FlowTalkerDto>(), protocols = new Map<number, number>()
|
|
const sources = new Set<string>(), destinations = new Set<string>(), exporters = new Set<number>()
|
|
let totalBytes = 0
|
|
for (const row of rows) {
|
|
const bytes = flowCounter(row.bytes), packets = flowCounter(row.packets)
|
|
totalBytes = flowCounterSum([totalBytes, bytes])
|
|
sources.add(row.src); destinations.add(row.dst); exporters.add(row.serverId)
|
|
protocols.set(row.proto, flowCounterSum([protocols.get(row.proto) ?? 0, bytes]))
|
|
const key = JSON.stringify([row.serverId, row.src, row.dst, row.proto, row.srcPort, row.dstPort, row.inIface])
|
|
const previous = agg.get(key)
|
|
if (previous) {
|
|
previous.bytes = flowCounterSum([previous.bytes, bytes]); previous.packets = flowCounterSum([previous.packets, packets])
|
|
} else {
|
|
const iface = resolve(row.serverId, row.inIface)
|
|
agg.set(key, { serverId: String(row.serverId), serverName: names.get(row.serverId) ?? String(row.serverId),
|
|
src: row.src, dst: row.dst, proto: row.proto, protoName: protoName(row.proto), srcPort: row.srcPort, dstPort: row.dstPort,
|
|
bytes, packets, bps: 0, inIface: iface.name, inIfaceIndex: iface.index, application: applicationName(row.proto, row.dstPort, row.srcPort) })
|
|
}
|
|
}
|
|
const ordered = [...agg.entries()].sort((a, b) => b[1].bytes - a[1].bytes || a[0].localeCompare(b[0]))
|
|
const talkers = ordered.slice(0, topN).map(([, row]) => ({ ...row, bps: row.bytes * 8 / (minutes * 60) }))
|
|
const topProtocol = [...protocols].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0]
|
|
return { talkers, totalConversations: agg.size, retainedRowsBytes: totalBytes, observedExporters: exporters.size,
|
|
bytesPerMin: totalBytes / minutes, uniqueSrc: sources.size, uniqueDst: destinations.size, topProto: topProtocol ? protoName(topProtocol[0]) : "—" }
|
|
}
|