Compare commits

...
1 Commits
Author SHA1 Message Date
Denozordec bec8de7c95 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
2026-11-22 03:00:26 +07:00
17 changed files with 166 additions and 53 deletions

No files matched your search

+5 -2
View File
@@ -823,7 +823,7 @@ export default function TrafficPage() {
const [flowScope, setFlowScope] = useState<FlowScope>("servers")
const [flowRetry, setFlowRetry] = useState(0)
const flowKey = JSON.stringify([isLive, groupMode, backendUrl, range, flowScope, flowRetry])
const [flowResult, setFlowResult] = useState<{ key: string; receivedAt?: number; monthlyServers?: ServerRead[]; stats?: FlowStatsDto; exporters?: FlowEntityCard[]; clients?: FlowEntityCard[]; error?: string } | null>(null)
const [flowResult, setFlowResult] = useState<{ key: string; receivedAt?: number; monthlyServers?: ServerRead[]; stats?: FlowStatsDto; exporters?: FlowEntityCard[]; clients?: FlowEntityCard[]; cardWindow?: FlowStatsDto["sourceWindow"]; error?: string } | null>(null)
const currentFlows = flowResult?.key === flowKey ? flowResult : null
const liveBusy = isLive && groupMode === "flows" && !currentFlows
const liveError = currentFlows?.error
@@ -932,7 +932,8 @@ export default function TrafficPage() {
if (cancelled) return
const clients = await getFlowClients(backendUrl, range)
if (cancelled) return
setFlowResult({ key: flowKey, receivedAt: Date.now(), stats, exporters: exporters.exporters, clients: clients.clients })
setFlowResult({ key: flowKey, receivedAt: Date.now(), stats, exporters: exporters.exporters, clients: clients.clients,
cardWindow: flowScope === "users" ? clients.sourceWindow : exporters.sourceWindow })
setSelectedId(prev => {
const list = flowScope === "users" ? clients.clients : exporters.exporters
return list.some(x => x.id === prev) ? prev : (list[0]?.id ?? "")
@@ -1250,6 +1251,8 @@ export default function TrafficPage() {
</Button>
</div>
{isLive && <TrafficDataTime label="Получение списка потоков" receivedAt={currentFlows?.receivedAt} source="API" />}
{flowStats?.sourceWindow && <p role="status" className="text-sm text-muted-foreground">Сводка потоков за последние {flowStats.sourceWindow.effectiveMinutes} мин из запрошенных {flowStats.sourceWindow.requestedMinutes} мин.</p>}
{currentFlows?.cardWindow && <p role="status" className="text-sm text-muted-foreground">Данные карточек за последние {currentFlows.cardWindow.effectiveMinutes} мин из запрошенных {currentFlows.cardWindow.requestedMinutes} мин.</p>}
{liveBusy && <p role="status">Загрузка потоков…</p>}
{liveError && <Alert variant="destructive" role="alert"><AlertTitle>Потоки недоступны</AlertTitle><AlertDescription>{liveError}<Button size="sm" variant="outline" onClick={() => setFlowRetry(value => value + 1)}>Повторить загрузку потоков</Button></AlertDescription></Alert>}
{flowError && !liveError && (
@@ -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,
+8 -5
View File
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto"
import { channel } from "node:diagnostics_channel"
import { createFlowReadResponseOwner, writeBoundedFlowSse, withFlowReadSourceWindow } from "../services/traffic-flow-read-budget.js"
import { flowReadBudget, flowResponseReadLimits, FLOW_READ_RESERVATION_BYTES, FLOW_SSE_MAX_FRAME_BYTES } from "../services/traffic-flow-read-policy.js"
import { readFlowWindow } from "../services/traffic-flow-read-window.js"
import { updateTrafficFlowSettingsWithListener } from "../services/traffic-flow-settings-service.js"
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import { mcpDatabaseRequestSignal, withDatabaseApiRequest } from "../modules/mcp/database-request-lease.js"
@@ -98,7 +99,7 @@ function analyticsQuery(req: FastifyRequest) {
async function sendFlowTalkers(req: FastifyRequest, reply: FastifyReply) {
const q = req.query as { range?: string }
return reply.send(await listFlowTalkers(rangeToMinutes(q.range)))
return reply.send(await readFlowWindow(rangeToMinutes(q.range), listFlowTalkers, mcpDatabaseRequestSignal()))
}
function requestPublicHost(req: FastifyRequest): string {
@@ -200,20 +201,22 @@ const trafficFlowRoutes: FastifyPluginAsyncZod = async (app) => {
app.get("/traffic/flow/exporters", async (req, reply) => {
const q = req.query as { range?: string }
return reply.send(await listFlowExporters(rangeToMinutes(q.range)))
return reply.send(await readFlowWindow(rangeToMinutes(q.range), listFlowExporters, mcpDatabaseRequestSignal()))
})
app.get("/traffic/flow/clients", async (req, reply) => {
const q = req.query as { range?: string }
return reply.send(await listFlowClients(rangeToMinutes(q.range)))
return reply.send(await readFlowWindow(rangeToMinutes(q.range), listFlowClients, mcpDatabaseRequestSignal()))
})
app.get("/traffic/flow/analytics", async (req, reply) => {
return reply.send(await buildFlowAnalytics(analyticsQuery(req)))
const query = analyticsQuery(req)
return reply.send(await readFlowWindow(query.minutes, minutes => buildFlowAnalytics({ ...query, minutes }), mcpDatabaseRequestSignal()))
})
app.get("/traffic/flow/map-hops", async (req, reply) => {
return reply.send(await buildFlowMapHops(analyticsQuery(req)))
const query = analyticsQuery(req)
return reply.send(await readFlowWindow(query.minutes, minutes => buildFlowMapHops({ ...query, minutes }), mcpDatabaseRequestSignal()))
})
app.get("/traffic/flow/monthly", async (req, reply) => {
@@ -1,4 +1,5 @@
import { flowReadDbAll } from "./traffic-flow-read-policy.js"
import { readFlowWindow } from "./traffic-flow-read-window.js"
import { isDeepStrictEqual } from "node:util"
import { readFlowSourceLimits } from "./traffic-flow-source-limits.js"
import { readFlowExporterInputs, readFlowClientInputs, flowCounter, flowCounterSum } from "./traffic-flow-catalog-read.js"
@@ -664,7 +665,7 @@ export async function safeBuildLiveFlowSample(q: Omit<FlowAnalyticsQuery, "minut
}> {
return formatLiveSseFromBuilder(async () => {
const skipHeavy = isFlowAnalyticsDegraded()
return await buildFlowAnalytics({ ...q, minutes: LIVE_ANALYTICS_MINUTES, skipHeavy }, scope)
return readFlowWindow(LIVE_ANALYTICS_MINUTES, minutes => buildFlowAnalytics({ ...q, minutes, skipHeavy }, scope))
})
}
@@ -1,6 +1,7 @@
import { getFlowReadResourceProfile } from "./traffic-flow-read-resource-profile.js"
import type { QueryResultRow } from "pg"
import { trackFlowReadSource } from "./traffic-flow-read-budget.js"
import { FlowSqlSourceTooLarge } from "./traffic-flow-read-window.js"
export interface FlowBoundedQueryClient {
query(sql: string, values: unknown[]): Promise<{ rows: Array<Record<string, unknown>>; fields?:Array<{name:string}> }>
@@ -24,7 +25,8 @@ export async function readBoundedFlowSql<T extends QueryResultRow>(client: FlowB
const preflight=await client.query(`WITH flow_read_source AS MATERIALIZED (${query}) SELECT count(*)::text AS "__flowRowCount",COALESCE(sum(octet_length(row_to_json(s)::text)),0)::text AS "__flowEncodedBytes" FROM flow_read_source s`,values)
const n=String(preflight.rows[0]?.__flowRowCount),b=String(preflight.rows[0]?.__flowEncodedBytes)
const measuredBytes=Number(b)+2+Math.max(Number(n)-1,0)
if(!/^\d{1,15}$/.test(n)||!/^\d{1,15}$/.test(b)||Number(n)>limits.maxRows||measuredBytes>sourceByteLimit)throw Object.assign(Error("Источник NetFlow превышает допустимый объём; сократите область или окно"),{statusCode:409,code:"STATE_UNAVAILABLE"})
if(!/^\d{1,15}$/.test(n)||!/^\d{1,15}$/.test(b))throw Error("Invalid bounded NetFlow source size")
if(Number(n)>limits.maxRows||measuredBytes>sourceByteLimit)throw new FlowSqlSourceTooLarge()
const reserved=admit(Number(n),measuredBytes)
const countIndex = values.length + 1, bytesIndex = values.length + 2
const result = await client.query(`WITH flow_read_source AS MATERIALIZED (${query}),
@@ -36,7 +38,8 @@ export async function readBoundedFlowSql<T extends QueryResultRow>(client: FlowB
if(result.fields && ["__flowRowCount","__flowEncodedBytes","__flowPresent"].some(name=>result.fields!.filter(field=>field.name===name).length!==1))throw Error("Reserved NetFlow source column collision")
const row = result.rows[0]
const count = String(row?.__flowRowCount), bytes = String(row?.__flowEncodedBytes)
if (!row || !/^\d{1,15}$/.test(count) || !/^\d{1,15}$/.test(bytes) || Number(count) > reserved.maxRows || Number(bytes) + 2 + Math.max(Number(count)-1,0) > reserved.maxEncodedBytes) throw Object.assign(Error("Источник NetFlow превышает допустимый объём; сократите область или окно"), { statusCode: 409, code: "STATE_UNAVAILABLE" })
if (!row || !/^\d{1,15}$/.test(count) || !/^\d{1,15}$/.test(bytes)) throw Error("Invalid bounded NetFlow source size")
if (Number(count) > reserved.maxRows || Number(bytes) + 2 + Math.max(Number(count)-1,0) > reserved.maxEncodedBytes) throw new FlowSqlSourceTooLarge()
if (Number(count) === 0) return []
if (result.rows.length !== Number(count) || result.rows.some(item => item.__flowPresent !== true)) throw Error("Invalid bounded NetFlow SQL result")
// Preserve the normal pg column parsers (not JSONB numeric/timestamp coercion).
@@ -18,9 +18,7 @@ export async function readFlowCatalogWindow(minutes: number, serverIds?: readonl
if (selected?.length === 0) return { rows: [] as PendingFlowRow[], since, until, topRowsPerBucketLimit: null, topConversationsLimit: null }
const settings = await getTrafficFlowSettingsRow()
if (!Number.isSafeInteger(settings.topN) || settings.topN < 1 || settings.topN > 1000) throw fail("Не подтверждён topN источника NetFlow")
const rows:PendingFlowRow[]=[]
if(selected===undefined)rows.push(...await listStoredFlowRows(since,undefined,{untilIso:until}))
else for(const serverId of selected)rows.push(...await listStoredFlowRows(since,serverId,{maxRows:Math.max(1,Math.floor(50000/selected.length)),untilIso:until}))
const rows = await listStoredFlowRows(since, undefined, { serverIds: selected, maxRows: 49999, untilIso: until })
for (const row of rows) { flowCounter(row.bytes); flowCounter(row.packets) }
return { rows, since, until, topRowsPerBucketLimit: Math.max(20, settings.topN), topConversationsLimit: settings.topN }
}
+3 -1
View File
@@ -557,7 +557,7 @@ function pruneRecent(sinceMs = Date.now() - LIVE_WINDOW_MS): void {
}
}
export interface PendingFlowReadOptions { serverId?:number; sinceIso?:string; untilIso?:string }
export interface PendingFlowReadOptions { serverId?:number; serverIds?:readonly number[]; sinceIso?:string; untilIso?:string }
export class FlowPendingReadUnconfirmed extends Error {
readonly code = "FLOW_PENDING_UNCONFIRMED"
constructor(readonly batchState:"running"|"unknown") { super(`NetFlow pending read unavailable: ${batchState} write batch`) }
@@ -566,8 +566,10 @@ function pendingReadMatches(options:PendingFlowReadOptions):(row:Pick<PendingFlo
const since=options.sinceIso===undefined?-Infinity:typeof options.sinceIso==="string"?Date.parse(options.sinceIso):NaN
const until=options.untilIso===undefined?Infinity:typeof options.untilIso==="string"?Date.parse(options.untilIso):NaN
if(options.serverId!==undefined&&(!Number.isSafeInteger(options.serverId)||options.serverId<=0)||Number.isNaN(since)||Number.isNaN(until)||since>until)throw Error("Invalid pending flow read scope")
const serverIds = options.serverIds && new Set(options.serverIds)
return row=>{
if(options.serverId!==undefined&&row.serverId!==options.serverId)return false
if(serverIds&&!serverIds.has(row.serverId))return false
const time=Date.parse(row.bucketAt)
if(!Number.isFinite(time))throw Error("Invalid pending flow timestamp")
return time>=since&&time<=until
+16 -7
View File
@@ -1,4 +1,5 @@
import { flowReadBucketSnapshot } from "./traffic-flow-read-policy.js"
import { FlowSourceWindowTooLarge, FlowSqlSourceTooLarge } from "./traffic-flow-read-window.js"
import {flowIngestQualitySchema} from "@mmapp/contracts/traffic-flow"
import { flowLifecycleBoundary, type FlowLifecycleAuthorization } from "./traffic-flow-lifecycle-fence.js"
import { flowCounter } from "./traffic-flow-observed-values.js"
@@ -475,12 +476,17 @@ interface StoredBucketRow {
nat_dst_port: number | null
}
export async function listStoredFlowRows(sinceIso: string, serverId?: number, options?: { maxRows?: number; untilIso?: string }): Promise<PendingFlowRow[]> {
export async function listStoredFlowRows(sinceIso: string, serverId?: number, options?: { maxRows?: number; untilIso?: string; serverIds?: readonly number[] }): Promise<PendingFlowRow[]> {
if (options?.maxRows !== undefined && (!Number.isSafeInteger(options.maxRows) || options.maxRows < 1 || options.maxRows > 100000)) throw new Error("Некорректный предел flow rows")
if (options?.untilIso && !Number.isFinite(Date.parse(options.untilIso))) throw new Error("Некорректная граница flow window")
const settings = options?.maxRows === undefined ? await getTrafficFlowSettingsRow() : await readFlowSourceLimits()
const keep = Math.max(20, settings.topN)
const parameters: Array<string | number> = serverId === undefined ? [sinceIso, keep] : [sinceIso, keep, serverId]
const serverIds = options?.serverIds
if (serverIds !== undefined && (serverId !== undefined || serverIds.some(id => !Number.isSafeInteger(id) || id < 1))) throw new Error("Некорректная область flow rows")
if (serverIds?.length === 0) return []
const parameters: Array<string | number | readonly number[]> = [sinceIso, keep]
if (serverId !== undefined || serverIds !== undefined) parameters.push(serverId ?? serverIds!)
const serverFilter = serverId !== undefined ? "AND server_id=$3" : serverIds ? "AND server_id=ANY($3::bigint[])" : ""
const untilParameter = options?.untilIso ? parameters.push(options.untilIso) : undefined
if (options?.maxRows !== undefined) parameters.push(options.maxRows + 1)
const stored = await flowReadBucketSnapshot<StoredBucketRow>(`
@@ -495,12 +501,15 @@ export async function listStoredFlowRows(sinceIso: string, serverId?: number, op
PARTITION BY server_id, bucket_at ORDER BY bytes DESC
) AS rn
FROM flow_buckets fb
WHERE bucket_at >= $1 ${serverId === undefined ? "" : "AND server_id=$3"} ${untilParameter ? `AND bucket_at <= $${untilParameter}` : ""}
WHERE bucket_at >= $1 ${serverFilter} ${untilParameter ? `AND bucket_at <= $${untilParameter}` : ""}
) ranked
WHERE rn <= $2
${options?.maxRows !== undefined ? `LIMIT $${parameters.length}` : ""}
`, parameters)
if (options?.maxRows !== undefined && stored.length > options.maxRows) throw new Error("Превышен предел flow rows; сократите окно или число серверов")
`, parameters).catch(error => {
if (error instanceof FlowSqlSourceTooLarge) throw new FlowSourceWindowTooLarge()
throw error
})
if (options?.maxRows !== undefined && stored.length > options.maxRows) throw new FlowSourceWindowTooLarge()
const merged = new Map<string, PendingFlowRow>()
for (const r of stored) {
mergeInto(merged, {
@@ -525,14 +534,14 @@ export async function listStoredFlowRows(sinceIso: string, serverId?: number, op
})
}
if (!worker) {
for (const p of peekPendingFlows({serverId,sinceIso,untilIso:options?.untilIso})) {
for (const p of peekPendingFlows({serverId,serverIds,sinceIso,untilIso:options?.untilIso})) {
if (p.bucketAt < sinceIso || options?.untilIso && p.bucketAt > options.untilIso || serverId !== undefined && p.serverId !== serverId) continue
flowCounter(p.bytes); flowCounter(p.packets)
mergeInto(merged, p)
}
}
const result = capFlowRowsPerServerBucket([...merged.values()], keep)
if (options?.maxRows !== undefined && result.length > options.maxRows) throw new Error("Превышен предел flow rows с pending; сократите окно или число серверов")
if (options?.maxRows !== undefined && result.length > options.maxRows) throw new FlowSourceWindowTooLarge()
return result
}
@@ -18,6 +18,7 @@ import { resetFlowRingsForTests,applyHeartbeatForTests } from './traffic-flow-in
import { createFlowIngestQuality } from './traffic-flow-ingest-quality.js'
import { disableRipeEnqueueForTests } from './traffic-flow-ripe.js'
import { readFlowCatalogWindow } from './traffic-flow-catalog-read.js'
import { invalidateFlowAnalyticsCache } from './traffic-flow-analytics.js'
import { sharedDatabaseGate } from './shared-database-gate.js'
import { getTrafficFlowSettingsRow,invalidateTrafficFlowSettingsCache } from './traffic-flow-settings.js'
import { createFlowReadBudget,createFlowReadResponseOwner } from './traffic-flow-read-budget.js'
@@ -40,7 +41,8 @@ try{
const collectorQuality=createFlowIngestQuality();collectorQuality.reject(987654,987,'aggregate-capacity')
// Synthetic quality goes through the actual validated heartbeat receiver;
// this test starts no collector Worker or remote exporter.
applyHeartbeatForTests({bound:false,address:null,packetsReceived:0,lastExporterIp:'',lastError:'',lastDatagramAt:null,pendingSize:0,dropped:0,rowsStored:0,workerAlive:true,rings:[],dataQuality:collectorQuality.snapshot()})
const heartbeat={bound:false,address:null,packetsReceived:0,lastExporterIp:'',lastError:'',lastDatagramAt:null,pendingSize:0,dropped:0,rowsStored:0,workerAlive:true,rings:[],dataQuality:collectorQuality.snapshot()}
applyHeartbeatForTests(heartbeat)
await readFlowCatalogWindow(5,[1])
{
const budget=createFlowReadBudget({maxOwners:2,maxReservedBytes:200}),response=new EventEmitter() as ServerResponse,owner=createFlowReadResponseOwner(response,budget,{maxOwners:1,maxReservedBytes:100})
@@ -119,6 +121,45 @@ try{
const scopedQuality=(result.structuredContent as {result:Record<string,unknown>}).result
assert.equal(scopedQuality.dataQuality,null);assert.equal(scopedQuality.collectorQualityUnavailableReason,'global-telemetry-not-granted')
assert.ok(!JSON.stringify(result).includes('987654'),'Scoped read must not disclose collector-wide loss amounts')
const oldFlowStart = new Date(Date.now() - 7 * 3600000)
await ensurePartitionFor(pool, 'flow_buckets', 'day', oldFlowStart)
await ensurePartitionFor(pool, 'flow_buckets', 'day', new Date(oldFlowStart.getTime() + 251 * 60000))
await pool.query(`INSERT INTO flow_buckets(server_id,bucket_at,src,dst,proto,src_port,dst_port,bytes,packets,in_iface)
SELECT 1,$1::timestamptz + minutes * interval '1 minute','198.18.3.0'::inet + host, '8.8.4.4',6,1234,443,50,1,'ether1'
FROM generate_series(0,251) minutes CROSS JOIN generate_series(1,200) host`, [oldFlowStart])
const denseRest = await fetch(endpoint+'/api/traffic/flow?range=24h')
assert.equal(denseRest.status,200)
const restWindow = (await denseRest.json() as {sourceWindow:{requestedMinutes:number;effectiveMinutes:number}}).sourceWindow
assert.equal(restWindow.requestedMinutes,1440)
assert(restWindow.effectiveMinutes<1440)
const denseMcp = await client.callTool({name:'mm_netflow_talkers_get',arguments:{serverId:1,minutes:1440}})
assert.ok(!denseMcp.isError,JSON.stringify(denseMcp))
const mcpDay = (denseMcp.structuredContent as {result:{sourceWindow:{requestedMinutes:number;effectiveMinutes:number}; retainedRowsBytes:number; from:string;to:string}}).result
assert.equal(mcpDay.sourceWindow.requestedMinutes,1440)
assert(mcpDay.sourceWindow.effectiveMinutes<1440)
assert.equal(Date.parse(mcpDay.to)-Date.parse(mcpDay.from),mcpDay.sourceWindow.effectiveMinutes*60000)
assert(!JSON.stringify(denseMcp).includes('FORBIDDEN_'))
console.log('PASS dense REST and MCP NetFlow windows report the actual safely admitted interval')
const counterStart = new Date(Date.now()-10*60000)
await ensurePartitionFor(pool,'traffic_samples','week',counterStart)
await ensurePartitionFor(pool,'traffic_samples','week',new Date(counterStart.getTime()+50010))
await pool.query(`INSERT INTO traffic_samples(server_id,interface_name,sampled_at,rx_bps,tx_bps,rx_bytes,tx_bytes)
SELECT 1,'gre-test',$1::timestamptz + n * interval '1 millisecond',n,2*n,3*n,4*n FROM generate_series(1,50010) n`,[counterStart])
await pool.query(`INSERT INTO flow_buckets(server_id,bucket_at,src,dst,proto,src_port,dst_port,bytes,packets,in_iface)
VALUES(1,$1,'198.18.1.3','8.8.8.8',6,3,443,50,1,'gre-test')`,[bucket])
applyHeartbeatForTests({...heartbeat,dataQuality:createFlowIngestQuality().snapshot()})
try {
const analytics = await fetch(endpoint+'/api/traffic/flow/analytics?range=5m&serverId=1')
assert.equal(analytics.status,200,await analytics.clone().text())
const shortReport = await analytics.json() as {bpsWire:number;bytesWire:number;sourceWindow?:unknown}
assert.equal(shortReport.bpsWire,150030)
assert.equal(shortReport.bytesWire,350070)
assert.equal(shortReport.sourceWindow,undefined)
} finally {
applyHeartbeatForTests(heartbeat)
invalidateFlowAnalyticsCache()
}
console.log('PASS five-minute REST analysis uses one latest counter per interface despite 50,010 historical samples')
const globalAccess=await createMcpConnection(mcpConnectionCreateSchema.parse({name:'owned global telemetry',mode:'observer',permissions:['mm:traffic:read'],expiresAt:new Date(Date.now()+600000).toISOString(),scope:{serverIds:[1],operationIds:['traffic.flow.talkers.read','netflow.settings.read'],allowGlobal:true},limits:{callsPerMinute:240}}),actor)
const globalClient=new Client({name:'owned-global-quality',version:'1'})
try{
@@ -0,0 +1,27 @@
export class FlowSqlSourceTooLarge extends Error {
readonly statusCode = 409
readonly code = "STATE_UNAVAILABLE"
constructor() {
super("Источник NetFlow превышает допустимый объём; сократите область или окно")
}
}
export class FlowSourceWindowTooLarge extends FlowSqlSourceTooLarge {}
type FlowReadWindow = { requestedMinutes: number; effectiveMinutes: number }
/** Retrying a smaller historical window keeps the same response reservation.
* Only an explicit source-size refusal allows fallback; other errors propagate. */
export async function readFlowWindow<T extends object>(requestedMinutes: number, read: (minutes: number) => Promise<T>, signal?: AbortSignal): Promise<T & { sourceWindow?: FlowReadWindow }> {
let effectiveMinutes = requestedMinutes
for (;;) {
signal?.throwIfAborted()
try {
const result = await read(effectiveMinutes)
return effectiveMinutes === requestedMinutes ? result : { ...result, sourceWindow: { requestedMinutes, effectiveMinutes } }
} catch (error) {
if (!(error instanceof FlowSourceWindowTooLarge) || effectiveMinutes <= 1) throw error
effectiveMinutes = Math.max(1, Math.floor(effectiveMinutes / (effectiveMinutes <= 15 ? 2 : 4)))
}
}
}
@@ -247,7 +247,6 @@ export function enGreIfaceNames(topo: FlowTopology, serverId: number, ifaceNames
export async function latestWireBps(serverId: number, ifaceNames: string[], bounded = false): Promise<{ bps: number; bytes: number }> {
if (!ifaceNames.length) return { bps: 0, bytes: 0 }
if (bounded && ifaceNames.length > 1000) throw new Error("Превышен предел физических интерфейсов NetFlow")
const placeholders = ifaceNames.map(() => "?").join(",")
const rows = await flowReadDbAll<{
name: string
rxBps: number
@@ -255,18 +254,18 @@ export async function latestWireBps(serverId: number, ifaceNames: string[], boun
rxBytes: number
txBytes: number
}>(`
SELECT ${bounded ? "DISTINCT ON (interface_name)" : ""} interface_name AS name, rx_bps AS "rxBps", tx_bps AS "txBps", rx_bytes AS "rxBytes", tx_bytes AS "txBytes"
FROM traffic_samples
WHERE server_id = ? AND interface_name IN (${placeholders})
ORDER BY ${bounded ? "interface_name," : ""} sampled_at DESC
`, [serverId, ...ifaceNames])
const seen = new Set<string>()
SELECT iface.name, sample.rx_bps AS "rxBps", sample.tx_bps AS "txBps", sample.rx_bytes AS "rxBytes", sample.tx_bytes AS "txBytes"
FROM (SELECT DISTINCT unnest(?::text[]) AS name) iface
CROSS JOIN LATERAL (
SELECT rx_bps, tx_bps, rx_bytes, tx_bytes FROM traffic_samples
WHERE server_id = ? AND interface_name = iface.name
ORDER BY sampled_at DESC LIMIT 1
) sample
`, [ifaceNames, serverId])
let bps = 0
let bytes = 0
for (const r of rows) {
if (bounded && ([r.rxBps,r.txBps].some(value => value === null || !Number.isFinite(Number(value)) || Number(value) < 0 || Number(value) > Number.MAX_SAFE_INTEGER) || [r.rxBytes,r.txBytes].some(value => value === null || !Number.isSafeInteger(Number(value)) || Number(value) < 0))) throw new Error("Не подтверждены физические счётчики NetFlow")
if (seen.has(r.name)) continue
seen.add(r.name)
bps += (Number(r.rxBps) || 0) + (Number(r.txBps) || 0)
bytes += (Number(r.rxBytes) || 0) + (Number(r.txBytes) || 0)
}
+3 -1
View File
@@ -70,15 +70,17 @@ export function TrafficRxTxChart({
rx,
tx,
range = "1h",
rangeMinutes: actualMinutes,
embedded = false,
}: {
rx: (number|null)[]
tx: (number|null)[]
range?: string
rangeMinutes?: number
/** Skip outer Frame when already inside OpsPanel / Frame. */
embedded?: boolean
}) {
const rangeMinutes = TRAFFIC_RANGE_MINUTES[range] ?? 60
const rangeMinutes = actualMinutes ?? TRAFFIC_RANGE_MINUTES[range] ?? 60
const data = toChartData(rx, tx, rangeMinutes)
const tickEvery = Math.max(1, Math.ceil(data.length / 6))
@@ -474,10 +474,12 @@ export function FlowAnalyticsDetail({
) : null}
{analytics && <>
{analytics.sourceWindow && <p role="status" className="mb-3 text-sm text-muted-foreground">Данные за последние {analytics.sourceWindow.effectiveMinutes} мин из запрошенных {analytics.sourceWindow.requestedMinutes} мин.</p>}
<TrafficRxTxChart
rx={analytics?.rxSeries ?? card?.rxSeries ?? []}
tx={analytics?.txSeries ?? card?.txSeries ?? []}
range={range}
rangeMinutes={analytics.sourceWindow?.effectiveMinutes}
/>
<div className="mt-4 pt-4 border-t">
+10
View File
@@ -163,7 +163,13 @@ export const flowTalkerDtoSchema = z.object({
plane: z.string().optional(),
})
const flowSourceWindowSchema = z.object({
requestedMinutes: z.number().int().positive(),
effectiveMinutes: z.number().int().positive(),
}).strict().refine(value => value.effectiveMinutes < value.requestedMinutes)
export const flowStatsDtoSchema = z.object({
sourceWindow: flowSourceWindowSchema.optional(),
dataQuality:flowIngestQualitySchema.nullable().optional(),
exportersOnline: z.number().int().nonnegative(),
bytesPerMin: z.number().nonnegative(),
@@ -246,6 +252,7 @@ export const flowPathRowSchema = z.object({
})
export const flowAnalyticsDtoSchema = z.object({
sourceWindow: flowSourceWindowSchema.optional(),
bpsNow: z.number().nonnegative(),
bytes: z.number().nonnegative(),
packets: z.number().nonnegative(),
@@ -284,6 +291,7 @@ export const flowAnalyticsDtoSchema = z.object({
})
export const flowExportersDtoSchema = z.object({
sourceWindow: flowSourceWindowSchema.optional(),
exporters: z.array(flowEntityCardSchema),
lastExporterIp: z.string().nullable().optional(),
lastError: z.string().nullable().optional(),
@@ -294,6 +302,7 @@ export const flowExportersDtoSchema = z.object({
})
export const flowClientsDtoSchema = z.object({
sourceWindow: flowSourceWindowSchema.optional(),
clients: z.array(flowEntityCardSchema),
})
@@ -390,6 +399,7 @@ export const flowMapCountryServiceGroupDtoSchema = z.object({
})
export const flowMapHopsDtoSchema = z.object({
sourceWindow: flowSourceWindowSchema.optional(),
hops: z.array(flowMapHopDtoSchema),
live: z.boolean(),
rangeMinutes: z.number().int().positive(),
+4 -1
View File
@@ -13,7 +13,9 @@ for (const mode of ['servers','flows'] as const) for (const minutes of [5,15]) {
const url=new URL(r.request().url()),path=url.pathname,span=url.searchParams.get('range')==='5m'?5:url.searchParams.get('range')==='15m'?15:60
const built=history(span),server={id:'1',name,site:'TEST',country:'RU',status:'online',...built,rxTotal:1,txTotal:1,volumeUnit:'GiB'}
const card={id:'1',name,subtitle:'',site:'TEST',country:'RU',status:'online',rxNow:1,txNow:0,sessions:1,bytes:60000,rxSeries:[1,2,1],txSeries:[0,0,0]}
const analytics={bpsNow:1000000,bytes:60000,packets:10,conversations:1,uniqueSrc:1,uniqueDst:1,topProto:'TCP',rxSeries:Array.from({length:span},(_,i)=>1+i%3),txSeries:Array(span).fill(0),applications:[],protocols:[],sources:[],destinations:[],interfaces:[],conversationsList:[],ifaces:[],live:false}
const sourceWindow=mode==='flows'&&span===15?{requestedMinutes:15,effectiveMinutes:7}:undefined
const chartMinutes=sourceWindow?.effectiveMinutes??span
const analytics={bpsNow:1000000,bytes:60000,packets:10,conversations:1,uniqueSrc:1,uniqueDst:1,topProto:'TCP',rxSeries:Array.from({length:chartMinutes},(_,i)=>1+i%3),txSeries:Array(chartMinutes).fill(0),applications:[],protocols:[],sources:[],destinations:[],interfaces:[],conversationsList:[],ifaces:[],live:false,sourceWindow}
if(path.endsWith('/live'))return r.fulfill({status:503,json:{error:'Live выключен в проверке истории'}})
const json=path==='/api/auth/config'?{required:false}:path==='/api/traffic/servers'?{servers:[server]}:
path==='/api/traffic/servers/1'?{server}:path==='/api/traffic/flow/exporters'?{exporters:[card]}:
@@ -28,6 +30,7 @@ for (const mode of ['servers','flows'] as const) for (const minutes of [5,15]) {
await page.getByRole('button',{name:`${minutes}м`,exact:true}).click()
const chart=page.getByRole('region',{name:'История RX/TX'})
await expect(chart).toBeVisible()
if(mode==='flows'&&minutes===15)await expect(page.getByText('Данные за последние 7 мин из запрошенных 15 мин.')).toBeVisible()
const curves=chart.locator('path.recharts-line-curve')
await expect(curves).toHaveCount(2)
await expect.poll(async()=>((await curves.first().getAttribute('d'))?.match(/[CL]/g)||[]).length).toBeGreaterThan(2)