Files
MikrotikManager/backend/src/modules/mcp/flow-map-actions.ts
T
Denozordec bec8de7c95
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
fix(netflow): ограничить чтение истории и показывать фактическое окно
2026-11-22 03:00:26 +07:00

68 lines
5.3 KiB
TypeScript

import { assertBoundedFlowSource as assertTrafficHistorySource } from "./flow-source-scope.js"
import { withCurrentFlowReadQuality } from "./flow-read-quality.js"
import { z } from "zod"
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"
import type { add } from "./actions.js"
export function registerFlowMapActions(register: typeof add) {
register("traffic.flow.map.read", "mm_netflow_map_hops_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(20),
nestedOffset: z.number().int().min(0).max(100000).default(0), nestedLimit: z.number().int().min(1).max(50).default(20),
}).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), startedAt = new Date().toISOString()
try {
const limits = await readFlowMapSourceLimits()
await authorize()
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 }), 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)) {
const offset = Number(depth === 1 ? input.offset : input.nestedOffset), limit = Number(depth === 1 ? input.limit : input.nestedLimit)
pages[path] = { total: value.length, nextOffset: offset + limit < value.length ? offset + limit : null }
return value.slice(offset, offset + limit).map((row, index) => project(row, `${path}[${offset + index}]`, depth + 1))
}
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, row]) => [key, project(row, path ? `${path}.${key}` : key, depth + 1)]))
return value
}
const { live: listenerBound, ...map } = result
const projected = project(map)
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, 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,
referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false,
rowSumIsNetworkTotal: false, historicalOwnershipVerified: false,
attribution: "current named whole-interface bindings; users with hidden bindings excluded",
collectorStarted: false, backgroundEnrichmentStarted: false, tracerouteExecuted: 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)
}
},
})
}