Files
MikrotikManager/backend/src/modules/mcp/flow-live-actions.ts
T
Denozordec 7cf17c7283
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m46s
Docker images / backend-image (push) Successful in 1m59s
Docker images / frontend-image (push) Successful in 2m16s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 31s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
fix(traffic): согласовать трафик пользователей и уточнить данные карты
2026-11-27 00:59:36 +07:00

75 lines
5.8 KiB
TypeScript

import { assertBoundedFlowSource as assertTrafficHistorySource } from "./flow-source-scope.js"
import { withCurrentFlowReadQuality } from "./flow-read-quality.js"
import { setTimeout as delay } from "node:timers/promises"
import { z } from "zod"
import { flowAnalyticsDtoSchema } from "@mmapp/contracts/traffic-flow"
import { safeBuildLiveFlowSample, LIVE_ANALYTICS_MINUTES } from "../../services/traffic-flow-analytics.js"
import { FLOW_LIVE_TICK_MS, tryAcquireFlowLiveSlot, releaseFlowLiveSlot } from "../../services/traffic-flow-live-slots.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 registerFlowLiveActions(register: typeof add) {
register("traffic.flow.live.read", "mm_netflow_live_observe", "NetFlow: ограниченное наблюдение live-потока", "traffic", "mm:traffic:read", "read", "servers", z.object({
serverId: z.number().int().positive().safe(), userId: z.string().trim().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),
samples: z.number().int().min(1).max(3).default(1),
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 serverId = Number(input.serverId)
// Keep this check local too: direct action invocations must not read a foreign source.
if (!context.connection.policy.scope.serverIds.includes(serverId)) throw new McpError("SCOPE_DENIED", "Сервер вне разрешённой области", 403)
const server = await getServerRowById(serverId)
if (!server) throw new McpError("NOT_FOUND", "Сервер не найден", 404)
const authorize = () => assertTrafficHistorySource(context, server)
await authorize()
if (!tryAcquireFlowLiveSlot()) throw new McpError("RATE_LIMITED", "Слишком много live-подписок", 429)
const readStartedAt = new Date().toISOString()
try {
const events = []
for (let index = 0; index < Number(input.samples); index++) {
if (index) await delay(FLOW_LIVE_TICK_MS, undefined, { signal: context.signal })
await authorize()
const sampleStartedAt = new Date().toISOString()
const event = await safeBuildLiveFlowSample({ serverId, 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 })
await authorize()
// The REST formatter includes raw source error messages. Never publish these over MCP.
if (event.event !== "sample") throw new McpError("STATE_UNAVAILABLE", "Live NetFlow недоступен, источник изменился или превышает предел 20000 строк", 409)
const dto = flowAnalyticsDtoSchema.parse(event.data)
const data: Record<string, unknown> = { ...dto }
const pages: Record<string, { total: number; nextOffset: number | null }> = {}
const offset = Number(input.offset), limit = Number(input.limit)
for (const [key, value] of Object.entries(dto)) if (Array.isArray(value) && key !== "rxSeries" && key !== "txSeries") {
data[key] = value.slice(offset, offset + limit)
pages[key] = { total: value.length, nextOffset: offset + limit < value.length ? offset + limit : null }
}
events.push({ event: "sample" as const, sampleStartedAt, observedAt: new Date().toISOString(), data, pages })
await authorize()
}
const output = { serverId, userId: input.userId ?? null, interface: input.interface ?? null, events, readStartedAt, observedAt: new Date().toISOString(),
observationComplete: true, streamContinues: false, sampleIntervalMs: FLOW_LIVE_TICK_MS, windowMinutes: LIVE_ANALYTICS_MINUTES,
source: "REST live sample engine: current ring estimates and rolling flow_buckets plus pending; uncached scoped reads",
rowLimit: 20000, incomplete: true, coverageVerified: false, forwardingVerified: false, rowSumIsNetworkTotal: false,
historicalOwnershipVerified: false, currentTrafficVerified: false,
rateSemantics: "REST live rates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback",
liveMeaning: "events[].data.live means listener bound; it does not prove exporter freshness or forwarding",
attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
collectorStarted: false, backgroundEnrichmentStarted: false }
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ live превышает 1 МиБ; уменьшите страницу или число samples", 409)
await authorize()
return withCurrentFlowReadQuality(output,context)
} catch (error) {
await authorize()
if (error instanceof McpError) throw error
throw new McpError("STATE_UNAVAILABLE", "Live NetFlow недоступен или чтение отменено", 409)
} finally { releaseFlowLiveSlot() }
},
})
}