import { assertBoundedFlowSource as assertTrafficHistorySource } from "./flow-source-scope.js" import { withCurrentFlowReadQuality } from "./flow-read-quality.js" 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" import type { add } from "./actions.js" export function registerLegacyFlowAnalyticsAction(register: typeof add) { register("monitoring.flow.analytics", "mm_netflow_analytics_get", "NetFlow выбранного сервера", "traffic", "mm:traffic:read", "read", "servers", z.object({ serverId: z.number().int().positive().safe(), minutes: z.number().int().min(1).max(1440).default(15), interface: z.string().min(1).max(100).optional(), }).strict(), { read: async (input, context) => { await assertTrafficHistoryAccess(context) const server = await getServerRowById(Number(input.serverId)) if (!server) throw new McpError("NOT_FOUND", "Сервер не найден", 404) const authorize = () => assertTrafficHistorySource(context, server) try { 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(), sourceWindow: result.sourceWindow, timeBasis: result.timeBasis, admittedTotals: result.admittedTotals, 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, categories: result.categories, services: result.services, sources: result.sources.map(row => ({ ...row, label: row.id })), destinations: result.destinations.map(row => ({ ...row, label: row.id })), } } catch (error) { await assertTrafficHistoryAccess(context) if (error instanceof McpError) throw error throw new McpError("STATE_UNAVAILABLE", "Аналитика недоступна, изменилась во время чтения или превышает предел; уменьшите окно", 409) } }, }) } export function registerFlowAnalyticsActions(register: typeof add) { register("traffic.flow.analytics.read", "mm_netflow_analytics_report_get", "NetFlow: нагрузка, приложения и разговоры выбранного сервера", "traffic", "mm:traffic:read", "read", "servers", z.object({ serverId: z.number().int().positive().safe(), minutes: z.number().int().min(1).max(1440).default(15), userId: z.string().min(1).max(100).optional(), interface: z.string().trim().min(1).max(200).refine(value => !/[\u0000-\u001f\u007f]/.test(value) && value !== "__all__").optional(), dedup: z.boolean().default(true), excludeMesh: z.boolean().default(true), excludeOverlay: z.boolean().default(true), offset: z.number().int().min(0).max(100000).default(0), limit: z.number().int().min(1).max(100).default(50), }).strict(), { read: async (input, context) => { await assertTrafficHistoryAccess(context) const server = await getServerRowById(Number(input.serverId)) if (!server) throw new McpError("NOT_FOUND", "Сервер не найден", 404) const authorize = () => assertTrafficHistorySource(context, server) const startedAt = new Date().toISOString() try { const limits = await readFlowSourceLimits() await authorize() 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 }), context.signal) const result = flowAnalyticsDtoSchema.parse(raw) const offset = Number(input.offset), limit = Number(input.limit), pages: Record = {} const analytics: Record = { ...result } for (const [key, value] of Object.entries(result)) if (Array.isArray(value) && !["rxSeries", "txSeries"].includes(key)) { analytics[key] = value.slice(offset, offset + limit) pages[key] = { total: value.length, nextOffset: offset + limit < value.length ? offset + limit : null } } // Wire rate uses interface counters. Keep rate estimates separate from retained volume. const { bpsNow: _bpsNow, bpsWire: _bpsWire, bpsOverlay: _bpsOverlay, bytesWire: _bytesWire, live: _live, ...retained } = analytics await authorize() if ((await readFlowSourceLimits()).topN !== limits.topN) throw new McpError("STATE_CONFLICT", "Предел источника NetFlow изменился во время чтения", 409) await authorize() 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: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback; wire uses current interface snapshots" }, readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false, source: "retained flow_buckets plus pending; same REST analytics engine with scoped topology", rowLimit: 20000, topRowsPerBucketLimit: Math.max(20, limits.topN), engineTopListLimit: Math.min(50, Math.max(10, limits.topN)), incomplete: true, coverageVerified: false, rowSumIsNetworkTotal: false, forwardingVerified: false, inferredPathsVerified: false, historicalOwnershipVerified: false, attribution: "current named whole-interface bindings; users with hidden bindings excluded", backgroundEnrichmentStarted: false, collectorStarted: false } if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ аналитики превышает 1 МиБ; уменьшите страницу", 409) return withCurrentFlowReadQuality(output,context) } catch (error) { await assertTrafficHistoryAccess(context) if (error instanceof McpError) throw error throw new McpError("STATE_UNAVAILABLE", "Аналитика недоступна, изменилась во время чтения или превышает предел; уменьшите окно", 409) } }, }) }