Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 3s
Docker images / frontend-image (push) Successful in 2m14s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 16s
Docker images / publish-release (push) Successful in 10s
Docker images / notify-webhook (push) Successful in 1s
208 lines
17 KiB
TypeScript
208 lines
17 KiB
TypeScript
"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 } 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"
|
||
|
||
export function InspectorMetrics({ rows }: { rows: [string, ReactNode, string?][] }) {
|
||
return <dl className="grid grid-cols-2 gap-px overflow-hidden rounded-t-lg border-b bg-border">
|
||
{rows.map(([name, value, title]) => <div key={name} title={title} className="flex min-w-0 flex-col gap-0.5 bg-card px-3.5 py-2.5">
|
||
<dt className="text-[11px] text-muted-foreground">{name}</dt>
|
||
<dd className="font-mono text-sm font-semibold leading-tight [overflow-wrap:anywhere]">{value}</dd>
|
||
</div>)}
|
||
</dl>
|
||
}
|
||
|
||
export function serviceUsers(service: FlowMapService, paths: FlowMapServicePath[]): FlowMapUser[] {
|
||
const users = new Map<string, FlowMapUser>()
|
||
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 <section aria-label="Трафик по пользователям" title="Сохранённые потоки NetFlow и привязки интерфейсов. Узел может быть определён по наблюдаемому GRE-соседу." className="space-y-2 border-b px-3.5 py-3">
|
||
<h3 className="flex justify-between gap-2 font-mono text-[11px] text-muted-foreground">
|
||
<span>Пользователи</span><span>NetFlow · {windowLabel}</span>
|
||
</h3>
|
||
{!ranked.length && <p className="text-xs text-muted-foreground">{users ? "Нет сохранённых потоков в этом интервале" : "Разбивка в этом снимке недоступна"}</p>}
|
||
{ranked.length > 0 && <ul className="max-h-52 space-y-2 overflow-y-auto">
|
||
{ranked.map(user => <li key={user.clientId} className="flex items-start justify-between gap-2 text-xs">
|
||
<span className="min-w-0 font-medium [overflow-wrap:anywhere]">{user.clientId === "—" ? "Без привязки к пользователю" : user.clientName}</span>
|
||
<span className="shrink-0 text-right font-mono tabular-nums">
|
||
{formatNetflowRate(user)}
|
||
<span className="block text-[10px] text-muted-foreground">{formatBytes(user.bytes)}{total > 0 && ` · ${Math.round(user.bytes / total * 100)}%`}</span>
|
||
</span>
|
||
</li>)}
|
||
</ul>}
|
||
</section>
|
||
}
|
||
|
||
export function NodeHistory({ base, id, refresh, degraded }: { base: string | null; id: string; refresh: number; degraded: boolean }) {
|
||
const [sample, setSample] = useState<ReturnType<typeof projectTrafficObservations> | 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) && <div className="border-b px-3 py-2"><div className="rounded-md border border-warning/30 bg-warning/10 px-2.5 py-2 text-xs text-warning-foreground [overflow-wrap:anywhere]">
|
||
{warning ? <>Сбор трафика{obs?.lastAttemptAt ? " · " + new Date(obs.lastAttemptAt).toLocaleString("ru-RU") : ""}. {warning}</> : "Последний опрос устройства вернул статус «Внимание»."}
|
||
</div></div>}
|
||
<section aria-label="История трафика устройства" title="Сумма RX и TX по сохранённым счётчикам интерфейсов за последние 24 часа" className="border-b px-3.5 py-3">
|
||
<div className="flex justify-between gap-2 text-[11px] text-muted-foreground"><span>Трафик · 24 ч</span><span className="font-mono">{peak !== null ? "пик " + fmtRate(peak) : "—"}</span></div>
|
||
{peak !== null ? <><div className="my-2 [&_svg]:h-12 [&_svg]:w-full"><Sparkline data={points} width={244} height={48} filled color="var(--chart-1)" /></div>
|
||
<div className="flex justify-between font-mono text-[10px] text-muted-foreground"><span>−24 ч</span><span>−12 ч</span><span>конец окна</span></div></>
|
||
: <p className="py-3 text-xs text-muted-foreground">{base !== null && !sample && !unavailable ? "Загрузка истории…" : "Нет подтверждённых измерений RX и TX"}</p>}
|
||
</section>
|
||
</>
|
||
}
|
||
|
||
export function ServiceInspector({ service, paths, exits, exitName, country, base, refresh, windowLabel, 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
|
||
activePath: FlowMapServicePath | null; onPath: (path: FlowMapServicePath) => void
|
||
onClose: () => void; filtered: boolean; onFilter: () => void
|
||
userId?: string; ix?: boolean; topology?: ReadonlySet<string>
|
||
}) {
|
||
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 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 <>
|
||
<header className="flex items-center gap-2 px-3 py-3">
|
||
<div className="grid size-8 shrink-0 place-items-center rounded-md bg-muted"><ServiceBrandIcon label={service.label} size={18} /></div>
|
||
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold" title={service.label}>{service.label}</h2>
|
||
<p className="truncate text-[11px] text-muted-foreground" title={flowAt ? new Date(flowAt).toLocaleString("ru-RU") : undefined}>{[service.category, asns.length === 1 ? "AS" + asns[0] : null, country, windowLabel].filter(Boolean).join(" · ")}</p></div>
|
||
<Badge size="sm" variant={observed ? "success-light" : "secondary"} title="Наличие трафика в окне NetFlow"><span aria-hidden>•</span>{stale ? "Архив" : observed ? "Есть трафик" : "Нет трафика"}</Badge>
|
||
<Button size="icon-xs" variant="ghost" aria-label="Закрыть детали назначения" onClick={onClose}><XIcon /></Button>
|
||
</header>
|
||
<div className="mx-0.5 mb-0.5 min-h-0 overflow-y-auto rounded-lg border">
|
||
<InspectorMetrics rows={[
|
||
["Скорость", formatNetflowRate({ bps: service.bps }), "Средняя скорость NetFlow за " + windowLabel],
|
||
[country ? "Доля страны" : "Доля трафика", new Intl.NumberFormat("ru-RU", {style:"percent", maximumFractionDigits:1}).format(service.share)],
|
||
["Объём · " + (currentVolume ? windowLabel : volume?.window ?? "24 ч"), <>{currentVolume ? formatBytes(service.bytes) : volume?.bytes == null ? "—" : formatBytes(volume.bytes)}{volume && <time dateTime={volume.at} title={new Date(volume.at).toLocaleString("ru-RU")} className="block text-[10px] font-normal text-muted-foreground">ответ {new Date(volume.at).toLocaleTimeString("ru-RU")}</time>}</>],
|
||
exitIds.length || !exporterIds.length
|
||
? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined]
|
||
: ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"],
|
||
]} />
|
||
<InspectorUsers users={serviceUsers(service, paths)} windowLabel={windowLabel} />
|
||
<section className="space-y-2 border-b px-3.5 py-3"><h3 className="text-[11px] text-muted-foreground">Путь трафика</h3>
|
||
{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 <button type="button" key={key} onClick={() => onPath(p)} aria-pressed={Boolean(active)} title={formatNetflowRate(p)} className={cn("flex w-full flex-wrap items-center gap-1 rounded-sm text-left", active && "ring-1 ring-primary")}>
|
||
{parts.map((name, i) => <span key={i} className="inline-flex max-w-full items-center gap-1">{i > 0 && <ChevronRightIcon aria-hidden className="size-3 shrink-0 text-muted-foreground" />}<span className={cn("truncate rounded-md bg-muted px-1.5 py-1 font-mono text-[10px] font-semibold", i === parts.length - 1 && "bg-chart-4/20")}>{name}</span></span>)}
|
||
{!p.enId && <span className="basis-full text-[10px] text-muted-foreground">
|
||
Наблюдение IPFIX{p.viaIface ? ` · интерфейс ${p.viaIface}` : ""} · выход не подтверждён
|
||
</span>}
|
||
</button>
|
||
})}
|
||
{rates.filter(e => !paths.some(p => (p.enId || p.viaId) === e.fromId && Boolean(p.enId) !== Boolean(e.observedOnly))).map(e => <div key={e.fromId} className="flex justify-between gap-2 text-xs"><span>{exitName(e.fromId)} → {service.label}{e.observedOnly && " · наблюдение IPFIX"}</span><span className="shrink-0 font-mono">{formatNetflowRate(e)}</span></div>)}
|
||
{remainder > 0 && <div className="flex justify-between gap-2 text-xs text-muted-foreground"><span>Выход не определён</span><span className="font-mono">{formatNetflowRate({bps:service.bps * remainder / service.bytes})}</span></div>}
|
||
{!paths.length && !rates.length && !remainder && <p className="text-xs text-muted-foreground">Маршрут не определён</p>}
|
||
</section>
|
||
<section className="space-y-3 border-b px-3.5 py-3"><h3 className="flex items-center justify-between font-mono text-[11px] text-muted-foreground"><span>Крупные потоки · {recent?.data.sourceWindow?.effectiveMinutes ?? 5} мин</span><span title="Наблюдения экспортёров">{recent ? flows.length : "—"}</span></h3>
|
||
{flows.map((f,i) => <div key={i} className="flex items-center gap-2 text-xs"><span aria-hidden className="size-1.5 shrink-0 rounded-full bg-[var(--status-online)]" /><div className="min-w-0 flex-1"><p className="font-medium [overflow-wrap:anywhere]">{f.src} → {f.dst}</p><p className="truncate text-[11px] text-muted-foreground" title={`Экспортёр: ${f.serverName || f.serverId}`}><span>{f.protoName}{f.dstPort ? "/" + f.dstPort : ""}</span> · {f.serverName || f.serverId}</p></div><span className="font-mono text-[11px] text-muted-foreground">{formatNetflowRate({bps:f.bps})}</span></div>)}
|
||
{!flows.length && <p className="text-xs text-muted-foreground">{recent ? "Сервис отсутствует в выборке крупных потоков" : "Нет подтверждённых записей"}</p>}
|
||
{recent && <time dateTime={recent.at} title={new Date(recent.at).toLocaleString("ru-RU")} className="block font-mono text-[10px] text-muted-foreground">ответ {new Date(recent.at).toLocaleTimeString("ru-RU")}</time>}
|
||
</section>
|
||
<div className="flex flex-wrap gap-1.5 px-3.5 py-3">
|
||
<Link href={`/traffic?${trafficQuery}`} className={buttonVariants({size:"xs"})}>Открыть в «Трафике»</Link>
|
||
<Button size="xs" variant="outline" aria-pressed={filtered} onClick={onFilter}>{filtered ? "Снять фильтр" : "Фильтр по сервису"}</Button>
|
||
</div>
|
||
</div>
|
||
</>
|
||
}
|