"use client" import { useEffect, useState, type ReactNode } from "react" import Link from "next/link" import { ChevronRightIcon, XIcon } from "lucide-react" import type { FlowAnalyticsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath, FlowMapUser, FlowServiceBasis } from "@mmapp/contracts/traffic-flow" import { flowMapHopsDtoSchema } from "@mmapp/contracts/traffic-flow" import { Badge } from "@/components/reui/badge" import { Sparkline } from "@/components/sparkline" import { Button, buttonVariants } from "@/components/ui/button" import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon" import { cn } from "@/lib/utils" import { formatBytes, fmtRate } from "@/lib/fmt-rate" import { formatNetflowRate } from "@/lib/map-netflow-hops" import { servicePathKey } from "@/lib/format-service-path-label" import { projectTrafficObservations } from "@/lib/traffic-observations" import { getFlowAnalytics, getFlowMapHops } from "@/shared/api/traffic-flow" import { requestJson } from "@/shared/api/http-client" import { matchesMapService } from "@/lib/flow-map-service-match" const evidenceLabel: Record = { catalog: "По каталогу", network: "По IP / ASN", port: "По протоколу / порту", heuristic: "Оценка по сети и порту", unknown: "Сервис не определён", } const percent = new Intl.NumberFormat("ru-RU", {style: "percent", maximumFractionDigits: 1}) export function InspectorMetrics({ rows }: { rows: [string, ReactNode, string?][] }) { return
{rows.map(([name, value, title]) =>
{name}
{value}
)}
} export function serviceUsers(service: FlowMapService, paths: FlowMapServicePath[]): FlowMapUser[] { const users = new Map() function add(clientId: string, clientName: string, bytes: number, bps: number) { const user = users.get(clientId) ?? { clientId, clientName, bytes: 0, bps: 0 } user.bytes += bytes user.bps += bps users.set(clientId, user) } let attributedBytes = 0 for (const p of paths) { add(p.clientId, p.clientName, p.bytes, p.bps) attributedBytes += p.bytes } if (service.bytes > attributedBytes) { const bytes = service.bytes - attributedBytes add("—", "—", bytes, service.bps * bytes / service.bytes) } return [...users.values()] } export function InspectorUsers({ users, windowLabel }: { users?: FlowMapUser[]; windowLabel: string }) { const ranked = [...(users ?? [])].sort((a, b) => b.bytes - a.bytes || a.clientName.localeCompare(b.clientName)) const total = ranked.reduce((sum, user) => sum + user.bytes, 0) return

ПользователиNetFlow · {windowLabel}

{!ranked.length &&

{users ? "Нет сохранённых потоков в этом интервале" : "Разбивка в этом снимке недоступна"}

} {ranked.length > 0 &&
    {ranked.map(user =>
  • {user.clientId === "—" ? "Без привязки к пользователю" : user.clientName} {formatNetflowRate(user)} {formatBytes(user.bytes)}{total > 0 && ` · ${Math.round(user.bytes / total * 100)}%`}
  • )}
}
} export function NodeHistory({ base, id, refresh, degraded }: { base: string | null; id: string; refresh: number; degraded: boolean }) { const [sample, setSample] = useState | null>(null) const [unavailable, setUnavailable] = useState(false) useEffect(() => { if (base === null) return const controller = new AbortController() void requestJson<{ server?: { id?: string } }>(base, `/api/traffic/servers/${encodeURIComponent(id)}?range=24h`, { signal: controller.signal }) .then(raw => { if (raw?.server?.id !== id) throw new Error("Не подтверждён сервер") const observations = projectTrafficObservations(raw.server) if (!controller.signal.aborted) { setSample(observations); setUnavailable(false) } }) .catch(() => { if (!controller.signal.aborted) { setSample(null); setUnavailable(true) } }) return () => controller.abort() }, [base, id, refresh]) const points = sample?.rxSeries.map((rx, i) => { const tx = sample.txSeries[i] return rx != null && tx != null ? rx + tx : null }) ?? [] const measured = points.filter((n): n is number => n !== null) const peak = measured.length ? Math.max(...measured) : null const obs = sample?.observations const warning = obs?.currentState === "error" ? obs.error : null return <> {(warning || degraded) &&
{warning ? <>Сбор трафика{obs?.lastAttemptAt ? " · " + new Date(obs.lastAttemptAt).toLocaleString("ru-RU") : ""}. {warning} : "Последний опрос устройства вернул статус «Внимание»."}
}
Трафик · 24 ч{peak !== null ? "пик " + fmtRate(peak) : "—"}
{peak !== null ? <>
−24 ч−12 чконец окна
:

{base !== null && !sample && !unavailable ? "Загрузка истории…" : "Нет подтверждённых измерений RX и TX"}

}
} export function ServiceInspector({ service, paths, exits, exitName, country, base, refresh, windowLabel, history, shareOfVisible, flowAt, stale, activePath, onPath, onClose, filtered, onFilter, userId, ix, topology }: { service: FlowMapService; paths: FlowMapServicePath[]; exits: FlowMapServiceEdge[]; exitName: (id: string) => string country?: string; base: string | null; refresh: number; windowLabel: string; flowAt: string | null; stale: boolean history?: {service?: FlowMapService; window: string} shareOfVisible: boolean activePath: FlowMapServicePath | null; onPath: (path: FlowMapServicePath) => void onClose: () => void; filtered: boolean; onFilter: () => void userId?: string; ix?: boolean; topology?: ReadonlySet }) { const [recent, setRecent] = useState<{ data: FlowAnalyticsDto; at: string } | null>(null) const [volume, setVolume] = useState<{ bytes: number | null; window: string; at: string } | null>(null) const canMatchService = !service.id.endsWith("svc:other") && service.label !== "Прочее" const sources = [...new Set(paths.map(path => path.viaId).filter(id => /^[1-9]\d*$/.test(id)))].sort() const exporter = sources.length === 1 && /^[1-9]\d*$/.test(sources[0]) ? sources[0] : undefined const scopedUser = userId && !userId.startsWith("ix:") ? userId : undefined const scoped = Boolean(userId || topology) useEffect(() => { if (base === null) return const controller = new AbortController() const init = { signal: controller.signal } if (canMatchService && (!scoped || scopedUser || exporter && !userId)) void getFlowAnalytics(base, { range: "5m", userId: scopedUser, serverId: !scopedUser && scoped ? exporter : undefined }, init) .then(data => { if (!controller.signal.aborted) setRecent({data, at: new Date().toISOString()}) }) .catch(() => { if (!controller.signal.aborted) setRecent(null) }) if (!scoped) void getFlowMapHops(base, { range: "24h" }, init) .then(raw => { if (controller.signal.aborted) return const data = flowMapHopsDtoSchema.parse(raw) const minutes = data.sourceWindow?.effectiveMinutes ?? 1440 if (data.rangeMinutes !== minutes || data.windowSec !== minutes * 60 || data.sourceWindow && data.sourceWindow.requestedMinutes !== 1440) throw new Error("Не подтверждено окно объёма") const services = country ? data.countryServiceGroups?.find(g => g.countryId === service.id.split("|")[0])?.services : data.services setVolume({bytes: services?.find(row => row.id === service.id)?.bytes ?? null, window: data.sourceWindow ? minutes + " мин" : "24 ч", at: new Date().toISOString()}) }) .catch(() => { if (!controller.signal.aborted) setVolume(null) }) return () => controller.abort() }, [base, refresh, country, service.id, canMatchService, scoped, scopedUser, exporter, userId]) const countryFilter = service.id.startsWith("cc:other|") ? "unknown" : country const flows = recent?.data.conversationsList.filter(row => (!topology || topology.has(row.enId || row.serverId)) && matchesMapService(row, service.label, countryFilter)) .sort((a, b) => b.bps - a.bps).slice(0, 5) ?? [] const asns = [...new Set(flows.flatMap(flow => flow.dstAsn ? [flow.dstAsn] : []))] const rates = [...exits].sort((a, b) => b.bps - a.bps) const exitIds = [...new Set([...rates.filter(e => !e.observedOnly).map(e => e.fromId), ...paths.map(p => p.enId).filter(Boolean)])] const exporterIds = [...new Set([...rates.filter(e => e.observedOnly).map(e => e.fromId), ...paths.filter(p => !p.enId).map(p => p.viaId)])] const attributedBytes = (country ? paths : exits).reduce((sum, entry) => sum + entry.bytes, 0) const remainder = Math.max(0, service.bytes - attributedBytes) const observed = service.bytes > 0 && !stale const currentVolume = base === null || scoped const average = history ? history.service : service const averageWindow = history?.window ?? windowLabel const volumeBytes = currentVolume ? average?.bytes : volume?.bytes const trafficTypes = service.trafficTypes ?? [] const serviceEvidence = service.serviceEvidence ?? [] const otherTypeBytes = Math.max(0, service.bytes - trafficTypes.reduce((sum, row) => sum + row.bytes, 0)) const typeShare = (bytes: number) => percent.format(Math.min(1, bytes / service.bytes)) const trafficQuery = new URLSearchParams({ view: "flows", service: service.label, serviceId: service.id, from: "map" }) if (scopedUser) trafficQuery.set("user", scopedUser) else if (exporter) trafficQuery.set("server", exporter) if (userId?.startsWith("ix:")) trafficQuery.set("mapUser", userId) if (ix) trafficQuery.set("mapView", "ix") if (topology) { if (!scopedUser) trafficQuery.set("exporters", sources.join(",")) trafficQuery.set("nodes", [...topology].filter(id => /^[1-9]\d*$/.test(id)).join(",")) } if (countryFilter) trafficQuery.set("country", countryFilter) return <>

{service.label}

{[service.category, asns.length === 1 ? "AS" + asns[0] : null, country, windowLabel].filter(Boolean).join(" · ")}

•{stale ? "Архив" : observed ? "Есть трафик" : "Нет трафика"}
{volumeBytes == null ? "—" : formatBytes(volumeBytes)}{!currentVolume && volume && }], exitIds.length || !exporterIds.length ? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined] : ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"], ]} /> {trafficTypes.length > 0 && service.bytes > 0 &&

Состав трафикаIPFIX · {windowLabel}

{trafficTypes.map(({transport, application, bytes}) =>
{application ? `${application} · ${transport}` : transport}
{typeShare(bytes)}
)} {otherTypeBytes > 0 &&
Остальные типы
{typeShare(otherTypeBytes)}
}
{trafficTypes.some(row => row.application) &&

Приложения определены по портам.

} {service.lastBucketAt &&

Последняя минута с потоками

} {serviceEvidence.length ?
    {serviceEvidence.map(row =>
  • {evidenceLabel[row.basis]}{serviceEvidence.length > 1 && ` · ${typeShare(row.bytes)}`}
  • )}
: null}
}

Путь трафика

{paths.map(p => { const parts = [p.clientName !== "—" ? p.clientName : "", p.viaId !== p.enId ? p.viaName : "", p.enName, service.label].filter(Boolean) const key = servicePathKey(p) const active = activePath && servicePathKey(activePath) === key return })} {rates.filter(e => !paths.some(p => (p.enId || p.viaId) === e.fromId && Boolean(p.enId) !== Boolean(e.observedOnly))).map(e =>
{exitName(e.fromId)} → {service.label}{e.observedOnly && " · наблюдение IPFIX"}{formatNetflowRate(e)}
)} {remainder > 0 &&
Выход не определён{formatNetflowRate({bps:service.bps * remainder / service.bytes})}
} {!paths.length && !rates.length && !remainder &&

Маршрут не определён

}

Крупные потоки · {recent?.data.sourceWindow?.effectiveMinutes ?? 5} мин{recent ? flows.length : "—"}

{flows.map((f,i) => { const port = f.internetPeerPort || f.dstPort const transport = port ? `${f.protoName}/${port}` : f.protoName return

{f.src} → {f.dst}

{transport}{f.application && f.application !== transport && f.application !== f.protoName && ` · ${f.application}`} · {f.serverName || f.serverId}

{formatNetflowRate({bps:f.bps})}
})} {!flows.length &&

{recent ? "Сервис отсутствует в выборке крупных потоков" : "Нет подтверждённых записей"}

} {recent && }
Открыть в «Трафике»
}