fix(netflow): ограничить чтение истории и показывать фактическое окно
Docker images / prepare-release (push) Successful in 17s
Docker images / backend-test (push) Failing after 7m23s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 3m10s
Docker images / updater-image (push) Successful in 1m33s
Docker images / netflow-agent-image (push) Successful in 41s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped

This commit is contained in:
Denozordec committed 2026-11-22 03:00:26 +07:00
1 parent e9639313c6
commit bec8de7c95
17 files changed
+166 -53

No files matched your search

@@ -4,6 +4,7 @@ import { z } from "zod"
import { flowAnalyticsDtoSchema } from "@mmapp/contracts/traffic-flow"
import { buildFlowAnalytics } from "../../services/traffic-flow-analytics.js"
import { readFlowSourceLimits } from "../../services/traffic-flow-source-limits.js"
import { readFlowWindow } from "../../services/traffic-flow-read-window.js"
import { getBoundedFlowServerRowById as getServerRowById } from "../../services/traffic-flow-server-source.js"
import { assertTrafficHistoryAccess } from "./traffic-history-actions.js"
import { McpError } from "./security.js"
@@ -20,10 +21,10 @@ export function registerLegacyFlowAnalyticsAction(register: typeof add) {
if (!server) throw new McpError("NOT_FOUND", "Сервер не найден", 404)
const authorize = () => assertTrafficHistorySource(context, server)
try {
const result = await buildFlowAnalytics({ serverId: server.id, minutes: Number(input.minutes), iface: input.interface as string | undefined, skipHeavy: true },
{ serverIds: context.connection.policy.scope.serverIds, maxRows: 20000, authorize })
const result = await readFlowWindow(Number(input.minutes), minutes => buildFlowAnalytics({ serverId: server.id, minutes, iface: input.interface as string | undefined, skipHeavy: true },
{ serverIds: context.connection.policy.scope.serverIds, maxRows: 20000, authorize }), context.signal)
return {
serverId: input.serverId, source: "PostgreSQL/flow_buckets", observedAt: new Date().toISOString(),
serverId: input.serverId, source: "PostgreSQL/flow_buckets", observedAt: new Date().toISOString(), sourceWindow: result.sourceWindow,
bpsNow: result.bpsNow, bytes: result.bytes, packets: result.packets, conversations: result.conversations,
uniqueSrc: result.uniqueSrc, uniqueDst: result.uniqueDst, rxSeries: result.rxSeries, txSeries: result.txSeries,
applications: result.applications, protocols: result.protocols, countries: result.countries,
@@ -57,9 +58,10 @@ export function registerFlowAnalyticsActions(register: typeof add) {
try {
const limits = await readFlowSourceLimits()
await authorize()
const result = flowAnalyticsDtoSchema.parse(await buildFlowAnalytics({ serverId: server.id, minutes: Number(input.minutes), userId: input.userId as string | undefined,
const { sourceWindow, ...raw } = await readFlowWindow(Number(input.minutes), minutes => buildFlowAnalytics({ serverId: server.id, minutes, userId: input.userId as string | undefined,
iface: input.interface as string | undefined, dedup: input.dedup === true, excludeMesh: input.excludeMesh === true, excludeOverlay: input.excludeOverlay === true },
{ serverIds: context.connection.policy.scope.serverIds, maxRows: 20000, authorize }))
{ serverIds: context.connection.policy.scope.serverIds, maxRows: 20000, authorize }), context.signal)
const result = flowAnalyticsDtoSchema.parse(raw)
const offset = Number(input.offset), limit = Number(input.limit), pages: Record<string, { total: number; nextOffset: number | null }> = {}
const analytics: Record<string, unknown> = { ...result }
for (const [key, value] of Object.entries(result)) if (Array.isArray(value) && !["rxSeries", "txSeries"].includes(key)) {
@@ -71,7 +73,7 @@ export function registerFlowAnalyticsActions(register: typeof add) {
await authorize()
if ((await readFlowSourceLimits()).topN !== limits.topN) throw new McpError("STATE_CONFLICT", "Предел источника NetFlow изменился во время чтения", 409)
await authorize()
const output = { serverId: server.id, minutes: Number(input.minutes), interface: input.interface ?? null, userId: input.userId ?? null,
const output = { serverId: server.id, minutes: sourceWindow?.effectiveMinutes ?? Number(input.minutes), sourceWindow, interface: input.interface ?? null, userId: input.userId ?? null,
analytics: retained, pages, contextRates: { bpsNowEstimate: _bpsNow, bpsWireEstimate: _bpsWire, bpsOverlayEstimate: _bpsOverlay, bytesWireEstimate: _bytesWire,
listenerBound: _live, userAttributionVerified: false, semantics: "REST estimates: current server/interface ring with retained-window fallback; wire projection uses current interface snapshots" },
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false,
+17 -11
View File
@@ -4,6 +4,7 @@ import { z } from "zod"
import { readFlowExporterInputs, readFlowClientInputs, observeFlowExporter, observeFlowClient } from "../../services/traffic-flow-catalog-read.js"
import { getFlowMonthly } from "../../services/traffic-flow-analytics.js"
import { readFlowCatalogWindow } from "../../services/traffic-flow-catalog-read.js"
import { readFlowWindow } from "../../services/traffic-flow-read-window.js"
import { projectFlowTalkers } from "../../services/traffic-flow-talkers-model.js"
import { resolveIfaceName } from "../../services/traffic-flow-ifindex.js"
import { assertTrafficHistoryAccess } from "./traffic-history-actions.js"
@@ -21,9 +22,10 @@ export function registerFlowCatalogActions(register: typeof add) {
await assertTrafficHistoryAccess(context)
const { selected, ...page } = await catalogDevices(input, context, { includeDisabled: true })
try {
const window = await readFlowCatalogWindow(Number(input.minutes), selected.map(row => row.id))
const requestedMinutes = Number(input.minutes)
const window = await readFlowWindow(requestedMinutes, minutes => readFlowCatalogWindow(minutes, selected.map(row => row.id)), context.signal)
const topN = window.topConversationsLimit ?? 20
const projection = projectFlowTalkers(window.rows, Number(input.minutes), topN, new Map(selected.map(row => [row.id, row.name])), resolveIfaceName)
const projection = projectFlowTalkers(window.rows, window.sourceWindow?.effectiveMinutes ?? requestedMinutes, topN, new Map(selected.map(row => [row.id, row.name])), resolveIfaceName)
const offset = Number(input.offset), limit = Number(input.limit), items = projection.talkers.slice(offset, offset + limit)
for (const server of selected) await assertTrafficHistorySource(context, server)
if (selected.length && (await getTrafficFlowSettingsRow()).topN !== topN) throw new McpError("STATE_CONFLICT", "Предел источника NetFlow изменился во время чтения", 409)
@@ -33,7 +35,7 @@ export function registerFlowCatalogActions(register: typeof add) {
retainedRowsBytes: projection.retainedRowsBytes, observedExporters: projection.observedExporters,
uniqueSrc: projection.uniqueSrc, uniqueDst: projection.uniqueDst, topProto: projection.topProto,
topConversationsLimit: topN, topRowsPerBucketLimit: window.topRowsPerBucketLimit,
incomplete: true, from: window.since, to: window.until,
incomplete: true, from: window.since, to: window.until, sourceWindow: window.sourceWindow,
source: "flow_buckets plus pending; scope before SQL and retained conversation aggregation",
bpsMeaning: "retained conversation bytes averaged over the entire requested window",
...sourceSemantics },context)
@@ -47,27 +49,31 @@ export function registerFlowCatalogActions(register: typeof add) {
register("traffic.flow.exporters.read", "mm_netflow_exporters_get", "NetFlow: экспортёры выбранной области", "traffic", "mm:traffic:read", "read", "servers", schema, {
read: async (input, context) => {
const { selected, ...page } = await catalogDevices(input, context, { includeDisabled: true })
const data = await readFlowExporterInputs(Number(input.minutes), selected.map(row => row.id))
const requestedMinutes = Number(input.minutes)
const data = await readFlowWindow(requestedMinutes, minutes => readFlowExporterInputs(minutes, selected.map(row => row.id)), context.signal)
const present = new Set([...data.window.rows.map(row => row.serverId), ...data.configuredIds])
const all = data.catalog.list.filter(row => present.has(row.id)).sort((a, b) => a.id - b.id)
const offset = Number(input.offset), limit = Number(input.limit)
return withCurrentFlowReadQuality({ ...page, exporters: all.slice(offset, offset + limit).map(row => observeFlowExporter(data, row.id, Number(input.minutes))), total: all.length,
nextOffset: offset + limit < all.length ? offset + limit : null, incomplete: page.incomplete || all.length > limit || offset > 0 || data.configurationMembershipVerified === false,
for (const server of selected) await assertTrafficHistorySource(context, server)
return withCurrentFlowReadQuality({ ...page, exporters: all.slice(offset, offset + limit).map(row => observeFlowExporter(data, row.id, data.sourceWindow?.effectiveMinutes ?? requestedMinutes)), total: all.length,
nextOffset: offset + limit < all.length ? offset + limit : null, incomplete: !!data.sourceWindow || page.incomplete || all.length > limit || offset > 0 || data.configurationMembershipVerified === false,
configurationMembershipVerified: data.configurationMembershipVerified, configurationEvidence: "stored-peer-records; device exporter settings and keys not verified", source: "flow_buckets plus pending; retained top rows per server/bucket",
failures: data.configurationMembershipVerified === false ? [{ source: "selected-peer-membership", code: "UNVERIFIED_SCHEMA" }] : [],
topRowsPerBucketLimit: data.window.topRowsPerBucketLimit, from: data.window.since, to: data.window.until, ...sourceSemantics },context)
topRowsPerBucketLimit: data.window.topRowsPerBucketLimit, from: data.window.since, to: data.window.until, sourceWindow: data.sourceWindow, ...sourceSemantics },context)
},
})
register("traffic.flow.clients.read", "mm_netflow_clients_get", "NetFlow: клиенты по доступным привязкам", "traffic", "mm:traffic:read", "read", "servers", schema.safeExtend({ limit: z.number().int().min(1).max(50).default(20) }), {
read: async (input, context) => {
const { selected, ...page } = await catalogDevices(input, context, { includeDisabled: true })
const offset = Number(input.offset), limit = Number(input.limit)
const data = await readFlowClientInputs(Number(input.minutes), { serverIds: selected.map(row => row.id), allowedServerIds: context.connection.policy.scope.serverIds, offset, limit })
const clients = data.users.sort((a, b) => a.id.localeCompare(b.id)).map(user => observeFlowClient(user, data.window.rows, Number(input.minutes)))
const requestedMinutes = Number(input.minutes)
const data = await readFlowWindow(requestedMinutes, minutes => readFlowClientInputs(minutes, { serverIds: selected.map(row => row.id), allowedServerIds: context.connection.policy.scope.serverIds, offset, limit }), context.signal)
const clients = data.users.sort((a, b) => a.id.localeCompare(b.id)).map(user => observeFlowClient(user, data.window.rows, data.sourceWindow?.effectiveMinutes ?? requestedMinutes))
for (const server of selected) await assertTrafficHistorySource(context, server)
return withCurrentFlowReadQuality({ ...page, clients, total: data.total, nextOffset: offset + clients.length < data.total ? offset + clients.length : null,
incomplete: page.incomplete || clients.length < data.total || clients.some(row => !row.completeSourceSet || !row.completeAttribution),
incomplete: !!data.sourceWindow || page.incomplete || clients.length < data.total || clients.some(row => !row.completeSourceSet || !row.completeAttribution),
source: "retained ingress rows and current named whole-interface bindings", topRowsPerBucketLimit: data.window.topRowsPerBucketLimit,
from: data.window.since, to: data.window.until, ...sourceSemantics },context)
from: data.window.since, to: data.window.until, sourceWindow: data.sourceWindow, ...sourceSemantics },context)
},
})
register("traffic.flow.monthly.read", "mm_netflow_monthly_report_get", "NetFlow: месячный отчёт выбранной области", "traffic", "mm:traffic:read", "read", "servers", catalogPaging.safeExtend({ month: z.string().regex(/^(?!0000)\d{4}-(0[1-9]|1[0-2])$/) }), {
+5 -3
View File
@@ -5,6 +5,7 @@ import { flowMapHopsDtoSchema } from "@mmapp/contracts/traffic-flow"
import { isDeepStrictEqual } from "node:util"
import { buildFlowMapHops } from "../../services/traffic-flow-map-hops.js"
import { readFlowMapSourceLimits } from "../../services/traffic-flow-source-limits.js"
import { readFlowWindow } from "../../services/traffic-flow-read-window.js"
import { getBoundedFlowServerRowById as getServerRowById } from "../../services/traffic-flow-server-source.js"
import { assertTrafficHistoryAccess } from "./traffic-history-actions.js"
import { McpError } from "./security.js"
@@ -27,9 +28,10 @@ export function registerFlowMapActions(register: typeof add) {
try {
const limits = await readFlowMapSourceLimits()
await authorize()
const result = flowMapHopsDtoSchema.parse(await buildFlowMapHops({ serverId: server.id, minutes: Number(input.minutes), userId: input.userId as string | undefined,
const { sourceWindow, ...raw } = await readFlowWindow(Number(input.minutes), minutes => buildFlowMapHops({ serverId: server.id, minutes, userId: input.userId as string | undefined,
iface: input.interface as string | undefined, dedup: input.dedup === true, excludeMesh: input.excludeMesh === true, excludeOverlay: input.excludeOverlay === true },
{ serverIds: context.connection.policy.scope.serverIds, maxRows: 20000, authorize }))
{ serverIds: context.connection.policy.scope.serverIds, maxRows: 20000, authorize }), context.signal)
const result = flowMapHopsDtoSchema.parse(raw)
const pages: Record<string, { total: number; nextOffset: number | null }> = {}
const project = (value: unknown, path = "", depth = 0): unknown => {
if (Array.isArray(value)) {
@@ -45,7 +47,7 @@ export function registerFlowMapActions(register: typeof add) {
await authorize()
if (!isDeepStrictEqual(limits, await readFlowMapSourceLimits())) throw new McpError("STATE_CONFLICT", "Пределы карты NetFlow изменились во время чтения", 409)
await authorize()
const output = { serverId: server.id, userId: input.userId ?? null, interface: input.interface ?? null, map: projected, pages,
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; same REST map engine with scoped topology",
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,