Compare commits

..
15 Commits
Author SHA1 Message Date
Denozordec d174bca5d6 fix(ui): интегрировать макет карты сети и трафика
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
2026-11-26 23:27:54 +07:00
Denozordec 2ca40fbb4d fix(map): исправить маршруты и легенду, показать трафик пользователей
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m33s
Docker images / frontend-image (push) Successful in 2m13s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 31s
Docker images / backend-image (push) Successful in 2m2s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
2026-11-26 11:58:31 +07:00
Denozordec 589fc782f9 fix(map): исправить трафик и карточки карты сети
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m29s
Docker images / frontend-image (push) Successful in 2m13s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 1m59s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-26 10:34:20 +07:00
DenozordecandClaude Opus 5.5 fcbf219725 fix(ui): оболочка общего макета v2 и карта сети без наложений по макету v3
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Successful in 10m21s
Docker images / frontend-image (push) Successful in 2m15s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 1m49s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
Вернуть оболочку общего макета v2 и EvoBGP вместо вложенной панели v3;
читаемые надписи состояния системы в светлой теме. Карта сети: одна
подпись на связь без наложений на карточки, ленты NetFlow вместо бейджей,
страница поэлементно по макету v3, исправлен расчёт скорости NetFlow в KPI.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 08:53:42 +07:00
DenozordecandClaude Opus 5.5 95a0ebeb18 fix(ui): подписи GRE из известных значений и карта над миникартой
Подпись связи собирается из того, что известно: RTT, скорость NetFlow
пары (записи одного роутера складываются, оба конца туннеля — максимум),
«GRE ×N»; «—» — только когда не известно ничего. Не влезающая между
карточками подпись не рисуется, полное значение — в title линии.
«N мс» на карточке скрывается, только если RTT туннеля уже на подписи.

Вписывание оставляет снизу полосу под панель масштаба и миникарту, они
не закрывают объекты; e2e проверяет и эти оверлеи. Подсказки поиска
закрываются, когда фокус уходит из поиска. В инспекторе устройства —
ряд переходов: Терминал, Firewall, GRE-туннели, Трафик, Навести на узел.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 03:35:49 +07:00
DenozordecandClaude Opus 5.5 2b0b9a5fa5 fix(ui): читаемая надпись состояния системы в светлой теме
«Внимание» / «Сбой» и счётчики в окне состояния системы были жёлтым и
красным токеном фона (контраст 1.66 в светлой теме). Текст — токены
*-foreground, как у бейджей ReUI; operational-a11y и server-rail снова
без нарушений контраста.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 03:35:49 +07:00
DenozordecandClaude Opus 5.5 9b2c2327a6 fix(ui): карта сети без наложений подписей и поэлементно как в макете v3
Холст: одна подпись на связь (параллельные GRE — «GRE ×N»), подписи
раскладываются по своей кривой без наложения на карточки и друг на друга,
не влезающая не рисуется; Exit → назначения — ленты NetFlow по скорости
без бейджей; имя хоста без домена, кегль 14→12 px и многоточие вместо
сжатия textLength; флаг справа сверху, WAN→JH — приглушённый пунктир.

Страница: подзаголовок со снимком и NetFlow вместо строки статистики,
панель инструментов в одну строку, поиск с подсказками вместо списка
устройств, масштаб «− % + Вписать Авто-раскладка» снизу слева, миникарта
справа, шкала времени как в макете, инспектор отдельным фреймом с
пустым состоянием, плитки и «Устройство» в две колонки, легенда макета.

KPI: скорость NetFlow считалась как Мбит/с из бит/с (показывало Гбит/с),
склонения «1 узел / 2 узла», Exit-узлы и недоступные GRE в подвалах.
Карта не падает, если /api/ix/topology вернул ответ без links.

Тесты: раскладка подписей и ленты (unit), отсутствие наложений на
наборе как на проде и в сетке JH × Exit (e2e), спеки карты обновлены.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 02:37:57 +07:00
DenozordecandClaude Opus 5.5 ec2fb54e04 fix(ui): вернуть оболочку общего макета v2 и EvoBGP
Оболочка приложения снова как в общем макете v2 (шаблон TplOps) и в EvoBGP
вместо варианта из макета v3:
- основная область без «вставки»-карточки, меню во всю высоту;
- меню: переключатель приложений с пунктом «Настроить на портале»,
  «Поиск и команды ⌘K», «Закреплённые» со звёздочкой, сворачиваемые
  группы, точки проблем у разделов вместо счётчиков;
- шапка: «Главная / раздел / страница», окно «Источники и свежесть
  данных», поиск на телефоне и «Состояние системы» (Норма / Внимание /
  Сбой) с проблемами, метриками и переходом в мониторинг;
- сетка приложений в шапке убрана: её заменяет переключатель в меню.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 00:44:37 +07:00
DenozordecandClaude Opus 5.5 c94d417f1b feat(ui): перенести пилотные разделы на макет v3
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m53s
Docker images / frontend-image (push) Successful in 2m15s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 1m54s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
Слияние ветки claude/sad-bassi-fe48a8: этап 0 и пилот интеграции макета v3.

- оболочка: inset-сайдбар, крошки «Главная / …», заголовок страницы
  и индикатор свежести данных; общие блоки reui-kit/ops-blocks;
- дашборд: ёмкость, показатели со спарклайнами, сводка источников,
  вкладки «Обзор / Источники и время получения / История RTT»;
- статистика: вкладки «Обзор / Сводная (куб) / Срезы», демо-куб;
- трафик: вкладки разделов, детали с периодом и скоростями,
  «Доля RX», «Интерфейсы сервера»;
- карта сети: колонки макета, карточки узлов, KPI-полоса, панель
  объекта с вкладками, «Момент времени» и рабочая панель снизу.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 21:30:25 +07:00
DenozordecandClaude Opus 5.5 dd6e6b0b77 feat(ui): разделы карты сети по макету v3
- панель инструментов: поиск первым, вид «Вся сеть / IX и клиенты»,
  «Сервисы / Страны», окно «Фильтр» со статусами и ролями, справа
  «Слои» и «Легенда»;
- панель объекта: шапка с плиткой роли, адресом и статусом, вкладки
  «Обзор» (RTT, сессии, входящий/исходящий трафик, устройство,
  назначения через узел, ресурсы, действия), «Интерфейсы» (WAN-аплинки
  и трафик интерфейсов за окно NetFlow) и «GRE»;
- «Момент времени» под картой: инциденты из ленты событий за 24 часа
  и метка Live; архив снимков карты бэкенд не хранит;
- рабочая панель под картой: вкладки «Потоки NetFlow», «RTT каналов»,
  «Назначения» и «События», строки выбранного объекта подсвечены;
- на телефоне окно легенды растягивается по ширине экрана.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 00:08:07 +07:00
DenozordecandClaude Opus 5.5 a4694b8481 feat(ui): перерисовать карту сети по колонкам макета v3
- полосы Home Router · WAN · JumpHost · Exit (и IX) · назначения
  с заголовками и счётчиками; WAN-аплинки в своей колонке и не
  наезжают друг на друга;
- узлы — карточки 160×56 с плиткой роли, точкой статуса, именем,
  задержкой, площадкой и флагом; длинное имя ужимается, а не обрезается;
- WAN — «таблетки», назначения — строки с иконкой, категорией,
  скоростью, долей и полосой; при раскрытой стране обе колонки компактные;
- связи — горизонтальные кривые между гранями карточек; подписи RTT
  и NetFlow рисуются поверх карточек и остаются кликабельными;
- легенда — выпадающее окно кнопки «Легенда» в панели инструментов,
  закрыта по умолчанию;
- масштаб, перетаскивание, миникарта, клавиатура и экспорт SVG сохранены;
  ревизия раскладки 8 сбрасывает старые ручные позиции.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 23:41:56 +07:00
DenozordecandClaude Opus 5.5 640726aa86 fix(ui): доводка трафика и карты сети по макету v3
- карта: счётчики онлайн/с проблемами/оффлайн остались только в KPI-полосе,
  подпись NetFlow описывает среднюю скорость всех потоков окна,
  у кнопок статусов читаемое имя «Оффлайн 1»;
- трафик: детали клиента и интерфейса показывают скорости двумя колонками,
  как у сервера; на странице и в панели потоков нет текста мельче text-xs;
- e2e: «Объяснить» открывает вкладку источников с баннером
  «Не обновлены источники», счётчик оффлайн проверяется в KPI-полосе.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 23:10:54 +07:00
DenozordecandClaude Opus 5.5 67b1d9cde2 feat(ui): перенести трафик и карту сети на макет v3
Трафик: шапка деталей с названием, статусом и сегментным периодом;
текущие и пиковые скорости двумя колонками; блоки «Доля RX» и
«Интерфейсы сервера»; сегментная сортировка и поле поиска как в макете;
в карточках списка нет текста мельче text-xs.

Карта сети: KPI-полоса над картой (узлы со статусами-фильтрами,
GRE-туннели, NetFlow за окно, узлы, требующие внимания), прокручиваемая
страница с картой фиксированной высоты, поиск в стиле макета.
На узких экранах KPI-полоса уходит под карту, чтобы карта помещалась
в экран и работал жест панорамирования.

Скриншоты docs/ux-ui обновлены прогоном e2e пилота.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 22:56:03 +07:00
DenozordecandClaude Opus 5.5 8781f68674 fix(ui): демо-куб статистики и честная подпись фактора здоровья
Без живого API статистика показывает демо-куб вместо пустого состояния,
как в макете v3. Фактор «Задержка (RTT)» переименован в «Пробы в норме»:
его полоса — доля проб в норме, а не задержка.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 22:31:02 +07:00
DenozordecandClaude Opus 5.5 5fd028800a feat(ui): перенести дашборд, статистику и трафик на макет v3
Этап 0 и пилот интеграции макета v3:
- оболочка: inset-сайдбар, крошки «Главная / … /», индикатор свежести,
  заголовок страницы PageTitle;
- общие блоки reui-kit/ops-blocks: SectionFrame, CapacityGrid, SparkKpiGrid,
  ToneBadge;
- дашборд: ёмкость, показатели со спарклайнами, сводка источников,
  вкладки «Обзор / Источники и время получения / История RTT»,
  здоровье сети, лента инцидентов, схема Internet path, сводка маршрута,
  таблица «Требует внимания», настройка видимости виджетов;
- статистика: вкладки «Обзор / Сводная (куб) / Срезы», доли объёма;
- трафик: вкладки разделов со счётчиками, рамки списка и деталей,
  кнопка «Месячный отчёт».

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 22:23:16 +07:00
94 changed files with 5433 additions and 3440 deletions

No files matched your search

+394 -306
View File
@@ -1,349 +1,437 @@
"use client"
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { useEffect, useMemo, useState } from "react"
import Link from "next/link"
import {
ActivityIcon,
BellIcon,
CableIcon,
FilterIcon,
GitMergeIcon,
HardDriveIcon,
ChartColumnIcon,
CircleAlertIcon,
HeartPulseIcon,
MapIcon,
LayoutDashboardIcon,
ServerIcon,
ShieldIcon,
SlidersHorizontalIcon,
TableIcon,
} from "lucide-react"
import { Button, buttonVariants } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Alert, AlertAction, AlertDescription, AlertTitle } from "@/components/reui/alert"
import { Badge } from "@/components/reui/badge"
import { PageHeader } from "@/components/page-header"
import { OpsPanel } from "@/components/ops-panel"
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
import { QuickActionGrid } from "@/components/reui-kit/quick-action-grid"
import { AttentionQueue } from "@/components/reui-kit/attention-queue"
import { PageTitle } from "@/components/page-title"
import { DataFreshness } from "@/components/data-freshness"
import { EmptyState } from "@/components/empty-state"
import { CapacityGrid, SectionFrame, SparkKpiGrid, ToneBadge, seriesDelta, type Tone } from "@/components/reui-kit/ops-blocks"
import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart"
import { LatencyChart } from "@/components/dashboard/latency-chart"
import { DashboardEventsTimeline } from "@/components/dashboard/dashboard-events-timeline"
import { InternetPathPanel } from "@/components/dashboard/internet-path-panel"
import { DashboardSourcesSummary, dashboardSourceRows, sourceErrorText } from "@/components/dashboard/dashboard-sources-summary"
import {
DashboardAttentionGrid,
DashboardHealth,
DashboardIncidents,
DashboardQuickLinks,
type AttentionGridRow,
} from "@/components/dashboard/dashboard-overview-blocks"
import { DashboardActiveProbesDataGrid } from "@/components/data-grids/dashboard-active-probes-data-grid"
import { EmptyState } from "@/components/empty-state"
import { DashboardDataStatus } from "@/components/dashboard/dashboard-data-status"
import { Badge } from "@/components/reui/badge"
import { buttonVariants } from "@/components/ui/button"
import { cn } from "@/lib/utils"
import { fmtRate } from "@/lib/fmt-rate"
import { DASHBOARD_SOURCES, type DashboardSource, type DashboardSources } from "@/lib/dashboard-source-state"
import { useDashboardLive, type AttentionRow } from "@/hooks/use-dashboard-live"
const WIDGETS = {
cap: "Ёмкость",
spark: "Показатели",
sources: "Сводка источников",
health: "Здоровье сети",
timeline: "Лента инцидентов",
path: "Internet path",
attention: "Требует внимания",
latency: "Задержка до серверов",
traffic: "Пропускная способность",
probes: "Активные пробы",
links: "Быстрые переходы",
} as const
type Widget = keyof typeof WIDGETS
const HIDDEN_WIDGETS_LS = "mm:dashboard-hidden-widgets"
function useHiddenWidgets() {
const [hidden, setHidden] = useState<Set<Widget>>(new Set())
useEffect(() => {
try {
const raw = JSON.parse(localStorage.getItem(HIDDEN_WIDGETS_LS) ?? "[]")
if (Array.isArray(raw)) queueMicrotask(() => setHidden(new Set(raw.filter((key): key is Widget => key in WIDGETS))))
} catch {
/* повреждённое значение — показываем все виджеты */
}
}, [])
function toggle(key: Widget, visible: boolean) {
setHidden((previous) => {
const next = new Set(previous)
if (visible) next.delete(key)
else next.add(key)
try {
localStorage.setItem(HIDDEN_WIDGETS_LS, JSON.stringify([...next]))
} catch {
/* хранилище недоступно — настройка действует до перезагрузки */
}
return next
})
}
return { hidden, toggle }
}
function fmtIntRu(n: number): string {
return n.toLocaleString("ru-RU")
}
function AttentionRows({ rows }: { rows: AttentionRow[] }) {
const [expanded,setExpanded]=useState(false)
const [visible,setVisible]=useState(55)
function renderRow(row: AttentionRow) {
return (
<Link
key={row.id}
href={row.href}
className="hover:bg-muted/40 focus-visible:ring-ring flex min-w-0 items-start justify-between gap-2 rounded-md px-1 py-1.5 focus-visible:ring-2"
>
<span className="min-w-0 wrap-anywhere text-sm font-medium">{row.title}</span>
<Badge
size="sm"
variant={row.tone === "warning" ? "warning-light" : "destructive-light"}
className="shrink-0"
>
{row.hint}
</Badge>
</Link>
)
function averageSeries(series: Record<string, (number | null)[]>): number[] {
const rows = Object.values(series)
const length = Math.max(0, ...rows.map((values) => values.length))
const out: number[] = []
for (let i = 0; i < length; i++) {
const values = rows.map((row) => row[i]).filter((v): v is number => typeof v === "number" && Number.isFinite(v))
if (values.length) out.push(values.reduce((sum, v) => sum + v, 0) / values.length)
}
return out
}
return (
<div className="flex flex-col gap-0.5">
{rows.slice(0, 5).map(renderRow)}
{rows.length > 5 && (
<details onToggle={event=>{setExpanded(event.currentTarget.open);if(!event.currentTarget.open)setVisible(55)}}>
<summary className="cursor-pointer rounded-md px-1 py-2 text-xs text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring">Ещё {rows.length - 5}</summary>
{expanded && rows.slice(5,visible).map(renderRow)}
{expanded && rows.length>visible && <Button type="button" variant="ghost" size="sm" onClick={()=>setVisible(count=>Math.min(count+50,rows.length))}>Показать ещё {Math.min(50,rows.length-visible)}</Button>}
</details>
)}
</div>
)
function toGridRows(rows: AttentionRow[], kind: AttentionGridRow["kind"]): AttentionGridRow[] {
return rows.map((row) => ({
id: row.id,
title: row.title,
kind,
hint: row.hint,
href: row.href,
tone: row.tone === "destructive" ? "er" : "wn",
confirmed: row.hint !== "Статус неизвестен",
}))
}
export default function DashboardPage() {
const dash = useDashboardLive()
const { hidden, toggle } = useHiddenWidgets()
const [tab, setTab] = useState("over")
const [mockAt] = useState(() => Date.now())
const show = (key: Widget) => !hidden.has(key)
// Демо-режим не опрашивает API: показываем источники полученными в момент открытия страницы.
const sources: DashboardSources = useMemo(
() => dash.isLive ? dash.sources : Object.fromEntries((Object.keys(DASHBOARD_SOURCES) as DashboardSource[]).map((key) => [key, { receivedAt: mockAt, error: null }])),
[dash.isLive, dash.sources, mockAt],
)
const sourceRows = dashboardSourceRows(sources)
const failedSources = sourceRows.filter((row) => row.error)
const received = sourceRows.map((row) => row.receivedAt).filter((at): at is number => at != null)
const freshAt = received.length ? Math.max(...received) : null
const offline = dash.offlineCount
const health = dash.probeDown + dash.probeWarn
const problems = dash.probeDown + dash.probeWarn
const serverTrouble = offline > 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0
const serverCaption = !dash.availability.servers ? "нет данных" : !dash.isLive
? "демо"
: serverTrouble
? [offline > 0 ? `${offline} не в сети` : null, dash.unknownServerCount > 0 ? `Статус неизвестен: ${dash.unknownServerCount}` : null, dash.degradedServerCount > 0 ? `Ухудшение: ${dash.degradedServerCount}` : null].filter(Boolean).join(" · ")
: dash.totalServers > 0 ? "все в сети" : "нет серверов"
const latencySeries = dash.latency.kind === "mock" || dash.latency.kind === "live" ? averageSeries(dash.latency.series) : []
const rttNow = latencySeries.length ? Math.round(latencySeries[latencySeries.length - 1]) : null
const probesMeasured = useMemo(() => dash.enabledProbes.filter((p) => p.status !== "unknown"), [dash.enabledProbes])
const avgLoss = probesMeasured.length ? probesMeasured.reduce((sum, p) => sum + (p.loss ?? 0), 0) / probesMeasured.length : null
const okSources = sourceRows.filter((row) => row.tone === "ok").length
const attentionRows = [
...toGridRows(dash.attentionServers, "Сервер"),
...toGridRows(dash.attentionOverlay, "Туннель"),
...toGridRows(dash.attentionProbes, "Проверка"),
]
const emptyNotes = [
dash.attentionServers.length ? null : dash.reliable.servers ? (dash.totalServers > 0 ? "Серверы без проблем" : "Нет серверов") : "Серверы: состояние не подтверждено",
dash.attentionOverlay.length ? null : dash.reliable.overlay ? (dash.overlay.total > 0 ? "Туннели работают" : "Нет туннелей") : "Туннели: состояние не подтверждено",
dash.attentionProbes.length ? null : dash.reliable.probes ? (dash.probeCount > 0 ? "Проверки без ошибок" : "Нет активных проверок") : "Проверки: состояние не подтверждено",
].filter((note): note is string => note != null)
const latencyBody = dash.latency.kind === "loading" ? (
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" />
) : dash.latency.kind === "empty" ? (
<p className="text-muted-foreground px-4 py-10 text-center text-sm">{dash.latency.message}</p>
) : (
<LatencyChart series={dash.latency.series} labels={dash.latency.labels} />
)
const latencyDescription = dash.latency.kind === "mock" || dash.latency.kind === "live" ? dash.latency.subtitle : dash.latency.kind === "loading" ? "Загрузка…" : "Нет серии RTT"
return (
<div className="flex h-full flex-col">
<PageHeader crumbs={[{ label: "Обзор" }, { label: "Дашборд" }]} />
<PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Дашборд" }]} status={<DataFreshness at={freshAt} live={dash.isLive} />} />
<div className="flex-1 overflow-y-auto">
<div className="flex flex-col gap-4 px-4 py-4 md:gap-6 md:px-6 md:py-5">
{dash.isLive && <DashboardDataStatus sources={dash.sources} refreshing={dash.refreshing} onRefresh={dash.retry} />}
<KpiStatGrid
aria-label="Сводка дашборда"
isLoading={dash.loading}
items={[
{
id: "fleet",
label: "Серверы онлайн",
value: dash.availability.servers ? `${dash.onlineCount} / ${dash.totalServers}` : "—",
hint: !dash.availability.servers ? "нет данных" : !dash.isLive
? "демо"
: offline > 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0
? [offline > 0 ? `${offline} не в сети` : null,dash.unknownServerCount > 0 ? `Статус неизвестен: ${dash.unknownServerCount}` : null,dash.degradedServerCount > 0 ? `Ухудшение: ${dash.degradedServerCount}` : null].filter(Boolean).join(" · ")
: dash.totalServers > 0
? "все в сети"
: "нет серверов",
href: "/servers",
icon: <ServerIcon />,
iconClassName: "text-muted-foreground",
variant: offline > 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0 ? "warning" : "default",
},
{
id: "overlay",
label: "Туннели работают",
value: dash.availability.overlay ? String(dash.overlay.up) : "—",
hint: !dash.availability.overlay ? "не все источники доступны" : !dash.reliable.overlay ? "Последний успешный снимок; не все источники обновлены" : dash.overlay.total > 0 ? `Не работают: ${dash.overlay.down}` : "нет туннелей",
href: "/gre",
icon: <CableIcon />,
iconClassName: "text-info",
variant: dash.overlay.down > 0 ? "warning" : "default",
},
{
id: "bgp",
label: "Префиксы BGP",
value: dash.bgp?.prefixSum != null ? fmtIntRu(dash.bgp.prefixSum) : "—",
hint: dash.bgp ? `Сессий установлено: ${dash.bgp.establishedCount ?? "неизвестно"}${dash.bgp.prefixSum === null ? " · префиксы неизвестны" : ""}` : "нет данных",
href: "/bgp",
icon: <GitMergeIcon />,
iconClassName: "text-primary",
},
{
id: "health",
label: "Проверки с проблемами",
value: dash.availability.probes && dash.unknownProbeCount===0 ? String(health) : "—",
hint: dash.availability.probes ? `${dash.probeDown} ошибок · ${dash.probeWarn} предупреждений${dash.unknownProbeCount>0?` · неизвестны: ${dash.unknownProbeCount}`:""}` : "нет данных",
href: "/uptime",
icon: <BellIcon />,
iconClassName: health > 0 ? "text-destructive" : "text-muted-foreground",
variant: health > 0 ? "destructive" : "default",
},
]}
<div className="flex flex-col gap-6 px-4 pt-5 pb-10 md:px-7 md:pt-6">
<PageTitle
icon={<LayoutDashboardIcon />}
title="Дашборд"
description="Здоровье сети: индекс, события за период, Internet path, пробы и источники"
actions={
<>
<DropdownMenu>
<DropdownMenuTrigger render={<Button type="button" variant="outline"><SlidersHorizontalIcon data-icon="inline-start" />Настроить виджеты</Button>} />
<DropdownMenuContent align="end" className="w-60">
<DropdownMenuGroup>
<DropdownMenuLabel>Виджеты дашборда</DropdownMenuLabel>
{(Object.keys(WIDGETS) as Widget[]).map((key) => (
<DropdownMenuCheckboxItem key={key} checked={show(key)} onCheckedChange={(value) => toggle(key, !!value)}>
{WIDGETS[key]}
</DropdownMenuCheckboxItem>
))}
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
<Button type="button" onClick={dash.retry} disabled={dash.refreshing}>Обновить данные</Button>
</>
}
/>
<section aria-labelledby="dashboard-attention-title" className="flex min-w-0 flex-col gap-2">
<h2 id="dashboard-attention-title" className="text-sm font-semibold">Требует внимания</h2>
<AttentionQueue
className="lg:grid-cols-3"
columns={[
{
id: "nodes",
title: "Серверы",
icon: ServerIcon,
count: dash.attentionServers.length,
countVariant: "warning-light",
emptyTitle: dash.reliable.servers ? (dash.totalServers > 0 ? "Серверы без проблем" : "Нет серверов") : "Состояние не подтверждено",
emptyDescription: dash.reliable.servers ? "Нет включённых серверов с ошибками доступности." : "Проверьте состояние источников выше.",
children: <AttentionRows rows={dash.attentionServers} />,
},
{
id: "overlay",
title: "Туннели",
icon: CableIcon,
iconClassName: "text-info",
count: dash.attentionOverlay.length,
countVariant: "destructive-light",
emptyTitle: dash.reliable.overlay ? (dash.overlay.total > 0 ? "Туннели работают" : "Нет туннелей") : "Состояние не подтверждено",
emptyDescription: dash.reliable.overlay ? "В GRE, WireGuard и VXLAN проблем не обнаружено." : "Проверьте состояние источников выше.",
children: <AttentionRows rows={dash.attentionOverlay} />,
},
{
id: "probes",
title: "Проверки",
icon: HeartPulseIcon,
iconClassName: "text-destructive",
count: dash.attentionProbes.length,
countVariant: "destructive-light",
emptyTitle: dash.reliable.probes ? (dash.probeCount > 0 ? "Проверки без ошибок" : "Нет активных проверок") : "Состояние не подтверждено",
emptyDescription: dash.reliable.probes ? "Нет ошибок и предупреждений активных проверок." : "Проверьте состояние источников выше.",
children: <AttentionRows rows={dash.attentionProbes} />,
},
]}
/>
</section>
<div className="flex flex-col gap-5">
{failedSources.length > 0 ? (
<Alert variant="warning">
<CircleAlertIcon />
<AlertTitle>Не все источники доступны.</AlertTitle>
<AlertDescription>
Последний успешный снимок; не все источники обновлены. Не обновлены: {failedSources.map((row) => row.name).join(", ")}. Проверьте состояние источников ниже.
</AlertDescription>
<AlertAction>
<Button type="button" size="sm" variant="outline" onClick={() => setTab("src")}>Объяснить</Button>
</AlertAction>
</Alert>
) : null}
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[2fr_1fr]">
<OpsPanel
title="Задержка до серверов"
description={
dash.latency.kind === "mock" || dash.latency.kind === "live"
? dash.latency.subtitle
: dash.latency.kind === "loading"
? "Загрузка…"
: "Нет серии RTT"
}
contentClassName="px-3 pb-3"
>
{dash.latency.kind === "loading" && (
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" />
)}
{dash.latency.kind === "empty" && (
<p className="text-muted-foreground px-4 py-10 text-center text-sm">{dash.latency.message}</p>
)}
{(dash.latency.kind === "mock" || dash.latency.kind === "live") && (
<LatencyChart series={dash.latency.series} labels={dash.latency.labels} />
)}
</OpsPanel>
<OpsPanel
title="Последние события"
description="Система и BGP"
headerRight={
<Link href="/alerts" className={cn(buttonVariants({ variant: "ghost", size: "sm" }), "h-7 text-xs")}>
Все →
</Link>
}
>
<DashboardEventsTimeline
events={dash.recentEvents}
loading={dash.eventsLoading}
error={dash.eventsError}
{show("cap") ? (
<CapacityGrid
label="Ёмкость сети"
items={[
{
id: "fleet",
title: "Серверы онлайн",
caption: serverCaption,
value: dash.availability.servers ? dash.onlineCount : null,
total: dash.availability.servers ? dash.totalServers : null,
tone: serverTrouble ? "wn" : "ok",
icon: <ServerIcon />,
href: "/servers",
},
{
id: "overlay",
title: "Туннели работают",
caption: !dash.availability.overlay ? "не все источники доступны" : !dash.reliable.overlay ? "Последний успешный снимок; не все источники обновлены" : dash.overlay.total > 0 ? `GRE · WireGuard · VXLAN · не работают: ${dash.overlay.down}` : "нет туннелей",
value: dash.availability.overlay ? dash.overlay.up : null,
total: dash.availability.overlay ? dash.overlay.total : null,
tone: dash.overlay.down > 0 ? "wn" : "ok",
icon: <CableIcon />,
href: "/gre",
},
{
id: "health",
title: "Проверки с проблемами",
caption: dash.availability.probes ? `${dash.probeDown} ошибок · ${dash.probeWarn} предупреждений${dash.unknownProbeCount > 0 ? ` · неизвестны: ${dash.unknownProbeCount}` : ""}` : "нет данных",
value: dash.availability.probes && dash.unknownProbeCount === 0 ? problems : null,
total: dash.availability.probes && dash.unknownProbeCount === 0 ? dash.probeCount : null,
tone: problems > 0 ? "er" : "ok",
icon: <HeartPulseIcon />,
href: "/uptime",
},
]}
/>
</OpsPanel>
</div>
) : null}
<div>
<OpsPanel
title="Пропускная способность"
description={dash.traffic?.demo ? "Суммарный RX / TX · демо" : "Суммарная история RX / TX · 1 ч; значения — последний измеренный снимок"}
headerRight={<Link href="/traffic" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 text-xs")}>Трафик →</Link>}
contentClassName="px-3 pb-3"
>
{dash.loading && !dash.traffic ? (
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" />
) : !dash.traffic ? (
<p className="text-muted-foreground px-4 py-10 text-center text-sm">
Нет данных трафика за последний час.{" "}
<Link href="/traffic" className="underline underline-offset-2">
Открыть трафик
</Link>
</p>
) : (
<>
<div className="flex flex-wrap items-center gap-3 px-2 py-3 text-xs">
{dash.traffic.demo ? <Badge variant="outline" size="sm">демо</Badge> : !dash.traffic.observationsKnown ? <Badge variant="outline" size="sm">Измерения не подтверждены API</Badge> : null}
<span className="tabular-nums">RX {dash.traffic.rxNow===null?"—":fmtRate(dash.traffic.rxNow)}</span>
<span className="tabular-nums">TX {dash.traffic.txNow===null?"—":fmtRate(dash.traffic.txNow)}</span>
{show("spark") ? (
<SparkKpiGrid
label="Показатели сети"
items={[
{
id: "bgp",
title: "Префиксы BGP",
value: dash.bgp?.prefixSum != null ? fmtIntRu(dash.bgp.prefixSum) : "—",
footnote: dash.bgp ? `Сессий установлено: ${dash.bgp.establishedCount ?? "неизвестно"}${dash.bgp.prefixSum === null ? " · префиксы неизвестны" : ""}` : "нет данных",
href: "/bgp",
},
{
id: "rtt",
title: "Средний RTT",
value: rttNow ?? "—",
unit: rttNow != null ? " мс" : undefined,
series: latencySeries,
delta: seriesDelta(latencySeries, "wn", "ok"),
footnote: "за 1 ч",
href: "/uptime",
},
{
id: "rx",
title: "RX",
value: dash.traffic?.rxNow != null ? fmtRate(dash.traffic.rxNow) : "—",
series: dash.traffic?.rx.filter((v): v is number => typeof v === "number"),
delta: seriesDelta(dash.traffic?.rx.filter((v): v is number => typeof v === "number")),
footnote: "суммарно · 1 ч",
href: "/traffic",
},
{
id: "tx",
title: "TX",
value: dash.traffic?.txNow != null ? fmtRate(dash.traffic.txNow) : "—",
series: dash.traffic?.tx.filter((v): v is number => typeof v === "number"),
delta: seriesDelta(dash.traffic?.tx.filter((v): v is number => typeof v === "number")),
footnote: "суммарно · 1 ч",
href: "/traffic",
},
]}
/>
) : null}
{show("sources") ? <DashboardSourcesSummary rows={sourceRows} refreshing={dash.refreshing} onRefresh={dash.retry} /> : null}
<Tabs value={tab} onValueChange={(value) => setTab(String(value))} className="gap-5">
<TabsList variant="line" className="h-auto w-full justify-start gap-1 overflow-x-auto border-b p-0">
<TabsTrigger value="over" className="h-auto flex-none px-3 py-2.5 after:bottom-[-1px]">Обзор</TabsTrigger>
<TabsTrigger value="src" className="h-auto flex-none px-3 py-2.5 after:bottom-[-1px]">
Источники и время получения
<Badge variant="secondary" className="font-mono">{sourceRows.length}</Badge>
</TabsTrigger>
<TabsTrigger value="rtt" className="h-auto flex-none px-3 py-2.5 after:bottom-[-1px]">История RTT</TabsTrigger>
</TabsList>
<TabsContent value="over" className="flex flex-col gap-5">
{show("health") ? (
<DashboardHealth
factors={[
{ label: "Потери пакетов", value: avgLoss == null ? "—" : `${avgLoss.toLocaleString("ru-RU", { maximumFractionDigits: 1 })}%`, ratio: probesMeasured.length ? probesMeasured.filter((p) => (p.loss ?? 0) === 0).length / probesMeasured.length : null },
{ label: "Пробы в норме", value: probesMeasured.length ? `${probesMeasured.filter((p) => p.status === "up").length} из ${probesMeasured.length}` : "—", ratio: probesMeasured.length ? probesMeasured.filter((p) => p.status === "up").length / probesMeasured.length : null },
{ label: "Свежесть данных", value: `${okSources} из ${sourceRows.length}`, ratio: sourceRows.length ? okSources / sourceRows.length : null },
{ label: "Серверы в сети", value: dash.availability.servers ? `${dash.onlineCount} из ${dash.totalServers}` : "—", ratio: dash.availability.servers && dash.totalServers > 0 ? dash.onlineCount / dash.totalServers : null },
{ label: "Туннели", value: dash.availability.overlay ? `${dash.overlay.up} из ${dash.overlay.total}` : "—", ratio: dash.availability.overlay && dash.overlay.total > 0 ? dash.overlay.up / dash.overlay.total : null },
]}
/>
) : null}
{show("timeline") ? <DashboardIncidents events={dash.recentEvents} loading={dash.eventsLoading} error={dash.eventsError} /> : null}
{show("path") ? <InternetPathPanel model={dash.internetPath} loading={dash.internetPathLoading} error={dash.isLive ? dash.internetPathError : null} /> : null}
{show("attention") ? <DashboardAttentionGrid rows={attentionRows} emptyNotes={emptyNotes} /> : null}
{show("latency") ? (
<SectionFrame title="Задержка до серверов" description={latencyDescription} panelClassName="px-3.5 pt-3.5">
{latencyBody}
</SectionFrame>
) : null}
{show("traffic") ? (
<SectionFrame
title="Пропускная способность"
description={dash.traffic?.demo ? "Суммарный RX / TX · демо" : "Суммарная история RX / TX · 1 ч; значения — последний измеренный снимок"}
actions={<Link href="/traffic" className={buttonVariants({ variant: "outline", size: "sm" })}>Трафик →</Link>}
panelClassName="px-3.5 pt-3.5 pb-2"
>
{dash.loading && !dash.traffic ? (
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" />
) : !dash.traffic ? (
<p className="text-muted-foreground px-4 py-10 text-center text-sm">
Нет данных трафика за последний час.{" "}
<Link href="/traffic" className="underline underline-offset-2">Открыть трафик</Link>
</p>
) : (
<>
<div className="flex flex-wrap items-center gap-3 px-1 pb-3 text-xs">
{dash.traffic.demo ? <Badge variant="outline" size="sm">демо</Badge> : !dash.traffic.observationsKnown ? <Badge variant="outline" size="sm">Измерения не подтверждены API</Badge> : null}
<span className="tabular-nums">RX {dash.traffic.rxNow === null ? "—" : fmtRate(dash.traffic.rxNow)}</span>
<span className="tabular-nums">TX {dash.traffic.txNow === null ? "—" : fmtRate(dash.traffic.txNow)}</span>
</div>
<TrafficRxTxChart rx={dash.traffic.rx} tx={dash.traffic.tx} range="1h" embedded />
</>
)}
</SectionFrame>
) : null}
{show("probes") ? (
<SectionFrame
title="Активные пробы"
description={<span className={dash.error && dash.isLive ? "text-destructive" : undefined}>{dash.probesSubtitle}</span>}
icon={<TableIcon />}
actions={<Link href="/uptime" className={buttonVariants({ variant: "outline", size: "sm" })}>Мониторинг →</Link>}
>
{dash.activeProbes.length === 0 && !dash.probesLoading ? (
<EmptyState
className="py-10"
title={dash.availability.probes ? "Нет проб на дашборде" : "Данные проб недоступны"}
description={dash.availability.probes ? "Включите пробу и отметьте ★ на странице мониторинга." : "Повторите обновление данных."}
action={<Link href="/uptime" className={buttonVariants({ variant: "outline", size: "sm" })}>Открыть мониторинг</Link>}
/>
) : (
<DashboardActiveProbesDataGrid probes={dash.activeProbes} catalog={dash.servers} isLoading={dash.probesLoading} emptyDescription="Нет проб с звездой на дашборде." />
)}
</SectionFrame>
) : null}
{show("links") ? (
<DashboardQuickLinks
links={[
{ id: "traffic", title: "Трафик", description: "Приём, передача и потоки IPFIX", href: "/traffic" },
{ id: "map", title: "Карта сети", description: "Топология GRE и WAN", href: "/network-map" },
{ id: "filters", title: "Фильтры", description: "Правила обхода и списки · цепочки filter / nat", href: "/filters" },
{ id: "backups", title: "Бэкапы", description: "Снапшоты и расписание", href: "/backups" },
{ id: "uptime", title: "Мониторинг", description: "Сессии и префиксы · пробы", href: "/uptime" },
]}
/>
) : null}
</TabsContent>
<TabsContent value="src" className="flex flex-col gap-5">
{failedSources.length > 0 ? (
<Alert variant="destructive">
<CircleAlertIcon />
<AlertTitle>Не обновлены источники: {failedSources.length}</AlertTitle>
<AlertDescription>Последние полученные данные сохранены. Если источник ещё не загрузился, его показатели неизвестны.</AlertDescription>
</Alert>
) : null}
<SectionFrame title="Источники и время получения" description="Каждый источник дашборда: состояние, время получения и замера" icon={<ChartColumnIcon />}>
<div className="overflow-x-auto">
<table className="w-full min-w-[640px] text-sm">
<thead className="bg-muted/55 text-muted-foreground text-xs">
<tr className="h-10 border-b text-left">
<th className="px-3.5 font-medium">Источник</th>
<th className="px-3 font-medium">Статус</th>
<th className="px-3 font-medium">Получено</th>
<th className="px-3 font-medium">Замер</th>
<th className="px-3 font-medium">Ошибка</th>
</tr>
</thead>
<tbody>
{sourceRows.map((row) => (
<tr key={row.key} className="h-[52px] border-b last:border-b-0">
<td className="px-3.5 font-mono text-[13px] font-medium">{row.name}</td>
<td className="px-3"><ToneBadge tone={row.tone as Tone}>{row.label}</ToneBadge></td>
<td className="px-3 font-mono text-[12.5px]">{row.receivedAt != null ? new Date(row.receivedAt).toLocaleString("ru-RU") : "—"}</td>
<td className="px-3 font-mono text-[12.5px]">{row.sampledAt ? new Date(row.sampledAt).toLocaleString("ru-RU") : "—"}</td>
<td className="text-muted-foreground px-3 text-xs">{sourceErrorText(row) ?? "—"}</td>
</tr>
))}
</tbody>
</table>
</div>
<TrafficRxTxChart rx={dash.traffic.rx} tx={dash.traffic.tx} range="1h" embedded />
</>
)}
</OpsPanel>
</SectionFrame>
</TabsContent>
<TabsContent value="rtt" className="flex flex-col gap-5">
<SectionFrame title="История RTT по источникам" description={latencyDescription} panelClassName="px-3.5 pt-3.5">
{latencyBody}
</SectionFrame>
</TabsContent>
</Tabs>
</div>
<InternetPathPanel
model={dash.internetPath}
loading={dash.internetPathLoading}
error={dash.isLive ? dash.internetPathError : null}
/>
<OpsPanel
title="Активные пробы"
description={
<span className={dash.error && dash.isLive ? "text-destructive" : undefined}>{dash.probesSubtitle}</span>
}
headerRight={
<Link href="/uptime" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 text-xs")}>
Мониторинг →
</Link>
}
contentClassName="px-0 pb-0"
>
{dash.activeProbes.length === 0 && !dash.probesLoading ? (
<EmptyState
className="py-10"
title={dash.availability.probes ? "Нет проб на дашборде" : "Данные проб недоступны"}
description={dash.availability.probes ? "Включите пробу и отметьте ★ на странице мониторинга." : "Повторите обновление данных."}
action={
<Link href="/uptime" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
Открыть мониторинг
</Link>
}
/>
) : (
<DashboardActiveProbesDataGrid
probes={dash.activeProbes}
catalog={dash.servers}
isLoading={dash.probesLoading}
emptyDescription="Нет проб с звездой на дашборде."
/>
)}
</OpsPanel>
<QuickActionGrid
title="Быстрые переходы"
description="Другие разделы управления сетью"
actions={[
{
id: "traffic",
title: "Трафик",
description: "Приём, передача и потоки IPFIX",
href: "/traffic",
icon: <ActivityIcon />,
iconClassName: "text-info",
},
{
id: "map",
title: "Карта сети",
description: "Топология GRE и WAN",
href: "/network-map",
icon: <MapIcon />,
iconClassName: "text-primary",
},
{
id: "filters",
title: "Фильтры",
description: "Правила обхода и списки",
href: "/filters",
icon: <FilterIcon />,
iconClassName: "text-info",
},
{
id: "firewall",
title: "Firewall",
description: "Цепочки filter / nat",
href: "/firewall",
icon: <ShieldIcon />,
iconClassName: "text-warning",
},
{
id: "backups",
title: "Бэкапы",
description: "Снапшоты и расписание",
href: "/backups",
icon: <HardDriveIcon />,
iconClassName: "text-muted-foreground",
},
{
id: "bgp",
title: "BGP",
description: "Сессии и префиксы",
href: "/bgp",
icon: <GitMergeIcon />,
iconClassName: "text-primary",
},
]}
/>
</div>
</div>
</div>
File diff suppressed because it is too large. Load diff
+202 -168
View File
@@ -1,17 +1,22 @@
"use client"
import { Suspense, useCallback, useEffect, useMemo, useState } from "react"
import { Suspense, useCallback, useEffect, useMemo, useState, type ReactNode } from "react"
import { useSearchParams } from "next/navigation"
import {
ActivityIcon,
ChartColumnIcon,
DatabaseIcon,
GaugeIcon,
GlobeIcon,
ServerIcon,
UsersIcon,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { PageHeader } from "@/components/page-header"
import { PageTitle } from "@/components/page-title"
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
import { CapacityGrid, type CapacityItem } from "@/components/reui-kit/ops-blocks"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { DataPageCard } from "@/components/data-page-card"
import { DataPageToolbar } from "@/components/data-page-toolbar"
import { SegmentedControl } from "@/components/form-kit"
@@ -35,6 +40,7 @@ import {
} from "@/lib/statistics-dims"
import { statisticsContextError, STATISTICS_CONTEXT_KEYS } from "@/lib/statistics-context"
import { readStatisticsRange } from "@/lib/statistics-range"
import { demoStatistics, demoStatisticsPivot } from "@/lib/statistics-demo"
import { useDataSource } from "@/lib/data-source"
import { fmtBps, formatBytes } from "@/lib/fmt-rate"
import {
@@ -102,8 +108,13 @@ function readDim(sp: URLSearchParams): StatisticsSliceKind {
return t && isStatisticsSliceKind(t) ? t : "users"
}
function readView(sp: URLSearchParams): "explore" | "pivot" {
return sp.get("view") === "pivot" ? "pivot" : "explore"
type StatisticsView = "overview" | "explore" | "pivot"
/** Вкладка макета v3: Обзор, Срезы (explore) или Сводная (pivot); старые ссылки с разрезом открывают Срезы. */
function readView(sp: URLSearchParams): StatisticsView {
const v = sp.get("view")
if (v === "pivot" || v === "explore" || v === "overview") return v
return sp.has("dim") || sp.has("tab") || SLICE_KEYS.some((key) => sp.has(key)) ? "explore" : "overview"
}
function readPlanes(sp: URLSearchParams): "unique" | "all" {
@@ -241,7 +252,9 @@ function StatisticsPageInner() {
const pivotCol = useMemo(() => readPivotDim(searchParams, "pivotCol", "service"), [searchParams])
const [retry, setRetry] = useState(0)
const requestKey = JSON.stringify({ backendUrl, isLive, range, slices, view, pivotRow, pivotCol, planes, retry, rangeError, paramsError })
// Обзор и Срезы читают один и тот же куб — смена этих вкладок не перезапрашивает данные.
const pivotView = view === "pivot"
const requestKey = JSON.stringify({ backendUrl, isLive, range, slices, pivotView, pivotRow, pivotCol, planes, retry, rangeError, paramsError })
const [result, setResult] = useState<{
key: string; data: StatisticsDto; pivot: StatisticsPivotDto; error: string | null
} | null>(null)
@@ -249,7 +262,9 @@ function StatisticsPageInner() {
const loading = isLive && !rangeError && !paramsError && current === null
const error = rangeError ?? paramsError ?? current?.error ?? null
const dataReady = isLive && current !== null && !error
const pivot = dataReady ? current.pivot : EMPTY_PIVOT
// Демо-режим без API: показываем демо-куб, чтобы раздел выглядел как с данными.
const demo = useMemo(() => (isLive || rangeError ? null : demoStatistics(range.from, range.to, planes)), [isLive, rangeError, range, planes])
const pivot = dataReady ? current.pivot : demo && !paramsError ? demoStatisticsPivot(pivotRow, pivotCol) : EMPTY_PIVOT
const updateParams = useCallback(
(patch: Record<string, string | undefined>) => {
@@ -295,7 +310,7 @@ function StatisticsPageInner() {
const dto = await getStatistics(backendUrl, query)
if (cancelled) return
let matrix = EMPTY_PIVOT
if (view === "pivot" && pivotRow !== pivotCol) {
if (pivotView && pivotRow !== pivotCol) {
matrix = await getStatisticsPivot(backendUrl, {
...query,
row: pivotRow,
@@ -313,11 +328,11 @@ function StatisticsPageInner() {
return () => {
cancelled = true
}
}, [backendUrl, isLive, prefsHydrated, range, slices, view, pivotRow, pivotCol, planes, requestKey, rangeError, paramsError])
}, [backendUrl, isLive, prefsHydrated, range, slices, pivotView, pivotRow, pivotCol, planes, requestKey, rangeError, paramsError])
const viewData = dataReady ? current.data : EMPTY
const viewData = dataReady ? current.data : demo && !paramsError ? demo : EMPTY
const sliced = hasAnySlice(slices)
const emptyCube = !isLive || (!loading && viewData.kpis.bytes === 0 && viewData.interfaces.length === 0)
const emptyCube = !loading && viewData.kpis.bytes === 0 && viewData.interfaces.length === 0
function handleRowClick(kind: StatisticsSliceKind, row: StatisticsBreakdownRow) {
if (kind === "users" && row.id === STATISTICS_UNBOUND_USER_ID) return
@@ -348,175 +363,194 @@ function StatisticsPageInner() {
: sliced
? `${STATISTICS_DIMS.filter((d) => !hiddenKinds(slices).has(d.id)).length} разрезов`
: `${rowsForKind(viewData, dim).length} строк`
const hasContext = STATISTICS_CONTEXT_KEYS.some((key) => searchParams.has(key))
const resetContext = () => updateParams(Object.fromEntries(STATISTICS_CONTEXT_KEYS.map((key) => [key, undefined])))
const scope = planes === "all" ? "Все плоскости" : "GRE/WG клиентов, без hops"
const bytesOf = (rows: StatisticsBreakdownRow[]) => rows.reduce((total, row) => total + row.bytes, 0)
const shareOf = (bytes: number) => (kpis.bytes > 0 ? Math.min(1, bytes / kpis.bytes) : 0)
const bytesItem = (id: string, title: string, caption: string, bytes: number, icon: ReactNode): CapacityItem => {
const [valueText, ...unit] = formatBytes(bytes).split(" ")
return { id, title, caption, value: bytes, total: kpis.bytes, ratio: shareOf(bytes), tone: shareOf(bytes) >= 0.999 ? "wn" : "ok", icon, valueText, unit: unit.join(" ") }
}
const planesControl = (
<SegmentedControl
value={planes}
onChange={(next) => updateParams({ planes: next === "all" ? "all" : undefined })}
options={[
{ value: "all", label: "Все плоскости" },
{ value: "unique", label: "GRE/WG клиентов" },
]}
/>
)
const cubeState = isLive && !dataReady ? (
<div role="status" className="p-6 text-sm text-muted-foreground">{loading ? "Загрузка статистики…" : rangeError || paramsError ? "Исправьте параметры отчёта для загрузки статистики." : "Статистика недоступна. Повторите загрузку."}</div>
) : emptyCube ? (
<EmptyState
title="Нет данных куба"
description="За выбранный период нет IPFIX-фактов. Куб заполняется с момента деплоя, без бэкфилла за год."
/>
) : null
const sliceChips = (
<SliceChips
chips={chips}
onRemove={(key) => {
const next = { ...slices }
delete next[key as keyof CubeSlices]
setSlices(next)
}}
/>
)
const filters = <StatisticsFilters key={JSON.stringify(slices)} slices={slices} onApply={setSlices} />
const tabTrigger = "h-auto flex-none px-3 py-2.5 after:bottom-[-1px]"
return (
<div className="flex h-full flex-col">
<PageHeader
crumbs={[{ label: "Обзор", href: "/dashboard" }, { label: "Статистика" }]}
actions={rangeError ? <Button type="button" variant="outline" onClick={() => setRange(rangeForPreset("7d"))}>Выбрать последние 7 дней</Button> : <PeriodSelector range={range} onChange={setRange} />}
/>
<PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Статистика" }]} />
<div className="flex flex-1 flex-col gap-4 overflow-y-auto px-4 py-4 md:gap-6 md:px-6 md:py-5">
{!isLive ? (
<Alert>
<AlertTitle>Живые данные выключены</AlertTitle>
<AlertDescription>
Куб статистики строится из IPFIX. Переключитесь на живой источник, чтобы увидеть отчёт.
</AlertDescription>
</Alert>
) : null}
<div className="flex flex-1 flex-col gap-6 overflow-y-auto px-4 pt-5 pb-10 md:px-7 md:pt-6">
<PageTitle
icon={<ChartColumnIcon />}
title="Статистика"
description="Куб NetFlow: измерения, срезы и период · уникальный объём без дублей"
actions={
<>
{rangeError ? <Button type="button" variant="outline" onClick={() => setRange(rangeForPreset("7d"))}>Выбрать последние 7 дней</Button> : <PeriodSelector range={range} onChange={setRange} />}
<Button type="button" variant="outline" onClick={resetContext} disabled={!hasContext}>Сбросить параметры отчёта</Button>
</>
}
/>
{error ? (
<Alert variant="destructive" role="alert">
<AlertTitle>{rangeError ? "Некорректный период" : paramsError ? "Параметры отчёта требуют внимания" : "Ошибка загрузки"}</AlertTitle>
<AlertDescription>{error}{!rangeError && !paramsError && <Button type="button" variant="outline" size="sm" onClick={() => setRetry(n => n + 1)}>Повторить загрузку</Button>}{paramsError && <Button type="button" variant="outline" size="sm" onClick={() => updateParams(Object.fromEntries(STATISTICS_CONTEXT_KEYS.map(key => [key, undefined])))}>Сбросить параметры отчёта</Button>}</AlertDescription>
</Alert>
) : null}
<div className="flex flex-col gap-5">
{!isLive ? (
<Alert variant="warning">
<AlertTitle>Живые данные выключены</AlertTitle>
<AlertDescription>
Показан демо-куб. Статистика строится из IPFIX — переключитесь на живой источник, чтобы увидеть свой отчёт.
</AlertDescription>
</Alert>
) : null}
{!slices.serverId && dataReady && !emptyCube ? (
<Alert>
<AlertTitle>Уникальный объём</AlertTitle>
<AlertDescription>
Объём — трафик клиентов на GRE/WG, без повторного учёта JH↔EN и WAN.
</AlertDescription>
</Alert>
) : null}
{error ? (
<Alert variant={paramsError ? "warning" : "destructive"} role="alert">
<AlertTitle>{rangeError ? "Некорректный период" : paramsError ? "Параметры отчёта требуют внимания" : "Ошибка загрузки"}</AlertTitle>
<AlertDescription>{error}{!rangeError && !paramsError && <Button type="button" variant="outline" size="sm" onClick={() => setRetry(n => n + 1)}>Повторить загрузку</Button>}</AlertDescription>
</Alert>
) : null}
{(dataReady || loading) && <KpiStatGrid
aria-label="Сводка трафика"
isLoading={loading}
skeletonCount={5}
items={[
{
id: "bytes",
label: "Объём",
value: formatBytes(kpis.bytes),
hint: "GRE/WG клиентов, без hops",
icon: <DatabaseIcon />,
iconClassName: "text-muted-foreground",
},
{
id: "packets",
label: "Пакеты",
value: kpis.packets.toLocaleString("ru-RU"),
hint: kpis.topService ? `топ: ${kpis.topService}` : undefined,
icon: <ActivityIcon />,
iconClassName: "text-muted-foreground",
},
{
id: "bps",
label: "Средний bitrate",
value: fmtBps(kpis.avgBps),
icon: <GaugeIcon />,
iconClassName: "text-muted-foreground",
},
{
id: "users",
label: "Пользователи",
value: String(kpis.users),
icon: <UsersIcon />,
iconClassName: "text-muted-foreground",
},
{
id: "servers",
label: "Серверы",
value: String(kpis.servers),
hint: slices.serverId
? (kpis.ifaces ? `${kpis.ifaces} iface` : undefined)
: planes === "all"
? "WAN и дубли в списке"
: "без WAN и overlay",
icon: <ServerIcon />,
iconClassName: "text-muted-foreground",
},
]}
/>}
{(dataReady || loading || (demo && !paramsError)) && <KpiStatGrid
aria-label="Сводка трафика"
isLoading={loading}
skeletonCount={4}
items={[
{
id: "bytes",
label: planes === "all" ? "Объём" : "Уникальный объём",
value: formatBytes(kpis.bytes),
hint: slices.serverId ? (kpis.ifaces ? `${kpis.ifaces} iface` : undefined) : planes === "all" ? "WAN и дубли в списке" : "без WAN и overlay",
icon: <DatabaseIcon />,
iconClassName: planes === "all" ? "text-muted-foreground" : "text-success",
},
{
id: "packets",
label: "Пакеты",
value: kpis.packets.toLocaleString("ru-RU"),
hint: kpis.topService ? `топ: ${kpis.topService}` : undefined,
icon: <ActivityIcon />,
iconClassName: "text-muted-foreground",
},
{
id: "bps",
label: "Средний bitrate",
value: fmtBps(kpis.avgBps),
icon: <GaugeIcon />,
iconClassName: "text-muted-foreground",
},
{
id: "users",
label: "Пользователи",
value: String(kpis.users),
hint: `Серверы: ${kpis.servers}`,
icon: <UsersIcon />,
iconClassName: "text-muted-foreground",
},
]}
/>}
{dataReady && <StatisticsVolumeChart series={viewData.series} grain={viewData.grain} />}
<Tabs value={view} onValueChange={(next) => updateParams({ view: String(next) })} className="gap-5">
<TabsList variant="line" className="h-auto w-full justify-start gap-1 overflow-x-auto border-b p-0">
<TabsTrigger value="overview" className={tabTrigger}>Обзор</TabsTrigger>
<TabsTrigger value="pivot" className={tabTrigger}>Сводная (куб)</TabsTrigger>
<TabsTrigger value="explore" className={tabTrigger}>Срезы</TabsTrigger>
</TabsList>
<DataPageCard>
<DataPageToolbar
leading={
<div className="flex flex-wrap items-center gap-3">
<SegmentedControl
value={view}
onChange={(next) => updateParams({ view: next === "pivot" ? "pivot" : "explore" })}
options={[
{ value: "explore", label: "Разрез" },
{ value: "pivot", label: "Сводка" },
]}
/>
<SegmentedControl
value={planes}
onChange={(next) => updateParams({ planes: next === "all" ? "all" : undefined })}
options={[
{ value: "unique", label: "Уникальный" },
{ value: "all", label: "Все плоскости" },
]}
/>
{view === "explore" && !sliced ? (
<DimensionSelect
label="Критерий"
value={dim}
onChange={(next) => updateParams({ dim: next, tab: undefined })}
<TabsContent value="overview" className="flex flex-col gap-5">
{cubeState ?? (
<>
<StatisticsVolumeChart series={viewData.series} grain={viewData.grain} scope={scope} actions={planesControl} />
<CapacityGrid
label="Доли объёма"
items={[
bytesItem("users", "Пользователи", "GRE/WG клиентов, без hops", bytesOf(viewData.users), <UsersIcon />),
bytesItem("servers", "Серверы", planes === "all" ? "WAN и дубли в списке" : "без WAN и overlay", bytesOf(viewData.servers), <ServerIcon />),
bytesItem("countries", "Страны", "Топ-10", bytesOf([...viewData.countries].sort((a, b) => b.bytes - a.bytes).slice(0, 10)), <GlobeIcon />),
]}
/>
) : null}
{view === "pivot" ? (
<>
<PivotDimSelect
label="Строки"
value={pivotRow}
exclude={pivotCol}
onChange={(next) => updateParams({ pivotRow: next })}
/>
<PivotDimSelect
label="Колонки"
value={pivotCol}
exclude={pivotRow}
onChange={(next) => updateParams({ pivotCol: next })}
/>
</>
) : null}
</div>
}
filterControl={<StatisticsFilters key={JSON.stringify(slices)} slices={slices} onApply={setSlices} />}
countLabel={dataReady ? countLabel : undefined}
/>
<SliceChips
chips={chips}
onRemove={(key) => {
const next = { ...slices }
delete next[key as keyof CubeSlices]
setSlices(next)
}}
/>
{isLive && !dataReady ? (
<div role="status" className="p-6 text-sm text-muted-foreground">{loading ? "Загрузка статистики…" : rangeError || paramsError ? "Исправьте параметры отчёта для загрузки статистики." : "Статистика недоступна. Повторите загрузку."}</div>
) : emptyCube ? (
<EmptyState
title="Нет данных куба"
description="За выбранный период нет IPFIX-фактов. Куб заполняется с момента деплоя, без бэкфилла за год."
/>
) : view === "pivot" ? (
<StatisticsPivotGrid data={isLive ? pivot : EMPTY_PIVOT} onCellClick={handlePivotCell} isLoading={loading} />
) : sliced ? (
<BreakdownDashboard
data={viewData}
hidden={hiddenKinds(slices)}
selectedIdFor={(kind) => selectedIdForKind(kind, slices)}
onRowClick={handleRowClick}
isLoading={loading}
/>
) : (
<StatisticsBreakdownDataGrid
rows={rowsForKind(viewData, dim)}
kind={dim}
selectedId={selectedIdForKind(dim, slices)}
onRowClick={(row) => handleRowClick(dim, row)}
isLoading={loading}
/>
)}
</DataPageCard>
</>
)}
</TabsContent>
<TabsContent value="pivot">
<DataPageCard>
<DataPageToolbar
leading={
<div className="flex flex-wrap items-center gap-3">
{planesControl}
<PivotDimSelect label="Строки" value={pivotRow} exclude={pivotCol} onChange={(next) => updateParams({ pivotRow: next })} />
<PivotDimSelect label="Колонки" value={pivotCol} exclude={pivotRow} onChange={(next) => updateParams({ pivotCol: next })} />
</div>
}
filterControl={filters}
countLabel={dataReady ? countLabel : undefined}
/>
{sliceChips}
{cubeState ?? <StatisticsPivotGrid data={pivot} onCellClick={handlePivotCell} isLoading={loading} />}
</DataPageCard>
</TabsContent>
<TabsContent value="explore">
<DataPageCard>
<DataPageToolbar
leading={
<div className="flex flex-wrap items-center gap-3">
{planesControl}
{!sliced ? <DimensionSelect label="Критерий" value={dim} onChange={(next) => updateParams({ dim: next, tab: undefined })} /> : null}
</div>
}
filterControl={filters}
countLabel={dataReady ? countLabel : undefined}
/>
{sliceChips}
{cubeState ?? (sliced ? (
<BreakdownDashboard
data={viewData}
hidden={hiddenKinds(slices)}
selectedIdFor={(kind) => selectedIdForKind(kind, slices)}
onRowClick={handleRowClick}
isLoading={loading}
/>
) : (
<StatisticsBreakdownDataGrid
rows={rowsForKind(viewData, dim)}
kind={dim}
selectedId={selectedIdForKind(dim, slices)}
onRowClick={(row) => handleRowClick(dim, row)}
isLoading={loading}
/>
))}
</DataPageCard>
</TabsContent>
</Tabs>
</div>
</div>
</div>
)
+317 -205
View File
@@ -1,23 +1,27 @@
"use client"
import { useState, useMemo, useEffect, type ReactNode } from "react"
import { Suspense, useState, useMemo, useEffect, type ReactNode } from "react"
import Link from "next/link"
import { useSearchParams } from "next/navigation"
import { Alert, AlertTitle, AlertDescription } from "@/components/reui/alert"
import { peakOfCombinedTraffic, projectTrafficObservations, sumObservedTraffic, type TrafficObservationMeta } from "@/lib/traffic-observations"
import { projectTrafficBindingStatus } from "@/lib/traffic-binding-status"
import { TrafficObservationStatus } from "@/components/traffic/traffic-observation-status"
import { TrafficDataTime } from "@/components/traffic/traffic-data-time"
import { PageHeader } from "@/components/page-header"
import { Frame, FramePanel } from "@/components/reui/frame"
import { PageTitle } from "@/components/page-title"
import { FramePanel } from "@/components/reui/frame"
import { SectionFrame, ToneBadge, type Tone } from "@/components/reui-kit/ops-blocks"
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
import { TrafficMiniChart } from "@/components/reui-kit/traffic-mini-chart"
import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart"
import { Button } from "@/components/ui/button"
import { Button, buttonVariants } from "@/components/ui/button"
import { Sparkline } from "@/components/sparkline"
import { StatusDot } from "@/components/status-dot"
import { Flag } from "@/components/flag"
import {
RefreshCwIcon, TrendingUpIcon, TrendingDownIcon,
ArrowUpIcon, ArrowDownIcon, ActivityIcon, UsersIcon, CableIcon, ServerIcon, SearchIcon, GitBranchIcon, PlusIcon,
RefreshCwIcon, TrendingUpIcon, ChartPieIcon,
ArrowUpIcon, ArrowDownIcon, ActivityIcon, UsersIcon, CableIcon, ServerIcon, SearchIcon, GitBranchIcon, PlusIcon, MapIcon,
} from "lucide-react"
import { cn } from "@/lib/utils"
import { fmtGiB, fmtRate } from "@/lib/fmt-rate"
@@ -35,6 +39,7 @@ import { Badge } from "@/components/reui/badge"
import {
IFACE_TYPE_LABEL,
INIT_USERS,
MOCK_IFACE_CATALOG,
ROLE_LABEL,
type InterfaceType,
} from "@/lib/users"
@@ -336,22 +341,12 @@ const TRAFFIC_RANGE_LABELS: Record<(typeof TRAFFIC_RANGE_KEYS)[number], string>
type GroupMode = "servers" | "users" | "ifaces" | "flows"
type FlowScope = "servers" | "users"
const ALL_EXPORTERS = "__all_exporters__"
type SortField = "rx" | "tx" | "name" | "sessions"
type SortDir = "asc" | "desc"
// ─── shared sub-components ────────────────────────────────────────────────────
function StatChip({ icon, label, value }: { icon: ReactNode; label: string; value: string }) {
return (
<div className="flex items-center gap-2">
<div className="flex items-center justify-center size-7 rounded-md bg-muted shrink-0">{icon}</div>
<div className="leading-tight min-w-0 break-words">
<p className="text-xs text-muted-foreground">{label}</p>
<p className="text-sm font-semibold tabular-nums">{value}</p>
</div>
</div>
)
}
// ─── left-panel entity cards ──────────────────────────────────────────────────
@@ -368,22 +363,22 @@ function ServerCard({ s, selected, onClick }: { s: ServerTraffic; selected: bool
<StatusDot status={s.status} />
<span className="text-xs font-medium truncate">{s.name}</span>
</div>
<span className="text-[10px] font-mono text-muted-foreground shrink-0 flex items-center gap-1">
<span className="text-xs font-mono text-muted-foreground shrink-0 flex items-center gap-1">
<Flag code={s.country} />{s.site}
</span>
</div>
<TrafficMiniChart rx={s.rxSeries} tx={s.txSeries} />
<div className="flex justify-between mt-2 gap-2">
<div className="flex items-center gap-1 text-[11px]">
<div className="flex items-center gap-1 text-xs">
<ArrowDownIcon className="size-3 text-emerald-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(s.rxNow)}</span>
</div>
<div className="flex items-center gap-1 text-[11px]">
<div className="flex items-center gap-1 text-xs">
<ArrowUpIcon className="size-3 text-blue-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(s.txNow)}</span>
</div>
{s.boundIfaces.length > 0 && (
<div className="flex items-center gap-0.5 text-[10px] text-muted-foreground">
<div className="flex items-center gap-0.5 text-xs text-muted-foreground">
<CableIcon className="size-3" />{s.boundIfaces.length}
</div>
)}
@@ -407,10 +402,10 @@ function UserCard({ u, selected, onClick }: { u: UserTraffic; selected: boolean;
</div>
<div className="min-w-0">
<p className="text-xs font-medium truncate">{u.login}</p>
<p className="text-[10px] text-muted-foreground truncate">{u.displayName}</p>
<p className="text-xs text-muted-foreground truncate">{u.displayName}</p>
</div>
</div>
<div className="flex items-center gap-0.5 text-[10px] text-muted-foreground shrink-0">
<div className="flex items-center gap-0.5 text-xs text-muted-foreground shrink-0">
<CableIcon className="size-3" />{u.interfaces.length}
</div>
</div>
@@ -418,18 +413,18 @@ function UserCard({ u, selected, onClick }: { u: UserTraffic; selected: boolean;
<>
<TrafficMiniChart rx={u.rxSeries} tx={u.txSeries} />
<div className="flex justify-between mt-2 gap-2">
<div className="flex items-center gap-1 text-[11px]">
<div className="flex items-center gap-1 text-xs">
<ArrowDownIcon className="size-3 text-emerald-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(u.rxNow)}</span>
</div>
<div className="flex items-center gap-1 text-[11px]">
<div className="flex items-center gap-1 text-xs">
<ArrowUpIcon className="size-3 text-blue-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(u.txNow)}</span>
</div>
</div>
</>
) : (
<p className="text-[10px] text-muted-foreground">Нет привязанных интерфейсов</p>
<p className="text-xs text-muted-foreground">Нет привязанных интерфейсов</p>
)}
</button>
)
@@ -447,20 +442,20 @@ function IfaceCard({ c, selected, onClick }: { c: BoundIfaceTraffic; selected: b
<StatusDot status={c.status} />
<div className="min-w-0">
<p className="text-xs font-mono font-medium truncate">{boundIfaceLabel(c)}</p>
<p className="text-[10px] text-muted-foreground truncate">{c.userLogin}</p>
<p className="text-xs text-muted-foreground truncate">{c.userLogin}</p>
</div>
</div>
<span className="text-[10px] font-mono text-muted-foreground shrink-0 flex items-center gap-1">
<span className="text-xs font-mono text-muted-foreground shrink-0 flex items-center gap-1">
<Flag code={c.serverCountry} />{c.serverSite}
</span>
</div>
<TrafficMiniChart rx={c.rxSeries} tx={c.txSeries} />
<div className="flex justify-between mt-2 gap-2">
<div className="flex items-center gap-1 text-[11px]">
<div className="flex items-center gap-1 text-xs">
<ArrowDownIcon className="size-3 text-emerald-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(c.rxNow)}</span>
</div>
<div className="flex items-center gap-1 text-[11px]">
<div className="flex items-center gap-1 text-xs">
<ArrowUpIcon className="size-3 text-blue-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(c.txNow)}</span>
</div>
@@ -487,12 +482,12 @@ function IfaceRow({ c, showServer = false }: { c: BoundIfaceTraffic; showServer?
<span className="text-xs font-mono font-semibold break-all">{boundIfaceLabel(c)}</span>
<Badge variant={TYPE_VARIANT[c.interfaceType]} size="sm">{IFACE_TYPE_LABEL[c.interfaceType]}</Badge>
{showServer && (
<span className="inline-flex items-center gap-1 text-[10px] font-mono text-muted-foreground bg-muted px-1.5 py-0.5 rounded">
<span className="inline-flex items-center gap-1 text-xs font-mono text-muted-foreground bg-muted px-1.5 py-0.5 rounded">
<Flag code={c.serverCountry} />{c.serverSite}
</span>
)}
</div>
<p className="text-[10px] text-muted-foreground truncate mt-0.5">{c.comment || c.userLogin}</p>
<p className="text-xs text-muted-foreground truncate mt-0.5">{c.comment || c.userLogin}</p>
</div>
<div className="shrink-0 text-right leading-tight">
<div className="flex items-center gap-1 justify-end text-xs font-mono font-medium text-emerald-600 dark:text-emerald-400">
@@ -502,12 +497,12 @@ function IfaceRow({ c, showServer = false }: { c: BoundIfaceTraffic; showServer?
<ArrowUpIcon className="size-3" />{fmtRate(c.txNow)}
</div>
</div>
<div className="shrink-0 text-right leading-tight text-[10px] text-muted-foreground w-[72px]">
<div className="shrink-0 text-right leading-tight text-xs text-muted-foreground w-[72px]">
<p className="tabular-nums">{fmtGiB(c.rxTotal)}</p>
<p className="tabular-nums">{fmtGiB(c.txTotal)}</p>
</div>
<span className={cn(
"shrink-0 text-[10px] px-1.5 py-0.5 rounded-full font-medium tabular-nums",
"shrink-0 text-xs px-1.5 py-0.5 rounded-full font-medium tabular-nums",
c.status === "online" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground",
)}>
{c.status === "online" ? "Работает" : c.status === "unknown" ? "Нет данных" : "Неактивен"}
@@ -516,6 +511,61 @@ function IfaceRow({ c, showServer = false }: { c: BoundIfaceTraffic; showServer?
)
}
/** Интерфейсы выбранного сервера таблицей (блок «Интерфейсы сервера» макета v3). */
function ServerIfacesFrame({ server }: { server: ServerTraffic }) {
const cols = "grid-cols-[minmax(170px,1.6fr)_minmax(90px,1fr)_110px_100px_100px_150px]"
return (
<SectionFrame title="Интерфейсы сервера" description={`${server.name} · трафик по каждому интерфейсу`} icon={<CableIcon />} panelClassName="overflow-x-auto">
<div className="min-w-[740px]">
<div aria-hidden="true" className={cn("bg-muted/55 text-muted-foreground grid h-10 items-center gap-x-3 border-b px-3.5 text-xs font-medium", cols)}>
<span>Интерфейс</span><span>Сервер</span><span>Статус</span><span>RX</span><span>TX</span><span>Учтено</span>
</div>
{server.boundIfaces.map((c) => (
<div key={c.id} className={cn("grid min-h-[52px] items-center gap-x-3 border-b px-3.5 last:border-b-0", cols, c.status === "offline" && "opacity-55")}>
<span className="flex min-w-0 items-center gap-2 py-2">
<StatusDot status={c.status} />
<span className="min-w-0">
<span className="block truncate font-mono text-[13px] font-medium">{boundIfaceLabel(c)}</span>
<span className="text-muted-foreground block truncate font-mono text-xs">{IFACE_TYPE_LABEL[c.interfaceType]} · {c.comment || c.userLogin}</span>
</span>
</span>
<span className="truncate font-mono text-xs">{server.name}</span>
<span><ToneBadge tone={c.status === "online" ? "ok" : c.status === "unknown" ? "mu" : "er"}>{c.status === "online" ? "Работает" : c.status === "unknown" ? "Нет данных" : "Неактивен"}</ToneBadge></span>
<span className="font-mono text-xs tabular-nums">{fmtRate(c.rxNow)}</span>
<span className="font-mono text-xs tabular-nums">{fmtRate(c.txNow)}</span>
<span className="text-muted-foreground font-mono text-xs tabular-nums">{fmtGiB(c.rxTotal)} / {fmtGiB(c.txTotal)}</span>
</div>
))}
</div>
</SectionFrame>
)
}
/** Доля RX по серверам с данными (блок rbl макета v3). */
function RxShareFrame({ servers }: { servers: ServerTraffic[] }) {
const rows = servers.filter((s) => typeof s.rxNow === "number" && s.rxNow > 0).sort((a, b) => (b.rxNow ?? 0) - (a.rxNow ?? 0)).slice(0, 5)
const total = rows.reduce((sum, s) => sum + (s.rxNow ?? 0), 0)
if (!rows.length || total <= 0) return null
const max = rows[0].rxNow ?? 1
const colors = ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-4)", "var(--muted-foreground)"]
return (
<SectionFrame title="Доля RX" description="сейчас · по серверам с данными" icon={<ChartPieIcon />} panelClassName="flex flex-col gap-1.5 p-2.5">
{rows.map((s, i) => (
<div key={s.id} className="flex min-w-0 items-center gap-2">
<span className="bg-muted/70 relative h-7 min-w-0 flex-1 overflow-hidden rounded-full">
<i className="absolute inset-y-0 left-0 rounded-full opacity-40" style={{ width: `${Math.round(((s.rxNow ?? 0) / max) * 100)}%`, background: colors[i] }} />
<span className="relative flex h-full items-center gap-1.5 truncate px-2.5 text-xs font-medium">
<span aria-hidden="true" className="size-1.5 shrink-0 rounded-full" style={{ background: colors[i] }} />{s.name}
</span>
</span>
<span className="min-w-[72px] text-right font-mono text-xs">{fmtRate(s.rxNow)}</span>
<span className="text-muted-foreground min-w-11 text-right font-mono text-xs">{Math.round(((s.rxNow ?? 0) / total) * 100)}%</span>
</div>
))}
</SectionFrame>
)
}
function BoundIfacesList({ clients, showServer = false }: { clients: BoundIfaceTraffic[]; showServer?: boolean }) {
if (clients.length === 0)
return <p className="text-xs text-muted-foreground py-1">Нет привязанных интерфейсов</p>
@@ -528,24 +578,46 @@ function BoundIfacesList({ clients, showServer = false }: { clients: BoundIfaceT
// ─── detail panel helpers ─────────────────────────────────────────────────────
function DetailHeader({ range, setRange, children }: {
range: Range; setRange: (r: Range) => void; children: ReactNode
function DetailHeader({ range, setRange, children, status }: {
range: Range; setRange: (r: Range) => void; children: ReactNode; status?: ReactNode
}) {
return (
<div className="flex flex-wrap items-start justify-between mb-3 gap-3">
<div className="flex items-center gap-2 flex-wrap min-w-0">{children}</div>
<div className="flex flex-wrap gap-1">
<div className="mb-3 flex flex-wrap items-center gap-3">
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">{children}</div>
{status}
<div className="bg-muted inline-flex h-9 items-center gap-0.5 rounded-lg p-[3px]">
{TRAFFIC_RANGE_KEYS.map((r) => (
<Button key={r} type="button" aria-pressed={range === r} size="sm" variant={r === range ? "default" : "ghost"}
className="h-7 px-2 text-xs" onClick={() => setRange(r)}>
<button key={r} type="button" aria-pressed={range === r} onClick={() => setRange(r)}
className={cn("text-muted-foreground hover:text-foreground h-[30px] rounded-md px-2.5 text-[13px] font-medium transition-colors", range === r && "bg-background text-foreground shadow-sm")}>
{TRAFFIC_RANGE_LABELS[r]}
</Button>
</button>
))}
</div>
</div>
)
}
const SERVER_STATUS: Record<ServerTraffic["status"], { tone: Tone; label: string }> = {
online: { tone: "ok", label: "Онлайн" },
degraded: { tone: "wn", label: "Ухудшение" },
offline: { tone: "er", label: "Оффлайн" },
}
/** Текущие и пиковые скорости двумя колонками (блок kv макета v3). */
function KvStats({ label, items }: { label: string; items: Array<{ id: string; label: string; value: string; hint?: string }> }) {
return (
<div role="group" aria-label={label} className="mt-3 grid grid-cols-2 gap-x-3.5 gap-y-3 border-t pt-3.5">
{items.map((item) => (
<div key={item.id} className="min-w-0">
<small className="text-muted-foreground block text-xs">{item.label}</small>
<b className="font-mono text-[13px] font-medium tabular-nums">{item.value}</b>
{item.hint ? <span className="text-muted-foreground ml-2 text-xs">{item.hint}</span> : null}
</div>
))}
</div>
)
}
function OfflinePlaceholder({ text = "Нет данных — объект недоступен" }: { text?: string }) {
return (
<div className="flex items-center justify-center h-[220px] text-muted-foreground/40">
@@ -596,63 +668,24 @@ function ServerDetail({
const txNow = liveTx ?? sel.txNow
return (
<>
<DetailHeader range={range} setRange={setRange}>
<StatusDot status={sel.status} />
<h2 className="text-base font-semibold break-all">{sel.name}</h2>
<span className="text-xs font-mono bg-muted px-1.5 py-0.5 rounded flex items-center gap-1">
<Flag code={sel.country} />{sel.site}
</span>
<DetailHeader range={range} setRange={setRange} status={<ToneBadge tone={SERVER_STATUS[sel.status].tone} size="lg">{SERVER_STATUS[sel.status].label}</ToneBadge>}>
<div className="min-w-0">
<h2 className="text-sm font-semibold break-all">{sel.name}</h2>
<p className="text-muted-foreground flex items-center gap-1 text-[0.78rem]"><Flag code={sel.country} />{sel.site}</p>
</div>
</DetailHeader>
<TrafficObservationStatus observations={sel.observations} unknown={sel.rxNow == null || sel.txNow == null} />
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
<div className="mt-4 pt-4 border-t">
<KpiStatGrid
aria-label="Скорость выбранного сервера"
items={[
{
id: "rx-now",
label: "RX",
value: fmtRate(rxNow),
hint: liveHint,
icon: <ArrowDownIcon className="size-4" />,
iconClassName: "text-success",
},
{
id: "tx-now",
label: "TX",
value: fmtRate(txNow),
hint: liveHint,
icon: <ArrowUpIcon className="size-4" />,
iconClassName: "text-info",
},
{
id: "rx-peak",
label: "Пик RX",
value: fmtRate(sel.rxPeak),
icon: <TrendingUpIcon className="size-4" />,
iconClassName: "text-warning",
},
{
id: "tx-peak",
label: "Пик TX",
value: fmtRate(sel.txPeak),
icon: <TrendingDownIcon className="size-4" />,
iconClassName: "text-warning",
},
]}
/>
</div>
<TrafficRxTxChart key={range} rx={sel.rxSeries} tx={sel.txSeries} range={range} scrub embedded />
<KvStats
label="Скорость выбранного сервера"
items={[
{ id: "rx-now", label: "RX сейчас", value: fmtRate(rxNow), hint: liveHint },
{ id: "tx-now", label: "TX сейчас", value: fmtRate(txNow), hint: liveHint },
{ id: "rx-peak", label: "Пик RX", value: fmtRate(sel.rxPeak) },
{ id: "tx-peak", label: "Пик TX", value: fmtRate(sel.txPeak) },
]}
/>
<TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} />
{sel.boundIfaces.length > 0 && (
<div className="mt-4 pt-4 border-t">
<h3 className="text-sm font-semibold mb-2 flex items-center gap-2">
<CableIcon className="size-4 text-muted-foreground" />
Привязанные интерфейсы
<span className="text-xs text-muted-foreground font-normal">({sel.boundIfaces.length})</span>
</h3>
<BoundIfacesList clients={sel.boundIfaces} />
</div>
)}
</>
)
}
@@ -666,7 +699,7 @@ function UserDetail({ sel, range, setRange }: { sel: UserTraffic; range: Range;
<UsersIcon className="size-4 text-muted-foreground" />
</div>
<div className="leading-tight">
<h2 className="text-base font-semibold break-all">{sel.login}</h2>
<h2 className="text-sm font-semibold break-all">{sel.login}</h2>
<p className="text-xs text-muted-foreground break-all">{sel.displayName} · {sel.role}</p>
</div>
</DetailHeader>
@@ -674,13 +707,16 @@ function UserDetail({ sel, range, setRange }: { sel: UserTraffic; range: Range;
<OfflinePlaceholder text="Нет привязанных интерфейсов у этого пользователя" />
) : (
<>
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mt-4 pt-4 border-t">
<StatChip icon={<ArrowDownIcon className="size-3.5 text-emerald-500" />} label="RX" value={fmtRate(sel.rxNow)} />
<StatChip icon={<ArrowUpIcon className="size-3.5 text-blue-500" />} label="TX" value={fmtRate(sel.txNow)} />
<StatChip icon={<TrendingUpIcon className="size-3.5 text-amber-500" />} label="Пик RX" value={fmtRate(sel.rxPeak)} />
<StatChip icon={<CableIcon className="size-3.5 text-purple-500" />} label="Интерфейсы" value={`${sel.interfaces.length}`} />
</div>
<TrafficRxTxChart key={range} rx={sel.rxSeries} tx={sel.txSeries} range={range} scrub embedded />
<KvStats
label="Скорость выбранного клиента"
items={[
{ id: "rx", label: "RX сейчас", value: fmtRate(sel.rxNow) },
{ id: "tx", label: "TX сейчас", value: fmtRate(sel.txNow) },
{ id: "rx-peak", label: "Пик RX", value: fmtRate(sel.rxPeak) },
{ id: "ifaces", label: "Интерфейсы", value: String(sel.interfaces.length) },
]}
/>
<TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} />
<div className="mt-4 pt-4 border-t">
<h3 className="text-sm font-semibold mb-2 flex items-center gap-2">
@@ -702,7 +738,7 @@ function IfaceDetail({ sel, range, setRange }: { sel: BoundIfaceTraffic; range:
<DetailHeader range={range} setRange={setRange}>
<StatusDot status={sel.status} />
<div className="leading-tight min-w-0">
<h2 className="text-base font-mono font-semibold break-all">{boundIfaceLabel(sel)}</h2>
<h2 className="text-sm font-mono font-semibold break-all">{boundIfaceLabel(sel)}</h2>
<p className="text-xs text-muted-foreground truncate">{sel.comment || sel.userLogin}</p>
</div>
<Badge variant={TYPE_VARIANT[sel.interfaceType]} size="sm">{IFACE_TYPE_LABEL[sel.interfaceType]}</Badge>
@@ -710,13 +746,16 @@ function IfaceDetail({ sel, range, setRange }: { sel: BoundIfaceTraffic; range:
<Flag code={sel.serverCountry} />{sel.serverSite}
</span>
</DetailHeader>
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mt-4 pt-4 border-t">
<StatChip icon={<ArrowDownIcon className="size-3.5 text-emerald-500" />} label="RX" value={fmtRate(sel.rxNow)} />
<StatChip icon={<ArrowUpIcon className="size-3.5 text-blue-500" />} label="TX" value={fmtRate(sel.txNow)} />
<StatChip icon={<TrendingUpIcon className="size-3.5 text-amber-500" />} label="Пик RX" value={fmtRate(sel.rxPeak)} />
<StatChip icon={<TrendingUpIcon className="size-3.5 text-amber-500" />} label="Пик TX" value={fmtRate(sel.txPeak)} />
</div>
<TrafficRxTxChart key={range} rx={sel.rxSeries} tx={sel.txSeries} range={range} scrub embedded />
<KvStats
label="Скорость выбранного интерфейса"
items={[
{ id: "rx", label: "RX сейчас", value: fmtRate(sel.rxNow) },
{ id: "tx", label: "TX сейчас", value: fmtRate(sel.txNow) },
{ id: "rx-peak", label: "Пик RX", value: fmtRate(sel.rxPeak) },
{ id: "tx-peak", label: "Пик TX", value: fmtRate(sel.txPeak) },
]}
/>
<TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} />
<div className="mt-4 pt-4 border-t grid grid-cols-2 sm:grid-cols-3 gap-4">
<div>
@@ -783,6 +822,38 @@ const toLiveUser = (u: UserTraffic & { interfaces?: BoundIfaceTraffic[] }): User
}
export default function TrafficPage() {
return <Suspense fallback={<p role="status" className="p-4 text-sm">Загрузка трафика…</p>}><TrafficRoute /></Suspense>
}
function TrafficRoute() {
const params = useSearchParams()
const read = (name: string, limit: number) => {
const value = params.get(name)?.trim()
return value && value.length <= limit ? value : undefined
}
const user = read("user", 128), server = read("server", 64)
const service = read("service", 200)
const map = new URLSearchParams()
const ix = params.get("mapView") === "ix"
if (ix) map.set("filter", "ix-node")
const mapUser = read("mapUser", 128) ?? user
if (mapUser) map.set("user", mapUser)
const serviceId = read("serviceId", 240)
if (serviceId) {
map.set("service", serviceId)
if (serviceId.startsWith("cc:")) map.set("dest", "countries")
}
else if (server) map.set("server", server)
const view: GroupMode = params.get("view") === "flows" ? "flows" : user ? "users" : "servers"
const ids = (name: string) => (params.get(name) ?? "").slice(0, 4096).split(",").filter(id => /^[1-9]\d*$/.test(id))
const exporters = view === "flows" && params.has("exporters") ? ids("exporters") : undefined
return <TrafficContent key={params.toString()} view={view} user={user} server={server} service={service} country={read("country", 32)}
exporters={exporters} mapNodes={params.has("nodes") ? ids("nodes") : undefined} returnHref={params.get("from") === "map" ? `/network-map${map.size ? `?${map}` : ""}` : undefined} />
}
function TrafficContent({ view, user, server, service, country, exporters: mapExporters, mapNodes, returnHref }: {
view: GroupMode; user?: string; server?: string; service?: string; country?: string; exporters?: string[]; mapNodes?: string[]; returnHref?: string
}) {
const { mode, backendUrl } = useDataSource()
const isLive = mode === "live"
const [trafficClock, setTrafficClock] = useState(() => Date.now())
@@ -793,11 +864,13 @@ export default function TrafficPage() {
}, [isLive])
const apiFetch = useMemo(() => makeApiFetch(backendUrl), [backendUrl])
const [groupMode, setGroupMode] = useState<GroupMode>("servers")
const [groupMode, setGroupMode] = useState<GroupMode>(view)
const [sortField, setSortField] = useState<SortField>("rx")
const [sortDir, setSortDir] = useState<SortDir>("desc")
const [selectedId, setSelectedId] = useState("srv1")
const [range, setRange] = useState<Range>("1h")
const linkedId = view === "servers" ? server : user ?? server
const [selectedId, setSelectedId] = useState(linkedId ?? (view === "flows" ? mapExporters ? "" : ALL_EXPORTERS : "srv1"))
const keptLink = groupMode === view && selectedId === linkedId
const [range, setRange] = useState<Range>(view === "flows" ? "5m" : "1h")
const [search, setSearch] = useState("")
const [trafficRetry, setTrafficRetry] = useState(0)
const [liveRetry, setLiveRetry] = useState(0)
@@ -819,7 +892,7 @@ export default function TrafficPage() {
const [detailResult, setDetailResult] = useState<{ key: string; server: ServerTraffic | null; receivedAt?: number; error: string | null } | null>(null)
const [liveUsers, setLiveUsers] = useState<UserTraffic[]>([])
const [liveBoundIfaces, setLiveBoundIfaces] = useState<BoundIfaceTraffic[]>([])
const [flowScope, setFlowScope] = useState<FlowScope>("servers")
const [flowScope, setFlowScope] = useState<FlowScope>(user ? "users" : "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[]; cardWindow?: FlowStatsDto["sourceWindow"]; error?: string } | null>(null)
@@ -833,7 +906,7 @@ export default function TrafficPage() {
&& trafficClock - collectorReading.receivedAt > 35_000
? { ...collectorReading.status, listenerBound: false, collectorCountersSource: "last-known" }
: collectorReading.status
const flowExporters = useMemo(() => currentFlows?.exporters ?? [], [currentFlows])
const flowExporters = useMemo(() => (currentFlows?.exporters ?? []).filter(card => !mapExporters || mapExporters.includes(card.id)), [currentFlows, mapExporters])
const flowClients = useMemo(() => currentFlows?.clients ?? [], [currentFlows])
const [flowMonth, setFlowMonth] = useState(() => new Date().toISOString().slice(0, 7))
const flowMonthValid = /^(?!0000)\d{4}-(0[1-9]|1[0-2])$/.test(flowMonth) && flowMonth <= new Date().toISOString().slice(0, 7)
@@ -849,6 +922,7 @@ export default function TrafficPage() {
const [overlayOpen, setOverlayOpen] = useState(false)
const [catalogServers, setCatalogServers] = useState<ServerRead[]>([])
const effectiveMode: GroupMode = groupMode
const allExporters = !mapExporters && flowScope === "servers" && selectedId === ALL_EXPORTERS && range !== "30d"
const detailKey = JSON.stringify([isLive, backendUrl, effectiveMode, selectedId, range, selectedIface, detailRetry])
const currentDetail = detailResult?.key === detailKey ? detailResult : null
const detailBusy = isLive && effectiveMode === "servers" && Boolean(selectedId) && currentDetail === null
@@ -863,7 +937,7 @@ export default function TrafficPage() {
range === "30d"
? /^[1-9]\d*$/.test(selectedId) && Number.isSafeInteger(Number(selectedId)) && Boolean(currentFlows?.monthlyServers?.some(server => String(server.id) === selectedId))
: flowScope === "servers"
? /^[1-9]\d*$/.test(selectedId) && Number.isSafeInteger(Number(selectedId)) && flowExporters.some(card => card.id === selectedId)
? allExporters || /^[1-9]\d*$/.test(selectedId) && Number.isSafeInteger(Number(selectedId)) && flowExporters.some(card => card.id === selectedId)
: Boolean(selectedId) && flowClients.some(card => card.id === selectedId)
)
const flowLiveEnabled = confirmedFlowSelection && effectiveMode === "flows" && range === "5m"
@@ -871,7 +945,7 @@ export default function TrafficPage() {
enabled: flowLiveEnabled,
backendUrl,
range,
serverId: flowScope === "servers" ? selectedId : undefined,
serverId: flowScope === "servers" && !allExporters ? selectedId : undefined,
userId: flowScope === "users" ? selectedId : undefined,
iface: flowIface,
dedup: flowDedup,
@@ -904,6 +978,7 @@ export default function TrafficPage() {
setLiveBoundIfaces(liveIfaces)
setTrafficState({ key, status: "ready", receivedAt: Date.now(), peaks: srvRes.peaks })
setSelectedId((prev) => {
if (groupMode === view && prev === linkedId) return prev
if (groupMode === "users") return mappedUsers.some((x) => x.id === prev) ? prev : (mappedUsers[0]?.id ?? "")
if (groupMode === "ifaces") return liveIfaces.some((x) => x.id === prev) ? prev : (liveIfaces[0]?.id ?? "")
return mapped.some((x) => x.id === prev) ? prev : (mapped[0]?.id ?? "")
@@ -914,7 +989,7 @@ export default function TrafficPage() {
}
void loadLiveTraffic(range)
return () => { cancelled = true }
}, [apiFetch, isLive, groupMode, backendUrl, trafficRetry, range])
}, [apiFetch, isLive, groupMode, backendUrl, trafficRetry, range, view, linkedId])
useEffect(() => {
if (!isLive || groupMode !== "flows" || range === "30d") return
@@ -944,8 +1019,9 @@ export default function TrafficPage() {
if (range === "30d") {
void listServers(backendUrl).then(servers => {
if (cancelled) return
setFlowResult({ key: flowKey, receivedAt: Date.now(), monthlyServers: servers })
setSelectedId(prev => servers.some(server => String(server.id) === prev) ? prev : String(servers[0]?.id ?? ""))
const available = mapExporters ? servers.filter(server => mapExporters.includes(String(server.id))) : servers
setFlowResult({ key: flowKey, receivedAt: Date.now(), monthlyServers: available })
setSelectedId(prev => available.some(server => String(server.id) === prev) ? prev : String(available[0]?.id ?? ""))
}).catch(error => {
if (!cancelled) setFlowResult({ key: flowKey, error: error instanceof Error ? error.message : "Не удалось загрузить каталог серверов" })
})
@@ -962,7 +1038,9 @@ export default function TrafficPage() {
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
const list = flowScope === "users" ? clients.clients : exporters.exporters.filter(card => !mapExporters || mapExporters.includes(card.id))
if (flowScope === "servers" && (prev === ALL_EXPORTERS || mapExporters && !prev)) return prev
if (flowScope === (user ? "users" : "servers") && prev === linkedId) return prev
return list.some(x => x.id === prev) ? prev : (list[0]?.id ?? "")
})
}
@@ -970,7 +1048,7 @@ export default function TrafficPage() {
if (!cancelled) setFlowResult({ key: flowKey, error: e instanceof Error ? e.message : "Не удалось загрузить потоки" })
})
return () => { cancelled = true }
}, [isLive, effectiveMode, backendUrl, range, flowScope, flowKey])
}, [isLive, effectiveMode, backendUrl, range, flowScope, flowKey, user, linkedId, mapExporters])
const analyticsKey = JSON.stringify([flowKey, selectedId, flowIface, flowDedup, flowExcludeMesh, flowExcludeOverlay, analyticsRetry, range === "30d" ? flowMonth : null])
const currentAnalytics = analyticsResult?.key === analyticsKey ? analyticsResult : null
@@ -981,7 +1059,7 @@ export default function TrafficPage() {
const request = range === "30d"
? getFlowMonthly(backendUrl, { month: flowMonth, serverId: flowScope === "servers" ? selectedId : undefined }).then(monthly => ({ monthly }))
: getFlowAnalytics(backendUrl, {
range, serverId: flowScope === "servers" ? selectedId : undefined,
range, serverId: flowScope === "servers" && !allExporters ? selectedId : undefined,
userId: flowScope === "users" ? selectedId : undefined,
iface: flowIface, dedup: flowDedup, excludeMesh: flowExcludeMesh, excludeOverlay: flowExcludeOverlay,
}).then(data => ({ data }))
@@ -991,7 +1069,7 @@ export default function TrafficPage() {
if (!cancelled) setAnalyticsResult({ key: analyticsKey, error: e instanceof Error ? e.message : "Не удалось загрузить аналитику" })
})
return () => { cancelled = true }
}, [confirmedFlowSelection, isLive, effectiveMode, selectedId, range, flowScope, flowIface, flowDedup, flowExcludeMesh, flowExcludeOverlay, backendUrl, analyticsKey, flowMonth, flowMonthValid])
}, [confirmedFlowSelection, isLive, effectiveMode, selectedId, range, flowScope, allExporters, flowIface, flowDedup, flowExcludeMesh, flowExcludeOverlay, backendUrl, analyticsKey, flowMonth, flowMonthValid])
useEffect(() => {
if (!isLive) return
@@ -1001,26 +1079,22 @@ export default function TrafficPage() {
const activeServerTraffic = useMemo(() => isLive ? (trafficReady ? liveServers.map(s => ({ ...s, ...projectTrafficObservations(s, trafficClock) })) : []) : serverTraffic, [isLive, trafficReady, liveServers, trafficClock])
const activeUserTraffic = useMemo(() => isLive ? (trafficReady ? liveUsers.map(u => ({ ...u, ...projectTrafficObservations(u, trafficClock), interfaces: u.interfaces.map(toLiveBound) })) : []) : userTraffic, [isLive, trafficReady, liveUsers, trafficClock])
const activeBoundIfaces = useMemo(() => isLive ? (trafficReady ? liveBoundIfaces.map(c => ({ ...c, ...projectTrafficObservations(c, trafficClock), status: projectTrafficBindingStatus(c.status,c.statusObservedAt,c.statusExpiresAt,trafficClock) })) : []) : boundIfaces, [isLive, trafficReady, liveBoundIfaces, trafficClock])
const visibleIfaces = useMemo(
() => hideDisabledIfaces ? serverIfaces.filter((i) => !i.disabled && i.running) : serverIfaces,
[serverIfaces, hideDisabledIfaces],
)
const ifaceCatalog = isLive ? serverIfaces : MOCK_IFACE_CATALOG[selectedId] ?? []
const visibleIfaces = hideDisabledIfaces ? ifaceCatalog.filter(i => !i.disabled && i.running) : ifaceCatalog
useEffect(() => {
if (!confirmedLiveServer || effectiveMode !== "servers") {
if (!isLive || !confirmedLiveServer || effectiveMode !== "servers") {
// eslint-disable-next-line react-hooks/set-state-in-effect
setServerIfaces([])
setSelectedIface("__all__")
return
}
let cancelled = false
setServerIfaces([])
setSelectedIface("__all__")
apiFetch<{ interfaces: LiveTrafficInterface[] }>(`/api/traffic/servers/${encodeURIComponent(selectedId)}/interfaces`)
.then((res) => { if (!cancelled) setServerIfaces(res.interfaces) })
.catch(() => { if (!cancelled) setServerIfaces([]) })
return () => { cancelled = true }
}, [confirmedLiveServer, selectedId, effectiveMode, apiFetch])
}, [isLive, confirmedLiveServer, selectedId, effectiveMode, apiFetch])
useEffect(() => {
if (!confirmedLiveServer || effectiveMode !== "servers") {
@@ -1043,6 +1117,7 @@ export default function TrafficPage() {
const handleModeChange = (next: GroupMode) => {
setGroupMode(next)
setSelectedIface("__all__")
if (next === "servers") {
setSelectedId(activeServerTraffic[0]?.id ?? "srv1")
if (range === "30d") setRange("1h")
@@ -1130,12 +1205,15 @@ export default function TrafficPage() {
const monthlyServer = monthlyServers.find(server => String(server.id) === selectedId)
const selFlowCard = range === "30d"
? (monthlyServer ? { id: String(monthlyServer.id), name: monthlyServer.name, country: monthlyServer.country, site: monthlyServer.site } : null)
: flowCards.find((c) => c.id === selectedId) ?? null
: allExporters ? { id: ALL_EXPORTERS, name: "Все экспортёры", country: "", site: "" } : flowCards.find((c) => c.id === selectedId) ?? null
const displayedFlow = currentFlows && !liveError ? (flowLiveSample ?? currentAnalytics?.data ?? null) : null
const selServer = useMemo(() => activeServerTraffic.find(s => s.id === selectedId) ?? activeServerTraffic[0], [selectedId, activeServerTraffic])
const detailServer = isLive ? (currentDetail?.server ? { ...currentDetail.server, ...projectTrafficObservations(currentDetail.server, trafficClock), boundIfaces: currentDetail.server.boundIfaces.map(toLiveBound) } : null) : selServer
const selUser = useMemo(() => activeUserTraffic.find(u => u.id === selectedId) ?? activeUserTraffic[0], [selectedId, activeUserTraffic])
const selServer = activeServerTraffic.find(s => s.id === selectedId) ?? (keptLink ? undefined : activeServerTraffic[0])
const demoIfaceRows = !isLive && selectedIface !== "__all__" ? selServer?.boundIfaces.filter(row => row.interfaceName === selectedIface && !row.peerPublicKey) ?? [] : []
const detailServer = isLive ? (currentDetail?.server ? { ...currentDetail.server, ...projectTrafficObservations(currentDetail.server, trafficClock), boundIfaces: currentDetail.server.boundIfaces.map(toLiveBound) } : null)
: selServer && selectedIface !== "__all__" ? demoIfaceRows.length === 1 ? { ...selServer, ...demoIfaceRows[0], id: selServer.id, name: selServer.name, status: selServer.status, boundIfaces: [] } : null
: selServer
const selUser = activeUserTraffic.find(u => u.id === selectedId) ?? (keptLink ? undefined : activeUserTraffic[0])
const selIface = useMemo(() => activeBoundIfaces.find(c => c.id === selectedId) ?? activeBoundIfaces[0], [selectedId, activeBoundIfaces])
const kpiSource = effectiveMode === "users"
@@ -1229,46 +1307,68 @@ export default function TrafficPage() {
},
]
const modeCount: Record<GroupMode, number | null> = {
servers: activeServerTraffic.length,
users: (isLive ? liveUsers : userTraffic).length,
ifaces: (isLive ? liveBoundIfaces : boundIfaces).length,
flows: null,
}
const refreshBusy = isLive && (effectiveMode === "flows" ? liveBusy || analyticsLoading : trafficLoading || detailBusy && confirmedLiveServer)
const listTitle = effectiveMode === "servers" ? "Серверы" : effectiveMode === "users" ? "Клиенты" : "Интерфейсы"
const listShown = effectiveMode === "servers" ? sortedServers.length : effectiveMode === "users" ? sortedUsers.length : sortedIfaces.length
return (
<div className="flex flex-col h-full">
<PageHeader
crumbs={[{ label: "Обзор" }, { label: "Трафик" }]}
actions={
<>
<Button
variant="outline"
size="sm"
onClick={() => {
if (effectiveMode === "flows") setFlowRetry(value => value + 1)
else setTrafficRetry(value => value + 1)
}}
disabled={isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)}
>
<RefreshCwIcon className={cn("size-4", isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading) && "animate-spin")} />Обновить
</Button>
</>
}
/>
<PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Трафик" }]} />
{/* ── mode tab bar ── */}
<div className="border-b bg-background shrink-0">
<div role="group" aria-label="Разделы трафика" className="flex items-center overflow-x-auto px-3 sm:px-6">
{GROUP_MODES.map(({ mode, icon, label }) => (
<button type="button" aria-pressed={effectiveMode === mode} key={mode} onClick={() => handleModeChange(mode)}
className={cn(
"flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-colors -mb-px",
effectiveMode === mode
? "border-primary text-foreground"
: "border-transparent text-muted-foreground hover:text-foreground hover:border-border",
)}>
{icon}{label}
</button>
))}
</div>
</div>
<div className="flex-1 min-w-0 overflow-y-auto p-3 sm:p-6">
<div className="flex-1 min-w-0 overflow-y-auto px-4 pt-5 pb-10 md:px-7 md:pt-6">
<div className="flex flex-col gap-6">
<PageTitle
icon={<ActivityIcon />}
title="Трафик"
description="Счётчики интерфейсов и потоки IPFIX по серверам, клиентам и интерфейсам"
actions={
<>
{returnHref && <Link className={buttonVariants({variant:"outline"})} href={returnHref}><MapIcon aria-hidden />Вернуться на карту</Link>}
<Button type="button" variant="outline" onClick={() => { handleModeChange("flows"); setRange("30d") }}>Месячный отчёт</Button>
<Button
type="button"
onClick={() => {
if (effectiveMode === "flows") setFlowRetry(value => value + 1)
else {
setTrafficRetry(value => value + 1)
if (effectiveMode === "servers") { setDetailRetry(value => value + 1); setLiveRetry(value => value + 1) }
}
}}
disabled={refreshBusy}
aria-busy={refreshBusy}
>
<RefreshCwIcon className={cn("size-4", refreshBusy && "animate-spin")} />Обновить
</Button>
</>
}
/>
<div className="flex flex-col gap-5">
<div role="group" aria-label="Разделы трафика" className="flex items-center gap-1 overflow-x-auto border-b">
{GROUP_MODES.map(({ mode, label }) => (
<button type="button" aria-pressed={effectiveMode === mode} key={mode} onClick={() => handleModeChange(mode)}
className={cn(
"text-muted-foreground hover:text-foreground -mb-px inline-flex items-center gap-1.5 border-b-2 border-transparent px-3 py-2.5 text-sm font-medium whitespace-nowrap transition-colors",
effectiveMode === mode && "border-foreground text-foreground",
)}>
{label}
{modeCount[mode] != null ? (
<em aria-hidden="true" className={cn("bg-muted text-muted-foreground inline-flex h-5 min-w-5 items-center justify-center rounded-md px-1.5 font-mono text-xs not-italic", effectiveMode === mode && "bg-foreground/12 text-foreground")}>{modeCount[mode]}</em>
) : null}
</button>
))}
</div>
<details className="text-sm text-muted-foreground">
<summary className="cursor-pointer font-medium text-foreground">Как читать трафик</summary>
<p className="mt-2">Серверы, клиенты и интерфейсы показывают измеренные RX и TX. В «Потоках» скорость усреднена по доступному окну IPFIX. Месячный отчёт показывает накопленный объём.</p>
</details>
{keptLink && (effectiveMode === "flows" ? !liveBusy && !liveError && !selFlowCard : (trafficReady || !isLive) && (effectiveMode === "users" ? !selUser : !selServer)) &&
<Alert><AlertTitle>Объект из ссылки недоступен</AlertTitle><AlertDescription>Выберите доступный объект в списке.</AlertDescription></Alert>}
{!(effectiveMode === "flows" && range === "30d") && (!isLive || !(effectiveMode === "flows" ? liveError : trafficError)) && <KpiStatGrid
isLoading={isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)}
aria-label="Сводка трафика"
@@ -1297,15 +1397,15 @@ export default function TrafficPage() {
{flowError}
</div>
)}
<div className="grid min-w-0 grid-cols-1 xl:grid-cols-[300px_minmax(0,1fr)] gap-5 items-start">
<div className="flex flex-col gap-3">
<div className="grid min-w-0 grid-cols-1 xl:grid-cols-[300px_minmax(0,1fr)] gap-4 items-start">
<SectionFrame title={flowScope === "users" ? "Клиенты" : "Экспортёры"} description="Потоки IPFIX · сортировка и поиск" panelClassName="flex flex-col gap-3 p-2.5">
<div role="group" aria-label="Источник потоков" className="flex gap-1">
<button
type="button"
aria-pressed={flowScope === "servers"}
onClick={() => { setFlowScope("servers"); setFlowIface("__all__") }}
className={cn(
"text-[10px] px-2 py-0.5 rounded border transition-colors",
"text-xs px-2 py-0.5 rounded border transition-colors",
flowScope === "servers"
? "border-primary bg-primary/10 text-primary font-medium"
: "border-border text-muted-foreground hover:text-foreground",
@@ -1316,9 +1416,10 @@ export default function TrafficPage() {
<button
type="button"
aria-pressed={flowScope === "users"}
disabled={Boolean(mapExporters)}
onClick={() => { setFlowScope("users"); setFlowIface("__all__"); if (range === "30d") setRange("1h") }}
className={cn(
"text-[10px] px-2 py-0.5 rounded border transition-colors",
"text-xs px-2 py-0.5 rounded border transition-colors",
flowScope === "users"
? "border-primary bg-primary/10 text-primary font-medium"
: "border-border text-muted-foreground hover:text-foreground",
@@ -1338,14 +1439,14 @@ export default function TrafficPage() {
/>
</div>
<div className={cn("flex gap-1 flex-wrap", range === "30d" && "hidden")}>
<span className="text-[10px] text-muted-foreground self-center mr-0.5">Сортировка:</span>
<span className="text-xs text-muted-foreground self-center mr-0.5">Сортировка:</span>
{visibleSortFields.map(({ field, label }) => (
<button
key={field}
type="button"
onClick={() => toggleSort(field)}
className={cn(
"text-[10px] px-2 py-0.5 rounded border transition-colors",
"text-xs px-2 py-0.5 rounded border transition-colors",
sortField === field
? "border-primary bg-primary/10 text-primary font-medium"
: "border-border text-muted-foreground hover:text-foreground",
@@ -1357,6 +1458,8 @@ export default function TrafficPage() {
</div>
{range === "30d" && <p className="text-xs text-muted-foreground">Серверы из каталога, включая неактивные. Удалённые серверы в список не входят.</p>}
<div className="flex flex-col gap-2">
{!mapExporters && flowScope === "servers" && range !== "30d" && <Button type="button" size="sm" variant={allExporters ? "secondary" : "outline"} aria-pressed={allExporters} onClick={() => setSelectedId(ALL_EXPORTERS)}>Все экспортёры</Button>}
{mapExporters && flowScope === "servers" && range !== "30d" && !selectedId && <p className="text-xs text-muted-foreground">{mapExporters.length ? "Выберите экспортёра этого сервиса." : "Экспортёр этого сервиса не подтверждён."}</p>}
{range === "30d" ? visibleMonthlyServers.map(server => <Button key={server.id} variant="outline" className="justify-start whitespace-normal break-all h-auto py-2" aria-pressed={String(server.id) === selectedId} onClick={() => setSelectedId(String(server.id))}>{server.name}</Button>) : sortedFlowCards.map((card) => (
<FlowEntityCardView
key={card.id}
@@ -1371,8 +1474,8 @@ export default function TrafficPage() {
</p>
) : null}
</div>
</div>
<Frame dense className="w-full min-w-0 flex flex-col">
</SectionFrame>
<SectionFrame bare className="w-full min-w-0">
<FramePanel className="flex-1 min-w-0 p-3 sm:p-5">
{analyticsLoading && <p role="status">Загрузка аналитики…</p>}
{currentAnalytics?.error && <Alert variant="destructive" role="alert"><AlertTitle>Аналитика недоступна</AlertTitle><AlertDescription>{currentAnalytics.error}<Button size="sm" variant="outline" onClick={() => setAnalyticsRetry(value => value + 1)}>Повторить аналитику</Button></AlertDescription></Alert>}
@@ -1396,10 +1499,13 @@ export default function TrafficPage() {
excludeOverlay={flowExcludeOverlay}
onExcludeOverlay={setFlowExcludeOverlay}
liveHint={flowLiveHint}
initialService={view === "flows" ? service : undefined}
initialCountry={country}
mapNodes={mapNodes}
emptyHint={analyticsLoading ? "Загрузка аналитики…" : currentAnalytics?.error ? "Не удалось получить данные выбранного среза" : flowEmptyHint(collectorStatus)}
/>
</FramePanel>
</Frame>
</SectionFrame>
</div>
<FlowOverlaySheet
open={overlayOpen}
@@ -1410,9 +1516,10 @@ export default function TrafficPage() {
/>
</div>
) : (
<div className="grid min-w-0 grid-cols-1 xl:grid-cols-[300px_minmax(0,1fr)] gap-5 items-start">
<div className="grid min-w-0 grid-cols-1 gap-3 items-start lg:grid-cols-[minmax(12rem,17rem)_minmax(0,1fr)]">
{/* ── left panel ── */}
<div className="flex flex-col gap-3">
<div className="flex min-w-0 flex-col gap-4">
<SectionFrame title={listTitle} description={`${listShown} из ${modeCount[effectiveMode] ?? listShown} · сортировка и поиск`} panelClassName="flex flex-col gap-3 p-2.5">
{/* search */}
<div className="relative">
@@ -1422,20 +1529,17 @@ export default function TrafficPage() {
value={search}
onChange={e => setSearch(e.target.value)}
aria-label="Поиск трафика" placeholder="Поиск…"
className="w-full pl-8 pr-3 h-8 text-xs bg-muted/50 border border-border rounded-md outline-none focus:border-primary transition-colors"
className="border-input bg-input/30 focus:border-ring h-8 w-full rounded-lg border pr-3 pl-8 text-[13px] outline-none transition-colors"
/>
</div>
{/* sort controls */}
<div className="flex gap-1 flex-wrap">
<span className="text-[10px] text-muted-foreground self-center mr-0.5">Сортировка:</span>
<div role="group" aria-label="Сортировка" className="bg-muted inline-flex h-9 w-fit items-center gap-0.5 rounded-lg p-[3px]">
{visibleSortFields.map(({ field, label }) => (
<button type="button" aria-pressed={sortField === field} key={field} onClick={() => toggleSort(field)}
className={cn(
"text-[10px] px-2 py-0.5 rounded border transition-colors",
sortField === field
? "border-primary bg-primary/10 text-primary font-medium"
: "border-border text-muted-foreground hover:text-foreground",
"text-muted-foreground hover:text-foreground h-[30px] rounded-md px-2.5 text-[13px] font-medium transition-colors",
sortField === field && "bg-background text-foreground shadow-sm",
)}>
{label}{sortField === field ? (sortDir === "desc" ? " ↓" : " ↑") : ""}
</button>
@@ -1450,9 +1554,9 @@ export default function TrafficPage() {
</p>
)}
{/* entity list */}
<div className="flex flex-col gap-2">
<div className="flex max-h-72 flex-col gap-2 overflow-y-auto p-0.5 lg:max-h-[26rem]">
{effectiveMode === "servers" && sortedServers.map(s => (
<ServerCard key={s.id} s={s} selected={s.id === selectedId} onClick={() => setSelectedId(s.id)} />
<ServerCard key={s.id} s={s} selected={s.id === selectedId} onClick={() => { if (s.id !== selectedId) setSelectedIface("__all__"); setSelectedId(s.id) }} />
))}
{effectiveMode === "users" && sortedUsers.map(u => (
<UserCard key={u.id} u={u} selected={u.id === selectedId} onClick={() => setSelectedId(u.id)} />
@@ -1461,20 +1565,23 @@ export default function TrafficPage() {
<IfaceCard key={c.id} c={c} selected={c.id === selectedId} onClick={() => setSelectedId(c.id)} />
))}
</div>
</SectionFrame>
{effectiveMode === "servers" ? <RxShareFrame servers={activeServerTraffic} /> : null}
</div>
{/* ── detail panel ── */}
<Frame dense className="w-full min-w-0 flex flex-col">
<div className="flex min-w-0 flex-col gap-4">
<SectionFrame bare className="w-full min-w-0">
<FramePanel className="flex-1 min-w-0 p-3 sm:p-5">
{isLive && effectiveMode === "servers" && (
<div className="mb-3 pb-3 border-b">
{effectiveMode === "servers" && (
<div role="group" aria-label="Интерфейсы выбранного сервера" className="mb-3 pb-3 border-b">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[11px] text-muted-foreground mr-1">Интерфейс:</span>
<span className="text-xs text-muted-foreground mr-1">Интерфейс:</span>
<button
type="button" aria-pressed={hideDisabledIfaces}
onClick={() => setHideDisabledIfaces((v) => !v)}
onClick={() => { if (!hideDisabledIfaces && ifaceCatalog.some(iface => iface.name === selectedIface && (iface.disabled || !iface.running))) setSelectedIface("__all__"); setHideDisabledIfaces(value => !value) }}
className={cn(
"inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-medium transition-all",
"inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium transition-all",
hideDisabledIfaces
? "bg-muted text-foreground border-border"
: "text-muted-foreground border-border hover:text-foreground hover:border-foreground/40",
@@ -1486,7 +1593,7 @@ export default function TrafficPage() {
type="button" aria-pressed={selectedIface === "__all__"}
onClick={() => setSelectedIface("__all__")}
className={cn(
"inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-[10px] font-medium transition-all",
"inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs font-medium transition-all",
selectedIface === "__all__"
? "bg-foreground text-background border-foreground"
: "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40",
@@ -1502,7 +1609,7 @@ export default function TrafficPage() {
type="button" aria-pressed={active}
onClick={() => setSelectedIface(iface.name)}
className={cn(
"inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[10px] font-medium transition-all",
"inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-xs font-medium transition-all",
active
? "bg-foreground text-background border-foreground"
: "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40",
@@ -1514,10 +1621,11 @@ export default function TrafficPage() {
</button>
)
})}
{detailBusy && <span className="text-[10px] text-muted-foreground ml-2">Загрузка...</span>}
{detailBusy && <span className="text-xs text-muted-foreground ml-2">Загрузка...</span>}
</div>
</div>
)}
{!isLive && effectiveMode === "servers" && selectedIface !== "__all__" && !detailServer && <OfflinePlaceholder text="В демоснимке нет замеров этого интерфейса" />}
{isLive && effectiveMode === "servers" && !detailServer && <>
<DetailHeader range={range} setRange={setRange}><h2 className="text-base font-semibold">{selServer?.name ?? "Трафик сервера"}</h2></DetailHeader>
{detailBusy && <p role="status" className="text-sm text-muted-foreground">Загрузка выбранного периода и интерфейса…</p>}
@@ -1536,6 +1644,7 @@ export default function TrafficPage() {
</>}
{effectiveMode === "servers" && detailServer && (
<ServerDetail
key={selectedId + ":" + selectedIface}
sel={detailServer}
range={range}
setRange={setRange}
@@ -1547,14 +1656,17 @@ export default function TrafficPage() {
: liveSample ? "live" : isLive ? "История · ожидание live" : undefined}
/>
)}
{effectiveMode === "users" && selUser && <UserDetail sel={selUser} range={range} setRange={setRange} />}
{effectiveMode === "ifaces" && selIface && <IfaceDetail sel={selIface} range={range} setRange={setRange} />}
{effectiveMode === "users" && selUser && <UserDetail key={selUser.id} sel={selUser} range={range} setRange={setRange} />}
{effectiveMode === "ifaces" && selIface && <IfaceDetail key={selIface.id} sel={selIface} range={range} setRange={setRange} />}
</FramePanel>
</Frame>
</SectionFrame>
{effectiveMode === "servers" && detailServer && detailServer.boundIfaces.length > 0 ? <ServerIfacesFrame server={detailServer} /> : null}
</div>
</div>
)}
</div>
</div>
</div>
</div>
)
+1 -1
View File
@@ -49,7 +49,7 @@ export function registerFlowMapActions(register: typeof add) {
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: "closed minutes for all rates; retained flows for services, exit exporter or observed GRE peer/next hop for paths; interfaceTraffic includes private routed traffic before top-N",
source: "closed minutes for all rates; retained flows for services and user breakdowns; paths use an exit exporter or observed GRE peer/next hop, otherwise identify the observing exporter; interfaceTraffic includes private routed traffic before top-N",
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,
referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false,
rowSumIsNetworkTotal: false, historicalOwnershipVerified: false,
+3 -1
View File
@@ -210,7 +210,9 @@ const trafficFlowRoutes: FastifyPluginAsyncZod = async (app) => {
app.get("/traffic/flow/map-hops", async (req, reply) => {
const query = analyticsQuery(req)
return reply.send(await readFlowWindow(query.minutes, minutes => buildFlowMapHops({ ...query, minutes }), mcpDatabaseRequestSignal()))
const includeCurrentMinute = (req.query as { range?: string }).range?.toLowerCase() === "1m"
const requestedMinutes = includeCurrentMinute ? 1 : query.minutes
return reply.send(await readFlowWindow(requestedMinutes, minutes => buildFlowMapHops({ ...query, minutes, includeCurrentMinute }), mcpDatabaseRequestSignal()))
})
app.get("/traffic/flow/monthly", async (req, reply) => {
+16 -7
View File
@@ -13,7 +13,7 @@ import {
} from "../services/traffic-collector.js"
import { refreshScheduler } from "../services/scheduler.js"
import { collectTrafficManually } from "../services/manual-traffic-collection.js"
import { readTrafficLiveSample, TrafficLiveSourceChanged } from "../services/traffic-live.js"
import { readTrafficLiveInterfaces, readTrafficLiveSample, TrafficLiveSourceChanged } from "../services/traffic-live.js"
import { MikrotikClient, MikrotikError } from "../services/mikrotik.js"
import { getEnabledServerById } from "../services/wireguard-live.js"
import { readTrafficCollectionContext } from "../services/traffic-collection-state.js"
@@ -106,9 +106,15 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
})
app.get("/traffic/servers/:id/live", async (req, reply) => {
const p = req.params as { id?: string | number }
const q = req.query as { iface?: string; once?: string }
if (q.once === "1" && (typeof q.iface !== "string" || !q.iface.trim() ||
q.iface.length > 128 || q.iface === "__all__" || /[,\x00-\x1f\x7f]/.test(q.iface))) {
const q = req.query as { iface?: string; ifaces?: string; once?: string }
const validIface = (name: unknown): name is string => typeof name === "string" && Boolean(name.trim()) &&
name.length <= 128 && name !== "__all__" && !/[,\x00-\x1f\x7f]/.test(name)
const interfaces = typeof q.ifaces === "string" ? q.ifaces.split(",") : []
if (q.ifaces !== undefined && (q.once !== "1" || q.iface !== undefined || !interfaces.length ||
interfaces.length > 16 || new Set(interfaces).size !== interfaces.length || !interfaces.every(validIface))) {
return reply.code(400).send({ error: "Укажите до 16 разных интерфейсов для live-измерения" })
}
if (q.once === "1" && !interfaces.length && !validIface(q.iface)) {
return reply.code(400).send({ error: "Укажите один интерфейс для live-измерения" })
}
const readServer = (id: string | number, signal?: AbortSignal) => withDatabaseApiRequest(async () => {
@@ -123,11 +129,12 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
const onlyInterface = q.iface && q.iface !== "__all__" ? q.iface : undefined
const client = MikrotikClient.fromServer(server)
const cache = { names: onlyInterface ? [onlyInterface] : [] as string[], joinedFailed: false }
const readSample = (signal: AbortSignal) => readTrafficLiveSample(client, onlyInterface, cache, signal, async () => {
const assertSource = async (signal: AbortSignal) => {
const current = await readServer(server.id, signal)
if (!current) throw new TrafficLiveSourceChanged("Устройство выключено или удалено. Переподключите live-поток")
if (Date.parse(current.updatedAt) !== Date.parse(server.updatedAt)) throw new TrafficLiveSourceChanged("Конфигурация устройства изменилась. Переподключите live-поток")
})
}
const readSample = (signal: AbortSignal) => readTrafficLiveSample(client, onlyInterface, cache, signal, () => assertSource(signal))
const abort = new AbortController()
const onClose = () => abort.abort()
registerDatabaseStreamAbort(req, onClose)
@@ -136,7 +143,9 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
if (q.once === "1") {
reply.raw.once("close", onClose)
try {
const sample = await readSample(abort.signal)
const sample = interfaces.length
? { interfaces: await readTrafficLiveInterfaces(client, interfaces, abort.signal, () => assertSource(abort.signal)) }
: await readSample(abort.signal)
return reply.header("Cache-Control", "no-store").send(sample)
} catch {
if (!reply.raw.destroyed) return reply.code(503).send({ error: "Live-измерение интерфейса недоступно" })
@@ -46,6 +46,8 @@ assert.equal(isNamedInternetService("DNS", "DNS"), false)
assert.equal(mapServiceNodeId("AWS"), "svc:aws")
assert.equal(mapServiceNodeId("Cloudflare"), "svc:cloudflare")
assert.equal(mapServiceNodeId("Прочее"), "svc:other")
assert.notEqual(mapServiceNodeId("Видео"), mapServiceNodeId("Игры"))
assert.notEqual(mapServiceNodeId("Microsoft Работа"), mapServiceNodeId("Microsoft Игры"))
assert.equal(mapCountryNodeId("US"), "cc:us")
assert.equal(mapCountryNodeId("nl"), "cc:nl")
assert.equal(mapCountryNodeId(""), "cc:other")
@@ -358,6 +358,7 @@ export function isNamedInternetService(service: string, category: string): boole
export function mapServiceNodeId(label: string): string {
const raw = label.trim()
if (raw === OTHER_SERVICE) return "svc:other"
if (/[^\x00-\x7f]/.test(raw)) return `svc:label:${encodeURIComponent(raw.normalize("NFC").toLowerCase())}`
const slug = raw
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
@@ -5,12 +5,16 @@ import { classifyFlowDst, disableCatalogFetchForTests, resetFlowCatalogForTests,
disableCatalogFetchForTests()
resetFlowCatalogForTests()
seedFlowCatalogForTests({
cidrs: [{ cidr: "192.0.2.0/24", purpose: "steam-gaming" }],
cidrs: [{ cidr: "192.0.2.0/24", purpose: "steam-gaming" },
{ cidr: "198.51.100.0/25", purpose: "Игры" },
{ cidr: "198.51.100.128/25", purpose: "Видео / стриминг" }],
})
const hit = classifyFlowDst("192.0.2.10", 6, 443, 50000, null)
assert.equal(hit.category, "Игры")
assert.equal(hit.service, "steam-gaming")
assert.equal(classifyFlowDst("198.51.100.10", 6, 443, 50000, null).category, "Игры")
assert.equal(classifyFlowDst("198.51.100.150", 6, 443, 50000, null).category, "Видео / стриминг")
const miss = classifyFlowDst("203.0.113.9", 17, 53, 53000, null)
assert.equal(miss.category, "DNS")
@@ -50,12 +50,12 @@ export function seedFlowCatalogForTests(input: {
}
export function categoryFromPurpose(purpose: string, proto: number, dstPort: number, srcPort: number): string {
const p = purpose.toLowerCase()
if (/gaming|steam|epic|riot|playstation|roblox|ubisoft/.test(p)) return "Игры"
if (/streaming|youtube|netflix|twitch|video|spotify|instagram/.test(p)) return "Видео / стриминг"
const p = purpose.trim().toLowerCase()
if (/игры|gaming|steam|epic|riot|playstation|roblox|ubisoft/.test(p)) return "Игры"
if (/видео|стриминг|streaming|youtube|netflix|twitch|video|spotify|instagram/.test(p)) return "Видео / стриминг"
if (/cdn|cloudflare|akamai|fastly|hetzner|ovh|apple/.test(p)) return "CDN"
if (/voip|discord|zoom/.test(p)) return "Голос"
if (/openai|chatgpt|\bai\b/.test(p)) return "ИИ"
if (/голос|voip|discord|zoom/.test(p)) return "Голос"
if (p === "ии" || /openai|chatgpt|\bai\b/.test(p)) return "ИИ"
if (/quad9|opendns/.test(p)) return "DNS"
if (/веб|web|google|github|paypal|vk|linkedin/.test(p)) return "Веб"
const app = applicationName(proto, dstPort, srcPort)
@@ -142,6 +142,7 @@ assert.equal(classifyInternetBrand("8.8.8.8", 6, 443, 51234, {
fetchedAt: Date.now(),
})?.service, "Google")
assert.equal(mapInternetBrand("203.0.113.50", 6, 443, 51234, null).service, "Прочее")
assert.deepEqual(mapInternetBrand("185.246.117.91", 17, 53, 53000, null), { service: "DNS", category: "DNS" })
assert.equal(mapInternetBrand("8.8.8.8", 47, 0, 0, null).service, "Прочее")
assert.equal(mapInternetBrand("8.8.8.8", 6, 443, 51234, {
prefix: "8.8.8.0/24",
+1 -1
View File
@@ -105,7 +105,7 @@ export function mapInternetBrand(
if (isTunnelProto(proto, dstPort, srcPort)) return OTHER_BRAND
const classified = classifyFlowDst(dst, proto, dstPort, srcPort, ripe, { ignoreTunnelProto: true })
if (isNamedInternetService(classified.service, classified.category)) return classified
return OTHER_BRAND
return { service: classified.category, category: classified.category }
}
export function resolveInternetDest(opts: {
@@ -18,7 +18,7 @@ import {
resetFlowMapHopsCacheForTests,
} from "./traffic-flow-map-hops.js"
import { withPgOrSkip } from "../test/pg.js"
import { seedFlowTopologyForTests, type FlowTopology } from "./traffic-flow-topology.js"
import { loadFlowTopology, resolveClient, seedFlowTopologyForTests, type FlowTopology } from "./traffic-flow-topology.js"
import { disableCatalogFetchForTests, resetFlowCatalogForTests } from "./traffic-flow-classify.js"
import {
disableRipeEnqueueForTests,
@@ -698,7 +698,7 @@ try {
const googleEdge = wan.serviceEdges?.find((e) => e.toId === "svc:google")
assert.ok(googleEdge, "Google с WAN JH")
assert.equal(googleEdge.fromId, "9", "якорь на EN, не на JH")
assert.ok(!(wan.serviceEdges ?? []).some((e) => e.fromId === "7"), "нет пунктира с JH")
assert.ok(!(wan.serviceEdges ?? []).some((e) => e.fromId === "7"), "исторический снимок сопоставил GRE с Exit")
const viaGre = wan.serviceEdges?.find((e) => e.toId === "svc:google")
assert.ok(viaGre?.clients?.some((c) => c.name === "Alice") || viaGre?.clientName === "Alice")
} finally {
@@ -730,15 +730,20 @@ ingestClosed(7, [
outIface: "1",
nextHop: "",
},
{ ...payloadFlow("1.2.3.4", 6000), proto: 17, dstPort: 53, inIface: "gre-client", outIface: "ether1", nextHop: "" },
])
try {
resetFlowMapHopsCacheForTests()
const wanOnly = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
assert.equal(wanOnly.services?.find(s => s.id === "svc:youtube")?.bytes, 9000)
assert.deepEqual(wanOnly.serviceEdges, [])
assert.deepEqual(wanOnly.servicePaths, [])
assert.deepEqual(wanOnly.countryEdges, [])
assert.ok(wanOnly.countryServiceGroups?.every(group => !group.edges.length && !group.paths.length))
const dns = wanOnly.serviceEdges?.find(e => e.toId === "svc:dns")
assert.deepEqual(dns && [dns.fromId, dns.observedOnly, dns.bytes], ["7", true, 6000])
const dnsPath = wanOnly.servicePaths?.find(p => p.serviceId === "svc:dns")
assert.deepEqual(dnsPath && [dnsPath.viaId, dnsPath.viaIface, dnsPath.enId, dnsPath.clientName], ["7", "ether1", "", "Alice"])
assert.ok(wanOnly.countryEdges?.every(e => e.observedOnly && e.fromId === "7"))
assert.ok(wanOnly.countryServiceGroups?.some(group => group.edges.some(e => e.toId.endsWith("|svc:dns"))))
assert.deepEqual(wanOnly.nodeUsers?.["7"]?.map(u => [u.clientName, u.bytes]), [["—", 9000], ["Alice", 6000]])
assert.equal(wanOnly.nodeUsers?.["9"], undefined)
} finally {
seedFlowTopologyForTests(null)
@@ -768,7 +773,7 @@ ingestClosed(9, [{
proto: 6,
srcPort: 51234,
dstPort: 443,
bytes: 12_000,
bytes: 120_000,
packets: 10,
inIface: "1",
outIface: "1",
@@ -786,7 +791,10 @@ try {
assert.equal(googlePaths[0]?.viaId, "7")
const googleEdge = dual.serviceEdges?.find((e) => e.toId === "svc:google" && e.fromId === "9")
assert.ok(googleEdge)
assert.equal(googleEdge.bytes, 12_000)
assert.equal(googleEdge.bytes, 120_000)
assert.equal(dual.totalBytes, 120_000, "объём крупнейшей копии с атрибуцией маршрута JH")
assert.equal(dual.nodeUsers?.["7"]?.find(u => u.clientName === "Alice")?.bytes, 12_000)
assert.equal(dual.nodeUsers?.["9"]?.find(u => u.clientName === "Alice")?.bytes, 120_000)
assert.equal(googleEdge.bps, googlePaths[0]?.bps)
} finally {
seedFlowTopologyForTests(null)
@@ -1031,12 +1039,21 @@ try {
{ ...flow, src: "10.0.0.2", bytes: 2000, outIface: "gre-second" },
{ ...flow, src: "10.0.0.3", bytes: 9000, outIface: "ether1" },
])
// This open minute must affect neither the service nor the link rate.
ingestParsedFlowsForServerForTests(7, [{ ...flow, bytes: 90000, outIface: "SWE-VEESP" }])
const map = await buildFlowMapHops({ serverId: 7, minutes: 5, minSharePct: 0 })
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.bytes, 12000)
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes]), [["10", 2000], ["9", 1000]])
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 3000)
ingestClosed(7, [{ ...flow, bytes: 900_000_000, outIface: "SWE-VEESP" }], bucket + 90_000)
const clock = mock.method(Date, "now", () => bucket + 90_000)
try {
const map = await buildFlowMapHops({ serverId: 7, minutes: 5, minSharePct: 0 })
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.bytes, 12000)
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes, Boolean(e.observedOnly)]), [["7", 9000, true], ["10", 2000, false], ["9", 1000, false]])
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 12000)
assert.equal(map.nodeUsers?.["7"]?.find(u => u.clientName === "Alice")?.bytes, 12000)
assert.equal(map.nodeUsers?.["9"]?.find(u => u.clientName === "Alice")?.bytes, 1000)
const recent = await buildFlowMapHops({ serverId: 7, minutes: 1, includeCurrentMinute: true, minSharePct: 0 })
assert.equal(recent.windowSec, 90)
assert.equal(recent.services?.find(s => s.id === "svc:youtube")?.bps, 900_012_000 * 8 / 90)
assert.equal(recent.serviceEdges?.find(edge => edge.fromId === "9")?.bps, 900_001_000 * 8 / 90)
} finally { clock.mock.restore() }
} finally {
await dbQuery("DELETE FROM internet_path_snapshots WHERE id=?", [snapshot.id])
resetFlowRingsForTests()
@@ -1096,12 +1113,28 @@ try {
ingestClosed(sid, [split], bucket - 60000)
const mixed = await buildFlowMapHops({serverId: sid, minutes: 5, iface: "mixed-lan"})
assert.equal(mixed.totalBytes, 6000)
assert.deepEqual(mixed.serviceEdges, [])
assert.ok(mixed.serviceEdges?.every(e => e.observedOnly && e.fromId === String(sid)))
assert.ok(mixed.servicePaths?.every(p => !p.enId))
await flushEngineNow({ prune: false })
assert.deepEqual((await dbQuery("SELECT out_iface,next_hop FROM flow_buckets WHERE server_id=? AND in_iface='mixed-lan'", [sid])).rows,
[{out_iface: "", next_hop: null}, {out_iface: "", next_hop: null}])
const user = await buildFlowMapHops({serverId: sid, minutes: 5, userId: "no-interface-binding"})
assert.equal(user.interfaceTraffic, undefined)
const alice = `map-alice-${sid}`, bob = `map-bob-${sid}`
try {
await dbQuery("INSERT INTO app_users(id,login,name) VALUES (?,?,'Alice'),(?,?,'Bob')", [alice, alice, bob, bob])
await dbQuery(`
INSERT INTO user_interface_bindings(id,user_id,server_id,interface_name,interface_type,peer_public_key)
VALUES (?, ?, ?, 'wg-shared', 'wg', 'alice-key'), (?, ?, ?, 'wg-shared', 'wg', 'bob-key'), (?, ?, ?, 'gre-owner', 'gre', '')
`, [alice + "-wg", alice, sid, bob + "-wg", bob, sid, alice + "-gre", alice, sid])
seedFlowTopologyForTests(null)
for (const topology of [await loadFlowTopology(), await loadFlowTopology([sid])]) {
assert.equal(resolveClient(topology, sid, "wg-shared"), null, "общий WG не присваивается одному пользователю")
assert.equal(resolveClient(topology, sid, "gre-owner")?.userId, alice)
}
} finally {
await dbQuery("DELETE FROM app_users WHERE id IN (?,?)", [alice, bob])
}
console.log("CHR NetFlow v5 through PostgreSQL and map: GRE A RX / GRE B TX both 192 B, 3 packets; Top-200 and GRE encapsulation verified")
} finally {
await dbQuery("DELETE FROM servers WHERE id=?", [sid])
+91 -63
View File
@@ -17,7 +17,7 @@ import { destCtxForIface, flowRateDirection, mapInternetBrand } from "./traffic-
import { resolveFlowEndpoints } from "./traffic-flow-ip.js"
import { geoipReadersStatus, resolveFlowIp } from "./traffic-flow-geoip.js"
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
import { loadFlowTopology, resolveClient, getServerCatalog, type FlowTopology } from "./traffic-flow-topology.js"
import { loadFlowTopology, resolveClient, getServerCatalog, type FlowClientBinding, type FlowTopology } from "./traffic-flow-topology.js"
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM } from "./traffic-flow-engine.js"
export const DEFAULT_MAP_SERVICE_MIN_SHARE_PCT = 5
@@ -33,6 +33,7 @@ const HOPS_CACHE_TTL_MS = 2000
export interface FlowMapHopsQuery {
minutes: number
includeCurrentMinute?: boolean
serverId?: number
userId?: string
iface?: string
@@ -63,6 +64,7 @@ interface ClientAcc {
interface FromAcc {
exporterId: string
enId: string
viaIface?: string
reverseBytes: number
bytes: number
clients: Map<string, ClientAcc>
@@ -90,6 +92,7 @@ interface DestEdgeAcc {
bytesFwd: number
bytesRev: number
clients: Map<string, string>
observedOnly?: true
}
interface DestPathAcc {
@@ -97,6 +100,7 @@ interface DestPathAcc {
clientName: string
viaId: string
viaName: string
viaIface?: string
enId: string
enName: string
serviceId: string
@@ -114,12 +118,12 @@ function bumpClient(clients: Map<string, ClientAcc>, bytes: number, client: { us
clients.set(id, { name, bytes })
}
function bumpFrom(acc: DstAcc, exporterId: string, enId: string, bytes: number, reverse: boolean, client: { userId: string; name: string } | null): void {
const key = exporterId + "|" + enId
const from = acc.fromBytes.get(key) ?? { exporterId, enId, bytes: 0, reverseBytes: 0, clients: new Map<string, ClientAcc>() }
function bumpFrom(acc: DstAcc, exporterId: string, enId: string, viaIface: string | undefined, bytes: number, reverse: boolean, client: FlowClientBinding | null | undefined): void {
const key = JSON.stringify([exporterId, enId, viaIface])
const from = acc.fromBytes.get(key) ?? { exporterId, enId, viaIface, bytes: 0, reverseBytes: 0, clients: new Map<string, ClientAcc>() }
from.bytes += bytes
if (reverse) from.reverseBytes += bytes
bumpClient(from.clients, bytes, client)
bumpClient(from.clients, bytes, client ?? null)
acc.fromBytes.set(key, from)
}
@@ -170,7 +174,7 @@ function bumpDestFrom(
enName: string,
viaName: string,
/** fromId ребра, если отличается от EN (вложенный слой: страна → сервис). */
edgeFromId: string = fromId,
edgeFromId: string = fromId || exporterId,
): void {
const edgeKey = `${edgeFromId}|${toId}`
const prevEdge = edges.get(edgeKey)
@@ -191,10 +195,11 @@ function bumpDestFrom(
bytesFwd: from.bytes - from.reverseBytes,
bytesRev: from.reverseBytes,
clients: namedClients,
...(!fromId && edgeFromId === exporterId ? { observedOnly: true as const } : {}),
})
}
for (const [clientId, c] of from.clients) {
const pathKey = `${clientId}|${exporterId}|${fromId}|${toId}`
const pathKey = JSON.stringify([clientId, exporterId, fromId, toId, from.viaIface])
const prevPath = paths.get(pathKey)
if (prevPath) {
prevPath.bytes += c.bytes
@@ -205,6 +210,7 @@ function bumpDestFrom(
clientName: c.name,
viaId: exporterId,
viaName,
...(from.viaIface ? { viaIface: from.viaIface } : {}),
enId: fromId,
enName,
serviceId: toId,
@@ -252,6 +258,7 @@ function finalizeDestLayer(
bps: (e.bytes * 8) / windowSec,
bpsFwd: (e.bytesFwd * 8) / windowSec,
bpsRev: (e.bytesRev * 8) / windowSec,
...(e.observedOnly ? { observedOnly: e.observedOnly } : {}),
...(first ? { clientId: first.id, clientName: first.name } : {}),
...(clients.length ? { clients } : {}),
}
@@ -264,6 +271,7 @@ function finalizeDestLayer(
clientName: p.clientName,
viaId: p.viaId,
viaName: p.viaName,
...(p.viaIface ? { viaIface: p.viaIface } : {}),
enId: p.enId,
enName: p.enName,
serviceId: p.serviceId,
@@ -329,6 +337,7 @@ function hopsQueryKey(q: FlowMapHopsQuery, minSharePct: number): string {
return JSON.stringify({
epoch: flowDataEpoch(),
minutes: q.minutes,
includeCurrentMinute: q.includeCurrentMinute === true,
serverId: q.serverId ?? null,
userId: q.userId ?? null,
iface: q.iface ?? null,
@@ -339,18 +348,6 @@ function hopsQueryKey(q: FlowMapHopsQuery, minSharePct: number): string {
})
}
async function userIfaceAllow(userId: string): Promise<Map<number, Set<string>> | null> {
if (!userId) return null
const binds = await flowReadDbAll<{serverId:number;interfaceName:string}>('SELECT server_id AS "serverId",interface_name AS "interfaceName" FROM user_interface_bindings WHERE user_id=?',[userId])
const allow = new Map<number, Set<string>>()
for (const b of binds) {
const set = allow.get(b.serverId) ?? new Set<string>()
set.add(b.interfaceName)
allow.set(b.serverId, set)
}
return allow
}
function ifaceUsable(name: string): boolean {
return Boolean(name) && name !== "—"
}
@@ -360,9 +357,11 @@ function resolveMapClient(
serverId: number,
inName: string,
outName: string,
) {
return resolveClient(topo, serverId, inName)
?? (ifaceUsable(outName) ? resolveClient(topo, serverId, outName) : null)
): FlowClientBinding | null | undefined {
const ingress = resolveClient(topo, serverId, inName)
const egress = resolveClient(topo, serverId, outName)
if (ingress && egress && ingress.userId !== egress.userId) return null
return ingress ?? egress ?? undefined
}
function bump(acc: Map<string, HopAcc>, key: string, seed: Omit<HopAcc, "bytes" | "bytesFwd" | "bytesRev">, bytes: number, dir: "fwd" | "rev" | "both"): void {
@@ -409,21 +408,19 @@ async function resolveMinSharePct(q: FlowMapHopsQuery): Promise<number> {
}
}
// Closed minute buckets from every admitted export. Keep an hour of last-seen context for idle links.
async function readInterfaceTraffic(serverIds: number[], iface: string, q: FlowMapHopsQuery, end: number): Promise<FlowMapInterfaceTraffic[]> {
// Keep an hour of last-seen context for idle links.
async function readInterfaceTraffic(serverIds: number[], iface: string, q: FlowMapHopsQuery, start: string, end: number): Promise<FlowMapInterfaceTraffic[]> {
if (!serverIds.length) return []
const { minutes } = q
// Private site-to-site flows are traffic on the link even when the destination graph hides mesh paths.
const planes = q.excludeOverlay === false ? ["payload", "client_mesh", "overlay"] : ["payload", "client_mesh"]
const dimensions = planes.flatMap(plane => [FLOW_IFACE_RX_DIM + ":" + plane, FLOW_IFACE_TX_DIM + ":" + plane])
const start = new Date(end - minutes * 60000).toISOString()
const rows = await flowReadDbAll<{server_id: number; key: string; dim: string; bytes: string; packets: string; last_at: Date | string}>(`
SELECT server_id, key, dim, COALESCE(SUM(bytes) FILTER (WHERE bucket_at >= ?), 0) AS bytes,
COALESCE(SUM(packets) FILTER (WHERE bucket_at >= ?), 0) AS packets, MAX(bucket_at) AS last_at
FROM flow_minute_dims
WHERE server_id = ANY(?::bigint[]) AND bucket_at >= ? AND bucket_at < ? AND dim = ANY(?::text[])
GROUP BY server_id, key, dim
`, [start, start, serverIds, new Date(end - Math.max(minutes, 60) * 60000).toISOString(),
`, [start, start, serverIds, new Date(Math.min(Date.parse(start), end - 60 * 60_000)).toISOString(),
new Date(end).toISOString(), dimensions])
const totals = new Map<string, FlowMapInterfaceTraffic>()
for (const row of rows) {
@@ -481,10 +478,13 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
if (!scope) refreshFlowCatalogInBackground()
await authorize()
const limits = scope ? await readFlowMapSourceLimits() : undefined
const windowSec = Math.max(60, q.minutes * 60)
const now = Date.now()
const completeUntil = Math.floor(now / 60_000) * 60_000
const startMs = completeUntil - Math.max(1, q.minutes) * 60_000
const end = q.includeCurrentMinute ? now : completeUntil
const windowSec = (end - startMs) / 1000
await authorize()
const end = Math.floor(Date.now() / 60000) * 60000
const start = new Date(end - windowSec * 1000).toISOString()
const start = new Date(startMs).toISOString()
const raw = await listStoredFlowRows(start, q.serverId, { ...(scope ? { maxRows: scope.maxRows } : {}), untilIso: new Date(end - 1).toISOString() })
if (scope && raw.some(row => row.serverId !== q.serverId)) throw new Error("Строка карты вне выбранного сервера")
await authorize()
@@ -496,21 +496,24 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
const excludeOverlay = q.excludeOverlay !== false
await authorize()
const topo = await loadFlowTopology(scope?.serverIds, authorize)
let allow: Map<number, Set<string>> | null = null
if (q.userId) {
if (!scope) allow = await userIfaceAllow(q.userId)
else {
allow = new Map()
for (const binding of topo.clientByIface.values()) if (binding.userId === q.userId) {
const names = allow.get(binding.serverId) ?? new Set<string>(); names.add(binding.interfaceName); allow.set(binding.serverId, names)
}
if (!allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
const allow = q.userId ? new Map<number, Set<string>>() : null
if (allow) {
for (const binding of topo.clientByIface.values()) if (binding.userId === q.userId) {
const names = allow.get(binding.serverId) ?? new Set<string>()
names.add(binding.interfaceName)
allow.set(binding.serverId, names)
}
if (scope && !allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
}
function rowClient(r: (typeof raw)[number]) {
return resolveMapClient(topo, r.serverId, resolveIfaceName(r.serverId, r.inIface).name, resolveIfaceName(r.serverId, r.outIface).name)
}
const matches = (serverId: number, iface: string) =>
flowRowMatchesFilter({ serverId, inIface: iface }, resolveIfaceName(serverId, iface).name, q, allow)
const selected = raw.filter(r => matches(r.serverId, r.inIface) || matches(r.serverId, r.outIface))
const selected = raw.filter(r => (!q.userId || rowClient(r)?.userId === q.userId) &&
(matches(r.serverId, r.inIface) || matches(r.serverId, r.outIface)))
const { rows } = collapseGreEspRows(selected, r => {
if (ifaceFilter) {
const ingress = matches(r.serverId, r.inIface), egress = matches(r.serverId, r.outIface)
@@ -548,16 +551,14 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
}
await authorize()
const peers = await readMapGrePeers(working)
const observed = new Map<(typeof working)[number], { endpoints: ReturnType<typeof resolveFlowEndpoints>; exitId?: number; reverse: boolean }>()
const observed = new Map<(typeof working)[number], {
endpoints: ReturnType<typeof resolveFlowEndpoints>; exitId?: number; viaIface?: string; reverse: boolean
client: ReturnType<typeof rowClient>; nodeBytes: Map<number, number>
}>()
const nodeUsers = new Map<number, Map<string, ClientAcc>>()
const enIds = new Set(topo.enNodes.map((n) => n.id))
let totalBytes = 0
function rowClient(r: (typeof working)[number]) {
const inName = resolveIfaceName(r.serverId, r.inIface).name
const outName = resolveIfaceName(r.serverId, r.outIface).name
return resolveMapClient(topo, r.serverId, inName, outName)
}
for (const r of working) {
const inRes = resolveIfaceName(r.serverId, r.inIface)
const outRes = resolveIfaceName(r.serverId, r.outIface)
@@ -623,7 +624,14 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
const reverse = !!endpoints.internetPeer && (endpoints.internetPeer === endpoints.packetSrc || endpoints.internetPeer === r.natSrc)
const serviceSide = endpoints.internetPeer ? (reverse ? inId : outId) : peerId
const exitId = enIds.has(r.serverId) ? r.serverId : serviceSide ?? undefined
observed.set(r, { endpoints, exitId, reverse })
const serviceIface = reverse ? inName : outName
const otherIface = reverse ? outName : inName
const viaIface = exitId === undefined
? ifaceUsable(serviceIface) ? serviceIface : ifaceUsable(otherIface) ? otherIface : undefined
: undefined
const nodeBytes = new Map([[r.serverId, r.bytes]])
if (exitId !== undefined) nodeBytes.set(exitId, r.bytes)
observed.set(r, { endpoints, exitId, viaIface, reverse, client: resolveMapClient(topo, r.serverId, inName, outName), nodeBytes })
if (peerId && peerId !== r.serverId) {
const toId = String(peerId)
const dir = outId === peerId ? "fwd" : "rev"
@@ -662,31 +670,47 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
}
}
const payloadBytes = new Map<(typeof working)[number], number>()
const payloadRows = wantDedup
? dedupFlowRowsAcrossExporters(working, (a, b) => {
const aRouted = observed.get(a)?.exitId !== undefined
const bRouted = observed.get(b)?.exitId !== undefined
if (aRouted !== bRouted) return aRouted ? a : b
const aCli = Boolean(rowClient(a))
const bCli = Boolean(rowClient(b))
if (aCli !== bCli) return aCli ? a : b
return a.bytes >= b.bytes ? a : b
const observationA = observed.get(a)!
const observationB = observed.get(b)!
const aRouted = observationA.exitId !== undefined
const bRouted = observationB.exitId !== undefined
const aCli = Boolean(observationA.client)
const bCli = Boolean(observationB.client)
const attributed = aRouted !== bRouted ? (aRouted ? a : b)
: aCli !== bCli ? (aCli ? a : b)
: a.bytes >= b.bytes ? a : b
// Route/client evidence and the largest byte observation can come from different exporters.
payloadBytes.set(attributed, Math.max(payloadBytes.get(a) ?? a.bytes, b.bytes))
const clientA = observationA.client, clientB = observationB.client
const chosen = observed.get(attributed)!
chosen.client = clientA === null || clientB === null || (clientA && clientB && clientA.userId !== clientB.userId)
? null : clientA ?? clientB
for (const [id, bytes] of (attributed === a ? observationB : observationA).nodeBytes) {
chosen.nodeBytes.set(id, Math.max(chosen.nodeBytes.get(id) ?? 0, bytes))
}
return attributed
})
: working
for (const r of payloadRows) {
const inName = resolveIfaceName(r.serverId, r.inIface).name
const outName = resolveIfaceName(r.serverId, r.outIface).name
totalBytes += r.bytes
const { endpoints: ep, exitId, reverse } = observed.get(r)!
const bytes = payloadBytes.get(r) ?? r.bytes
totalBytes += bytes
const { endpoints: ep, exitId, viaIface, reverse, client, nodeBytes } = observed.get(r)!
for (const [id, observedBytes] of nodeBytes) {
const users = nodeUsers.get(id) ?? new Map<string, ClientAcc>()
bumpClient(users, observedBytes, client ?? null)
nodeUsers.set(id, users)
}
const dst = ep.internetPeer
const dstPort = ep.peerPort || r.dstPort
const srcPort = ep.otherPort || r.srcPort
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : ""
const client = resolveMapClient(topo, r.serverId, inName, outName)
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, proto: r.proto, dstPort, srcPort, fromBytes: new Map<string, FromAcc>() }
acc.bytes += r.bytes
if (exitId !== undefined) bumpFrom(acc, String(r.serverId), String(exitId), r.bytes, reverse, client)
acc.bytes += bytes
bumpFrom(acc, String(r.serverId), exitId === undefined ? "" : String(exitId), viaIface, bytes, reverse, client)
dstAcc.set(destKey, acc)
}
@@ -755,15 +779,19 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
if (scope && (!isDeepStrictEqual(topo, await loadFlowTopology(scope.serverIds, authorize)) || !isDeepStrictEqual(limits, await readFlowMapSourceLimits()))) throw new Error("Топология или пределы карты NetFlow изменились во время чтения")
await authorize()
// Whole-interface counters must never be exposed as per-user payload or added to totalBytes.
const interfaceTraffic = q.userId ? undefined : await readInterfaceTraffic(q.serverId ? [q.serverId] : [...catalog.byId.keys()], ifaceFilter, q, end)
const interfaceTraffic = q.userId ? undefined : await readInterfaceTraffic(q.serverId ? [q.serverId] : [...catalog.byId.keys()], ifaceFilter, q, start, end)
await authorize()
return {
...(interfaceTraffic ? { interfaceTraffic } : {}),
nodeUsers: Object.fromEntries([...nodeUsers].map(([id, users]) => [id, [...users].map(([clientId, { name, bytes }]) => (
{ clientId, clientName: name, bytes, bps: bytes * 8 / windowSec }
)).sort((a, b) => b.bytes - a.bytes)])),
hops: [...hops.values()]
.map((a) => toHop(a, windowSec))
.sort((a, b) => a.bytes === b.bytes ? 0 : b.bytes - a.bytes),
live: listener.bound,
rangeMinutes: q.minutes,
...(q.includeCurrentMinute ? { includesCurrentMinute: true as const } : {}),
windowSec,
totalBytes,
namedBytes,
+17 -3
View File
@@ -124,23 +124,37 @@ export async function loadFlowTopology(serverIds?: readonly number[], authorize:
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=u.id AND NOT(hidden.server_id=ANY(?::bigint[]))) LIMIT 1001
`, [serverIds, serverIds])
await authorize()
const binds = serverIds === undefined ? await flowReadDbAll<{userId:string;serverId:number;interfaceName:string}>('SELECT user_id AS "userId",server_id AS "serverId",interface_name AS "interfaceName" FROM user_interface_bindings') : await flowReadDbAll<{ userId: string; serverId: number; interfaceName: string }>(`
const binds = serverIds === undefined ? await flowReadDbAll<{userId:string;serverId:number;interfaceName:string;peerPublicKey?:string}>(
'SELECT user_id AS "userId",server_id AS "serverId",interface_name AS "interfaceName",peer_public_key AS "peerPublicKey" FROM user_interface_bindings',
) : await flowReadDbAll<{ userId: string; serverId: number; interfaceName: string; peerPublicKey?: string }>(`
SELECT b.user_id AS "userId",b.server_id AS "serverId",b.interface_name AS "interfaceName" FROM user_interface_bindings b
WHERE b.server_id=ANY(?::bigint[]) AND b.peer_public_key='' AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=b.user_id AND NOT(hidden.server_id=ANY(?::bigint[]))) ORDER BY b.id
WHERE b.server_id=ANY(?::bigint[]) AND b.peer_public_key=''
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=b.user_id AND NOT(hidden.server_id=ANY(?::bigint[])))
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings conflict WHERE conflict.server_id=b.server_id
AND conflict.interface_name=b.interface_name AND (conflict.peer_public_key<>'' OR conflict.user_id<>b.user_id))
ORDER BY b.id
LIMIT 1001
`, [serverIds, serverIds])
if (serverIds !== undefined && (binds.length > 1000 || users.length > 1000)) throw new Error("Превышен предел топологии NetFlow")
const loginById = new Map(users.map((u) => [u.id, u]))
const clientIfaces = new Map<number, Set<string>>()
const clientByIface = new Map<string, FlowClientBinding>()
const ambiguousIfaces = new Set<string>()
const allClientNames = new Set<string>()
for (const b of binds) {
const set = clientIfaces.get(b.serverId) ?? new Set<string>()
set.add(b.interfaceName)
clientIfaces.set(b.serverId, set)
allClientNames.add(b.interfaceName)
const key = ifaceKey(b.serverId, b.interfaceName)
const previous = clientByIface.get(key)
if (b.peerPublicKey || previous && previous.userId !== b.userId) {
ambiguousIfaces.add(key)
clientByIface.delete(key)
}
if (ambiguousIfaces.has(key)) continue
const user = loginById.get(b.userId)
clientByIface.set(ifaceKey(b.serverId, b.interfaceName), {
clientByIface.set(key, {
userId: b.userId,
login: user?.login || b.userId,
name: user?.name || user?.login || b.userId,
@@ -47,10 +47,18 @@ else {
assert.equal(sample.headers["cache-control"], "no-store")
assert.deepEqual(sample.json(), { rxMbps: 0, txMbps: 0, at: sample.json().at, timestampKind: "backend-receipt" })
assert.equal(nativeRequests, beforeSample + 1)
assert.equal((await app.inject(sampleUrl + "&ifaces=ether1,ether1")).statusCode, 400)
assert.equal((await app.inject(sampleUrl + "&ifaces=ether1,ether2&iface=ether1")).statusCode, 400)
assert.equal(nativeRequests, beforeSample + 1)
const batch = await app.inject(sampleUrl + "&ifaces=ether1,ether2")
assert.equal(batch.statusCode, 200)
assert.equal(batch.headers["cache-control"], "no-store")
assert.deepEqual(Object.keys(batch.json().interfaces), ["ether1", "ether2"])
assert.equal(nativeRequests, beforeSample + 2)
mode = "malformed"
assert.equal((await app.inject(sampleUrl + "&iface=ether1")).statusCode, 503)
mode = "zero"
cases += 3
cases += 6
let stream=await open(),event=await stream.next();assert.equal(event?.event,"sample");assert.equal(event?.data.rxMbps,0);assert.equal(event?.data.timestampKind,"backend-receipt");stream.close();cases++
for(const kind of ["empty","malformed","partial"]){mode=kind;two=kind==="partial";stream=await open();event=await stream.next();assert.equal(event?.event,"error");stream.close();cases++}
mode="fallback";two=true;stream=await open();event=await stream.next();assert.equal(event?.event,"sample");assert.equal(event?.data.rxMbps,0);stream.close();cases++
+15 -1
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict"
import { parseMonitorTraffic, rateBpsFromDelta, bpsToMbps } from "./traffic-rate.js"
import { readTrafficLiveSample, TrafficLiveSourceChanged } from "./traffic-live.js"
import { readTrafficLiveInterfaces, readTrafficLiveSample, TrafficLiveSourceChanged } from "./traffic-live.js"
import { MikrotikError, type MikrotikClient } from "./mikrotik.js"
const point=(name="ether1",rx:unknown="0",tx:unknown="0")=>({name,"rx-bits-per-second":rx,"tx-bits-per-second":tx})
for(const raw of [[],{},null,[null],[{...point(),"rx-bits-per-second":undefined}], [point("ether1","12bad")],[point("ether1",-1)], [point("ether1"),point("ether1")]]) {
@@ -34,4 +34,18 @@ const many={get:async()=>Array.from({length:10},(_,i)=>({name:`ether${i}`,runnin
}} as unknown as Pick<MikrotikClient,"get"|"post">
const bounded=await readTrafficLiveSample(many,undefined,{names:[],joinedFailed:false},new AbortController().signal,async()=>{})
assert.equal(bounded.rxMbps,0);assert.equal(maximum,4)
const batch = (testClient = cast) =>
readTrafficLiveInterfaces(testClient, ["ether1", "ether2"], new AbortController().signal, async () => {})
const joined = { ...cast, post: async () => [point("ether2", "0", "80000000"), point("ether1", "1300000", "0")] } as typeof cast
const measurements = await batch(joined)
assert.equal(measurements.ether1.rxMbps, 1.3)
assert.equal(measurements.ether2.txMbps, 80)
assert.equal(measurements.ether1.at, measurements.ether2.at)
mode = "partial"
assert.deepEqual(Object.keys(await batch()), ["ether1"])
mode = "fallback"
assert.deepEqual(Object.keys(await batch()), ["ether1", "ether2"])
mode = "auth"
await assert.rejects(batch(), /401/)
console.log("traffic live completeness/fallback/auth/source/abort/positive-small-rate tests ok")
+77 -48
View File
@@ -1,14 +1,15 @@
import { MikrotikError, type MikrotikClient } from "./mikrotik.js"
import { isLoopbackName, parseMonitorTraffic, type MonitorLiveSample } from "./traffic-rate.js"
import { isLoopbackName, parseMonitorTraffic, parseMonitorTrafficInterfaces, type MonitorLiveSample } from "./traffic-rate.js"
const TIMEOUT_MS = 4000
export class TrafficLiveSourceChanged extends Error {}
export interface TrafficLiveCache { names: string[]; joinedFailed: boolean }
type Client = Pick<MikrotikClient, "get" | "post">
type Monitor = (names: string) => Promise<unknown>
/** Never emit a partial sum, and check the source before every new native request. */
export async function readTrafficLiveSample(client: Client, onlyInterface: string | undefined,
cache: TrafficLiveCache, signal: AbortSignal, assertSource: () => Promise<void>): Promise<MonitorLiveSample> {
/** Check the source before every new native request. */
async function withTrafficMonitor<T>(client: Client, signal: AbortSignal, assertSource: () => Promise<void>,
read: (monitor: Monitor, ensure: () => Promise<void>) => Promise<T>): Promise<T> {
const parentSignal = signal, wave = new AbortController()
const onAbort = () => wave.abort(parentSignal.reason)
parentSignal.addEventListener("abort", onAbort, { once: true })
@@ -16,52 +17,12 @@ export async function readTrafficLiveSample(client: Client, onlyInterface: strin
const timeout = setTimeout(() => wave.abort(new Error("Не успели получить полный live-срез за 8 секунд. Выберите отдельный интерфейс")), 8000)
signal = wave.signal
try {
const ensure = async () => { signal.throwIfAborted(); await assertSource(); signal.throwIfAborted() }
const monitor = async (name: string) => {
await ensure()
return client.post<unknown>("/interface/monitor-traffic", { interface: name, once: "" }, TIMEOUT_MS, signal)
}
if (onlyInterface) {
const raw = await monitor(onlyInterface)
await ensure()
return parseMonitorTraffic(raw, { onlyInterface })
}
await ensure()
const raw = await client.get<unknown>("/interface", TIMEOUT_MS)
if (!Array.isArray(raw)) throw new Error("Не получен каталог интерфейсов live")
const names: string[] = []
const flag = (value: unknown) => {
if (value === true || value === "true" || value === "yes") return true
if (value === false || value === "false" || value === "no") return false
throw new Error("Неизвестное состояние интерфейса live")
}
for (const row of raw) {
if (!row || typeof row !== "object" || Array.isArray(row) || typeof row.name !== "string" || !row.name.trim()) throw new Error("Некорректный каталог интерфейсов live")
if (flag(row.running) && !flag(row.disabled) && !isLoopbackName(row.name)) names.push(row.name)
}
if (!names.length || new Set(names).size !== names.length) throw new Error("Нет достоверного набора активных интерфейсов live")
if ([...names].sort().join("\0") !== [...cache.names].sort().join("\0")) cache.joinedFailed = false
cache.names = names
if (!cache.joinedFailed) {
try {
const result = await monitor(names.join(","))
const ensure = async () => { signal.throwIfAborted(); await assertSource(); signal.throwIfAborted() }
const monitor = async (name: string) => {
await ensure()
return parseMonitorTraffic(result, { expectedInterfaces: names })
} catch (error) {
// Unsupported joined command may fall back; auth/transport/invalid payload cannot become partial zero.
if (!(error instanceof MikrotikError) || error.statusCode !== 400 || names.length < 2) throw error
cache.joinedFailed = true
return client.post<unknown>("/interface/monitor-traffic", { interface: name, once: "" }, TIMEOUT_MS, signal)
}
}
const results: MonitorLiveSample[] = []
for (let i = 0; i < names.length; i += 4) {
results.push(...await Promise.all(names.slice(i, i + 4).map(async name =>
parseMonitorTraffic(await monitor(name), { onlyInterface: name }))))
}
await ensure()
const rxMbps = results.reduce((sum, r) => sum + r.rxMbps, 0), txMbps = results.reduce((sum, r) => sum + r.txMbps, 0)
if (![rxMbps, txMbps].every(n => Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER / 1_000_000)) throw new Error("Суммарная live-скорость вне допустимого диапазона")
return { rxMbps, txMbps, at: new Date().toISOString(), timestampKind: "backend-receipt" }
return await read(monitor, ensure)
} catch (error) {
if (signal.aborted && !parentSignal.aborted && signal.reason instanceof Error) throw signal.reason
throw error
@@ -71,3 +32,71 @@ export async function readTrafficLiveSample(client: Client, onlyInterface: strin
wave.abort()
}
}
export function readTrafficLiveInterfaces(client: Client, names: readonly string[], signal: AbortSignal, assertSource: () => Promise<void>) {
return withTrafficMonitor(client, signal, assertSource, async (monitor, ensure) => {
let raw: unknown
try {
raw = await monitor(names.join(","))
} catch (error) {
if (!(error instanceof MikrotikError) || error.statusCode !== 400 || names.length < 2) throw error
const samples = []
for (let offset = 0; offset < names.length; offset += 4) {
const reads = await Promise.allSettled(names.slice(offset, offset + 4).map(async name =>
[name, parseMonitorTraffic(await monitor(name), { onlyInterface: name })] as const))
for (const read of reads) if (read.status === "fulfilled") samples.push(read.value)
}
await ensure()
return Object.fromEntries(samples)
}
await ensure()
return parseMonitorTrafficInterfaces(raw, names)
})
}
export function readTrafficLiveSample(client: Client, onlyInterface: string | undefined,
cache: TrafficLiveCache, signal: AbortSignal, assertSource: () => Promise<void>): Promise<MonitorLiveSample> {
return withTrafficMonitor(client, signal, assertSource, async (monitor, ensure) => {
if (onlyInterface) {
const raw = await monitor(onlyInterface)
await ensure()
return parseMonitorTraffic(raw, { onlyInterface })
}
await ensure()
const raw = await client.get<unknown>("/interface", TIMEOUT_MS)
if (!Array.isArray(raw)) throw new Error("Не получен каталог интерфейсов live")
const names: string[] = []
const flag = (value: unknown) => {
if (value === true || value === "true" || value === "yes") return true
if (value === false || value === "false" || value === "no") return false
throw new Error("Неизвестное состояние интерфейса live")
}
for (const row of raw) {
if (!row || typeof row !== "object" || Array.isArray(row) || typeof row.name !== "string" || !row.name.trim()) throw new Error("Некорректный каталог интерфейсов live")
if (flag(row.running) && !flag(row.disabled) && !isLoopbackName(row.name)) names.push(row.name)
}
if (!names.length || new Set(names).size !== names.length) throw new Error("Нет достоверного набора активных интерфейсов live")
if ([...names].sort().join("\0") !== [...cache.names].sort().join("\0")) cache.joinedFailed = false
cache.names = names
if (!cache.joinedFailed) {
try {
const result = await monitor(names.join(","))
await ensure()
return parseMonitorTraffic(result, { expectedInterfaces: names })
} catch (error) {
// Unsupported joined command may fall back; auth/transport/invalid payload cannot become partial zero.
if (!(error instanceof MikrotikError) || error.statusCode !== 400 || names.length < 2) throw error
cache.joinedFailed = true
}
}
const results: MonitorLiveSample[] = []
for (let i = 0; i < names.length; i += 4) {
results.push(...await Promise.all(names.slice(i, i + 4).map(async name =>
parseMonitorTraffic(await monitor(name), { onlyInterface: name }))))
}
await ensure()
const rxMbps = results.reduce((sum, r) => sum + r.rxMbps, 0), txMbps = results.reduce((sum, r) => sum + r.txMbps, 0)
if (![rxMbps, txMbps].every(n => Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER / 1_000_000)) throw new Error("Суммарная live-скорость вне допустимого диапазона")
return { rxMbps, txMbps, at: new Date().toISOString(), timestampKind: "backend-receipt" }
})
}
+30 -21
View File
@@ -360,14 +360,11 @@ export function mergeBuiltTraffic(parts: BuiltTrafficSeries[]): BuiltTrafficSeri
} } : acc,waves)
}
export function parseMonitorTraffic(
raw: unknown,
opts?: { onlyInterface?: string; expectedInterfaces?: readonly string[] },
): MonitorLiveSample {
type MonitorTrafficSelection = { onlyInterface?: string; expectedInterfaces?: readonly string[]; allowMissing?: boolean }
function monitorTrafficRates(raw: unknown, opts?: MonitorTrafficSelection) {
const items = Array.isArray(raw) ? raw : raw != null ? [raw] : []
let rxBps = 0
let txBps = 0
const seen = new Set<string>()
const samples = new Map<string, { rxBps: number; txBps: number }>()
const expected = opts?.expectedInterfaces ? new Set(opts.expectedInterfaces) : null
const rate = (raw: unknown) => {
if (typeof raw !== "number" && (typeof raw !== "string" || !/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(raw.trim()))) throw new Error("Некорректная скорость monitor-traffic")
@@ -382,21 +379,33 @@ export function parseMonitorTraffic(
if (typeof name !== "string" || !name.trim()) throw new Error("Не указан интерфейс monitor-traffic")
if (opts?.onlyInterface) {
if (name !== opts.onlyInterface) throw new Error("Ответ monitor-traffic относится к другому интерфейсу")
} else if (isLoopbackName(name)) {
} else if (isLoopbackName(name) && !expected?.has(name)) {
continue
}
if (seen.has(name) || expected && !expected.has(name)) throw new Error("Некорректный набор интерфейсов monitor-traffic")
seen.add(name)
rxBps += rate(rec["rx-bits-per-second"])
txBps += rate(rec["tx-bits-per-second"])
}
if (!seen.size || expected && (expected.size !== opts!.expectedInterfaces!.length ||
[...expected].some(name => !seen.has(name)))) throw new Error("Не получены все live-измерения интерфейсов")
if (![rxBps, txBps].every(n => Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER)) throw new Error("Суммарная live-скорость вне допустимого диапазона")
return {
rxMbps: rxBps / 1_000_000,
txMbps: txBps / 1_000_000,
at: new Date().toISOString(),
timestampKind: "backend-receipt",
if (samples.has(name) || expected && !expected.has(name)) throw new Error("Некорректный набор интерфейсов monitor-traffic")
samples.set(name, {
rxBps: rate(rec["rx-bits-per-second"]),
txBps: rate(rec["tx-bits-per-second"]),
})
}
if (!opts?.allowMissing && (!samples.size || expected && (expected.size !== opts!.expectedInterfaces!.length ||
samples.size !== expected.size))) throw new Error("Не получены все live-измерения интерфейсов")
return samples
}
export function parseMonitorTrafficInterfaces(raw: unknown, expectedInterfaces: readonly string[]): Record<string, MonitorLiveSample> {
const at = new Date().toISOString()
return Object.fromEntries([...monitorTrafficRates(raw, { expectedInterfaces, allowMissing: true })].map(([name, sample]) =>
[name, { rxMbps: sample.rxBps / 1_000_000, txMbps: sample.txBps / 1_000_000, at, timestampKind: "backend-receipt" }]))
}
export function parseMonitorTraffic(
raw: unknown,
opts?: { onlyInterface?: string; expectedInterfaces?: readonly string[] },
): MonitorLiveSample {
const samples = [...monitorTrafficRates(raw, opts).values()]
const rxBps = samples.reduce((sum, row) => sum + row.rxBps, 0)
const txBps = samples.reduce((sum, row) => sum + row.txBps, 0)
if (![rxBps, txBps].every(n => Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER)) throw new Error("Суммарная live-скорость вне допустимого диапазона")
return { rxMbps: rxBps / 1_000_000, txMbps: txBps / 1_000_000, at: new Date().toISOString(), timestampKind: "backend-receipt" }
}
+21 -81
View File
@@ -1,7 +1,7 @@
"use client"
import * as React from "react"
import { NavMain, type NavGroup } from "@/components/nav-main"
import { NavMain, type NavGroup, type NavItem } from "@/components/nav-main"
import { AppSwitcher } from "@/components/app-switcher"
import { NavUser } from "@/components/nav-user"
import {
@@ -12,103 +12,43 @@ import {
} from "@/components/ui/sidebar"
import { navigationGroups } from "@/lib/navigation"
import { useDataSource } from "@/lib/data-source"
import { can,ensureAuthConfig } from "@/lib/auth"
import { useEvoBGP } from "@/lib/evobgp-context"
import {getSidebarCounts,getSidebarGreCount} from "@/shared/api/sidebar-counts"
import {
formatSidebarBadgeCount,
mockSidebarBadgesByUrl,
type SidebarCountsDto,
} from "@/lib/sidebar-badges"
import { pingProbes, servers } from "@/lib/data"
type LiveSidebarCounts = Partial<SidebarCountsDto> & {
greTunnels?: number
certificates?: number
wireguard?: number
ipsec?: number
users?: number
bgpSessions?: number
vxlan?: number
containers?: number
/**
* Точки проблем у разделов. В демо — из моков; живой источник проблем по разделам API пока не отдаёт,
* поэтому в live-режиме точек нет (неизвестное не выдаём за «всё в норме» и не рисуем ложные сбои).
*/
function demoProblems(): Record<string, NavItem["problem"]> {
const offline = servers.filter((s) => s.enabled && s.status === "offline").length
const degraded = servers.filter((s) => s.enabled && s.status === "degraded").length
const down = pingProbes.filter((p) => p.enabled && p.status === "down").length
const warn = pingProbes.filter((p) => p.enabled && p.status === "warn").length
return {
"/servers": offline ? { tone: "er", label: `Не в сети: ${offline}` } : degraded ? { tone: "wn", label: `С ухудшением: ${degraded}` } : undefined,
"/uptime": down ? { tone: "er", label: `Проверок с ошибкой: ${down}` } : warn ? { tone: "wn", label: `Проверок с предупреждением: ${warn}` } : undefined,
}
}
/** Боковое меню общего макета v2 и EvoBGP: переключатель приложений, поиск ⌘K, закреплённые, группы, профиль. */
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
const { mode, backendUrl, prefsHydrated } = useDataSource()
const evo = useEvoBGP()
const [mounted, setMounted] = React.useState(false)
const [snapshot, setSnapshot] = React.useState<{source:string;counts:LiveSidebarCounts}|null>(null)
const source=JSON.stringify([mode,backendUrl]),liveCounts=snapshot?.source===source?snapshot.counts:null
const countsAllowed=can("mm:dashboard:read"),greAllowed=can("mm:filters:read")
const mockBadges = React.useMemo(() => mockSidebarBadgesByUrl(), [])
React.useEffect(() => {
let cancelled=false
void ensureAuthConfig().then(()=>{if(!cancelled)setMounted(true)})
return()=>{cancelled=true}
}, [])
React.useEffect(() => {
if(!mounted||!prefsHydrated||mode!=="live")return
let cancelled=false,revision=0,controller:AbortController|null=null
const load=async()=>{
controller?.abort();controller=new AbortController();const request=++revision,signal=AbortSignal.any([controller.signal,AbortSignal.timeout(30_000)])
const publish=(counts:LiveSidebarCounts)=>{if(cancelled||request!==revision)return;setSnapshot(previous=>({source,counts:{...(previous?.source===source?previous.counts:{}),...counts}}))}
await Promise.allSettled([
can("mm:dashboard:read")?getSidebarCounts(backendUrl,signal).then(counts=>{if(can("mm:dashboard:read"))publish(counts)}):Promise.resolve(),
can("mm:filters:read")?getSidebarGreCount(backendUrl,signal).then(greTunnels=>{if(can("mm:filters:read"))publish({greTunnels})}):Promise.resolve(),
])
}
void load();const timer=window.setInterval(load,120_000)
return()=>{cancelled=true;revision++;controller?.abort();window.clearInterval(timer)}
},[mounted,mode,backendUrl,prefsHydrated,source,countsAllowed,greAllowed])
const { mode, prefsHydrated } = useDataSource()
const navGroups = React.useMemo((): NavGroup[] => {
function badgeFor(url: string): string | undefined {
if (mode !== "live") return mockBadges[url]
if (url === "/domains" || url === "/ip-ranges" || url === "/asns") {
if (!evo.settingsLoaded || !evo.enabled || !can("mm:settings:admin")) return undefined
if (!evo.snapshot) return undefined
if (url === "/domains") return formatSidebarBadgeCount(evo.snapshot.domains.length)
if (url === "/ip-ranges") return formatSidebarBadgeCount(evo.snapshot.ipRanges.length)
return formatSidebarBadgeCount(evo.snapshot.asns.length)
}
if (!liveCounts||(!countsAllowed&&url!=="/gre")) return undefined
const permission=({"/servers":"mm:servers:read","/users":"mm:users:read","/filters":"mm:filters:read","/uptime":"mm:uptime:read","/gre":"mm:filters:read","/certificates":"mm:certificates:read","/wireguard":"mm:network:read","/ipsec":"mm:network:read","/bgp":"mm:bgp:read","/vxlan":"mm:network:read","/containers":"mm:dashboard:read"} as Record<string,string>)[url]
if(permission&&!can(permission))return undefined
const format=(value:number|undefined)=>value===undefined?undefined:formatSidebarBadgeCount(value)
if (url === "/servers") return format(liveCounts.servers)
if (url === "/users") return format(liveCounts.users )
if (url === "/filters") return format(liveCounts.filterRules)
if (url === "/uptime") return format(liveCounts.monitoringItems)
if (url === "/gre") return format(liveCounts.greTunnels )
if (url === "/certificates") return format(liveCounts.certificates )
if (url === "/wireguard") return format(liveCounts.wireguard )
if (url === "/ipsec") return format(liveCounts.ipsec )
if (url === "/bgp") return format(liveCounts.bgpSessions )
if (url === "/vxlan") return format(liveCounts.vxlan )
if (url === "/containers") return format(liveCounts.containers )
return undefined
}
const problems = prefsHydrated && mode !== "live" ? demoProblems() : {}
return navigationGroups.map((g) => ({
label: g.label,
items: g.items.map((it) => ({
title: it.title,
url: it.url,
icon: React.createElement(it.icon, { "aria-hidden": true }),
badge: mounted ? badgeFor(it.url) : undefined,
problem: problems[it.url],
})),
}))
}, [mounted, mode, liveCounts, countsAllowed, mockBadges, evo.settingsLoaded, evo.enabled, evo.snapshot])
}, [mode, prefsHydrated])
return (
<Sidebar collapsible="icon" {...props}>
<SidebarHeader>
<SidebarHeader className="pb-1.5">
<AppSwitcher />
</SidebarHeader>
<SidebarContent>
+11 -1
View File
@@ -5,6 +5,7 @@ import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
@@ -17,6 +18,7 @@ import {
import {
APP_SWITCHER_ICONS,
CURRENT_APP_ID,
authPortalBaseUrl,
getCurrentApp,
} from "@/lib/app-switcher-config"
import { useAppSwitcherConfig } from "@/hooks/use-app-switcher"
@@ -26,6 +28,8 @@ export function AppSwitcher() {
const { isMobile } = useSidebar()
const { config, isLoading } = useAppSwitcherConfig()
const current = getCurrentApp(config)
const portalBase = authPortalBaseUrl()
const portalAppsUrl = portalBase ? `${portalBase}/admin/apps` : null
const CurrentIcon = APP_SWITCHER_ICONS[current.icon] ?? APP_SWITCHER_ICONS.server
return (
@@ -34,7 +38,7 @@ export function AppSwitcher() {
<DropdownMenu>
<DropdownMenuTrigger
render={
<SidebarMenuButton size="lg" className="aria-expanded:bg-muted" />
<SidebarMenuButton size="lg" aria-label={`Переключатель приложений: ${current.name}`} className="aria-expanded:bg-muted" />
}
>
<div
@@ -89,6 +93,12 @@ export function AppSwitcher() {
</DropdownMenuItem>
)
})}
{portalAppsUrl ? (
<>
<DropdownMenuSeparator />
<DropdownMenuItem render={<a href={portalAppsUrl} />}>Настроить на портале</DropdownMenuItem>
</>
) : null}
</DropdownMenuContent>
</DropdownMenu>
</SidebarMenuItem>
-96
View File
@@ -1,96 +0,0 @@
"use client"
import { LayoutGridIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
APP_SWITCHER_ICONS,
CURRENT_APP_ID,
authPortalBaseUrl,
} from "@/lib/app-switcher-config"
import { useAppSwitcherConfig } from "@/hooks/use-app-switcher"
/** Header apps grid — app-shell-12. @see https://reui.io/preview/base/app-shell-12 */
export function AppsMenu() {
const { config, isLoading } = useAppSwitcherConfig()
const portalBase = authPortalBaseUrl()
const portalAppsUrl = portalBase ? `${portalBase}/admin/apps` : null
return (
<DropdownMenu>
<DropdownMenuTrigger
render={
<Button variant="ghost" size="icon" aria-label="Приложения" />
}
>
<LayoutGridIcon className="size-4.5" aria-hidden="true" />
</DropdownMenuTrigger>
<DropdownMenuContent
side="bottom"
align="end"
sideOffset={8}
className="w-72"
>
<DropdownMenuGroup>
<DropdownMenuLabel>
{isLoading ? "Загрузка…" : config.menuLabel}
</DropdownMenuLabel>
<div className="grid grid-cols-3 gap-1 p-1">
{config.apps.map((app) => {
const Icon = APP_SWITCHER_ICONS[app.icon] ?? APP_SWITCHER_ICONS.server
const isCurrent = app.id === CURRENT_APP_ID
if (isCurrent) {
return (
<DropdownMenuItem
key={app.id}
disabled
className="h-auto flex-col gap-1.5 py-3 text-center [&_svg]:size-5"
>
<span className="text-muted-foreground">
<Icon aria-hidden="true" />
</span>
<span className="text-xs font-medium">{app.name}</span>
</DropdownMenuItem>
)
}
return (
<DropdownMenuItem
key={app.id}
render={<a href={app.url} />}
className="h-auto flex-col gap-1.5 py-3 text-center [&_svg]:size-5"
>
<span className="text-muted-foreground">
<Icon aria-hidden="true" />
</span>
<span className="text-xs font-medium">{app.name}</span>
</DropdownMenuItem>
)
})}
</div>
{portalAppsUrl ? (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
render={<a href={portalAppsUrl} />}
className="justify-center text-sm font-medium"
>
Настроить на портале
</DropdownMenuItem>
</>
) : null}
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
)
}
+18 -1
View File
@@ -6,6 +6,13 @@ import { navigationGroups } from "@/lib/navigation"
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command"
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog"
const OPEN_EVENT = "mm:open-command-palette"
/** Открыть палитру из кнопки «Поиск и команды» (сайдбар) или поиска в шапке на телефоне. */
export function openCommandPalette() {
window.dispatchEvent(new Event(OPEN_EVENT))
}
/** Keyboard search from the App Shell 12 composition, using installed Base UI primitives. */
export function CommandPalette() {
const [open, setOpen] = useState(false)
@@ -26,8 +33,18 @@ export function CommandPalette() {
setOpen(!open)
}
}
function onOpen() {
if (open) return
returnFocusRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null
setQuery("")
setOpen(true)
}
window.addEventListener("keydown", onKey)
return () => window.removeEventListener("keydown", onKey)
window.addEventListener(OPEN_EVENT, onOpen)
return () => {
window.removeEventListener("keydown", onKey)
window.removeEventListener(OPEN_EVENT, onOpen)
}
}, [open])
useEffect(() => {
@@ -1,39 +0,0 @@
"use client"
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
import { Button } from "@/components/ui/button"
import { DASHBOARD_SOURCES, type DashboardSource, type DashboardSources } from "@/lib/dashboard-source-state"
export function DashboardDataStatus({ sources, refreshing, onRefresh }: {
sources: DashboardSources
refreshing: boolean
onRefresh: () => void
}) {
const failed = Object.values(sources).filter(source => source.error)
const summary = failed.length ? `Не обновлены источники: ${failed.length}` : "Состояние источников"
return <div className="flex flex-col gap-2">
{failed.length > 0 && <Alert variant="destructive">
<AlertTitle>{summary}</AlertTitle>
<AlertDescription>Последние полученные данные сохранены. Если источник ещё не загрузился, его показатели неизвестны.</AlertDescription>
</Alert>}
<div className="flex flex-wrap items-start justify-between gap-2">
<details className="min-w-0 text-sm" open={failed.length > 0 || undefined}>
<summary className="cursor-pointer">Источники и время получения</summary>
<ul className="mt-2 flex flex-col gap-1 text-xs">
{(Object.keys(DASHBOARD_SOURCES) as DashboardSource[]).map(key => {
const source = sources[key]
return <li key={key} data-source={key} className={`break-words ${source?.error ? "text-destructive" : "text-muted-foreground"}`}>
{DASHBOARD_SOURCES[key]}: {source?.error ? `ошибка обновления — ${source.error}. ` : ""}
{source?.receivedAt != null ? <>Получено <time dateTime={new Date(source.receivedAt).toISOString()}>{new Date(source.receivedAt).toLocaleString("ru-RU")}</time>{source.error ? " · данные могут быть устаревшими" : ""}</> : "Успешных загрузок ещё нет"}
{source?.sampledAt && Number.isFinite(Date.parse(source.sampledAt)) && <> · замер <time dateTime={source.sampledAt}>{new Date(source.sampledAt).toLocaleString("ru-RU")}</time></>}
</li>
})}
</ul>
</details>
<div className="flex items-center gap-2">
<span role="status" className="text-xs text-muted-foreground">{refreshing ? "Обновление данных…" : "Обновление завершено"}</span>
<Button type="button" size="sm" variant="outline" onClick={onRefresh} disabled={refreshing}>Обновить данные</Button>
</div>
</div>
</div>
}
@@ -1,90 +0,0 @@
"use client"
import Link from "next/link"
import {
Timeline,
TimelineContent,
TimelineDate,
TimelineHeader,
TimelineIndicator,
TimelineItem,
TimelineSeparator,
TimelineTitle,
} from "@/components/reui/timeline"
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
import { cn } from "@/lib/utils"
import type { EventItem } from "@mmapp/contracts/events"
function formatEventAge(iso: string): string {
const ts = Date.parse(iso)
if (!Number.isFinite(ts)) return "—"
const diffMs = Math.max(0, Date.now() - ts)
const minutes = Math.floor(diffMs / 60_000)
if (minutes < 1) return "сейчас"
if (minutes < 60) return `${minutes}м`
const hours = Math.floor(minutes / 60)
if (hours < 24) return `${hours}ч`
const days = Math.floor(hours / 24)
return `${days}д`
}
const LEVEL_DOT: Record<EventItem["level"], string> = {
critical: "border-destructive bg-destructive/20 group-data-completed/timeline-item:border-destructive",
warning: "border-warning bg-warning/20 group-data-completed/timeline-item:border-warning",
info: "border-info bg-info/20 group-data-completed/timeline-item:border-info",
}
/**
* Compact activity timeline.
* Preview: https://reui.io/preview/base/timeline-3
* Docs: https://reui.io/docs/components/base/timeline
*/
export function DashboardEventsTimeline({
events,
loading,
error,
}: {
events: EventItem[]
loading?: boolean
error?: string | null
}) {
if (loading && events.length === 0) {
return <p className="text-muted-foreground px-5 py-6 text-sm">Загрузка событий…</p>
}
if (error && events.length === 0) {
return (
<div className="px-5 py-4">
<Alert variant="destructive">
<AlertTitle>События недоступны</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
</div>
)
}
if (events.length === 0) {
return (
<p className="text-muted-foreground px-5 py-6 text-sm">
Событий пока нет.{" "}
<Link href="/alerts" className="underline underline-offset-2">
Оповещения
</Link>
</p>
)
}
return (
<Timeline defaultValue={events.length} className="px-5 py-4">
{events.map((event, index) => (
<TimelineItem key={event.id} step={index + 1}>
<TimelineHeader>
<TimelineSeparator />
<TimelineDate>{formatEventAge(event.createdAt)}</TimelineDate>
<TimelineTitle className="text-[13px] leading-tight">{event.title}</TimelineTitle>
<TimelineIndicator className={cn(LEVEL_DOT[event.level])} />
</TimelineHeader>
<TimelineContent className="text-xs leading-snug">{event.message}</TimelineContent>
</TimelineItem>
))}
</Timeline>
)
}
@@ -0,0 +1,245 @@
"use client"
import { useState, type ReactNode } from "react"
import Link from "next/link"
import { SearchIcon, TableIcon } from "lucide-react"
import { Button, buttonVariants } from "@/components/ui/button"
import { FramePanel } from "@/components/reui/frame"
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
import { SectionFrame, ToneBadge, ToneDot, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
import { cn } from "@/lib/utils"
import type { EventItem } from "@mmapp/contracts/events"
export type HealthFactor = { label: string; value: string; ratio: number | null }
function factorTone(ratio: number): Tone {
return ratio >= 0.85 ? "ok" : ratio >= 0.6 ? "wn" : "er"
}
/**
* Здоровье сети (блок health макета v3): кольцо сводного индекса и факторы.
* Индекс — среднее долей исправных по факторам с известными данными.
*/
export function DashboardHealth({ factors }: { factors: HealthFactor[] }) {
const known = factors.filter((f): f is HealthFactor & { ratio: number } => f.ratio != null)
const score = known.length ? Math.round((known.reduce((sum, f) => sum + f.ratio, 0) / known.length) * 100) : null
const tone: Tone = score == null ? "mu" : factorTone(score / 100)
const badge = score == null ? "Нет данных" : tone === "ok" ? "В норме" : tone === "wn" ? "С замечаниями" : "Требует внимания"
const circumference = 2 * Math.PI * 52
return (
<SectionFrame
title="Здоровье сети"
description="Сводный индекс — среднее долей исправных: пробы, задержка, свежесть данных, серверы и туннели"
actions={<ToneBadge tone={tone} size="lg">{badge}</ToneBadge>}
panelClassName="grid grid-cols-1 items-center gap-6 p-5 md:grid-cols-[200px_minmax(0,1fr)]"
>
<div className="flex flex-col items-center gap-1.5">
<div className="relative size-[150px]">
<svg viewBox="0 0 140 140" width="150" height="150" role="img" aria-label={score == null ? "Индекс здоровья сети неизвестен" : `Индекс здоровья сети ${score} из 100`}>
<circle cx="70" cy="70" r="52" fill="none" stroke="var(--muted)" strokeWidth="12" />
{score != null ? (
<circle cx="70" cy="70" r="52" fill="none" stroke={TONE_COLOR[tone]} strokeWidth="12" strokeLinecap="round" strokeDasharray={`${(circumference * score) / 100} ${circumference}`} transform="rotate(-90 70 70)" />
) : null}
</svg>
<div className="absolute inset-0 flex flex-col items-center justify-center">
<b className="text-[34px] leading-none font-semibold tabular-nums">{score ?? "—"}</b>
<span className="text-muted-foreground mt-0.5 text-xs">из 100</span>
</div>
</div>
<span className="text-muted-foreground text-xs">{known.length} из {factors.length} факторов с данными</span>
</div>
<div className="flex flex-col gap-2.5">
{factors.map((factor) => (
<div key={factor.label} className="grid grid-cols-[130px_minmax(0,1fr)_auto] items-center gap-2.5 text-[13px]">
<span>{factor.label}</span>
<span aria-hidden="true" className="bg-muted h-1.5 overflow-hidden rounded-[3px]">
{factor.ratio != null ? (
<i className="block h-full rounded-[3px]" style={{ width: `${Math.round(factor.ratio * 100)}%`, background: TONE_COLOR[factorTone(factor.ratio)] }} />
) : null}
</span>
<span className="min-w-11 text-right font-mono">{factor.value}</span>
</div>
))}
</div>
</SectionFrame>
)
}
const LEVEL: Record<EventItem["level"], { tone: Tone; label: string }> = {
critical: { tone: "er", label: "Сбой" },
warning: { tone: "wn", label: "Внимание" },
info: { tone: "in", label: "Инфо" },
}
function hhmm(iso: string) {
const ts = Date.parse(iso)
return Number.isFinite(ts) ? new Date(ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }) : "—"
}
/** Лента инцидентов (блок timeline макета v3) из последних событий системы. */
export function DashboardIncidents({ events, loading, error }: { events: EventItem[]; loading?: boolean; error?: string | null }) {
let body: ReactNode
if (loading && events.length === 0) body = <p className="text-muted-foreground px-4 py-6 text-sm">Загрузка событий…</p>
else if (error && events.length === 0) {
body = (
<div className="p-4">
<Alert variant="destructive">
<AlertTitle>События недоступны</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
</div>
)
} else if (events.length === 0) body = <p className="text-muted-foreground px-4 py-6 text-sm">Событий пока нет.</p>
else {
body = (
<ol className="py-1.5">
{events.map((event, index) => {
const level = LEVEL[event.level] ?? LEVEL.info
return (
<li key={event.id} className="grid grid-cols-[62px_16px_minmax(0,1fr)] items-start gap-2.5 px-4 py-2 text-[13px]">
<time dateTime={event.createdAt} className="text-muted-foreground pt-px font-mono text-xs">{hhmm(event.createdAt)}</time>
<span aria-hidden="true" className="flex h-full flex-col items-center">
<i className="mt-1 size-[9px] rounded-full" style={{ background: TONE_COLOR[level.tone] }} />
{index < events.length - 1 ? <u className="bg-border mt-0.5 min-h-[18px] w-px flex-1" /> : null}
</span>
<span className="min-w-0">
<ToneBadge tone={level.tone} mark={false} className="mr-2">{level.label}</ToneBadge>
<b className="font-medium">{event.title}</b>
{event.message ? <span className="text-muted-foreground mt-0.5 block text-xs">{event.message}</span> : null}
</span>
</li>
)
})}
</ol>
)
}
return (
<SectionFrame
title="Лента инцидентов"
description="Последние события · причины и связанные объекты"
actions={<Link href="/alerts" className={buttonVariants({ variant: "outline", size: "sm" })}>Все события</Link>}
>
{body}
</SectionFrame>
)
}
export type AttentionGridRow = {
id: string
title: string
kind: "Сервер" | "Туннель" | "Проверка"
hint: string
href: string
tone: Tone
/** Подтверждённая проблема; false — состояние неизвестно. */
confirmed: boolean
}
const PAGE = 50
/**
* Требует внимания (блок grid макета v3): вкладки, поиск и строки-ссылки на объект.
* Пустые категории перечислены в подвале, чтобы «нет проблем» не путалось с «нет данных».
*/
export function DashboardAttentionGrid({ rows, emptyNotes }: { rows: AttentionGridRow[]; emptyNotes: string[] }) {
const [view, setView] = useState<"all" | "confirmed">("all")
const [query, setQuery] = useState("")
const [visible, setVisible] = useState(PAGE)
const confirmed = rows.filter((row) => row.confirmed)
const q = query.trim().toLowerCase()
const shown = (view === "all" ? rows : confirmed).filter((row) => !q || `${row.title} ${row.kind} ${row.hint}`.toLowerCase().includes(q))
const tabs = [
{ id: "all" as const, label: "Все", count: rows.length },
{ id: "confirmed" as const, label: "С проблемами", count: confirmed.length },
]
return (
<SectionFrame title="Требует внимания" description="Серверы · Туннели · Проверки" icon={<TableIcon />} bare>
<div role="tablist" aria-label="Виды" className="flex flex-wrap gap-x-1 border-b px-2.5">
{tabs.map((tab) => (
<button
key={tab.id}
type="button"
role="tab"
aria-selected={view === tab.id}
onClick={() => { setView(tab.id); setVisible(PAGE) }}
className={cn(
"text-muted-foreground hover:text-foreground -mb-px inline-flex h-[38px] items-center gap-1.5 border-b-2 border-transparent px-2 text-[13px] font-medium transition-colors",
view === tab.id && "border-foreground text-foreground",
)}
>
{tab.label}{" "}
<em className={cn("bg-muted text-muted-foreground inline-flex h-5 min-w-5 items-center justify-center rounded-md px-1.5 font-mono text-xs not-italic", view === tab.id && "bg-foreground/12 text-foreground")}>{tab.count}</em>
</button>
))}
</div>
<div className="flex flex-wrap items-center gap-2 px-2.5 py-2">
<label className="border-input bg-input/30 text-muted-foreground focus-within:border-ring flex h-8 min-w-[180px] flex-[0_1_320px] items-center gap-2 rounded-lg border px-2.5 transition-colors">
<SearchIcon aria-hidden="true" className="size-3.5 shrink-0" />
<input value={query} onChange={(event) => { setQuery(event.target.value); setVisible(PAGE) }} placeholder="Поиск по имени и полям…" aria-label="Поиск в таблице" className="text-foreground placeholder:text-muted-foreground min-w-0 flex-1 bg-transparent text-[13px] outline-none" />
</label>
{q ? <span className="text-muted-foreground ml-auto text-xs tabular-nums">{shown.length} из {rows.length}</span> : null}
</div>
<FramePanel className="max-h-[560px] overflow-auto p-0">
<div className="min-w-[640px]">
<div aria-hidden="true" className="bg-muted/55 text-muted-foreground sticky top-0 z-[1] grid h-10 grid-cols-[minmax(200px,2fr)_112px_minmax(120px,1fr)_minmax(160px,2fr)] items-center gap-x-3 border-b px-3.5 text-xs font-medium">
<span>Объект</span>
<span>Статус</span>
<span>Тип</span>
<span>Сообщение</span>
</div>
{shown.length === 0 ? (
<p className="text-muted-foreground px-4 py-8 text-center text-sm">{rows.length === 0 ? "Проблем не обнаружено" : "Ничего не найдено"}</p>
) : (
shown.slice(0, visible).map((row) => (
<Link
key={`${row.kind}:${row.id}`}
href={row.href}
className="hover:bg-muted/45 focus-visible:ring-ring grid min-h-[52px] grid-cols-[minmax(200px,2fr)_112px_minmax(120px,1fr)_minmax(160px,2fr)] items-center gap-x-3 border-b px-3.5 transition-colors outline-none last:border-b-0 focus-visible:ring-2 focus-visible:ring-inset"
>
<span className="flex min-w-0 items-center gap-2 py-2">
<ToneDot tone={row.tone} />
<span className="min-w-0">
<span className="block truncate font-mono text-[13px] font-medium">{row.title}</span>
<span className="text-muted-foreground block font-mono text-xs">{row.kind}</span>
</span>
</span>
<span><ToneBadge tone={row.tone}>{row.tone === "er" ? "Сбой" : row.confirmed ? "Внимание" : "Неизвестно"}</ToneBadge></span>
<span className="font-mono text-[12.5px]">{row.kind}</span>
<span className="min-w-0 font-mono text-[12.5px] wrap-anywhere">{row.hint}</span>
</Link>
))
)}
</div>
{shown.length > visible ? (
<div className="flex justify-center border-t p-2">
<Button type="button" variant="ghost" size="sm" onClick={() => setVisible((count) => count + PAGE)}>Показать ещё {Math.min(PAGE, shown.length - visible)}</Button>
</div>
) : null}
</FramePanel>
{emptyNotes.length ? (
<div className="text-muted-foreground flex flex-wrap gap-x-3 gap-y-1 px-4 py-2 text-xs">
{emptyNotes.map((note) => <span key={note}>{note}</span>)}
</div>
) : null}
</SectionFrame>
)
}
export type QuickLink = { id: string; title: string; description: string; href: string }
/** Быстрые переходы (блок cards макета v3). */
export function DashboardQuickLinks({ links }: { links: QuickLink[] }) {
return (
<SectionFrame title="Быстрые переходы" description="Другие разделы управления сетью" panelClassName="grid grid-cols-[repeat(auto-fit,minmax(260px,1fr))] gap-3 p-3">
{links.map((link) => (
<Link key={link.id} href={link.href} className="bg-muted/25 hover:bg-muted/50 focus-visible:ring-ring rounded-lg border p-3.5 transition-colors outline-none focus-visible:ring-2">
<div className="flex items-center justify-between gap-2">
<b className="text-sm font-semibold">{link.title}</b>
<ToneBadge tone="in" mark={false}>Открыть</ToneBadge>
</div>
<div className="text-muted-foreground mt-1.5 text-[13px]">{link.description}</div>
</Link>
))}
</SectionFrame>
)
}
@@ -0,0 +1,149 @@
"use client"
import type { ReactNode } from "react"
import { ActivityIcon, BellIcon, BoxIcon, ChartColumnIcon, DatabaseIcon, GlobeIcon, LinkIcon, LockIcon, RouteIcon, ServerIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
import { FramePanel } from "@/components/reui/frame"
import { IconTile } from "@/components/reui/icon-tile"
import { SectionFrame, ToneBadge, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
import { DASHBOARD_SOURCES, type DashboardSource, type DashboardSources } from "@/lib/dashboard-source-state"
import { cn } from "@/lib/utils"
const SOURCE_ICON: Record<DashboardSource, ReactNode> = {
servers: <ServerIcon />, probes: <ActivityIcon />, bgp: <RouteIcon />, gre: <LinkIcon />, wg: <LockIcon />,
vxlan: <BoxIcon />, traffic: <ChartColumnIcon />, internetPath: <GlobeIcon />, events: <BellIcon />,
}
export type SourceRow = {
key: DashboardSource
name: string
tone: Tone
label: string
receivedAt: number | null
sampledAt: string | null
error: string | null
}
/** Состояние каждого источника дашборда: обновлён, устарел (ошибка после успеха), нет загрузок или ожидание. */
export function dashboardSourceRows(sources: DashboardSources): SourceRow[] {
return (Object.keys(DASHBOARD_SOURCES) as DashboardSource[]).map((key) => {
const source = sources[key]
const receivedAt = source?.receivedAt ?? null
const error = source?.error ?? null
const sampledAt = source?.sampledAt && Number.isFinite(Date.parse(source.sampledAt)) ? source.sampledAt : null
const tone: Tone = error ? (receivedAt != null ? "wn" : "er") : receivedAt != null ? "ok" : "mu"
const label = error ? (receivedAt != null ? "Устарел" : "Нет загрузок") : receivedAt != null ? "Обновлён" : "Ожидание"
return { key, name: DASHBOARD_SOURCES[key], tone, label, receivedAt, sampledAt, error }
})
}
function Clock({ at }: { at: number | string | null }) {
if (at == null) return <b className="text-foreground font-mono font-medium">—</b>
const date = new Date(at)
return (
<time dateTime={typeof at === "string" ? at : date.toISOString()} className="text-foreground font-mono font-medium">
{date.toLocaleTimeString("ru-RU")}
</time>
)
}
export function sourceErrorText(row: SourceRow) {
if (!row.error) return null
return row.receivedAt != null
? `Ошибка обновления — ${row.error} · данные могут быть устаревшими`
: `Ошибка обновления — ${row.error} · успешных загрузок ещё нет`
}
/**
* Сводка источников дашборда (блок sources макета v3): итог слева, плитки источников справа.
* @see https://reui.io/docs/components/base/frame
*/
export function DashboardSourcesSummary({ rows, refreshing, onRefresh }: {
rows: SourceRow[]
refreshing: boolean
onRefresh: () => void
}) {
const count = (tone: Tone) => rows.filter((row) => row.tone === tone).length
const ok = count("ok")
const segments = ([
["ok", "Обновлены", count("ok")],
["wn", "С ошибкой", count("wn")],
["er", "Нет загрузок", count("er")],
["mu", "Ожидание", count("mu")],
] as const).filter(([, , n]) => n > 0)
const sub = [
count("wn") ? `${count("wn")} с ошибкой — показаны прошлые данные` : null,
count("er") ? `${count("er")} без успешных загрузок` : null,
count("mu") ? `${count("mu")} ожидают первой загрузки` : null,
].filter(Boolean).join(" · ") || "Все источники получены"
return (
<SectionFrame
title="Сводка источников"
description="Время получения и замера по каждому источнику дашборда · подробности — на вкладке «Источники и время получения»"
icon={<DatabaseIcon />}
bare
actions={
<>
<span role="status" className="text-muted-foreground text-xs">{refreshing ? "Обновление данных…" : "Обновление завершено"}</span>
<Button type="button" size="sm" variant="outline" onClick={onRefresh} disabled={refreshing} aria-label="Обновить данные источников">Обновить данные</Button>
</>
}
>
<FramePanel className="grid grid-cols-1 p-0 min-[1100px]:grid-cols-[260px_minmax(0,1fr)]">
<div className="flex min-w-0 flex-col gap-2 border-b px-[18px] py-4 min-[1100px]:border-r min-[1100px]:border-b-0">
<div className="text-muted-foreground text-[0.8rem]">Источники обновлены</div>
<div className="flex items-baseline gap-0.5">
<span className="text-[30px] leading-tight font-semibold tracking-tight tabular-nums">{ok}</span>
<span className="text-muted-foreground ml-0.5 text-base">/ {rows.length}</span>
</div>
<div className="text-muted-foreground text-xs">{sub}</div>
<div role="img" aria-label={segments.map(([, label, n]) => `${label}: ${n}`).join(", ")} className="mt-1.5 flex h-2 gap-[3px]">
{segments.map(([tone, label, n]) => (
<i key={label} className="block h-full min-w-1.5 rounded-full" style={{ flex: n, background: TONE_COLOR[tone] }} />
))}
</div>
<div className="text-muted-foreground grid grid-cols-2 gap-x-3.5 gap-y-1.5 text-xs">
{segments.map(([tone, label, n]) => (
<span key={label} className="flex min-w-0 items-center gap-1.5">
<i aria-hidden="true" className="size-2 shrink-0 rounded-full" style={{ background: TONE_COLOR[tone] }} />
{label}
<b className="text-foreground ml-auto font-medium tabular-nums">{n}</b>
</span>
))}
</div>
<p className="text-muted-foreground mt-auto border-t border-dashed pt-2.5 text-xs leading-snug">
Последние полученные данные сохранены. Если источник ещё не загрузился, его показатели неизвестны.
</p>
</div>
<ul className="grid grid-cols-2 min-[1100px]:grid-cols-3">
{rows.map((row) => {
const error = sourceErrorText(row)
return (
<li
key={row.key}
data-source={row.key}
className="flex min-w-0 flex-col gap-2 border-r border-b px-3.5 py-3 max-[1099px]:even:border-r-0 min-[1100px]:[&:nth-child(3n)]:border-r-0 min-[1100px]:[&:nth-last-child(-n+3)]:border-b-0"
>
<div className="flex min-w-0 items-center gap-2.5">
<IconTile variant="outline" size="sm" aria-hidden="true" style={{ color: row.tone === "ok" || row.tone === "mu" ? "var(--muted-foreground)" : TONE_COLOR[row.tone] }}>
{SOURCE_ICON[row.key]}
</IconTile>
<span className="min-w-0 flex-1 truncate text-sm font-medium">{row.name}</span>
<ToneBadge tone={row.tone} size="default">{row.label}</ToneBadge>
</div>
<div className="text-muted-foreground flex flex-wrap gap-x-3.5 gap-y-1 text-xs">
<span>Получено <Clock at={row.receivedAt} /></span>
<span>Замер <Clock at={row.sampledAt} /></span>
</div>
{error ? (
<p className={cn("text-xs leading-snug", row.tone === "wn" ? "text-warning-foreground" : "text-destructive-foreground")}>{error}</p>
) : null}
</li>
)
})}
</ul>
</FramePanel>
</SectionFrame>
)
}
-401
View File
@@ -1,401 +0,0 @@
"use client"
import { useMemo, useState } from "react"
import { Flag } from "@/components/flag"
import { cn } from "@/lib/utils"
import type { InternetPathViewModel } from "@/lib/dashboard-internet-path"
import { Maximize2Icon, ZoomInIcon, ZoomOutIcon } from "lucide-react"
type Pt = { x: number; y: number }
type ServerKind = "home-router" | "jump-host" | "exit-node"
const W = 1060
const H = 420
const ZOOM_MIN = 0.2
const ZOOM_MAX = 6
const STATUS_STYLE = {
unknown: { fill: "var(--muted)", stroke: "var(--muted-foreground)", glow: "transparent" },
online: { fill: "#0f2d1f", stroke: "#4ade80", glow: "rgba(74,222,128,0.15)" },
degraded: { fill: "#2d1e06", stroke: "#fbbf24", glow: "rgba(251,191,36,0.15)" },
offline: { fill: "#2d0f0f", stroke: "#f87171", glow: "transparent" },
}
const TYPE_STYLE: Record<ServerKind, { label: string; fill: string; r: number }> = {
"home-router": { label: "HR", fill: "#16a34a", r: 40 },
"jump-host": { label: "JH", fill: "#7c3aed", r: 34 },
"exit-node": { label: "EN", fill: "#0369a1", r: 30 },
}
const WAN_COLORS = ["#0ea5e9", "#f97316", "#a855f7", "#ec4899", "#14b8a6"]
function pingColor(ms: number | null) {
if (ms == null) return "#f87171"
if (ms < 15) return "#4ade80"
if (ms < 50) return "#fbbf24"
return "#fb923c"
}
function edgeBadgePosition(x1: number, y1: number, x2: number, y2: number, t: number, normalPx: number): { mx: number; my: number } {
const px = x1 + (x2 - x1) * t
const py = y1 + (y2 - y1) * t
const dx = x2 - x1
const dy = y2 - y1
const len = Math.hypot(dx, dy) || 1
const nx = -dy / len
const ny = dx / len
return { mx: px + nx * normalPx, my: py + ny * normalPx }
}
function ZoomControls({ zoom, onZoomIn, onZoomOut, onFit }: {
zoom: number
onZoomIn: () => void
onZoomOut: () => void
onFit: () => void
}) {
return (
<div className="absolute bottom-4 left-1/2 -translate-x-1/2 z-20 flex items-center gap-0 rounded-xl border border-white/10 bg-black/75 backdrop-blur-md shadow-xl overflow-hidden">
<button onClick={onZoomOut} className="px-3 py-2 text-white/60 hover:text-white hover:bg-white/5 transition-colors">
<ZoomOutIcon className="size-3.5" />
</button>
<span className="px-3 py-2 text-xs font-mono text-white/70 min-w-[52px] text-center border-x border-white/10 select-none">
{Math.round(zoom * 100)}%
</span>
<button onClick={onZoomIn} className="px-3 py-2 text-white/60 hover:text-white hover:bg-white/5 transition-colors">
<ZoomInIcon className="size-3.5" />
</button>
<div className="w-px h-5 bg-white/10" />
<button onClick={onFit} className="px-3 py-2 text-white/60 hover:text-white hover:bg-white/5 transition-colors">
<Maximize2Icon className="size-3.5" />
</button>
</div>
)
}
function PingBadge({
mx,
my,
ping,
dl,
ul,
color,
monitored,
}: {
mx: number
my: number
ping: number | null
dl: number | null
ul: number | null
color: string
monitored?: boolean
}) {
const hasSpeed = dl != null || ul != null
const dlText = dl != null ? Math.round(dl) : "—"
const ulText = ul != null ? Math.round(ul) : "—"
return (
<g transform={`translate(${mx},${my})`}>
<rect x="-34" y={-20} width="68" height={hasSpeed ? 42 : 24} rx="4" fill="#060d1a" stroke={color} strokeWidth="0.7" opacity="0.92" />
<text textAnchor="middle" y={hasSpeed ? "-5" : "4"} fontSize="8.5" fontWeight="600" fill={color} fontFamily="ui-monospace,monospace">
{ping == null ? "—" : `${ping} мс`}
</text>
{hasSpeed && (
<text textAnchor="middle" y="8" fontSize="7" fill="#64748b" fontFamily="ui-monospace,monospace">
{`↓${dlText} ↑${ulText}`}
</text>
)}
{monitored && (
<text textAnchor="middle" y={hasSpeed ? "17" : "14"} fontSize="6" fill="#38bdf8" fontFamily="ui-monospace,monospace">
mon
</text>
)}
</g>
)
}
function ServerNode({
pos,
type,
name,
site,
country,
status,
selected,
onClick,
}: {
pos: Pt
type: ServerKind
name: string
site: string
country: string
status: "online" | "offline" | "degraded" | "unknown"
selected: boolean
onClick: () => void
}) {
const ss = STATUS_STYLE[status]
const ts = TYPE_STYLE[type]
return (
<g transform={`translate(${pos.x},${pos.y})`} style={{ cursor: "pointer" }} onClick={onClick}>
{status === "online" && (
<circle r={ts.r + 14} fill={ss.glow} opacity="0.7">
<animate attributeName="r" values={`${ts.r + 10};${ts.r + 18};${ts.r + 10}`} dur="3s" repeatCount="indefinite" />
<animate attributeName="opacity" values="0.8;0.15;0.8" dur="3s" repeatCount="indefinite" />
</circle>
)}
{selected && (
<circle r={ts.r + 10} fill="none" stroke="rgba(255,255,255,0.45)" strokeWidth="1.5" strokeDasharray="4 3" />
)}
<circle r={ts.r} fill={ss.fill} stroke={ss.stroke} strokeWidth={selected ? 2.5 : 1.8} />
<g transform={`translate(${ts.r - 10},-${ts.r - 10})`}>
<circle r="10" fill={ts.fill} />
<text textAnchor="middle" y="4" fontSize="6.5" fontWeight="bold" fill="#fff">{ts.label}</text>
</g>
<foreignObject x={-110} y={-22} width={220} height={28} style={{ overflow: "visible", pointerEvents: "none" }}>
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 6, width: "100%", height: "100%", fontFamily: "ui-monospace, monospace" }} {...({ xmlns: "http://www.w3.org/1999/xhtml" } as Record<string, string>)}>
<span style={{ flexShrink: 0, lineHeight: 0 }}>
<Flag code={country || "UN"} size={16} />
</span>
<span style={{ maxWidth: 170, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontWeight: 700, fontSize: 11, color: "#f1f5f9", lineHeight: 1.25 }}>
{site || name}
</span>
</div>
</foreignObject>
<text textAnchor="middle" y={ts.r + 18} fontSize="8.5" fill="#94a3b8" fontFamily="ui-monospace,monospace">
{name}
</text>
</g>
)
}
export function InternetPathMapCanvas({ model }: { model: InternetPathViewModel | null }) {
const [zoom, setZoom] = useState(1)
const [pan, setPan] = useState({ x: 0, y: 0 })
const [isDragging, setIsDragging] = useState(false)
const [dragStart, setDragStart] = useState<{ x: number; y: number } | null>(null)
const [selectedNode, setSelectedNode] = useState<"home" | "jh" | "en" | "wan" | null>("home")
const mapData = useMemo(() => {
if (!model) return null
const hop = model.currentHop ?? model.primaryHop ?? (
model.activeWanUplink && model.fallbackJumpHost && model.fallbackExitNode
? {
home: model.homeRouter,
wan: model.activeWanUplink,
jumpHost: model.fallbackJumpHost,
exitNode: model.fallbackExitNode,
wanJhMetrics: {
pingMs: null,
dlMbps: null,
ulMbps: null,
fromMonitoring: false,
},
jhExitMetrics: {
pingMs: null,
dlMbps: null,
ulMbps: null,
fromMonitoring: false,
},
}
: null
)
if (!hop) return null
const axisY = 220
const homePos = { x: 180, y: axisY }
const wanPos = { x: 400, y: axisY }
const jhPos = { x: 660, y: axisY }
const enPos = { x: 900, y: axisY }
const directPos = { x: 900, y: axisY + 110 }
const pathDiff =
model.primaryPath &&
model.currentPath &&
(model.primaryPath.wanId !== model.currentPath.wanId || model.primaryPath.jhId !== model.currentPath.jhId || model.primaryPath.exitId !== model.currentPath.exitId)
return { hop, homePos, wanPos, jhPos, enPos, directPos, pathDiff, directWan: model.directWan }
}, [model])
function onWheel(e: React.WheelEvent<SVGSVGElement>) {
e.preventDefault()
const rect = e.currentTarget.getBoundingClientRect()
const px = e.clientX - rect.left
const py = e.clientY - rect.top
const worldX = (px - pan.x) / zoom
const worldY = (py - pan.y) / zoom
const factor = e.deltaY < 0 ? 1.1 : 1 / 1.1
const next = Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, zoom * factor))
setZoom(next)
setPan({ x: px - worldX * next, y: py - worldY * next })
}
return (
<div className="flex flex-col gap-3">
{!model && (
<div className="h-[240px] rounded-md border border-dashed border-border grid place-items-center text-sm text-muted-foreground">
Недостаточно данных для построения маршрута
</div>
)}
{model && mapData && (
<div
className="relative rounded-lg border border-[#1f2a3d] bg-gradient-to-b from-[#0a1424] to-[#060d17] overflow-hidden overscroll-contain"
onWheelCapture={(e) => {
// Когда курсор над картой, колесо управляет только картой (без прокрутки страницы).
e.preventDefault()
e.stopPropagation()
}}
>
<svg
viewBox={`0 0 ${W} ${H}`}
className={cn("w-full h-[320px] select-none", isDragging ? "cursor-grabbing" : "cursor-grab")}
onMouseDown={(e) => {
setIsDragging(true)
setDragStart({ x: e.clientX - pan.x, y: e.clientY - pan.y })
}}
onMouseMove={(e) => {
if (!isDragging || !dragStart) return
setPan({ x: e.clientX - dragStart.x, y: e.clientY - dragStart.y })
}}
onMouseUp={() => { setIsDragging(false); setDragStart(null) }}
onMouseLeave={() => { setIsDragging(false); setDragStart(null) }}
onWheel={onWheel}
>
<g transform={`translate(${pan.x} ${pan.y}) scale(${zoom})`}>
<line x1={mapData.homePos.x} y1={mapData.homePos.y} x2={mapData.wanPos.x} y2={mapData.wanPos.y} stroke={WAN_COLORS[0]} strokeWidth="2.2" opacity="0.75" />
<line
x1={mapData.wanPos.x}
y1={mapData.wanPos.y}
x2={mapData.jhPos.x}
y2={mapData.jhPos.y}
stroke={mapData.pathDiff ? "#fbbf24" : "#4ade80"}
strokeWidth={3.2}
/>
<line
x1={mapData.jhPos.x}
y1={mapData.jhPos.y}
x2={mapData.enPos.x}
y2={mapData.enPos.y}
stroke={mapData.pathDiff ? "#fbbf24" : "#4ade80"}
strokeWidth={3.2}
/>
{mapData.directWan.enabled && (
<line
x1={mapData.wanPos.x}
y1={mapData.wanPos.y}
x2={mapData.directPos.x}
y2={mapData.directPos.y}
stroke="#38bdf8"
strokeWidth="2.4"
opacity="0.9"
/>
)}
<g transform={`translate(${mapData.wanPos.x},${mapData.wanPos.y})`} onClick={() => setSelectedNode("wan")} style={{ cursor: "pointer" }}>
<circle r={24} fill={`${WAN_COLORS[0]}1a`} stroke={WAN_COLORS[0]} strokeWidth="2" />
<path d="M -5 2 Q 0 -5 5 2" fill="none" stroke={WAN_COLORS[0]} strokeWidth="1.5" strokeLinecap="round" />
<path d="M -8 5 Q 0 -10 8 5" fill="none" stroke={WAN_COLORS[0]} strokeWidth="1" strokeLinecap="round" opacity="0.6" />
<circle cx="0" cy="4" r="2" fill={WAN_COLORS[0]} />
<text textAnchor="middle" y="36" fontSize="8" fontWeight="700" fill={WAN_COLORS[0]} fontFamily="ui-monospace,monospace">
{mapData.hop.wan.name}
</text>
</g>
<ServerNode
pos={mapData.homePos}
type="home-router"
name={mapData.hop.home.name}
site={mapData.hop.home.site}
country={mapData.hop.home.country}
status={mapData.hop.home.status}
selected={selectedNode === "home"}
onClick={() => setSelectedNode("home")}
/>
{mapData.directWan.enabled && (
<g transform={`translate(${mapData.directPos.x},${mapData.directPos.y})`}>
<circle r={22} fill="#08243a" stroke="#38bdf8" strokeWidth="1.8" />
<text textAnchor="middle" y="4" fontSize="10" fontWeight="700" fill="#38bdf8">NET</text>
<text textAnchor="middle" y="34" fontSize="8" fill="#7dd3fc" fontFamily="ui-monospace,monospace">
{mapData.directWan.provider ?? "Direct WAN"}
</text>
</g>
)}
<ServerNode
pos={mapData.jhPos}
type="jump-host"
name={mapData.hop.jumpHost.name}
site={mapData.hop.jumpHost.site}
country={mapData.hop.jumpHost.country}
status={mapData.hop.jumpHost.status}
selected={selectedNode === "jh"}
onClick={() => setSelectedNode("jh")}
/>
<ServerNode
pos={mapData.enPos}
type="exit-node"
name={mapData.hop.exitNode.name}
site={mapData.hop.exitNode.site}
country={mapData.hop.exitNode.country}
status={mapData.hop.exitNode.status}
selected={selectedNode === "en"}
onClick={() => setSelectedNode("en")}
/>
<PingBadge
{...edgeBadgePosition(mapData.wanPos.x, mapData.wanPos.y, mapData.jhPos.x, mapData.jhPos.y, 0.52, -24)}
ping={mapData.hop.wanJhMetrics.pingMs}
dl={mapData.hop.wanJhMetrics.dlMbps}
ul={mapData.hop.wanJhMetrics.ulMbps}
color={pingColor(mapData.hop.wanJhMetrics.pingMs)}
monitored={mapData.hop.wanJhMetrics.fromMonitoring}
/>
<PingBadge
{...edgeBadgePosition(mapData.jhPos.x, mapData.jhPos.y, mapData.enPos.x, mapData.enPos.y, 0.5, -24)}
ping={mapData.hop.jhExitMetrics.pingMs}
dl={mapData.hop.jhExitMetrics.dlMbps}
ul={mapData.hop.jhExitMetrics.ulMbps}
color={pingColor(mapData.hop.jhExitMetrics.pingMs)}
monitored={mapData.hop.jhExitMetrics.fromMonitoring}
/>
{mapData.directWan.enabled && (
<PingBadge
{...edgeBadgePosition(mapData.wanPos.x, mapData.wanPos.y, mapData.directPos.x, mapData.directPos.y, 0.55, -22)}
ping={null}
dl={null}
ul={null}
color="#38bdf8"
monitored={false}
/>
)}
</g>
</svg>
<ZoomControls
zoom={zoom}
onZoomOut={() => setZoom((z) => Math.max(ZOOM_MIN, z * 0.9))}
onZoomIn={() => setZoom((z) => Math.min(ZOOM_MAX, z * 1.1))}
onFit={() => { setZoom(1); setPan({ x: 0, y: 0 }) }}
/>
</div>
)}
{model && !mapData && (
<div className="h-[240px] rounded-md border border-dashed border-border grid place-items-center text-sm text-muted-foreground">
Нет полного набора узлов для визуализации пути
</div>
)}
{model && (
<div className="mt-3 grid grid-cols-1 md:grid-cols-2 gap-2 text-xs">
<div className={cn("rounded-md border p-2", model.pathState === "failover" ? "border-amber-500/40 bg-amber-500/5" : "border-emerald-500/40 bg-emerald-500/5")}>
<p className="font-medium">Рекомендация оптимизатора</p>
<p className="text-muted-foreground mt-1">{model.primaryPath?.reason ?? "Не определен"}</p>
</div>
<div className={cn("rounded-md border p-2", model.pathState === "failover" ? "border-amber-500/40 bg-amber-500/5" : "border-emerald-500/40 bg-emerald-500/5")}>
<p className="font-medium">Наблюдаемый default route</p>
<p className="text-muted-foreground mt-1">{model.currentPath?.reason ?? "Не определен"}</p>
</div>
{model.directWan.enabled && (
<div className="rounded-md border p-2 border-sky-500/40 bg-sky-500/5 md:col-span-2">
<p className="font-medium">Direct WAN path</p>
<p className="text-muted-foreground mt-1">
{`gateway: ${model.directWan.gateway ?? "—"} · iface: ${model.directWan.iface ?? "—"} · dhcp ip: ${model.directWan.leasedIp ?? "—"} · isp: ${model.directWan.provider ?? "—"}`}
</p>
</div>
)}
</div>
)}
</div>
)
}
+72 -74
View File
@@ -1,35 +1,62 @@
"use client"
import { useEffect, useState } from "react"
import Link from "next/link"
import { ChevronDownIcon } from "lucide-react"
import { OpsPanel } from "@/components/ops-panel"
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
import { buttonVariants } from "@/components/ui/button"
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible"
import { cn } from "@/lib/utils"
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
import { SectionFrame, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
import type { InternetPathViewModel } from "@/lib/dashboard-internet-path"
import { InternetPathMapCanvas } from "@/components/dashboard/internet-path-map"
import type { ServerStatus } from "@/lib/data"
import { InternetPathSummary } from "@/components/dashboard/internet-path-summary"
const PATH_MAP_OPEN_LS = "mm:dashboard-path-map-open"
const STATUS_TONE: Record<ServerStatus, Tone> = { online: "ok", degraded: "wn", offline: "er", unknown: "mu" }
const X = [13, 37, 62, 86]
function readMapOpen(): boolean {
if (typeof window === "undefined") return true
try {
const raw = localStorage.getItem(PATH_MAP_OPEN_LS)
if (raw === "0") return false
if (raw === "1") return true
} catch {
/* ignore */
type TopoNode = { label: string; sub: string; tone: Tone }
/** Схема пути Home → WAN → JH → Exit (блок topo макета v3); участок WAN→JH — модель связности, пунктиром. */
function InternetPathTopo({ model }: { model: InternetPathViewModel | null }) {
const hop = model?.currentHop ?? model?.primaryHop ?? null
const wan = hop?.wan ?? model?.activeWanUplink ?? null
const jh = hop?.jumpHost ?? model?.fallbackJumpHost ?? null
const exit = hop?.exitNode ?? model?.fallbackExitNode ?? null
if (!model || !jh || !exit) {
return <p className="text-muted-foreground flex h-[300px] items-center justify-center text-sm">Нет полного набора узлов для схемы пути</p>
}
return true
const nodes: TopoNode[] = [
{ label: model.homeRouter.name, sub: "Home Router", tone: STATUS_TONE[model.homeRouter.status] },
{ label: wan ? wan.isp || wan.name : "WAN", sub: wan ? `WAN-аплинк ${wan.iface}` : "WAN не определён", tone: wan ? "ok" : "mu" },
{ label: jh.name, sub: "JumpHost", tone: STATUS_TONE[jh.status] },
{ label: exit.name, sub: `Exit Node${exit.country ? ` · ${exit.country}` : ""}`, tone: STATUS_TONE[exit.status] },
]
const links: Array<{ label: string | null; dashed: boolean }> = [
{ label: null, dashed: false },
{ label: hop?.wanJhMetrics.pingMs != null ? String(hop.wanJhMetrics.pingMs) : null, dashed: true },
{ label: hop?.jhExitMetrics.pingMs != null ? String(hop.jhExitMetrics.pingMs) : null, dashed: false },
]
return (
<div className="relative h-[300px]" role="img" aria-label={`Путь: ${nodes.map((n) => n.label).join(" → ")}`}>
<svg className="absolute inset-0 size-full" aria-hidden="true">
{links.map((link, i) => (
<line key={i} x1={`${X[i]}%`} y1="50%" x2={`${X[i + 1]}%`} y2="50%" stroke={link.dashed ? "var(--warning)" : "var(--success)"} strokeWidth="1.5" strokeDasharray={link.dashed ? "5 5" : undefined} />
))}
</svg>
{links.map((link, i) => link.label ? (
<span key={i} className="bg-card absolute -translate-1/2 rounded-[5px] border px-2 py-0.5 font-mono text-xs" style={{ left: `${(X[i] + X[i + 1]) / 2}%`, top: "50%" }}>{link.label}</span>
) : null)}
{nodes.map((node, i) => (
<div key={i} className="bg-card absolute flex min-w-[132px] -translate-1/2 items-center gap-2 rounded-[9px] border-[1.5px] py-1.5 pr-3 pl-2.5" style={{ left: `${X[i]}%`, top: "50%", borderColor: TONE_COLOR[node.tone] }}>
<span className="size-2 shrink-0 rounded-full" style={{ background: TONE_COLOR[node.tone] }} />
<span className="min-w-0">
<b className="block text-[13px] font-semibold whitespace-nowrap">{node.label}</b>
<span className="text-muted-foreground block text-xs whitespace-nowrap">{node.sub}</span>
</span>
</div>
))}
</div>
)
}
/** Internet path и Сводка маршрута — два блока макета v3 (topo и kv). */
export function InternetPathPanel({
model,
loading,
@@ -39,59 +66,30 @@ export function InternetPathPanel({
loading?: boolean
error?: string | null
}) {
const [open, setOpen] = useState(true)
const [hydrated, setHydrated] = useState(false)
useEffect(() => {
queueMicrotask(() => {
setOpen(readMapOpen())
setHydrated(true)
})
}, [])
function handleOpenChange(next: boolean) {
setOpen(next)
try {
localStorage.setItem(PATH_MAP_OPEN_LS, next ? "1" : "0")
} catch {
/* ignore */
}
}
return (
<OpsPanel
title="Internet path"
description="Home → WAN → JH → Exit"
headerRight={
<Link href="/network-map" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 text-xs")}>
Карта сети →
</Link>
}
contentClassName="flex flex-col gap-3 px-5 pb-4"
>
{error ? (
<Alert variant="destructive">
<AlertTitle>Не удалось загрузить путь</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
) : null}
{loading && !model ? (
<div className="h-20 animate-pulse rounded-md bg-muted/40" />
) : (
<InternetPathSummary model={model} />
)}
<Collapsible open={hydrated ? open : true} onOpenChange={handleOpenChange}>
<CollapsibleTrigger
className={cn(buttonVariants({ variant: "ghost", size: "sm" }), "h-7 w-fit gap-1.5 text-xs")}
>
<ChevronDownIcon className={cn("size-3.5 transition-transform", open && "rotate-180")} />
{open ? "Скрыть карту" : "Показать карту"}
</CollapsibleTrigger>
<CollapsibleContent>
<InternetPathMapCanvas model={model} />
</CollapsibleContent>
</Collapsible>
</OpsPanel>
<>
<SectionFrame
title="Internet path"
description="Home → WAN → JH → Exit · пунктир WAN→JH — модель связности, маршрут не подтверждён"
actions={<Link href="/network-map" className={buttonVariants({ variant: "outline", size: "sm" })}>Карта сети →</Link>}
panelClassName="overflow-x-auto bg-[radial-gradient(var(--border)_1px,transparent_1px)] bg-size-[20px_20px]"
>
{error ? (
<Alert variant="destructive" className="m-3 w-auto">
<AlertTitle>Не удалось загрузить путь</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
) : null}
<div className="min-w-[720px]">
{loading && !model ? <div className="bg-muted/40 m-4 h-[268px] animate-pulse rounded-md" /> : <InternetPathTopo model={model} />}
</div>
</SectionFrame>
<SectionFrame
title="Сводка маршрута"
description={`Модель связности; маршрут не подтверждён. ${model?.currentPath?.reason ?? "Текущий маршрут не подтверждён"}`}
>
{loading && !model ? <div className="bg-muted/40 m-4 h-20 animate-pulse rounded-md" /> : <InternetPathSummary model={model} />}
</SectionFrame>
</>
)
}
+30 -85
View File
@@ -3,13 +3,10 @@
import type { ReactNode } from "react"
import Link from "next/link"
import { Badge } from "@/components/reui/badge"
import { IconTile } from "@/components/reui/icon-tile"
import { StatusBadge } from "@/components/status-badge"
import { Flag } from "@/components/flag"
import type { InternetPathViewModel } from "@/lib/dashboard-internet-path"
import type { ServerStatus } from "@/lib/data"
import { cn } from "@/lib/utils"
import { ArrowRightIcon, HomeIcon, RadioIcon, ServerIcon, GlobeIcon } from "lucide-react"
function pathStateToServerStatus(state: InternetPathViewModel["pathState"]): ServerStatus {
if (state === "healthy") return "online"
@@ -17,44 +14,32 @@ function pathStateToServerStatus(state: InternetPathViewModel["pathState"]): Ser
return "unknown"
}
function HopChip({
label,
name,
country,
icon,
iconClassName,
}: {
label: string
name: string
country?: string
icon: ReactNode
iconClassName?: string
}) {
function Kv({ label, children }: { label: string; children: ReactNode }) {
return (
<div className="flex min-w-0 items-center gap-2 rounded-md border border-border/60 px-2 py-1.5">
<IconTile variant="elevated" size="sm" className={cn("shrink-0", iconClassName)} aria-hidden="true">
{icon}
</IconTile>
<div className="min-w-0">
<p className="text-muted-foreground text-[10px] font-medium uppercase tracking-wide">{label}</p>
<p className="flex items-center gap-1 truncate text-sm font-medium">
{country ? <Flag code={country} className="shrink-0" /> : null}
<span className="truncate">{name}</span>
</p>
</div>
<div className="min-w-0">
<small className="text-muted-foreground block text-xs">{label}</small>
<b className="mt-0.5 flex min-w-0 items-center gap-1.5 font-mono text-[13px] font-medium">{children}</b>
</div>
)
}
function Node({ name, country }: { name: string; country?: string }) {
return (
<>
{country ? <Flag code={country} className="shrink-0" /> : null}
<span className="truncate">{name}</span>
</>
)
}
/**
* Compact live path strip (Frame-friendly). Canvas lives separately.
* Preview: https://reui.io/preview/base/stats-12
* Docs: https://reui.io/docs/components/base/icon-tile
* Сводка маршрута (блок kv макета v3): узлы пути и последние подтверждённые метрики участка WAN → JH.
* Docs: https://reui.io/docs/components/base/frame
*/
export function InternetPathSummary({ model }: { model: InternetPathViewModel | null }) {
if (!model) {
return (
<p className="text-muted-foreground text-sm">
<p className="text-muted-foreground px-4 py-3.5 text-sm">
Недостаточно данных для пути. Добавьте home-router и проверьте{" "}
<Link href="/network-map" className="underline underline-offset-2">
карту сети
@@ -71,61 +56,21 @@ export function InternetPathSummary({ model }: { model: InternetPathViewModel |
const dl = hop?.wanJhMetrics.dlMbps
return (
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
<StatusBadge status={pathStateToServerStatus(model.pathState)} />
{model.pathState === "failover" ? (
<Badge variant="warning-light" size="sm">failover</Badge>
) : null}
{ping != null ? (
<Badge variant="outline" size="sm" className="tabular-nums">
{ping} мс
</Badge>
) : null}
{dl != null ? (
<Badge variant="outline" size="sm" className="tabular-nums">
{Math.round(dl)} ↓ Мбит/с
</Badge>
) : null}
<div className="flex flex-col gap-3 px-4 py-3.5">
<div className="grid grid-cols-1 gap-x-3.5 gap-y-3 sm:grid-cols-2">
<Kv label="Маршрут">Home → WAN → JH → Exit</Kv>
<Kv label="Состояние">
<StatusBadge status={pathStateToServerStatus(model.pathState)} />
{model.pathState === "failover" ? <Badge variant="warning-light" size="sm">failover</Badge> : null}
</Kv>
<Kv label="RTT WAN → JH">{ping != null ? <span className="tabular-nums">{`${ping} мс`}</span> : "—"}</Kv>
<Kv label="Загрузка WAN → JH">{dl != null ? <span className="tabular-nums">{`${Math.round(dl)} ↓ Мбит/с`}</span> : "—"}</Kv>
<Kv label="Home"><Node name={model.homeRouter.name} country={model.homeRouter.country} /></Kv>
<Kv label="Активный WAN"><span className="truncate">{`${wanName} · ${wanIsp}`}</span></Kv>
<Kv label="JumpHost"><Node name={hop?.jumpHost.name ?? model.fallbackJumpHost?.name ?? "—"} country={hop?.jumpHost.country ?? model.fallbackJumpHost?.country} /></Kv>
<Kv label="Exit"><Node name={hop?.exitNode.name ?? model.fallbackExitNode?.name ?? "—"} country={hop?.exitNode.country ?? model.fallbackExitNode?.country} /></Kv>
</div>
<p className="text-muted-foreground text-xs">JH/Exit — схема кандидатов. Default route подтверждает только WAN. Метрики — последние подтверждённые пробы участков.</p>
<div className="flex flex-col gap-2 @3xl:flex-row @3xl:items-center">
<HopChip
label="Home"
name={model.homeRouter.name}
country={model.homeRouter.country}
icon={<HomeIcon />}
iconClassName="text-success"
/>
<ArrowRightIcon className="text-muted-foreground hidden size-4 shrink-0 @3xl:block" aria-hidden="true" />
<HopChip
label="WAN"
name={`${wanName} · ${wanIsp}`}
icon={<RadioIcon />}
iconClassName="text-info"
/>
<ArrowRightIcon className="text-muted-foreground hidden size-4 shrink-0 @3xl:block" aria-hidden="true" />
<HopChip
label="JH"
name={hop?.jumpHost.name ?? model.fallbackJumpHost?.name ?? "—"}
country={hop?.jumpHost.country ?? model.fallbackJumpHost?.country}
icon={<ServerIcon />}
iconClassName="text-primary"
/>
<ArrowRightIcon className="text-muted-foreground hidden size-4 shrink-0 @3xl:block" aria-hidden="true" />
<HopChip
label="Exit"
name={hop?.exitNode.name ?? model.fallbackExitNode?.name ?? "—"}
country={hop?.exitNode.country ?? model.fallbackExitNode?.country}
icon={<GlobeIcon />}
iconClassName="text-muted-foreground"
/>
</div>
<p className="text-muted-foreground text-xs leading-relaxed">
{model.currentPath?.reason ?? "Текущий маршрут не подтверждён"}
</p>
<p className="text-muted-foreground border-t border-dashed pt-2.5 text-xs">JH/Exit — схема кандидатов. Default route подтверждает только WAN. Метрики — последние подтверждённые пробы участков.</p>
</div>
)
}
+22
View File
@@ -0,0 +1,22 @@
import { StatusDot } from "@/components/status-dot"
interface DataFreshnessProps {
/** Время последнего успешного получения данных (мс), null — данных ещё нет. */
at: number | null
live: boolean
}
/** Свежесть данных в шапке страницы: «Обновлено 14:02 · Live» или «Демо-данные». */
export function DataFreshness({ at, live }: DataFreshnessProps) {
const text = !live
? "Демо-данные"
: at == null
? "Данные ещё не получены"
: `Обновлено ${new Date(at).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · Live`
return (
<span role="status" className="text-muted-foreground hidden h-[30px] shrink-0 items-center gap-2 rounded-lg border px-2.5 text-xs min-[1320px]:inline-flex">
<StatusDot status={live && at != null ? "online" : "unknown"} />
{live && at != null ? <time dateTime={new Date(at).toISOString()}>{text}</time> : text}
</span>
)
}
+143 -27
View File
@@ -1,22 +1,30 @@
"use client"
import { useEffect, useState } from "react"
import Link from "next/link"
import { usePathname } from "next/navigation"
import { ChevronDownIcon, SearchIcon, StarIcon } from "lucide-react"
import {
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarMenu,
SidebarMenuAction,
SidebarMenuButton,
SidebarMenuItem,
SidebarSeparator,
useSidebar,
} from "@/components/ui/sidebar"
import { Kbd } from "@/components/ui/kbd"
import { cn } from "@/lib/utils"
import { openCommandPalette } from "@/components/command-palette"
export interface NavItem {
title: string
url: string
icon?: React.ReactNode
/** Если `undefined` — счётчик не показываем (нет данных или раздел без live-источника). */
badge?: string
/** Точка проблемы у пункта: сбой (er) или внимание (wn); без данных — не показываем. */
problem?: { tone: "er" | "wn"; label: string }
}
export interface NavGroup {
@@ -24,36 +32,144 @@ export interface NavGroup {
items: NavItem[]
}
export function NavMain({ groups }: { groups: NavGroup[] }) {
const PINS_KEY = "mm:sidebar-pins"
const CLOSED_KEY = "mm:sidebar-closed-groups"
const DOT_CLASS = { er: "bg-destructive", wn: "bg-warning" } as const
function readList(key: string): string[] {
try {
const raw = JSON.parse(localStorage.getItem(key) ?? "[]")
return Array.isArray(raw) ? raw.filter((v): v is string => typeof v === "string") : []
} catch {
return []
}
}
function writeList(key: string, list: string[]) {
try {
localStorage.setItem(key, JSON.stringify(list))
} catch {
/* хранилище недоступно — настройка действует до перезагрузки */
}
}
function NavEntry({ item, pinned, onTogglePin }: { item: NavItem; pinned: boolean; onTogglePin: () => void }) {
const pathname = usePathname()
const { setOpenMobile } = useSidebar()
const active = pathname === item.url || pathname.startsWith(`${item.url}/`)
return (
<SidebarMenuItem>
<SidebarMenuButton
isActive={active}
tooltip={item.problem ? `${item.title} · ${item.problem.label}` : item.title}
className="relative pr-8 group-data-[collapsible=icon]:pr-2!"
render={<Link href={item.url} aria-current={active ? "page" : undefined} onNavigate={() => setOpenMobile(false)} />}
>
{item.icon}
<span>{item.title}</span>
{item.problem ? (
<span
role="img"
aria-label={item.problem.label}
className={cn(
"ml-auto size-2 shrink-0 rounded-full group-data-[collapsible=icon]:absolute group-data-[collapsible=icon]:top-1 group-data-[collapsible=icon]:right-1 group-data-[collapsible=icon]:ml-0 group-data-[collapsible=icon]:size-1.5 group-data-[collapsible=icon]:ring-2 group-data-[collapsible=icon]:ring-sidebar",
DOT_CLASS[item.problem.tone],
)}
/>
) : null}
</SidebarMenuButton>
<SidebarMenuAction
showOnHover={!pinned}
aria-label={pinned ? `Открепить ${item.title}` : `Закрепить ${item.title}`}
aria-pressed={pinned}
onClick={onTogglePin}
>
<StarIcon className={cn(pinned && "fill-current")} aria-hidden />
</SidebarMenuAction>
</SidebarMenuItem>
)
}
/**
* Навигация общего макета v2 (как в EvoBGP): поиск ⌘K, «Закреплённые», сворачиваемые группы,
* точки проблем у разделов.
*/
export function NavMain({ groups }: { groups: NavGroup[] }) {
const [pins, setPins] = useState<string[]>([])
const [closed, setClosed] = useState<string[]>([])
useEffect(() => {
queueMicrotask(() => {
setPins(readList(PINS_KEY))
setClosed(readList(CLOSED_KEY))
})
}, [])
const items = groups.flatMap((g) => g.items)
const pinned = pins.map((url) => items.find((i) => i.url === url)).filter((i): i is NavItem => Boolean(i))
const togglePin = (url: string) => setPins((prev) => {
const next = prev.includes(url) ? prev.filter((u) => u !== url) : [...prev, url]
writeList(PINS_KEY, next)
return next
})
const toggleGroup = (label: string) => setClosed((prev) => {
const next = prev.includes(label) ? prev.filter((l) => l !== label) : [...prev, label]
writeList(CLOSED_KEY, next)
return next
})
return (
<nav aria-label="Основная навигация">
{groups.map((group) => (
<SidebarGroup key={group.label}>
<SidebarGroupLabel>{group.label}</SidebarGroupLabel>
<SidebarMenu>
{group.items.map((item) => (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton
isActive={pathname === item.url}
tooltip={item.title}
render={<Link href={item.url} aria-current={pathname === item.url ? "page" : undefined} onNavigate={() => setOpenMobile(false)} />}
>
{item.icon}
<span>{item.title}</span>
{item.badge != null && item.badge !== "" && (
<span className="ml-auto text-[10.5px] font-mono tabular-nums text-sidebar-foreground/50 group-data-[collapsible=icon]:hidden">
{item.badge}
</span>
)}
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
<nav aria-label="Основная навигация" className="flex flex-col">
<SidebarGroup className="pb-1">
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
tooltip="Поиск и команды"
onClick={openCommandPalette}
className="border-sidebar-border text-sidebar-foreground/70 border"
>
<SearchIcon aria-hidden />
<span>Поиск и команды</span>
<Kbd className="ml-auto group-data-[collapsible=icon]:hidden">⌘K</Kbd>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarGroup>
{pinned.length > 0 ? (
<SidebarGroup className="py-0 group-data-[collapsible=icon]:hidden">
<SidebarGroupLabel className="text-xs font-semibold tracking-wide uppercase">Закреплённые</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu className="gap-px">
{pinned.map((item) => <NavEntry key={item.url} item={item} pinned onTogglePin={() => togglePin(item.url)} />)}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
))}
) : null}
{groups.map((group, gi) => {
const isClosed = closed.includes(group.label)
return (
<div key={group.label} className="flex flex-col">
{gi > 0 ? <SidebarSeparator className="mx-2 my-1 hidden h-px shrink-0 group-data-[collapsible=icon]:block" /> : null}
<SidebarGroup className="py-0">
<SidebarGroupLabel
render={<button type="button" aria-expanded={!isClosed} onClick={() => toggleGroup(group.label)} />}
className="h-7 cursor-pointer justify-between text-xs font-semibold tracking-wide uppercase"
>
{group.label}
<ChevronDownIcon className={cn("size-3.5 transition-transform", isClosed && "-rotate-90")} aria-hidden />
</SidebarGroupLabel>
<SidebarGroupContent className={cn(isClosed && "hidden group-data-[collapsible=icon]:block")}>
<SidebarMenu className="gap-px">
{group.items.map((item) => (
<NavEntry key={item.url} item={item} pinned={pins.includes(item.url)} onTogglePin={() => togglePin(item.url)} />
))}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
</div>
)
})}
</nav>
)
}
+40 -37
View File
@@ -1,48 +1,51 @@
"use client"
import { useEffect, useRef } from "react"
import { Badge } from "@/components/ui/badge"
import { InfoIcon, LockIcon, UsersIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/reui/badge"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
const STATUS = [["var(--success)", "Онлайн"], ["var(--warning)", "Внимание"], ["var(--destructive)", "Оффлайн"], ["var(--muted-foreground)", "Неизвестно"]] as const
const ROLES = [["HR", "Home Router", "var(--chart-2)"], ["JH", "JumpHost", "var(--chart-1)"], ["EN", "Exit Node", "var(--chart-3)"], ["IX", "IX Node", "var(--chart-4)"]] as const
/** Легенда карты макета v3: статус, роли узлов, виды связей и что значат подписи. */
export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
const details = useRef<HTMLDetailsElement>(null)
useEffect(() => {
if ((compact || window.matchMedia("(max-width: 767px)").matches) && details.current) details.current.open = false
}, [compact])
const head = "text-muted-foreground mt-1 text-[11px] font-semibold tracking-wider uppercase"
return (
<details ref={details} open data-map-legend className="absolute left-3 top-3 z-20 max-w-[calc(100%-1.5rem)] rounded-lg border bg-popover text-popover-foreground shadow-sm">
<summary className="cursor-pointer px-3 py-2 text-xs font-semibold focus-visible:outline-2 focus-visible:outline-ring">Легенда карты</summary>
<div role="region" aria-label="Легенда карты" className="flex max-h-[42vh] w-44 max-w-full flex-col gap-2 overflow-y-auto border-t px-3 py-2 text-[11px]">
<div>
<p className="mb-1.5 font-medium text-muted-foreground">Статус устройства</p>
<div className="grid grid-cols-2 gap-x-2 gap-y-1.5">
{[["var(--status-online)", "Онлайн"], ["var(--status-degraded)", "Внимание"], ["var(--status-offline)", "Оффлайн"], ["var(--muted-foreground)", "Неизвестно"]].map(([color, label]) => (
<span key={label} className="flex items-center gap-1.5"><span aria-hidden className="size-2 shrink-0 rounded-full" style={{ background: color }} />{label}</span>
))}
</div>
</div>
<div className="flex flex-col gap-1.5">
<p className="font-medium text-muted-foreground">Тип узла</p>
{[["JH", "JumpHost", "var(--chart-1)"], ["EN", "Exit Node", "var(--chart-3)"], ["HR", "Home Router", "var(--chart-2)"], ["IX", "IX Node", "var(--chart-4)"]].map(([label, name, color]) => (
<span key={label} className="flex items-center gap-2"><Badge variant="secondary" style={{ color }} className="min-w-8 justify-center text-[10px]">{label}</Badge><span>{name}</span></span>
<Popover key={compact ? "compact" : "overview"}>
<PopoverTrigger render={<Button type="button" variant="outline" className="text-[13px]" />}>
<InfoIcon aria-hidden="true" className="size-4" />Легенда
</PopoverTrigger>
<PopoverContent align="end" role="region" aria-label="Легенда карты" className="max-h-[min(60vh,var(--available-height))] w-[310px] max-w-[calc(100vw-2rem)] gap-2 overflow-y-auto border p-3 text-xs">
<p className={head}>Статус</p>
<div className="grid grid-cols-2 gap-x-2.5 gap-y-1.5">
{STATUS.map(([color, label]) => (
<span key={label} className="flex items-center gap-2"><span aria-hidden className="size-2 shrink-0 rounded-full" style={{ background: color }} />{label}</span>
))}
<span className="flex items-center gap-2"><span aria-hidden className="mx-1 size-3 rounded-full border border-current" />WAN · аплинк</span>
<span className="flex items-center gap-2"><span aria-hidden className="mx-1 size-3 rounded border border-current" />Сервис / страна</span>
</div>
<div className="flex flex-col gap-1.5">
<p className="font-medium text-muted-foreground">Связи и измерения</p>
{[
["GRE", "var(--status-online)", undefined],
["GRE + IPsec", "var(--status-online)", "7 4"],
["Поток NetFlow", "var(--chart-4)", "6 5"],
["WAN → JH · модель", "var(--muted-foreground)", "5 4"],
].map(([label, color, dash]) => (
<span key={label} className="flex items-center gap-2"><svg aria-hidden width="28" height="12" className="shrink-0"><line x1="0" y1="6" x2="28" y2="6" stroke={color} strokeWidth="2" strokeDasharray={dash} /></svg>{label}</span>
<p className={head}>Узлы</p>
<div className="grid grid-cols-2 gap-x-2.5 gap-y-1.5">
{ROLES.map(([label, name, color]) => (
<span key={label} className="flex items-center gap-2">
<b className="bg-muted inline-flex h-[18px] w-7 items-center justify-center rounded-[5px] font-mono text-[10.5px] font-semibold" style={{ color }}>{label}</b><span>{name}</span>
</span>
))}
<p className="text-muted-foreground">RTT · задержка пробы. «—» · нет измерения.</p>
<p className="text-muted-foreground">NetFlow · трафик за 5 минут, не пропускная способность канала.</p>
<p className="text-muted-foreground">Live GRE · текущие RX/TX в деталях туннеля.</p>
<span className="flex items-center gap-2"><svg aria-hidden width="28" height="16" viewBox="0 0 28 16"><rect x="1" y="2" width="26" height="12" rx="6" fill="none" stroke="var(--muted-foreground)" strokeWidth="1.5" /></svg>WAN-аплинк</span>
<span className="flex items-center gap-2"><svg aria-hidden width="28" height="16" viewBox="0 0 28 16"><rect x="1" y="2" width="26" height="12" rx="3" fill="none" stroke="var(--muted-foreground)" strokeWidth="1.5" /></svg>Сервис / страна</span>
<span className="flex items-center gap-2"><UsersIcon aria-hidden className="size-4" />Пользователи</span>
</div>
</div>
</details>
<p className={head}>Связи</p>
<div className="flex flex-col gap-1.5">
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--success)" strokeWidth="3" /></svg>GRE-туннель</span>
<span className="flex items-center gap-2"><LockIcon aria-hidden className="mx-2 size-4" />GRE + IPsec</span>
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--destructive)" strokeWidth="3" /></svg>GRE · нет связи</span>
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeWidth="2" /></svg>Home Router → аплинк</span>
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeOpacity=".5" strokeWidth="2" /></svg>WAN → JH · модель связности</span>
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="12" viewBox="0 0 32 12"><path d="M0 3 C16 3 16 9 32 9" fill="none" stroke="var(--chart-4)" strokeWidth="2" /></svg>Связь с сервисом</span>
<span className="flex items-center gap-2"><Badge variant="outline" size="xs">IPFIX</Badge>Наблюдение экспортёра · выход не подтверждён</span>
</div>
<p className="text-muted-foreground leading-snug">Подпись линии GRE показывает последний замер RX/TX интерфейса RouterOS. Скорость сервиса и знак «≈» показывают среднюю скорость по принятым записям IPFIX. RTT — задержка пробы, «—» означает, что нет измерения.</p>
</PopoverContent>
</Popover>
)
}
@@ -0,0 +1,207 @@
"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>
</>
}
+177
View File
@@ -0,0 +1,177 @@
"use client"
import { useEffect, useState } from "react"
import Link from "next/link"
import { UsersIcon, XIcon } from "lucide-react"
import type { IxLinuxBinding, IxSegment } from "@mmapp/contracts/internet-exchange"
import type { FlowMapService, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
import { Badge } from "@/components/reui/badge"
import { Button, buttonVariants } from "@/components/ui/button"
import { Command, CommandDialog, CommandEmpty, CommandInput, CommandItem, CommandList } from "@/components/ui/command"
import { INIT_USERS } from "@/lib/users"
import { fmtRate } from "@/lib/fmt-rate"
import { formatNetflowRate } from "@/lib/map-netflow-hops"
import { projectTrafficObservations } from "@/lib/traffic-observations"
import { requestJson } from "@/shared/api/http-client"
import { listAppUsers } from "@/shared/api/users"
type AccessBinding = { id: string; node: string; name: string; kind: string; enabled?: boolean; peerScoped?: boolean; identity?: string }
export type MapAccessUser = { id: string; name: string; login?: string; linux?: true; bindings: AccessBinding[] }
type AccessRate = { rxNow: number | null; txNow: number | null }
const mapUsers = (users: typeof INIT_USERS): MapAccessUser[] => users.map(user => ({
id: user.id, name: user.name || user.login, login: user.login,
bindings: user.bindings.map(binding => ({ id: binding.id, node: binding.serverId, name: binding.interfaceName, kind: binding.interfaceType,
peerScoped: Boolean(binding.peerPublicKey), identity: JSON.stringify([binding.serverId, binding.interfaceName, binding.peerPublicKey || null]) })),
}))
const demoUsers = mapUsers(INIT_USERS)
export function useMapAccess(base: string | null, hasIx: boolean, refresh: number, userSelected: boolean) {
const [directory, setDirectory] = useState<{ base: string; users: MapAccessUser[]; unavailable: boolean }>()
const [linux, setLinux] = useState<{ base: string; users: MapAccessUser[]; unavailable: boolean }>()
const [traffic, setTraffic] = useState<{ base: string; rates: Map<string, AccessRate> }>()
useEffect(() => {
if (base === null) return
const controller = new AbortController()
void listAppUsers(base, { signal: controller.signal }).then(users => {
if (!controller.signal.aborted) setDirectory({ base, users: mapUsers(users), unavailable: false })
}).catch(() => { if (!controller.signal.aborted) setDirectory({ base, users: [], unavailable: true }) })
return () => controller.abort()
}, [base, refresh])
useEffect(() => {
if (base === null || !hasIx) return
const controller = new AbortController()
const init = { signal: controller.signal }
async function load() {
const payload = await requestJson<{ items: IxSegment[] }>(base!, "/api/ix/segments?limit=100", init)
const clients = new Map<string, MapAccessUser>()
function add(segment: IxSegment, node: number, iface: string, kind: string, name: string, enabled?: boolean, clientId?: string) {
const id = "ix:" + (clientId ?? `${segment.id}:${node}:${iface}`)
const user = clients.get(id) ?? { id, name, linux: true, bindings: [] }
if (!user.bindings.some(binding => binding.node === String(node) && binding.name === iface)) {
user.bindings.push({ id: `${node}:${iface}`, node: String(node), name: iface, kind, enabled })
}
clients.set(id, user)
}
const applied = await Promise.allSettled(payload.items.map(segment => segment.appliedRevision === null
? [] : requestJson<{ items: IxLinuxBinding[] }>(base!, `/api/ix/segments/${encodeURIComponent(segment.id)}/linux`, init).then(result => result.items)))
payload.items.forEach((segment, index) => {
const rows = applied[index]
if (rows.status === "fulfilled") for (const row of rows.value) {
add(segment, row.serverId, row.interfaceName, row.kind, row.name ?? row.interfaceName, row.enabled, row.policy?.clientId)
}
})
if (!controller.signal.aborted) setLinux({ base: base!, users: [...clients.values()], unavailable: applied.some(result => result.status === "rejected") })
}
void load().catch(() => { if (!controller.signal.aborted) setLinux({ base, users: [], unavailable: true }) })
return () => controller.abort()
}, [base, hasIx, refresh])
useEffect(() => {
if (base === null || !userSelected) return
const controller = new AbortController()
let timer: ReturnType<typeof setTimeout>
async function load() {
const rates = new Map<string, AccessRate>()
try {
const payload = await requestJson<{ interfaces: Array<{ bindingId: string; status?: string }> }>(base!, "/api/traffic/bound-interfaces?range=5m", { signal: controller.signal })
for (const row of payload.interfaces) {
if (row.status === "offline") continue
try { rates.set(row.bindingId, projectTrafficObservations(row)) } catch { /* Invalid measurements remain unknown. */ }
}
} finally {
if (!controller.signal.aborted) {
setTraffic({ base: base!, rates })
timer = setTimeout(() => { void load().catch(() => {}) }, 15_000)
}
}
}
void load().catch(() => {})
return () => { controller.abort(); clearTimeout(timer) }
}, [base, refresh, userSelected])
const users = base === null ? demoUsers : directory?.base === base ? directory.users : []
const rates = new Map(base !== null && traffic?.base === base ? traffic.rates : undefined)
const bindingsByInterface = new Map<string, { user: string; binding: AccessBinding }[]>()
for (const user of users) for (const binding of user.bindings) {
const key = JSON.stringify([binding.node, binding.name])
const entries = bindingsByInterface.get(key) ?? []
entries.push({ user: user.id, binding })
bindingsByInterface.set(key, entries)
}
for (const entries of bindingsByInterface.values()) for (const { user, binding } of entries) {
if (entries.some(other => other.user !== user && other.binding.identity === binding.identity) || !binding.peerScoped && entries.some(other => other.binding.peerScoped)) rates.delete(binding.id)
}
return {
users,
linux: base !== null && hasIx && linux?.base === base ? linux.users : [],
pending: base !== null && directory?.base !== base,
unavailable: base !== null && directory?.base === base && directory.unavailable,
linuxPending: base !== null && hasIx && linux?.base !== base,
linuxUnavailable: base !== null && hasIx && linux?.base === base && linux.unavailable,
rates,
}
}
export function accessRate(bindings: AccessBinding[], rates?: Map<string, AccessRate>) {
let measured = 0, rx = 0, tx = 0
const counted = new Set<string>()
for (const binding of bindings) {
const row = rates?.get(binding.id)
const identity = binding.identity ?? binding.id
if (row?.rxNow == null || row.txNow == null || counted.has(identity)) continue
counted.add(identity)
measured++
rx += row.rxNow
tx += row.txNow
}
const total = new Set(bindings.map(binding => binding.identity ?? binding.id)).size
return { measured, total, rx, tx, label: measured ? `${measured < total ? "≥ " : ""}${fmtRate(rx + tx)}` : "Нет замера" }
}
export function MapUserPicker({ open, onOpenChange, users, pending, unavailable, onPick }: {
open: boolean; onOpenChange: (open: boolean) => void; users: MapAccessUser[]; pending: boolean; unavailable: boolean; onPick: (user: MapAccessUser) => void
}) {
return <CommandDialog open={open} onOpenChange={onOpenChange} title="Выбор пользователя" description="Поиск по имени, логину или интерфейсу">
<Command>
<CommandInput aria-label="Поиск пользователей" placeholder="Имя, логин или интерфейс…" />
<CommandList>
<CommandEmpty>{pending ? "Загрузка пользователей…" : unavailable ? "Каталог пользователей недоступен" : "Пользователи не найдены"}</CommandEmpty>
{users.map(user => <CommandItem key={user.id} value={user.id} keywords={[user.name, user.login ?? "", ...user.bindings.map(binding => binding.name)]} onSelect={() => onPick(user)}>
<UsersIcon aria-hidden /><span className="min-w-0 flex-1 truncate">{user.name}</span>
<Badge variant="outline" size="xs">{user.bindings.length}</Badge>
</CommandItem>)}
</CommandList>
</Command>
</CommandDialog>
}
export function MapUserDetails({ user, groups, paths, services, rates, windowLabel, onClose, onService, nodeName, trafficHref }: {
user: MapAccessUser; groups: Map<string, AccessBinding[]>; paths: FlowMapServicePath[]; services: FlowMapService[]; rates?: Map<string, AccessRate>; windowLabel: string
onClose: () => void; onService: (service: FlowMapService) => void; nodeName: (id: string) => string; trafficHref?: string
}) {
return <>
<header className="flex items-center gap-2 border-b p-3">
<UsersIcon className="size-4 shrink-0" aria-hidden />
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold">{user.name}</h2><p className="text-xs text-muted-foreground">{user.linux ? "Linux-клиент IX" : user.login}</p></div>
<Button size="icon-xs" variant="ghost" onClick={onClose} aria-label="Закрыть детали пользователя"><XIcon /></Button>
</header>
<div className="flex flex-col gap-3 overflow-y-auto p-3">
<section className="grid gap-2"><h3 className="text-xs text-muted-foreground">Подключения</h3>
{[...groups].map(([node, bindings]) => {
const rate = accessRate(bindings, rates)
return <div key={node} className="grid gap-1 text-xs">
<p className="flex justify-between gap-2 font-medium"><span>{nodeName(node)}</span><span className="shrink-0 font-mono">{rate.label}</span></p>
<p className="text-muted-foreground wrap-anywhere">{bindings.map(binding => `${binding.name} · ${binding.kind}${binding.enabled === false ? " · отключён" : ""}`).join(", ")}</p>
{rate.measured > 0 && <p className="font-mono text-muted-foreground">RX {fmtRate(rate.rx)} · TX {fmtRate(rate.tx)} · {rate.measured}/{rate.total}</p>}
</div>
})}
{!groups.size && <p className="text-xs text-muted-foreground">Нет привязок к узлам текущего вида.</p>}
</section>
<section className="grid gap-1 border-t pt-3"><h3 className="text-xs text-muted-foreground">Сервисы · IPFIX · {windowLabel}</h3>
{services.filter(service => paths.some(path => path.serviceId === service.id)).map(service => <Button key={service.id} variant="ghost" size="xs" className="w-full justify-between" onClick={() => onService(service)}>{service.label}<span className="font-mono">{formatNetflowRate(service)}</span></Button>)}
{!paths.length && <p className="text-xs text-muted-foreground">Нет потоков с подтверждённой привязкой к пользователю.</p>}
</section>
{trafficHref && <Link href={trafficHref} className={buttonVariants({size:"xs"})}>{user.linux ? "Открыть Linux-клиентов IX" : "Открыть в «Трафике»"}</Link>}
</div>
</>
}
+174
View File
@@ -0,0 +1,174 @@
"use client"
import type { ReactNode } from "react"
import { FramePanel } from "@/components/reui/frame"
import { Badge } from "@/components/reui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { SectionFrame, ToneBadge, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
export type MapFlowRow = { id: string; client: string; exit: string; dest: string; rate: string; volume: string; hl: boolean }
export type MapRttRow = { id: string; name: string; route: string; rtt: string; speed: string; tone: Tone; status: string; hl: boolean }
export type MapDestRow = { id: string; label: string; category: string; rate: string; share: number; hl: boolean }
export type MapEventRow = { id: string; ts: number; tone: Tone; label: string; title: string; message: string; serverId?: string }
export type MapBottomTab = "flows" | "rtt" | "dest" | "events"
function Table({ head, cols, empty, children }: { head: string[]; cols: string; empty: string | null; children: ReactNode }) {
return (
<div className="max-h-[420px] overflow-auto">
<div className="min-w-[720px]">
<div aria-hidden="true" className={cn("bg-muted/55 text-muted-foreground sticky top-0 z-[1] grid h-10 items-center gap-x-3 border-b px-4 text-xs font-medium", cols)}>
{head.map((h) => <span key={h}>{h}</span>)}
</div>
{empty ? <p className="text-muted-foreground px-4 py-8 text-center text-sm">{empty}</p> : children}
</div>
</div>
)
}
function Row({ cols, hl, children }: { cols: string; hl?: boolean; children: ReactNode }) {
return <div className={cn("grid min-h-11 items-center gap-x-3 border-b px-4 py-1.5 text-[13px] last:border-b-0", cols, hl && "bg-primary/8")}>{children}</div>
}
const FLOW_COLS = "grid-cols-[minmax(160px,1.4fr)_minmax(120px,1fr)_minmax(140px,1.2fr)_110px_100px]"
const RTT_COLS = "grid-cols-[minmax(140px,1fr)_minmax(200px,1.6fr)_90px_minmax(120px,1fr)_110px]"
const DEST_COLS = "grid-cols-[minmax(160px,1.4fr)_minmax(120px,1fr)_110px_minmax(140px,1fr)]"
const EVENT_COLS = "grid-cols-[70px_110px_minmax(200px,1.4fr)_minmax(200px,2fr)]"
/**
* Рабочая панель под картой (макет v3): потоки NetFlow, RTT каналов, назначения и события.
* Строки выбранного объекта подсвечены.
*/
export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, onEvent, eventsError, stat }: {
tab: MapBottomTab
onTab: (tab: MapBottomTab) => void
flows: MapFlowRow[]
rtt: MapRttRow[]
destinations: MapDestRow[]
events: MapEventRow[]
onEvent: (event: MapEventRow) => void
eventsError: string | null
stat: string
}) {
const tabs: Array<{ id: MapBottomTab; label: string; count: number }> = [
{ id: "flows", label: "Потоки NetFlow", count: flows.length },
{ id: "rtt", label: "RTT каналов", count: rtt.length },
{ id: "dest", label: "Назначения", count: destinations.length },
{ id: "events", label: "События", count: events.length },
]
return (
<SectionFrame aria-label="Рабочая панель карты" bare>
<Tabs value={tab} onValueChange={(value) => onTab(value as MapBottomTab)} className="gap-1">
<div className="flex flex-wrap items-center gap-3 px-2 pt-1.5 pb-1">
<TabsList aria-label="Рабочая панель">
{tabs.map((t) => (
<TabsTrigger key={t.id} value={t.id} className="px-2.5">
{t.label}
<Badge variant="secondary" size="sm" className="font-mono">{t.count}</Badge>
</TabsTrigger>
))}
</TabsList>
<span className="text-muted-foreground ml-auto text-xs">{stat}</span>
</div>
<FramePanel className="p-0">
<TabsContent value="flows">
<Table head={["Пользователь", "Выход / экспортёр", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}>
{flows.map((r) => (
<Row key={r.id} cols={FLOW_COLS} hl={r.hl}>
<span className="truncate font-mono">{r.client}</span>
<span className="truncate font-mono">{r.exit}</span>
<span className="truncate">{r.dest}</span>
<span className="font-mono tabular-nums">{r.rate}</span>
<span className="text-muted-foreground font-mono tabular-nums">{r.volume}</span>
</Row>
))}
</Table>
</TabsContent>
<TabsContent value="rtt">
<Table head={["Туннель", "Участок", "RTT", "Скорость ↓/↑", "Статус"]} cols={RTT_COLS} empty={rtt.length ? null : "GRE-туннелей на карте нет"}>
{rtt.map((r) => (
<Row key={r.id} cols={RTT_COLS} hl={r.hl}>
<span className="truncate font-mono">{r.name}</span>
<span className="truncate font-mono">{r.route}</span>
<span className="font-mono tabular-nums">{r.rtt}</span>
<span className="font-mono tabular-nums">{r.speed}</span>
<span><ToneBadge tone={r.tone}>{r.status}</ToneBadge></span>
</Row>
))}
</Table>
</TabsContent>
<TabsContent value="dest">
<Table head={["Назначение", "Категория", "Скорость", "Доля окна"]} cols={DEST_COLS} empty={destinations.length ? null : "Назначений за окно нет"}>
{destinations.map((r) => (
<Row key={r.id} cols={DEST_COLS} hl={r.hl}>
<span className="truncate font-medium">{r.label}</span>
<span className="text-muted-foreground truncate">{r.category}</span>
<span className="font-mono tabular-nums">{r.rate}</span>
<span className="flex items-center gap-2">
<span className="bg-muted h-1.5 w-20 overflow-hidden rounded-full"><i className="block h-full rounded-full" style={{ width: `${Math.round(Math.min(1, r.share) * 100)}%`, background: "var(--chart-4)" }} /></span>
<span className="font-mono text-xs tabular-nums">{Math.round(r.share * 100)}%</span>
</span>
</Row>
))}
</Table>
</TabsContent>
<TabsContent value="events">
<Table head={["Время", "Тип", "Событие", "Подробности"]} cols={EVENT_COLS} empty={eventsError ? `События недоступны: ${eventsError}` : events.length ? null : "Событий пока нет"}>
{events.map((r) => (
<Row key={r.id} cols={EVENT_COLS}>
<time dateTime={new Date(r.ts).toISOString()} className="text-muted-foreground font-mono text-xs">{new Date(r.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })}</time>
<span><ToneBadge tone={r.tone} mark={false}>{r.label}</ToneBadge></span>
<Button type="button" variant="link" size="xs" className="min-w-0 justify-start" onClick={() => onEvent(r)}><span className="truncate">{r.title}</span></Button>
<span className="text-muted-foreground truncate text-xs">{r.message}</span>
</Row>
))}
</Table>
</TabsContent>
</FramePanel>
</Tabs>
</SectionFrame>
)
}
/**
* «Момент времени» (макет v3): инциденты за 24 часа на шкале и текущий Live-снимок.
* Архив снимков карты не хранится, поэтому прошлые моменты не выбираются.
*/
export function MapTimeline({ events, now, onPick }: { events: MapEventRow[]; now: number; onPick: (event: MapEventRow) => void }) {
const from = now - 24 * 3_600_000
const marks = events.filter((e) => e.ts >= from && e.ts <= now)
const at = (t: number) => `calc(10px + (100% - 20px) * ${t.toFixed(4)})`
// Шкала макета v3: остановки (кружок и подпись под ним), инциденты — цветные засечки над линией.
const stop = "absolute top-[7px] flex -translate-x-1/2 flex-col items-center gap-1 text-[11px] leading-none whitespace-nowrap"
return (
<div className="flex shrink-0 items-center gap-3 border-t px-3 pt-1.5 pb-1">
<small className="text-muted-foreground text-xs whitespace-nowrap">Момент времени</small>
<div role="group" aria-label="Инциденты карты за 24 часа" className="relative mx-3.5 h-9 min-w-0 flex-1">
<span aria-hidden="true" className="bg-border absolute inset-x-2.5 top-[11px] h-0.5 rounded-full" />
{[["−24 ч", 0], ["−6 ч", 0.75], ["−1 ч", 0.9583]].map(([label, t]) => (
<span key={label} aria-hidden="true" className={cn(stop, "text-muted-foreground")} style={{ left: at(Number(t)) }}>
<i className="bg-card border-muted-foreground block size-2.5 rounded-full border-2" />{label}
</span>
))}
{marks.map((e) => (
<button
key={e.id}
type="button"
onClick={() => onPick(e)}
aria-label={`${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}`}
title={`${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}`}
className="focus-visible:ring-ring absolute top-1 flex h-4 w-3 -translate-x-1/2 justify-center rounded-sm outline-none focus-visible:ring-2"
style={{ left: at((e.ts - from) / (now - from)) }}
>
<span aria-hidden="true" className="block h-full w-1.5 rounded-sm" style={{ background: TONE_COLOR[e.tone] }} />
</button>
))}
<span className={cn(stop, "text-foreground font-semibold")} style={{ left: at(1) }}>
<i className="bg-success border-success block size-2.5 rounded-full border-2 shadow-[0_0_0_4px_color-mix(in_oklch,var(--success)_25%,transparent)]" />Live
</span>
</div>
<small className="text-muted-foreground font-mono text-xs">{new Date(now).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })}</small>
</div>
)
}
+128
View File
@@ -0,0 +1,128 @@
"use client"
import type { Server } from "@/lib/data"
import { formatMapFlowWindow, formatNetflowRate } from "@/lib/map-netflow-hops"
import { TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
import { cn } from "@/lib/utils"
type StatusFilter = "online" | "degraded" | "offline" | "unknown"
const STATUS: Array<{ key: StatusFilter; label: string; tone: Tone }> = [
{ key: "online", label: "Онлайн", tone: "ok" },
{ key: "degraded", label: "Внимание", tone: "wn" },
{ key: "offline", label: "Оффлайн", tone: "er" },
{ key: "unknown", label: "Неизвестно", tone: "mu" },
]
const EXIT_COLORS = ["var(--chart-4)", "var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-5)"]
/** Русское склонение: 1 узел, 2 узла, 5 узлов. */
export function ruPlural(n: number, one: string, few: string, many: string) {
const m10 = n % 10, m100 = n % 100
return m10 === 1 && m100 !== 11 ? one : m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14) ? few : many
}
function Seg({ parts }: { parts: Array<{ n: number; color: string }> }) {
const shown = parts.filter((part) => part.n > 0)
return (
<div aria-hidden="true" className="flex h-1.5 gap-0.5">
{shown.length ? shown.map((part, i) => <i key={i} className="block h-full min-w-1.5 rounded-full" style={{ flex: part.n, background: part.color }} />) : <i className="bg-muted block h-full flex-1 rounded-full" />}
</div>
)
}
function Card({ title, value, unit, children }: { title: string; value: string; unit: string; children: React.ReactNode }) {
return (
<div className="bg-card flex min-w-0 flex-col gap-2 rounded-xl border px-4 py-3.5">
<small className="text-muted-foreground text-xs font-medium">{title}</small>
<div className="flex items-baseline gap-1.5 text-2xl leading-tight font-semibold tracking-tight tabular-nums">
{value}
<em className="text-muted-foreground text-[13px] font-normal tracking-normal not-italic">{unit}</em>
</div>
{children}
</div>
)
}
/**
* KPI-полоса над картой (макет v3): узлы, GRE-туннели, NetFlow и узлы, требующие внимания.
* Счётчики статусов фильтруют карту, строки проблем открывают узел.
*/
export function MapKpiStrip({ servers, tunnels, downRoutes = [], exits = [], liveLink, netflowBytes, windowSec, filter, onFilter, onSelect, className }: {
servers: Server[]
tunnels: Array<{ status: "up" | "down" | "degraded" }>
/** «A → B» недоступных GRE на карте — для подвала карточки туннелей. */
downRoutes?: string[]
/** Скорость NetFlow через Exit-узлы за окно, бит/с. */
exits?: Array<{ name: string; bps: number }>
liveLink?: { name: string; bps: number; bpsFwd: number; bpsRev: number }
/** Байты NetFlow за окно; null — потоки не загружены. */
netflowBytes: number | null
windowSec: number
filter: string
onFilter: (key: StatusFilter | "all") => void
onSelect: (server: Server) => void
className?: string
}) {
const count = (status: Server["status"]) => servers.filter((server) => server.status === status).length
const up = tunnels.filter((tunnel) => tunnel.status === "up").length
const degraded = tunnels.filter((tunnel) => tunnel.status === "degraded").length
const down = tunnels.length - up - degraded
const problems = servers.filter((server) => server.enabled !== false && server.status !== "online")
const topExits = netflowBytes == null ? [] : [...exits].filter((exit) => exit.bps > 0).sort((a, b) => b.bps - a.bps)
const flowRate = netflowBytes == null ? null : formatNetflowRate({ bps: (netflowBytes * 8) / Math.max(1, windowSec) })
const flowLabel = `NetFlow · ${formatMapFlowWindow(windowSec)}`
const greFoot = !tunnels.length ? "Туннелей на карте нет"
: downRoutes.length ? `${downRoutes[0]} — без ответа${downRoutes.length > 1 ? ` · ещё ${downRoutes.length - 1}` : ""}`
: degraded ? `С деградацией: ${degraded}` : "Все туннели на карте работают"
return (
<div className={cn("grid grid-cols-[repeat(auto-fit,minmax(min(240px,100%),1fr))] gap-3", className)}>
<Card title="Узлы на карте" value={String(servers.length)} unit={ruPlural(servers.length, "устройство", "устройства", "устройств")}>
<Seg parts={STATUS.map((s) => ({ n: count(s.key), color: TONE_COLOR[s.tone] }))} />
<div className="-mx-1.5 -mb-1 flex flex-wrap gap-0.5">
{STATUS.filter((s) => s.key !== "unknown" || count(s.key) > 0).map((s) => (
<button
key={s.key}
type="button"
aria-pressed={filter === s.key}
onClick={() => onFilter(filter === s.key ? "all" : s.key)}
className={cn("text-muted-foreground hover:bg-muted/70 inline-flex h-[26px] items-center gap-1.5 rounded-md border border-transparent px-1.5 text-[12.5px] transition-colors", filter === s.key && "bg-muted border-border text-foreground")}
>
<span aria-hidden="true" className="size-2 rounded-full" style={{ background: TONE_COLOR[s.tone] }} />
{s.label}{" "}
<b className="text-foreground font-semibold tabular-nums">{count(s.key)}</b>
</button>
))}
</div>
</Card>
<Card title="GRE-туннели на карте" value={tunnels.length ? `${up} из ${tunnels.length}` : "—"} unit="работают">
<Seg parts={[{ n: up, color: TONE_COLOR.ok }, { n: degraded, color: TONE_COLOR.wn }, { n: down, color: TONE_COLOR.er }]} />
<div className="text-muted-foreground text-xs [overflow-wrap:anywhere]">{greFoot}</div>
</Card>
<Card title={liveLink ? "Макс. из замеров · Live" : flowLabel} value={liveLink ? formatNetflowRate(liveLink) : flowRate ?? "—"} unit={liveLink ? "RX + TX" : "в среднем"}>
<Seg parts={liveLink ? [{ n: liveLink.bpsFwd, color: "var(--chart-4)" }, { n: liveLink.bpsRev, color: "var(--chart-1)" }]
: topExits.length ? topExits.map((exit, i) => ({ n: exit.bps, color: EXIT_COLORS[i % EXIT_COLORS.length] })) : [{ n: netflowBytes ? 1 : 0, color: "var(--chart-4)" }]} />
<div className="text-muted-foreground text-xs [overflow-wrap:anywhere]">
{liveLink && <div title={liveLink.name}>{liveLink.name}</div>}
{liveLink
? flowRate && `${flowLabel} · среднее ${flowRate}`
: netflowBytes == null ? "Потоки ещё не загружены" : topExits.length ? topExits.slice(0, 3).map((exit) => `${exit.name} ${formatNetflowRate({ bps: exit.bps })}`).join(" · ") : "Выборка IPFIX"}
</div>
</Card>
<Card title="Требуют внимания" value={String(problems.length)} unit={ruPlural(problems.length, "узел", "узла", "узлов")}>
{problems.length ? (
<div className="-mx-1.5 -mb-1 flex flex-col">
{problems.slice(0, 3).map((server) => (
<button key={server.id} type="button" onClick={() => onSelect(server)} className="hover:bg-muted/70 flex min-h-[26px] items-center gap-2 rounded-md px-1.5 text-left text-[12.5px] transition-colors">
<span aria-hidden="true" className="size-2 shrink-0 rounded-full" style={{ background: TONE_COLOR[server.status === "offline" ? "er" : server.status === "degraded" ? "wn" : "mu"] }} />
<span className="min-w-0 flex-1 truncate">{server.name} — {server.status === "offline" ? "нет ответа" : server.status === "degraded" ? "ухудшение" : "статус неизвестен"}</span>
</button>
))}
</div>
) : (
<div className="text-muted-foreground text-xs">На момент снимка все узлы отвечали.</div>
)}
</Card>
</div>
)
}
+53 -10
View File
@@ -1,8 +1,13 @@
"use client"
import { Fragment, type ReactNode } from "react"
import { usePathname } from "next/navigation"
import { InfoIcon, SearchIcon } from "lucide-react"
import { Separator } from "@/components/ui/separator"
import { SidebarTrigger } from "@/components/ui/sidebar"
import { Button } from "@/components/ui/button"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Badge } from "@/components/reui/badge"
import {
Breadcrumb,
BreadcrumbItem,
@@ -11,8 +16,8 @@ import {
BreadcrumbPage,
BreadcrumbSeparator,
} from "@/components/ui/breadcrumb"
import { AppsMenu } from "@/components/apps-menu"
import { SystemMonitorPopover } from "@/components/system-monitor-popover"
import { openCommandPalette } from "@/components/command-palette"
interface Crumb {
label: string
@@ -22,23 +27,57 @@ interface Crumb {
interface PageHeaderProps {
crumbs: Crumb[]
actions?: ReactNode
/** Состояние данных страницы в шапке, например `<DataFreshness />`. */
status?: ReactNode
}
/** Header chrome — AppsMenu + SystemMonitor; theme in NavUser. @see https://reui.io/preview/base/app-shell-12 */
export function PageHeader({ crumbs, actions }: PageHeaderProps) {
/** Откуда раздел берёт данные — окно «Источники и свежесть данных» (как в шапке EvoBGP и макета v2). */
const FRESH: Record<string, { badge: string; text: string }> = {
"/dashboard": { badge: "Live", text: "Серверы, туннели, пробы, BGP, трафик, Internet path и события из API · обновление каждые 30 с" },
"/traffic": { badge: "Live", text: "Счётчики интерфейсов RouterOS и потоки IPFIX · текущая скорость по live-потоку" },
"/statistics": { badge: "Куб", text: "Куб NetFlow: факты IPFIX по суткам и часам · уникальный объём без дублей" },
"/network-map": { badge: "Снимок", text: "Снимок карты из API и NetFlow за окно 5 мин · DNS для адресов GRE" },
"/uptime": { badge: "Пробы", text: "Пробы ping и скорости по серверам · история RTT за час" },
"/servers": { badge: "Каталог", text: "Каталог серверов и последний опрос RouterOS API" },
"/ix": { badge: "IX", text: "Сегменты, площадки и Linux-клиенты точек обмена трафиком" },
}
function freshFor(pathname: string) {
const key = Object.keys(FRESH).sort((a, b) => b.length - a.length).find((k) => pathname === k || pathname.startsWith(`${k}/`))
return key ? FRESH[key] : { badge: "API", text: "Данные раздела из API MikrotikManager" }
}
function FreshnessPopover() {
const fresh = freshFor(usePathname())
return (
<header className="bg-background sticky top-0 z-10 flex min-h-12 shrink-0 flex-wrap items-center gap-2 border-b px-4 py-1.5 md:px-6">
<Popover>
<PopoverTrigger render={<Button type="button" variant="ghost" size="icon" aria-label="Источники и свежесть данных" title="Источники и свежесть данных" />}>
<InfoIcon aria-hidden />
</PopoverTrigger>
<PopoverContent align="end" sideOffset={8} className="flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-2">
<Badge variant="success-light" size="sm" className="w-fit">{fresh.badge}</Badge>
<p className="text-muted-foreground text-sm">{fresh.text}</p>
</PopoverContent>
</Popover>
)
}
/** Шапка общего макета v2 и EvoBGP: меню, «Главная / раздел / страница», источники данных, поиск, состояние системы. */
export function PageHeader({ crumbs, actions, status }: PageHeaderProps) {
const trail = crumbs[0]?.label === "Главная" ? crumbs : [{ label: "Главная", href: "/dashboard" }, ...crumbs]
return (
<header className="bg-background/80 sticky top-0 z-10 flex min-h-12 shrink-0 flex-wrap items-center gap-2 border-b px-4 py-1.5 backdrop-blur md:px-6">
<SidebarTrigger className="-ml-1" />
<Separator orientation="vertical" className="mr-2 data-[orientation=vertical]:h-4" />
<Breadcrumb aria-label="Путь страницы" className="min-w-0 flex-1">
<BreadcrumbList className="flex-nowrap">
{crumbs.map((crumb, i) => (
{trail.map((crumb, i) => (
<Fragment key={i}>
{i > 0 && <BreadcrumbSeparator className="hidden shrink-0 sm:block" />}
<BreadcrumbItem className={i < crumbs.length - 1 ? "hidden shrink-0 sm:inline-flex" : "min-w-0"}>
{i < crumbs.length - 1 && crumb.href ? (
{i > 0 && <BreadcrumbSeparator className="text-muted-foreground hidden shrink-0 sm:block">/</BreadcrumbSeparator>}
<BreadcrumbItem className={i < trail.length - 1 ? "hidden shrink-0 sm:inline-flex" : "min-w-0"}>
{i < trail.length - 1 && crumb.href ? (
<BreadcrumbLink href={crumb.href}>{crumb.label}</BreadcrumbLink>
) : i < crumbs.length - 1 ? (
) : i < trail.length - 1 ? (
<span className="text-muted-foreground text-sm">{crumb.label}</span>
) : (
<BreadcrumbPage className="wrap-anywhere">{crumb.label}</BreadcrumbPage>
@@ -51,7 +90,11 @@ export function PageHeader({ crumbs, actions }: PageHeaderProps) {
<div className={`ml-auto flex max-w-full items-center gap-2 ${actions ? "w-full xl:w-auto" : "shrink-0"}`}>
{actions ? <div role="group" aria-label="Действия страницы" className="flex min-w-0 flex-1 flex-wrap items-center gap-2">{actions}</div> : null}
<div className="ml-auto flex shrink-0 items-center gap-2">
<AppsMenu />
{status}
<FreshnessPopover />
<Button type="button" variant="outline" size="icon" aria-label="Командная палитра (⌘K)" className="md:hidden" onClick={openCommandPalette}>
<SearchIcon aria-hidden />
</Button>
<SystemMonitorPopover />
</div>
</div>
+36
View File
@@ -0,0 +1,36 @@
import type { ReactNode } from "react"
import { IconTile } from "@/components/reui/icon-tile"
import { cn } from "@/lib/utils"
interface PageTitleProps {
icon?: ReactNode
title: ReactNode
description?: ReactNode
/** Главные действия страницы — одна основная кнопка и не больше двух вторичных. */
actions?: ReactNode
className?: string
}
/** Заголовочный блок страницы макета v3: иконка, h1, описание и действия справа. */
export function PageTitle({ icon, title, description, actions, className }: PageTitleProps) {
return (
<div className={cn("flex min-w-0 flex-wrap items-start justify-between gap-3", className)}>
<div className="flex min-w-0 items-center gap-3">
{icon ? (
<IconTile variant="outline" aria-hidden="true" className="text-muted-foreground shrink-0">
{icon}
</IconTile>
) : null}
<div className="flex min-w-0 flex-col gap-0.5">
<h1 className="text-xl font-semibold">{title}</h1>
{description ? <p className="text-muted-foreground text-sm">{description}</p> : null}
</div>
</div>
{actions ? (
<div role="group" aria-label="Действия страницы" className="flex flex-wrap items-center gap-2">
{actions}
</div>
) : null}
</div>
)
}
+240
View File
@@ -0,0 +1,240 @@
"use client"
import { useId, type ComponentProps, type ReactNode } from "react"
import Link from "next/link"
import { Frame, FramePanel } from "@/components/reui/frame"
import { Badge } from "@/components/reui/badge"
import { IconTile } from "@/components/reui/icon-tile"
import { cn } from "@/lib/utils"
/** Тон состояния из макета v3: ok — в норме, wn — внимание, er — сбой, in — инфо, mu — нет данных. */
export type Tone = "ok" | "wn" | "er" | "in" | "mu"
export const TONE_COLOR: Record<Tone, string> = {
ok: "var(--success)",
wn: "var(--warning)",
er: "var(--destructive)",
in: "var(--chart-4)",
mu: "var(--muted-foreground)",
}
const TONE_BADGE = {
ok: "success-light",
wn: "warning-light",
er: "destructive-light",
in: "info-light",
mu: "outline",
} as const
const TONE_MARK: Record<Tone, string | null> = { ok: "●", wn: "▲", er: "✕", in: null, mu: "○" }
/** Чип состояния макета: светлый Badge с маркером тона (форма дублирует цвет). */
export function ToneBadge({ tone, size = "sm", mark = true, className, children }: {
tone: Tone
size?: "sm" | "default" | "lg"
mark?: boolean
className?: string
children: ReactNode
}) {
const glyph = mark ? TONE_MARK[tone] : null
return (
<Badge variant={TONE_BADGE[tone]} size={size} className={cn("shrink-0", className)}>
{glyph ? <span aria-hidden="true" className="text-[0.5rem] leading-none">{glyph}</span> : null}
{children}
</Badge>
)
}
/** Точка состояния 8px. */
export function ToneDot({ tone, className }: { tone: Tone; className?: string }) {
return <span aria-hidden="true" className={cn("size-2 shrink-0 rounded-full", className)} style={{ background: TONE_COLOR[tone] }} />
}
interface SectionFrameProps extends Omit<ComponentProps<"section">, "title"> {
title?: ReactNode
description?: ReactNode
icon?: ReactNode
actions?: ReactNode
/** Без внутренней панели: дети сами рендерят FramePanel и полосы под шапкой. */
bare?: boolean
panelClassName?: string
}
/**
* Секция макета v3: Frame с шапкой (иконка, заголовок, описание, действия) и одной панелью.
* @see https://reui.io/docs/components/base/frame
*/
export function SectionFrame({ title, description, icon, actions, bare, panelClassName, className, children, ...props }: SectionFrameProps) {
const headingId = useId()
return (
<section aria-labelledby={title ? headingId : undefined} className={cn("min-w-0", className)} {...props}>
<Frame className="gap-1 bg-muted/40 p-1 [--frame-radius:calc(var(--radius)*1.6)] *:data-[slot=frame-panel]:rounded-[calc(var(--radius)*1.25)]">
{title ? (
<div className="flex flex-wrap items-center gap-3 px-2.5 pt-2 pb-1.5">
{icon ? <IconTile variant="outline" size="sm" aria-hidden="true" className="text-muted-foreground">{icon}</IconTile> : null}
<div className="min-w-0 flex-[1_1_200px]">
<h2 id={headingId} className="text-sm font-semibold">{title}</h2>
{description ? <p className="text-muted-foreground mt-px text-[0.78rem]">{description}</p> : null}
</div>
{actions ? <div className="flex flex-wrap items-center gap-2">{actions}</div> : null}
</div>
) : null}
{bare ? children : <FramePanel className={cn("p-0", panelClassName)}>{children}</FramePanel>}
</Frame>
</section>
)
}
/** Сегментная шкала заполнения: 40 делений, заполненные — цветом тона. */
export function SegmentMeter({ ratio, tone, segments = 40, label }: { ratio: number; tone: Tone; segments?: number; label: string }) {
const filled = Math.round(Math.min(1, Math.max(0, ratio)) * segments)
return (
<div role="img" aria-label={label} className="flex h-5 gap-[3px]">
{Array.from({ length: segments }, (_, i) => (
<span key={i} className="flex-1 rounded-full bg-muted" style={i < filled ? { background: TONE_COLOR[tone] } : undefined} />
))}
</div>
)
}
export type CapacityItem = {
id: string
title: string
caption: ReactNode
/** null — значение неизвестно, показывается «—». */
value: number | null
total: number | null
/** Доля заполнения шкалы 0–1; по умолчанию value/total. */
ratio?: number
tone: Tone
icon: ReactNode
href?: string
/** Подпись значения вместо числа (например «2,9»), unit — вместо «из M» (например «ТБ»). */
valueText?: string
unit?: string
}
function pct(ratio: number) {
return `${Math.round(ratio * 100)}%`
}
/**
* Ряд ёмкости «N из M» с сегментной шкалой (блок cap макета v3).
* @see https://reui.io/preview/base/stats-12
*/
export function CapacityGrid({ items, label }: { items: CapacityItem[]; label: string }) {
return (
<SectionFrame aria-label={label} panelClassName="grid grid-cols-1 gap-px bg-border xl:grid-cols-3">
{items.map((item) => {
const known = item.value != null && item.total != null
const ratio = item.ratio ?? (known && item.total! > 0 ? item.value! / item.total! : 0)
const body = (
<>
<div className="flex items-center gap-3">
<IconTile variant="elevated" aria-hidden="true">{item.icon}</IconTile>
<div className="min-w-0">
<h3 className="text-sm font-medium">{item.title}</h3>
<p className="text-muted-foreground text-xs">{item.caption}</p>
</div>
</div>
<div className="flex flex-col gap-3">
<div className="flex items-baseline justify-between">
<p className="flex items-baseline">
<span className="text-2xl font-semibold tracking-tight tabular-nums">{known ? item.valueText ?? item.value : "—"}</span>
{known ? <span className="text-muted-foreground ml-1.5 text-sm">{item.unit ?? `из ${item.total}`}</span> : null}
</p>
{known ? <span className="text-sm font-medium tabular-nums">{pct(ratio)}</span> : null}
</div>
<SegmentMeter ratio={known ? ratio : 0} tone={item.tone} label={`${item.title}: ${known ? `${item.valueText ?? item.value} ${item.unit ?? `из ${item.total}`}` : "нет данных"}`} />
</div>
</>
)
const cell = "bg-card flex min-w-0 flex-col gap-6 p-5"
return item.href ? (
<Link key={item.id} href={item.href} className={cn(cell, "hover:bg-muted/30 focus-visible:ring-ring transition-colors outline-none focus-visible:ring-2 focus-visible:ring-inset")}>
{body}
</Link>
) : (
<div key={item.id} className={cell}>{body}</div>
)
})}
</SectionFrame>
)
}
/** Мини-график 76×32 без осей (k4 sparkline макета). */
export function Sparkline({ values, className }: { values: number[]; className?: string }) {
const finite = values.filter(Number.isFinite)
if (finite.length < 2) return null
const min = Math.min(...finite)
const max = Math.max(...finite)
const span = max - min || 1
const points = finite
.map((v, i) => `${(2 + (i * 72) / (finite.length - 1)).toFixed(1)},${(30 - ((v - min) / span) * 26).toFixed(1)}`)
.join(" ")
return (
<svg viewBox="0 0 76 32" aria-hidden="true" className={cn("absolute top-5 right-4 h-8 w-[76px]", className)}>
<polyline fill="none" stroke="var(--muted-foreground)" strokeWidth="1.5" strokeLinejoin="round" points={points} />
</svg>
)
}
export type SparkKpiItem = {
id: string
title: string
value: ReactNode
unit?: string
series?: number[]
delta?: { text: string; tone: Tone } | null
footnote?: ReactNode
href?: string
}
/** Изменение за окно ряда: «↗ 1,2%», тон по направлению (рост — ok, падение — er, если не задано иначе). */
export function seriesDelta(series: number[] | undefined, upTone: Tone = "ok", downTone: Tone = "er"): SparkKpiItem["delta"] {
const finite = (series ?? []).filter(Number.isFinite)
if (finite.length < 2) return null
const first = finite[0]
const last = finite[finite.length - 1]
if (first === 0) return null
const change = ((last - first) / Math.abs(first)) * 100
const text = `${change >= 0 ? "↗" : "↘"} ${Math.abs(change).toLocaleString("ru-RU", { maximumFractionDigits: 1 })}%`
return { text, tone: change >= 0 ? upTone : downTone }
}
/**
* Четыре KPI со спарклайном и чипом изменения (блок spark макета v3).
* @see https://reui.io/preview/base/stats-12
*/
export function SparkKpiGrid({ items, label }: { items: SparkKpiItem[]; label: string }) {
return (
<SectionFrame aria-label={label} panelClassName="grid grid-cols-1 gap-px bg-border sm:grid-cols-2 xl:grid-cols-4">
{items.map((item) => {
const body = (
<>
{item.series ? <Sparkline values={item.series} /> : null}
<div className="pr-24">
<div className="text-xl font-semibold tabular-nums">
{item.value}
{item.unit ? <span className="text-muted-foreground/40 pl-0.5 font-semibold">{item.unit}</span> : null}
</div>
<h3 className="text-muted-foreground mt-0.5 text-xs leading-none font-normal">{item.title}</h3>
</div>
<div className="text-muted-foreground mt-5 flex items-center gap-2 text-xs">
{item.delta ? <ToneBadge tone={item.delta.tone} mark={false}>{item.delta.text}</ToneBadge> : null}
{item.footnote ? <span className="min-w-0 truncate">{item.footnote}</span> : null}
</div>
</>
)
const cell = "bg-card relative block min-h-[102px] overflow-hidden p-4"
return item.href ? (
<Link key={item.id} href={item.href} className={cn(cell, "hover:bg-muted/30 focus-visible:ring-ring transition-colors outline-none focus-visible:ring-2 focus-visible:ring-inset")}>
{body}
</Link>
) : (
<div key={item.id} className={cell}>{body}</div>
)
})}
</SectionFrame>
)
}
+20 -2
View File
@@ -1,6 +1,7 @@
"use client"
import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts"
import { useState } from "react"
import { CartesianGrid, Line, LineChart, ReferenceLine, XAxis, YAxis } from "recharts"
import { Frame, FramePanel } from "@/components/reui/frame"
import { ChartContainer, ChartTooltip, type ChartConfig } from "@/components/ui/chart"
import { fmtRate, formatRangeAgo, TRAFFIC_RANGE_MINUTES } from "@/lib/fmt-rate"
@@ -59,6 +60,7 @@ function toChartData(rx: (number|null)[], tx: (number|null)[], rangeMinutes: num
return Array.from({ length: n }, (_, i) => {
const minutesAgo = Math.round((1 - i / denom) * rangeMinutes)
return {
index: i,
time: formatRangeAgo(minutesAgo),
rx: typeof rx[i] === "number" && Number.isFinite(rx[i]) && rx[i] >= 0 ? rx[i] : null,
tx: typeof tx[i] === "number" && Number.isFinite(tx[i]) && tx[i] >= 0 ? tx[i] : null,
@@ -72,6 +74,7 @@ export function TrafficRxTxChart({
range = "1h",
rangeMinutes: actualMinutes,
embedded = false,
scrub = false,
}: {
rx: (number|null)[]
tx: (number|null)[]
@@ -79,9 +82,13 @@ export function TrafficRxTxChart({
rangeMinutes?: number
/** Skip outer Frame when already inside OpsPanel / Frame. */
embedded?: boolean
scrub?: boolean
}) {
const rangeMinutes = actualMinutes ?? TRAFFIC_RANGE_MINUTES[range] ?? 60
const data = toChartData(rx, tx, rangeMinutes)
const [selected, setSelected] = useState<number>()
const index = Math.min(selected ?? data.length - 1, data.length - 1)
const point = data[index]
const tickEvery = Math.max(1, Math.ceil(data.length / 6))
const hasRx = data.some(point => point.rx !== null)
@@ -105,7 +112,8 @@ export function TrafficRxTxChart({
stroke="var(--border)"
/>
<XAxis
dataKey="time"
dataKey="index"
tickFormatter={(value: number) => data[value]?.time ?? ""}
axisLine={false}
tickLine={false}
tick={{ fontSize: 11 }}
@@ -121,6 +129,7 @@ export function TrafficRxTxChart({
width={72}
/>
<ChartTooltip content={<CustomTooltip />} />
{scrub && selected !== undefined && <ReferenceLine x={index} stroke="var(--muted-foreground)" />}
{hasRx && <Line
dataKey="rx"
type="monotone"
@@ -141,6 +150,15 @@ export function TrafficRxTxChart({
<ChartLegendItem label="RX (входящий)" color="var(--chart-rx)" />
<ChartLegendItem label="TX (исходящий)" color="var(--chart-tx)" />
</div>
{scrub && data.length > 1 && <div className="grid gap-2 border-t pt-2 text-xs">
<label className="flex flex-wrap items-center gap-2 text-muted-foreground">
Точка на графике
<input type="range" className="min-w-24 flex-1 accent-primary" min={0} max={data.length - 1} value={index}
aria-valuetext={`${point.time} · RX ${fmtRate(point.rx)} · TX ${fmtRate(point.tx)}`}
onChange={event => setSelected(Number(event.target.value))} />
</label>
<p className="font-mono tabular-nums">{point.time} · RX {fmtRate(point.rx)} · TX {fmtRate(point.tx)}</p>
</div>}
</div>
)
@@ -1,7 +1,8 @@
"use client"
import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts"
import { Frame, FramePanel } from "@/components/reui/frame"
import type { ReactNode } from "react"
import { SectionFrame } from "@/components/reui-kit/ops-blocks"
import { ChartContainer, ChartTooltip, type ChartConfig } from "@/components/ui/chart"
import { formatBytes } from "@/lib/fmt-rate"
import type { StatisticsSeriesPoint } from "@mmapp/contracts/statistics"
@@ -45,9 +46,14 @@ function CustomTooltip({
export function StatisticsVolumeChart({
series,
grain,
scope,
actions,
}: {
series: StatisticsSeriesPoint[]
grain: "hour" | "day"
/** Какие плоскости в объёме, для подписи под заголовком. */
scope?: string
actions?: ReactNode
}) {
const data = series.map((p) => ({
t: p.t,
@@ -57,14 +63,12 @@ export function StatisticsVolumeChart({
const tickEvery = Math.max(1, Math.ceil(data.length / 8))
return (
<Frame className="w-full">
<FramePanel className="flex flex-col gap-4">
<div className="flex items-baseline justify-between gap-2">
<h2 className="text-sm font-medium">Объём по времени</h2>
<span className="text-muted-foreground text-xs">
{grain === "hour" ? "по часам" : "по суткам"}
</span>
</div>
<SectionFrame
title="Объём по времени"
description={[scope, grain === "hour" ? "по часам" : "по суткам"].filter(Boolean).join(" · ")}
actions={actions}
panelClassName="px-3.5 pt-3.5 pb-2"
>
{data.length === 0 ? (
<p className="text-muted-foreground py-10 text-center text-sm">Нет данных за выбранный период</p>
) : (
@@ -99,7 +103,6 @@ export function StatisticsVolumeChart({
</AreaChart>
</ChartContainer>
)}
</FramePanel>
</Frame>
</SectionFrame>
)
}
+64 -45
View File
@@ -1,7 +1,8 @@
"use client"
import { useEffect, useMemo, useState, type ReactNode } from "react"
import { Activity, Filter, HeartPulse, Server } from "lucide-react"
import Link from "next/link"
import { Activity, ArrowRightIcon, Filter, HeartPulse, Server } from "lucide-react"
import { Badge } from "@/components/reui/badge"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
@@ -151,7 +152,15 @@ export function SystemMonitorPopover() {
[apiOk, filtersCount, healthOk, monitoringCount, serversCount],
)
const spiking = metrics.some((m) => m.alert)
// Проблемы для «Состояния системы» — только подтверждённые сигналы: API и сводка.
const items: Array<{ id: string; tone: "er" | "wn"; title: string; text: string }> = []
if (healthOk === false) items.push({ id: "api", tone: "er", title: "API MikrotikManager не отвечает", text: "GET /health вернул ошибку или не ответил" })
if (data?.countsError) items.push({ id: "counts", tone: "wn", title: "Сводка не обновлена", text: data.countsError })
const errors = items.filter((i) => i.tone === "er").length
const warnings = items.length - errors
const okCount = metrics.length - items.length
const label = errors ? "Сбой" : warnings ? "Внимание" : healthOk == null ? "Нет данных" : "Норма"
const tone = errors ? "destructive" : warnings || healthOk == null ? "warning" : "success"
return (
<Popover>
@@ -159,63 +168,73 @@ export function SystemMonitorPopover() {
render={
<button
type="button"
aria-label="Монитор системы"
aria-label={`Состояние системы: ${label.toLowerCase()}, сбоев ${errors}, предупреждений ${warnings}`}
className={cn(
"relative inline-flex h-8 items-center gap-1.5 rounded-md border px-2 transition-colors outline-none",
"border-border hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",
"relative inline-flex h-8 items-center gap-2 rounded-md border px-2 text-sm font-medium transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring max-[760px]:w-8 max-[760px]:justify-center max-[760px]:border-transparent max-[760px]:bg-transparent max-[760px]:px-0",
tone === "destructive" && "border-destructive/40 bg-destructive/10 hover:bg-destructive/20 aria-expanded:bg-destructive/20",
tone === "warning" && "border-warning/40 bg-warning/10 hover:bg-warning/20 aria-expanded:bg-warning/20",
tone === "success" && "border-border hover:bg-accent aria-expanded:bg-accent",
)}
/>
}
>
<span className="relative flex size-3.5 items-center justify-center">
<Activity
aria-hidden
className={cn(
"size-3.5 transition-colors",
spiking ? "text-destructive" : "text-muted-foreground",
)}
/>
{spiking ? (
<span className="bg-destructive/25 absolute inset-0 animate-ping rounded-full" aria-hidden />
) : null}
<Activity aria-hidden className={cn("size-4", tone === "destructive" ? "text-destructive" : tone === "warning" ? "text-warning" : "text-success")} />
<span className={cn("hidden min-[1000px]:inline", tone === "destructive" ? "text-destructive-foreground" : tone === "warning" ? "text-warning-foreground" : "text-foreground")}>{label}</span>
<span className="hidden items-center gap-1.5 tabular-nums min-[1240px]:inline-flex">
<span className="bg-destructive size-1.5 rounded-full" aria-hidden />
{errors}
<span className="bg-warning size-1.5 rounded-full" aria-hidden />
{warnings}
</span>
<span className="text-foreground hidden text-xs font-medium sm:inline">Система</span>
<Badge
variant={spiking ? "destructive-light" : apiOk?"success-light":"outline"}
size="xs"
className={cn("h-4 px-1.5 text-[10px]",apiOk&&"text-emerald-700 dark:text-emerald-400",spiking&&"text-red-700 dark:text-red-400")}
>
{spiking?"Нет связи":apiOk?"API доступен":"Нет данных"}
</Badge>
{items.length ? <span className="bg-destructive ring-background absolute top-1 right-1 size-2 rounded-full ring-2 min-[760px]:hidden" aria-hidden /> : null}
</PopoverTrigger>
<PopoverContent align="end" sideOffset={8} className="flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-0! p-0!">
<div className="border-border flex items-center justify-between border-b px-3 py-2.5">
<span className="text-foreground text-xs font-medium">Монитор MikrotikManager</span>
<span className="text-muted-foreground text-[11px] tabular-nums">
{mode!=="live"?"Демо":data?.receivedAt?new Date(data.receivedAt).toLocaleTimeString("ru-RU"):"Снимок не получен"}
</span>
<PopoverContent align="end" sideOffset={8} className="flex w-[24rem] max-w-[calc(100vw-1.5rem)] flex-col gap-2 p-2">
<div className="flex items-start justify-between gap-2 px-1.5 pt-1.5">
<div className="grid leading-tight">
<b className="text-sm font-semibold">Состояние системы</b>
<span className="text-muted-foreground text-xs">
{mode !== "live" ? "Демо-данные" : data?.receivedAt ? `обновлено ${new Date(data.receivedAt).toLocaleTimeString("ru-RU")}` : "Снимок не получен"}
</span>
</div>
<Badge variant={errors ? "destructive-light" : warnings ? "warning-light" : "success-light"} size="sm" className={cn(!errors && !warnings && "text-emerald-700 dark:text-emerald-400", errors && "text-red-700 dark:text-red-400")}>{label}</Badge>
</div>
{data?.countsError?<p role="status" className="px-3 py-2 text-xs text-muted-foreground">{data.countsError}</p>:null}
<div className="grid grid-cols-2">
<div className="grid grid-cols-3 gap-1.5">
{[
{ n: errors, l: "сбой", c: "text-destructive-foreground" },
{ n: warnings, l: "предупреждения", c: "text-warning-foreground" },
{ n: Math.max(0, okCount), l: "в норме", c: "text-success-foreground" },
].map((x) => (
<span key={x.l} className="bg-muted/55 text-muted-foreground flex flex-col rounded-lg px-2.5 py-2 text-xs">
<b className={cn("text-lg leading-tight font-semibold tabular-nums", x.c)}>{x.n}</b>
{x.l}
</span>
))}
</div>
{items.length ? (
<div role="status"><ul className="flex flex-col gap-0.5">
{items.map((m) => (
<li key={m.id} className="flex items-center gap-2.5 rounded-md px-1.5 py-2">
<span aria-hidden className={cn("size-2 shrink-0 rounded-full", m.tone === "er" ? "bg-destructive" : "bg-warning")} />
<span className="grid min-w-0 flex-1 leading-tight">
<b className="truncate text-[13px] font-medium">{m.title}</b>
<span className="text-muted-foreground truncate text-xs">{m.text}</span>
</span>
</li>
))}
</ul></div>
) : null}
<div className="grid grid-cols-2 overflow-hidden rounded-lg border">
{metrics.map((metric, i) => (
<div
key={metric.id}
className={cn(
i % 2 === 1 && "border-border border-l",
i >= 2 && "border-border border-t",
)}
>
<div key={metric.id} className={cn(i % 2 === 1 && "border-l", i >= 2 && "border-t")}>
<MetricCell metric={metric} />
</div>
))}
</div>
<div className="border-border text-muted-foreground border-t px-3 py-2 text-[11px]">
Источник:{" "}
<span className="text-foreground font-medium">
{mode === "live" ? "API" : "мок"}
</span>
</div>
<Link href="/uptime" className="text-muted-foreground hover:text-foreground flex items-center justify-between px-1.5 pt-1 pb-0.5 text-sm">
Мониторинг
<ArrowRightIcon className="size-3.5" aria-hidden />
</Link>
</PopoverContent>
</Popover>
)
+22 -15
View File
@@ -21,6 +21,7 @@ import {
DATA_GRID_CELL_PAD_LAST,
} from "@/components/data-grids/shared/data-grid-layout"
import { TrafficFlowsDataGrid } from "@/components/data-grids/traffic-flows-data-grid"
import { matchesMapService } from "@/lib/flow-map-service-match"
import { FlowTrafficMap } from "@/components/traffic/flow-traffic-map"
import { StatusDot } from "@/components/status-dot"
import { Flag } from "@/components/flag"
@@ -74,22 +75,22 @@ export function FlowEntityCardView({
<StatusDot status={card.status} />
<span className="text-xs font-medium truncate">{card.name}</span>
</div>
<span className="text-[10px] font-mono text-muted-foreground shrink-0 flex items-center gap-1">
<span className="text-xs font-mono text-muted-foreground shrink-0 flex items-center gap-1">
{card.country !== "UN" ? <Flag code={card.country} /> : null}
{card.site}
</span>
</div>
<TrafficMiniChart rx={card.rxSeries} tx={card.txSeries} />
<div className="flex justify-between mt-2 gap-2">
<div className="flex items-center gap-1 text-[11px]">
<div className="flex items-center gap-1 text-xs">
<ArrowDownIcon className="size-3 text-success" />
<span className="font-mono font-medium text-success">{fmtRate(card.rxNow)}</span>
</div>
<div className="flex items-center gap-1 text-[11px]">
<div className="flex items-center gap-1 text-xs">
<ArrowUpIcon className="size-3 text-info" />
<span className="font-mono font-medium text-info">{fmtRate(card.txNow)}</span>
</div>
<div className="flex items-center gap-0.5 text-[10px] text-muted-foreground">
<div className="flex items-center gap-0.5 text-xs text-muted-foreground">
<GitBranchIcon className="size-3" />{card.sessions}
</div>
</div>
@@ -103,13 +104,14 @@ type BreakdownFilter = {
label: string
serverId?: string
}
type SessionFilter = BreakdownFilter | { kind: "path"; path: FlowPathRow; label: string }
type SessionFilter = BreakdownFilter | { kind: "path"; path: FlowPathRow; label: string } | { kind: "map-service"; label: string; country?: string }
function talkerMatchesFilter(row: FlowTalkerDto, filter: SessionFilter): boolean {
switch (filter.kind) {
case "application": return row.application === filter.value
case "category": return row.category === filter.value
case "service": return row.service === filter.value
case "map-service": return matchesMapService(row, filter.label, filter.country)
case "asn": return String(row.dstAsn ?? "unknown") === filter.value
case "country": return (!filter.serverId || row.serverId === filter.serverId) && (row.dstCountry || "unknown") === filter.value
case "protocol": return row.protoName === filter.value
@@ -265,7 +267,7 @@ function FlowPathsGrid({
cell: ({ row }) => (
<span className="flex min-w-0 flex-col gap-0.5 text-xs">
<span className="font-mono">{row.original.dst}</span>
<span className="text-[10px] text-muted-foreground truncate">
<span className="text-xs text-muted-foreground truncate">
{[row.original.category, row.original.service].filter(Boolean).join(" · ")}
</span>
</span>
@@ -329,6 +331,9 @@ export function FlowAnalyticsDetail({
onExcludeOverlay,
liveHint,
emptyHint,
initialService,
initialCountry,
mapNodes,
}: {
card: (Pick<FlowEntityCard, "id" | "name" | "country" | "site"> & Partial<FlowEntityCard>) | null
analytics: FlowAnalyticsDto | null
@@ -349,14 +354,16 @@ export function FlowAnalyticsDetail({
onExcludeOverlay: (value: boolean) => void
liveHint?: string
emptyHint?: string
initialService?: string
initialCountry?: string
mapNodes?: string[]
}) {
const [slice, setSlice] = useState("applications")
const [sessionFilter, setSessionFilter] = useState<SessionFilter | null>(null)
const [slice, setSlice] = useState(initialService ? "sessions" : "applications")
const [sessionFilter, setSessionFilter] = useState<SessionFilter | null>(initialService ? { kind: "map-service", label: initialService, country: initialCountry } : null)
const rxNow = analytics ? analytics.bpsNow / 1_000_000 : (card?.rxNow ?? 0)
const bytes = analytics?.bytes ?? card?.bytes ?? 0
const sessionRows = (analytics?.conversationsList ?? []).filter((row) =>
sessionFilter ? talkerMatchesFilter(row, sessionFilter) : true,
)
const sessionRows = (analytics?.conversationsList ?? []).filter(row =>
(!mapNodes || mapNodes.includes(row.enId || row.serverId)) && (!sessionFilter || talkerMatchesFilter(row, sessionFilter)))
function pickBreakdown(kind: BreakdownFilter["kind"], row: FlowBreakdownRow) {
setSessionFilter({ kind, value: row.id, label: row.label })
@@ -445,12 +452,12 @@ export function FlowAnalyticsDetail({
{analytics?.ifaces && analytics.ifaces.length > 0 ? (
<div className="mb-3 pb-3 border-b">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[11px] text-muted-foreground mr-1">Интерфейс:</span>
<span className="text-xs text-muted-foreground mr-1">Интерфейс:</span>
<button
type="button"
onClick={() => onIface("__all__")}
className={cn(
"inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-[10px] font-medium transition-all",
"inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs font-medium transition-all",
selectedIface === "__all__"
? "bg-foreground text-background border-foreground"
: "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40",
@@ -466,7 +473,7 @@ export function FlowAnalyticsDetail({
type="button"
onClick={() => onIface(iface.name)}
className={cn(
"inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[10px] font-medium transition-all",
"inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-xs font-medium transition-all",
active
? "bg-foreground text-background border-foreground"
: "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40",
@@ -477,7 +484,7 @@ export function FlowAnalyticsDetail({
)
})}
</div>
<p className="text-[10px] text-muted-foreground mt-1.5">по iface, без дедупа</p>
<p className="text-xs text-muted-foreground mt-1.5">по iface, без дедупа</p>
</div>
) : null}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 129 KiB

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 181 KiB

After

Width:  |  Height:  |  Size: 169 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 146 KiB

After

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 129 KiB

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

After

Width:  |  Height:  |  Size: 147 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.4 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 159 KiB

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

After

Width:  |  Height:  |  Size: 53 KiB

+23 -2
View File
@@ -7,6 +7,7 @@ import {
greTunnels as mockGreTunnels,
pingProbes,
servers as mockServers,
systemEvents as mockEvents,
traffic as mockTraffic,
vxlanTunnels as mockVxlan,
type GreTunnel,
@@ -581,6 +582,25 @@ export function useDashboardLive() {
}))
}, [enabledProbes])
// Демо-режим: события и Internet path из моков, чтобы раздел выглядел как с данными.
const [mockNow] = useState(() => Date.now())
const mockRecentEvents = useMemo<EventItem[]>(() => {
const unit: Record<string, number> = { м: 60_000, ч: 3_600_000, д: 86_400_000 }
return mockEvents.map((event) => {
const match = /^(d+)([мчд])$/.exec(event.when)
const ago = match ? Number(match[1]) * unit[match[2]] : 0
return {
id: event.id, title: event.title, message: event.message,
level: event.sev === "destructive" ? "critical" : event.sev === "warning" ? "warning" : "info",
sourceModule: "system", eventType: "demo", createdAt: new Date(mockNow - ago).toISOString(),
entityId: null, entityType: null, payload: {},
} as EventItem
})
}, [mockNow])
const mockInternetPath = useMemo(() => buildDashboardInternetPath({
servers: mockServers, greTunnels: mockGreTunnels, probes: [], filtersRulesets: [], routeLookupByServerId: {}, wanRuntimeByHomeId: {},
}), [])
const onlineCount = servers.filter((s) => s.status === "online").length
const probeDown = enabledProbes.filter((p) => p.status === "down").length
const probeWarn = enabledProbes.filter((p) => p.status === "warn").length
@@ -622,6 +642,7 @@ export function useDashboardLive() {
},
servers,
activeProbes,
enabledProbes,
overlay,
bgp: isLive ? bgp : { prefixSum: 8432, establishedCount: 3 },
traffic,
@@ -635,10 +656,10 @@ export function useDashboardLive() {
probeCount: enabledProbes.length,
unknownProbeCount:enabledProbes.filter(p=>p.status==="unknown").length,
latency,
recentEvents,
recentEvents: !prefsHydrated ? [] : isLive ? recentEvents : mockRecentEvents,
eventsLoading,
eventsError,
internetPath,
internetPath: !prefsHydrated ? null : isLive ? internetPath : mockInternetPath,
internetPathLoading: isLive && internetPathLoading && !internetPath,
internetPathError,
attentionServers,
-70
View File
@@ -1,70 +0,0 @@
"use client"
import { useEffect, useState } from "react"
import { isTrafficLiveSample } from "@/hooks/use-traffic-live"
import { requestJson } from "@/shared/api/http-client"
export interface GreTrafficTarget {
edgeId: string
serverId: string
iface: string
}
type Rate = { bps: number; bpsFwd: number; bpsRev: number; receivedAt: number }
const MAX_CONCURRENT_READS = 4
const REFRESH_MS = 8_000
const MAX_SAMPLE_AGE_MS = 30_000
export function useMapGreTraffic(backendUrl: string, targets: GreTrafficTarget[]) {
const key = JSON.stringify(targets)
const [snapshot, setSnapshot] = useState<{ backendUrl: string; key: string; rates: Map<string, Rate> }>()
useEffect(() => {
const scope: GreTrafficTarget[] = JSON.parse(key)
if (!scope.length) return
const controller = new AbortController()
let timer: ReturnType<typeof setTimeout>
const run = async () => {
if (document.hidden) {
timer = setTimeout(run, REFRESH_MS)
return
}
for (let offset = 0; offset < scope.length && !controller.signal.aborted; offset += MAX_CONCURRENT_READS) {
const batch = await Promise.all(scope.slice(offset, offset + MAX_CONCURRENT_READS).map(async ({ edgeId, serverId, iface }) => {
try {
const query = new URLSearchParams({ iface, once: "1" })
const sample = await requestJson<unknown>(backendUrl, `/api/traffic/servers/${encodeURIComponent(serverId)}/live?${query}`, {
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(6_000)]),
cache: "no-store",
})
if (isTrafficLiveSample(sample)) {
const bpsFwd = sample.rxMbps * 1_000_000
const bpsRev = sample.txMbps * 1_000_000
return { edgeId, rate: { bps: bpsFwd + bpsRev, bpsFwd, bpsRev, receivedAt: Date.now() } }
}
} catch {
// One unavailable interface cannot hide readings on other links.
}
return { edgeId }
}))
if (controller.signal.aborted) return
setSnapshot(previous => {
const rates = new Map(previous?.key === key && previous.backendUrl === backendUrl ? previous.rates : [])
for (const { edgeId, rate } of batch) {
if (rate) rates.set(edgeId, rate)
else rates.delete(edgeId)
}
return { backendUrl, key, rates }
})
}
if (!controller.signal.aborted) timer = setTimeout(run, REFRESH_MS)
}
void run()
return () => { controller.abort(); clearTimeout(timer) }
}, [backendUrl, key])
return (edgeId: string) => {
const rate = snapshot?.key === key && snapshot.backendUrl === backendUrl ? snapshot.rates.get(edgeId) : undefined
return rate && Date.now() - rate.receivedAt <= MAX_SAMPLE_AGE_MS ? rate : undefined
}
}
+96
View File
@@ -0,0 +1,96 @@
"use client"
import { useEffect, useState } from "react"
import { isTrafficLiveSample, type TrafficLiveSample } from "@/hooks/use-traffic-live"
import { requestJson } from "@/shared/api/http-client"
export interface MapTrafficTarget {
edgeId: string
serverId: string
iface: string
}
type Rate = { bps: number; bpsFwd: number; bpsRev: number; at: string; receivedAt: number }
const MAX_CONCURRENT_READS = 4
const REFRESH_MS = 8_000
const MAX_SAMPLE_AGE_MS = 30_000
export function isFreshMapTrafficSample(sample: unknown, now = Date.now()): sample is TrafficLiveSample {
return isTrafficLiveSample(sample) && Math.abs(now - Date.parse(sample.at)) <= MAX_SAMPLE_AGE_MS
}
export function useMapInterfaceTraffic(backendUrl: string, targets: MapTrafficTarget[]) {
const key = JSON.stringify(targets)
const [snapshot, setSnapshot] = useState<{ backendUrl: string; key: string; rates: Map<string, Rate> }>()
useEffect(() => {
const scope: MapTrafficTarget[] = JSON.parse(key)
if (!scope.length) return
const servers = new Map<string, Map<string, string[]>>()
for (const { edgeId, serverId, iface } of scope) {
const interfaces = servers.get(serverId) ?? new Map<string, string[]>()
interfaces.set(iface, [...(interfaces.get(iface) ?? []), edgeId])
servers.set(serverId, interfaces)
}
const requests = [...servers].flatMap(([serverId, interfaces]) => {
const entries = [...interfaces]
return Array.from({ length: Math.ceil(entries.length / 16) }, (_, i) => ({
serverId, entries: entries.slice(i * 16, (i + 1) * 16),
}))
})
const controller = new AbortController()
let timer: ReturnType<typeof setTimeout>
const run = async () => {
if (document.hidden) {
timer = setTimeout(run, REFRESH_MS)
return
}
for (let offset = 0; offset < requests.length && !controller.signal.aborted; offset += MAX_CONCURRENT_READS) {
const batch = await Promise.all(requests.slice(offset, offset + MAX_CONCURRENT_READS).map(async ({ serverId, entries }) => {
const single = entries.length === 1
let samples: Record<string, unknown> = {}
try {
const names = entries.map(([iface]) => iface).join(",")
const query = new URLSearchParams({ [single ? "iface" : "ifaces"]: names, once: "1" })
const response = await requestJson<{ interfaces?: Record<string, unknown> }>(backendUrl, `/api/traffic/servers/${encodeURIComponent(serverId)}/live?${query}`, {
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(9_000)]),
cache: "no-store",
})
samples = single ? { [names]: response } : response?.interfaces ?? {}
} catch {
// Other routers can still return fresh samples.
}
return entries.flatMap(([iface, edgeIds]) => {
const sample = samples[iface]
const receivedAt = Date.now()
const rate = isFreshMapTrafficSample(sample, receivedAt) ? {
bps: (sample.rxMbps + sample.txMbps) * 1_000_000,
bpsFwd: sample.rxMbps * 1_000_000,
bpsRev: sample.txMbps * 1_000_000,
at: sample.at,
receivedAt,
} : undefined
return edgeIds.map(edgeId => ({ edgeId, rate }))
})
}))
if (controller.signal.aborted) return
setSnapshot(previous => {
const rates = new Map(previous?.key === key && previous.backendUrl === backendUrl ? previous.rates : [])
for (const { edgeId, rate } of batch.flat()) {
if (rate) rates.set(edgeId, rate)
else rates.delete(edgeId)
}
return { backendUrl, key, rates }
})
}
if (!controller.signal.aborted) timer = setTimeout(run, REFRESH_MS)
}
void run()
return () => { controller.abort(); clearTimeout(timer) }
}, [backendUrl, key])
return (edgeId: string) => {
const rate = snapshot?.key === key && snapshot.backendUrl === backendUrl ? snapshot.rates.get(edgeId) : undefined
return rate && Date.now() - Math.min(rate.receivedAt, Date.parse(rate.at)) <= MAX_SAMPLE_AGE_MS ? rate : undefined
}
}
+7
View File
@@ -0,0 +1,7 @@
import type { FlowTalkerDto } from "@mmapp/contracts/traffic-flow"
export function matchesMapService(row: Pick<FlowTalkerDto, "service" | "category" | "dstCountry">, label: string, country?: string) {
const service = row.service === label || row.category === label && (row.service === "Прочее" || ["DNS", "SSH", "BGP"].includes(label))
if (!service || !country) return service
return country === "unknown" ? !row.dstCountry || row.dstCountry.toLowerCase() === "unknown" : row.dstCountry?.toUpperCase() === country.toUpperCase()
}
+4
View File
@@ -43,3 +43,7 @@ export function formatServicePathTitle(label: string, serviceLabel: string): str
if (label.includes(svc)) return label
return `${label} · ${svc}`
}
export function servicePathKey(p: { clientId: string; viaId: string; viaIface?: string; enId: string; serviceId: string }): string {
return JSON.stringify([p.clientId, p.viaId, p.viaIface, p.enId, p.serviceId])
}
+1
View File
@@ -18,6 +18,7 @@ export interface GreSpeedProbeSnapshot {
lastRxAvgMbps?: number | null
lastPingAt?: string | null
lastPingRttMs?: number | null
lastPingLossPct?: number | null
}
export type GreTunnelProbeEdge = {
+5
View File
@@ -51,6 +51,11 @@ export function formatNetflowDir(hop: Pick<MatchedNetflowHop, "bpsFwd" | "bpsRev
return `↓${formatNetflowRate({ bps: hop.bpsFwd })} ↑${formatNetflowRate({ bps: hop.bpsRev })}`
}
export function formatMapFlowWindow(windowSec: number): string {
const seconds = Math.floor(windowSec % 60)
return `${Math.floor(windowSec / 60)} мин${seconds ? ` ${seconds} с` : ""}`
}
/** GRE rates use RX/TX at the tunnel owner, regardless of its position on the map. */
function greInterfaceObservation(
tunnel: { name: string; serverId: string },
+1
View File
@@ -2,4 +2,5 @@ import {test} from "node:test"
import assert from "node:assert/strict"
import {fitNetworkMapCamera} from "./network-map-camera"
test("camera fits off-world nodes and labels across aspect ratios",()=>{for(const h of [580,1600]){const points=[{x:-200,y:50},{x:1000,y:700}],c=fitNetworkMapCamera(points,1240,h);for(const p of points){assert.ok(p.x>=c.pan.x+119);assert.ok(p.x<=c.pan.x+1240/c.zoom-119);assert.ok(p.y>=c.pan.y+99);assert.ok(p.y<=c.pan.y+h/c.zoom-99)}}})
test("camera keeps objects above the bottom overlay band",()=>{const points=[{x:0,y:0},{x:1000,y:600}],c=fitNetworkMapCamera(points,1240,900,.25);for(const p of points)assert.ok(p.y<=c.pan.y+(900*.75)/c.zoom-99)})
test("empty/invalid positions and maximum initial zoom",()=>{assert.deepEqual(fitNetworkMapCamera([],1240,580),{pan:{x:0,y:0},zoom:1});assert.deepEqual(fitNetworkMapCamera([{x:NaN,y:1}],1240,580),{pan:{x:0,y:0},zoom:1});assert.equal(fitNetworkMapCamera([{x:1,y:1}],1240,1600).zoom,3)})
+5 -3
View File
@@ -1,8 +1,10 @@
export interface MapPoint {x:number;y:number}
export function fitNetworkMapCamera(points:readonly MapPoint[],width:number,height:number) {
/** bottomReserve — доля высоты снизу под панель масштаба и миникарту: объекты вписываются над ней. */
export function fitNetworkMapCamera(points:readonly MapPoint[],width:number,height:number,bottomReserve=0) {
const valid=points.filter(p=>Number.isFinite(p.x)&&Number.isFinite(p.y))
if(!valid.length||width<=0||height<=0)return {pan:{x:0,y:0},zoom:1}
const xs=valid.map(p=>p.x),ys=valid.map(p=>p.y),left=Math.min(...xs)-120,right=Math.max(...xs)+120,top=Math.min(...ys)-100,bottom=Math.max(...ys)+100
const zoom=Math.max(.2,Math.min(3,width/(right-left),height/(bottom-top)))
return {pan:{x:(left+right)/2-width/(2*zoom),y:(top+bottom)/2-height/(2*zoom)},zoom}
const usable=height*(1-Math.min(.6,Math.max(0,bottomReserve)))
const zoom=Math.max(.2,Math.min(3,width/(right-left),usable/(bottom-top)))
return {pan:{x:(left+right)/2-width/(2*zoom),y:(top+bottom)/2-usable/(2*zoom)},zoom}
}
+171 -44
View File
@@ -37,14 +37,130 @@ export function greTunnelProbe(t: GreTunnel, demo = false): TunnelProbe {
}
const W = 1240
const H = 580
const MARGIN = 72
const SERVICE_COL_W = 150
export { SERVICE_COL_W }
const H = 640
/** Карточка конечного сервиса на карте (центр = позиция узла). */
export const MAP_SERVICE_NODE_W = 86
export const MAP_SERVICE_NODE_H = 58
/**
* Полосы карты макета v3 слева направо: Home Router · WAN · JumpHost · Exit (и IX) · назначения.
* x0/x1 — границы полосы на холсте, cx — центр карточек.
*/
export const MAP_LANES = {
home: { x0: 8, x1: 215, cx: 112 },
wan: { x0: 215, x1: 425, cx: 320 },
jh: { x0: 425, x1: 660, cx: 542 },
en: { x0: 660, x1: 900, cx: 780 },
dest: { x0: 900, x1: 1232, cx: 1080 },
} as const
/** Карточка устройства (HR/JH/EN/IX) и «таблетка» WAN-аплинка. */
export const MAP_CARD_W = 160
export const MAP_CARD_H = 56
export const MAP_WAN_W = 150
export const MAP_WAN_H = 44
/** Строка назначения; в раскрытой стране обе колонки компактные. */
export const MAP_SERVICE_NODE_W = 280
export const MAP_SERVICE_NODE_H = 48
export const MAP_SERVICE_COMPACT_W = 150
/** Сдвиг колонки стран влево, когда справа раскрыты сервисы одной страны. */
export const SERVICE_COL_W = 130
const NESTED_SERVICE_X = 1160
const MIN_NODE_Y = 80
const MAX_NODE_Y = H - 44
/**
* Плавная связь между боковыми гранями двух карточек: горизонтальная кривая Безье, как в макете.
* Если карточки в одной полосе — дуга справа от обеих.
*/
export function mapLinkPath(
a: { x: number; y: number }, aHalfW: number,
b: { x: number; y: number }, bHalfW: number,
): MapLink {
if (Math.abs(b.x - a.x) < aHalfW + bHalfW) {
const x1 = a.x + aHalfW, x2 = b.x + bHalfW, bend = Math.max(x1, x2) + 48
return { d: `M ${x1} ${a.y} C ${bend} ${a.y} ${bend} ${b.y} ${x2} ${b.y}`, x1, y1: a.y, x2, y2: b.y, cx: bend }
}
const dir = b.x > a.x ? 1 : -1
const x1 = a.x + dir * aHalfW, x2 = b.x - dir * bHalfW, mx = (x1 + x2) / 2
return { d: `M ${x1} ${a.y} C ${mx} ${a.y} ${mx} ${b.y} ${x2} ${b.y}`, x1, y1: a.y, x2, y2: b.y, cx: mx }
}
/** Связь карты: путь и опорные точки кривой (cx — x обеих управляющих точек). */
export interface MapLink { d: string; x1: number; y1: number; x2: number; y2: number; cx: number }
/** Точка кривой связи при параметре t ∈ [0, 1]. */
export function mapLinkPoint(l: MapLink, t: number): { x: number; y: number } {
const u = 1 - t, a = u * u * u, b = 3 * u * u * t, c = 3 * u * t * t, d = t * t * t
return { x: a * l.x1 + (b + c) * l.cx + d * l.x2, y: (a + b) * l.y1 + (c + d) * l.y2 }
}
/** Прямоугольник на холсте (левый верхний угол и размеры). */
export interface MapBox { x: number; y: number; w: number; h: number }
/** Подпись связи макета v3: «таблетка» 20 px, Geist Mono 11 px. */
export const MAP_PILL_H = 20
export const mapPillWidth = (text: string) => Math.round(text.length * 6.6 + 16)
const boxesHit = (a: MapBox, b: MapBox) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
/** Сначала середина кривой (как в макете), затем ближе к концам. */
const LABEL_T = [0.5, 0.42, 0.58, 0.34, 0.66, 0.27, 0.73]
/**
* Раскладка подписей связей без наложений: каждая подпись ставится на свою кривую в первое свободное место —
* не поверх карточек и других подписей. `texts` — варианты от полного к короткому; если не влезает ни один,
* подпись не рисуется (значение остаётся в aria-label связи и в панели деталей).
*/
export function placeMapLinkLabels<T extends { id: string; link: MapLink; texts: string[] }>(
labels: T[],
obstacles: MapBox[],
gap = 4,
): Array<T & { x: number; y: number; w: number; text: string }> {
const taken = obstacles.map((o) => ({ x: o.x - gap, y: o.y - gap, w: o.w + gap * 2, h: o.h + gap * 2 }))
const out: Array<T & { x: number; y: number; w: number; text: string }> = []
for (const label of labels) {
search: for (const text of label.texts) {
const w = mapPillWidth(text)
for (const t of LABEL_T) {
const p = mapLinkPoint(label.link, t)
const box = { x: p.x - w / 2, y: p.y - MAP_PILL_H / 2, w, h: MAP_PILL_H }
if (taken.some((o) => boxesHit(box, o))) continue
taken.push({ x: box.x - gap, y: box.y - gap, w: w + gap * 2, h: MAP_PILL_H + gap * 2 })
out.push({ ...label, x: Math.round(p.x), y: Math.round(p.y), w, text })
break search
}
}
}
return out
}
/**
* Ленты NetFlow (Sankey) макета v3: толщина — скорость, ленты одного узла уложены стопкой у его края,
* без подписей. Самая толстая стопка у узла — `maxPx`.
*/
export function mapRibbons<T extends { from: { x: number; y: number }; fromHalfW: number; to: { x: number; y: number }; toHalfW: number; bps: number }>(
flows: T[],
maxPx = 36,
): Array<T & { d: string; w: number }> {
const key = (p: { x: number; y: number }) => `${Math.round(p.x)},${Math.round(p.y)}`
const sum = (m: Map<string, number>, k: string, v: number) => m.set(k, (m.get(k) ?? 0) + v)
const outs = new Map<string, number>(), ins = new Map<string, number>()
for (const f of flows) { sum(outs, key(f.from), Math.max(0, f.bps)); sum(ins, key(f.to), Math.max(0, f.bps)) }
const peak = Math.max(0, ...outs.values(), ...ins.values())
const rows = flows.map((f) => ({ f, w: Math.max(1.5, peak > 0 ? (Math.max(0, f.bps) / peak) * maxPx : 1.5), sy: 0, ty: 0 }))
const stack = (side: "from" | "to", other: "from" | "to", y: "sy" | "ty") => {
const groups = new Map<string, typeof rows>()
for (const r of rows) groups.set(key(r.f[side]), [...(groups.get(key(r.f[side])) ?? []), r])
for (const group of groups.values()) {
group.sort((a, b) => a.f[other].y - b.f[other].y)
let cum = group[0].f[side].y - group.reduce((s, r) => s + r.w, 0) / 2
for (const r of group) { r[y] = cum + r.w / 2; cum += r.w }
}
}
stack("from", "to", "sy")
stack("to", "from", "ty")
return rows.map(({ f, w, sy, ty }) => {
const x1 = f.from.x + f.fromHalfW, x2 = f.to.x - f.toHalfW, cx = Math.round((x1 + x2) / 2)
return { ...f, w: Number(w.toFixed(1)), d: `M ${x1} ${sy.toFixed(1)} C ${cx} ${sy.toFixed(1)} ${cx} ${ty.toFixed(1)} ${x2} ${ty.toFixed(1)}` }
})
}
/** Одна горизонтальная «полка» на карте: Home → JH → Exit слева направо. */
export const NETWORK_MAP_PIPELINE_Y = 300
@@ -79,7 +195,7 @@ function layerOfServer(s: Server): number | null {
*/
export const NETWORK_MAP_W = W
export const NETWORK_MAP_H = H
export const NETWORK_MAP_LAYOUT_REVISION = 7
export const NETWORK_MAP_LAYOUT_REVISION = 8
export interface WanJhEdge {
homeId: string
@@ -266,9 +382,12 @@ export function computeNetworkMapLayout(
const nodePos: Record<string, { x: number; y: number }> = {}
const wanSatPos: Record<string, { x: number; y: number }[]> = {}
const span = W - 2 * MARGIN - SERVICE_COL_W
const laneGap = Math.min(44, span * 0.04)
const laneW = (span - 2 * laneGap) / 3
const laneCenterX: Record<ServerType, number> = {
"home-router": MAP_LANES.home.cx,
"jump-host": MAP_LANES.jh.cx,
"exit-node": MAP_LANES.en.cx,
"ix-node": MAP_LANES.en.cx,
}
// Жёсткое позиционирование по иерархическим слоям:
// - HR: левая полоса (0–20%),
@@ -277,9 +396,9 @@ export function computeNetworkMapLayout(
const laneOrder: ServerType[] = ["home-router", "jump-host", "exit-node"]
if (servers.some(server => server.type === "ix-node")) laneOrder.splice(2, 0, "ix-node")
const laneByType = new Map<ServerType, Server[]>()
const minNodeY = MARGIN + 70
const maxNodeY = H - 72
const laneMinGap = 110
const minNodeY = MIN_NODE_Y
const maxNodeY = MAX_NODE_Y
const laneMinGap = MAP_CARD_H + 18
const typeYOffset: Record<ServerType, number> = {
"home-router": -14,
"jump-host": 0,
@@ -309,7 +428,6 @@ export function computeNetworkMapLayout(
siteY.set(site, spreadInSegment(siteNames.length, i, minNodeY, maxNodeY))
})
const fallbackY = (minNodeY + maxNodeY) / 2
let xLane = MARGIN
for (const type of laneOrder) {
const group = servers
.filter((s) => s.type === type)
@@ -317,22 +435,17 @@ export function computeNetworkMapLayout(
.sort((a, b) => `${a.site}|${a.name}|${a.id}`.localeCompare(`${b.site}|${b.name}|${b.id}`))
laneByType.set(type, group)
const xMin = xLane
const xMax = xLane + laneW
const laneCenterX = (xMin + xMax) / 2
group.forEach((s) => {
const baseline = siteY.get(s.site) ?? fallbackY
const siblings = group.filter((g) => g.site === s.site)
const sibIdx = siblings.findIndex((g) => g.id === s.id)
const spread = siblings.length <= 1 ? 0 : (sibIdx - (siblings.length - 1) / 2) * 34
nodePos[s.id] = {
x: laneCenterX,
x: laneCenterX[type],
y: clamp(baseline + typeYOffset[type] + spread, minNodeY, maxNodeY),
}
})
xLane += laneW + laneGap
}
const homes = laneByType.get("home-router") ?? []
@@ -412,30 +525,41 @@ export function computeNetworkMapLayout(
resolveLaneCollisions(exits.map((s) => s.id), nodePos, minNodeY, maxNodeY, laneMinGap)
}
// IX-узлы делят полосу Exit: разводим их вместе с EN, чтобы карточки не наезжали.
const ixs = laneByType.get("ix-node") ?? []
if (ixs.length) resolveLaneCollisions([...exits, ...ixs].map((s) => s.id), nodePos, minNodeY, maxNodeY, laneMinGap)
const hr = homes
/** Центр колонки jump-host — спутники WAN ставим на X между HR и JH (как на схеме «шлюз → провайдеры → JH»). */
const jhColumnCenterX = MARGIN + laneW + laneGap + laneW / 2
for (const r of hr) {
const wans = r.wanUplinks?.length ? r.wanUplinks : []
const base = nodePos[r.id] ?? { x: W / 2, y: NETWORK_MAP_PIPELINE_Y }
const n = wans.length
const satX = (base.x + jhColumnCenterX) / 2
const satX = MAP_LANES.wan.cx
const rowY = base.y
const maxV = H - 2 * MARGIN - 96
// Разносим WAN-аплинки по высоте заметнее для читаемости подписей/бейджей.
const preferredGap = 140
const maxV = MAX_NODE_Y - MIN_NODE_Y
// Своя полоса WAN: «таблетки» аплинков друг под другом напротив роутера.
const preferredGap = MAP_WAN_H + 46
const vGap =
n <= 1 ? 0 : Math.min(preferredGap, maxV / Math.max(1, n - 1))
const positions: { x: number; y: number }[] = []
for (let i = 0; i < n; i++) {
const rawY = n === 1 ? rowY : rowY + (i - (n - 1) / 2) * vGap
const y = Math.max(MARGIN + 48, Math.min(H - 72, rawY))
const y = Math.max(MIN_NODE_Y, Math.min(MAX_NODE_Y, rawY))
positions.push({ x: satX, y })
}
wanSatPos[r.id] = positions
}
// Аплинки всех роутеров делят одну полосу: раздвигаем «таблетки», чтобы не наезжали друг на друга.
const sats = Object.values(wanSatPos).flat().sort((a, b) => a.y - b.y)
for (let i = 1; i < sats.length; i++) {
const min = sats[i - 1].y + MAP_WAN_H + 12
if (sats[i].y < min) sats[i].y = min
}
const overflow = (sats[sats.length - 1]?.y ?? 0) - MAX_NODE_Y
if (overflow > 0) for (const p of sats) p.y = Math.max(MIN_NODE_Y, p.y - overflow)
return { nodePos, wanSatPos }
}
@@ -446,13 +570,13 @@ export function placeServiceNodes(
): Record<string, { x: number; y: number }> {
const out: Record<string, { x: number; y: number }> = {}
if (serviceIds.length === 0) return out
const minY = MARGIN + 70
const maxY = H - 72
const x = W - MARGIN - SERVICE_COL_W / 2
const minY = MIN_NODE_Y
const maxY = MAX_NODE_Y
const x = MAP_LANES.dest.cx
const enYs = enPositions.map((p) => p.y).filter((y) => Number.isFinite(y))
const centerY = enYs.length ? enYs.reduce((a, b) => a + b, 0) / enYs.length : (minY + maxY) / 2
const n = serviceIds.length
const gap = Math.min(96, (maxY - minY) / Math.max(1, n))
const gap = Math.min(MAP_SERVICE_NODE_H + 14, (maxY - minY) / Math.max(1, n))
const span = gap * (n - 1)
const start = clamp(centerY - span / 2, minY, maxY - span)
serviceIds.forEach((id, i) => {
@@ -468,11 +592,11 @@ export function placeCountryServiceNodes(
): Record<string, { x: number; y: number }> {
const out: Record<string, { x: number; y: number }> = {}
if (serviceIds.length === 0 || !parentPos) return out
const minY = MARGIN + 70
const maxY = H - 72
const x = W - MARGIN - SERVICE_COL_W / 2
const minY = MIN_NODE_Y
const maxY = MAX_NODE_Y
const x = NESTED_SERVICE_X
const n = serviceIds.length
const gap = Math.min(80, (maxY - minY) / Math.max(1, n))
const gap = Math.min(MAP_SERVICE_NODE_H + 8, (maxY - minY) / Math.max(1, n))
const span = gap * (n - 1)
const start = clamp(parentPos.y - span / 2, minY, maxY - span)
serviceIds.forEach((id, i) => {
@@ -786,6 +910,7 @@ function greEndpointAnchor(
export interface GreMapEdge {
tunnel: GreTunnel
peerTunnel?: GreTunnel
ambiguousPeerKey?: string
from: { x: number; y: number }
to: { x: number; y: number }
fromServer: Server
@@ -835,17 +960,16 @@ export function buildGreMapEdges(
if (!a || !b) continue
if (a.id === b.id) continue
const la = layerOfServer(a)
const lb = layerOfServer(b)
if (la == null || lb == null) continue
// EN→EN, JH→JH и т.п. на карте не показываем — только межуровневые рёбра.
if (la === lb) continue
const aIsIx = a.type === "ix-node", bIsIx = b.type === "ix-node"
const la = aIsIx ? roleLayer("EN") : layerOfServer(a)
const lb = bIsIx ? roleLayer("EN") : layerOfServer(b)
if (la == null || lb == null || la === lb && !aIsIx && !bIsIx) continue
// Строгий поток слева направо: HR → JH → EN.
// Если направление туннеля против иерархии — переворачиваем визуальное ребро.
let fromServer = a
let toServer = b
if (la > lb) {
if (la > lb || la === lb && a.id > b.id) {
fromServer = b
toServer = a
}
@@ -858,8 +982,11 @@ export function buildGreMapEdges(
if (group) group.push(edge)
else links.set(key, [edge])
}
return [...links.values()].flatMap(group => {
if (group.length !== 2 || group[0].tunnel.serverId === group[1].tunnel.serverId) return group
return [...links.entries()].flatMap(([key, group]) => {
if (group.length !== 2 || group[0].tunnel.serverId === group[1].tunnel.serverId) {
return group.some(edge => edge.tunnel.serverId !== group[0].tunnel.serverId)
? group.map(edge => ({ ...edge, ambiguousPeerKey: key })) : group
}
const [one, two] = group
const [edge, peer] = tunnelPriority(two.tunnel) > tunnelPriority(one.tunnel) ? [two, one] : [one, two]
return [{ ...edge, peerTunnel: peer.tunnel }]
+4
View File
@@ -45,6 +45,10 @@ test("map Flow envelope retains zeros and refuses missing metadata and contradic
assert.throws(()=>networkMapFlowSchema.parse({...shorter,sourceWindow:{requestedMinutes:15,effectiveMinutes:2}}))
assert.throws(()=>networkMapFlowSchema.parse({...shorter,rangeMinutes:1,windowSec:60}))
assert.throws(()=>networkMapFlowSchema.parse({...shorter,windowSec:300}))
const recent={...empty,rangeMinutes:1,windowSec:90.125,includesCurrentMinute:true}
assert.equal(networkMapFlowSchema.parse(recent).windowSec,90.125)
assert.throws(()=>networkMapFlowSchema.parse({...recent,windowSec:120}))
assert.throws(()=>networkMapFlowSchema.parse({...recent,includesCurrentMinute:undefined}))
})
test("map DNS matches exactly requested names and accepts explicit unresolved null",()=>{
assert.deepEqual(validateNetworkMapDns({results:{"router.example":null}},["router.example"]),{"router.example":null})
+6 -5
View File
@@ -27,11 +27,12 @@ export function validateNetworkMapSnapshot(servers:unknown,gre:unknown,probes:un
import {flowMapHopsDtoSchema} from "@mmapp/contracts/traffic-flow"
import {isIpv4String} from "./gre-endpoint-resolve"
export const networkMapFlowSchema = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true }).refine(data =>
(data.sourceWindow
? data.sourceWindow.requestedMinutes === 5 && data.sourceWindow.effectiveMinutes === data.rangeMinutes
: data.rangeMinutes === 5) &&
data.windowSec === data.rangeMinutes * 60 &&
export const networkMapFlowSchema = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true, includesCurrentMinute: true, nodeUsers: true }).refine(data =>
(data.includesCurrentMinute
? !data.sourceWindow && data.rangeMinutes === 1 && data.windowSec >= 60 && data.windowSec < 120
: data.windowSec === data.rangeMinutes * 60 && (data.sourceWindow
? data.sourceWindow.requestedMinutes === 5 && data.sourceWindow.effectiveMinutes === data.rangeMinutes
: data.rangeMinutes === 5)) &&
data.namedBytes <= data.totalBytes && data.unclassifiedBytes <= data.totalBytes
)
export function validateNetworkMapDns(raw:unknown,hosts:string[]){
+64
View File
@@ -0,0 +1,64 @@
import type { FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
import type { Server } from "@/lib/data"
export function isolatedIxServers(servers: Pick<Server, "id" | "type">[], links: readonly (readonly [string, string])[]) {
const neighbors = new Map<string, string[]>()
for (const [from, to] of links) {
neighbors.set(from, [...(neighbors.get(from) ?? []), to])
neighbors.set(to, [...(neighbors.get(to) ?? []), from])
}
const connected = new Set(servers.filter(server => server.type === "jump-host" || server.type === "exit-node").map(server => server.id))
for (const id of connected) for (const neighbor of neighbors.get(id) ?? []) connected.add(neighbor)
return new Set(servers.filter(server => server.type === "ix-node" && !connected.has(server.id)).map(server => server.id))
}
export function scopeMapDestinations(
services: FlowMapService[], edges: FlowMapServiceEdge[], paths: FlowMapServicePath[],
includes: (id: string) => boolean, userId?: string, retainUnassigned = false,
) {
const visiblePaths = paths.filter(path => includes(path.enId || path.viaId) && (!userId || path.clientId === userId))
const visibleEdges = userId ? [] : edges.filter(edge => includes(edge.fromId))
if (userId) {
const bySource = new Map<string, FlowMapServiceEdge>()
for (const path of visiblePaths) {
const fromId = path.enId || path.viaId
const key = JSON.stringify([fromId, path.serviceId, Boolean(path.enId)])
const edge = bySource.get(key) ?? {
fromId, toId: path.serviceId, bytes: 0, bps: 0, bpsFwd: 0, bpsRev: 0,
...(path.enId ? {} : { observedOnly: true as const }),
}
edge.bytes += path.bytes
edge.bps += path.bps
bySource.set(key, edge)
}
visibleEdges.push(...bySource.values())
}
const totals = new Map<string, { bytes: number; bps: number }>()
const allByService = new Map<string, number>()
if (retainUnassigned) for (const edge of edges) allByService.set(edge.toId, (allByService.get(edge.toId) ?? 0) + edge.bytes)
let bytes = 0
for (const edge of visibleEdges) {
const total = totals.get(edge.toId) ?? { bytes: 0, bps: 0 }
total.bytes += edge.bytes
total.bps += edge.bps
bytes += edge.bytes
totals.set(edge.toId, total)
}
if (retainUnassigned) for (const service of services) {
const unassigned = service.bytes - (allByService.get(service.id) ?? 0)
if (unassigned <= 0) continue
const total = totals.get(service.id) ?? { bytes: 0, bps: 0 }
total.bytes += unassigned
total.bps += service.bps * unassigned / service.bytes
bytes += unassigned
totals.set(service.id, total)
}
return {
services: services.flatMap(service => {
const total = totals.get(service.id)
return total ? [{ ...service, ...total, share: bytes ? total.bytes / bytes : 0 }] : []
}).sort((a, b) => b.bytes - a.bytes || a.label.localeCompare(b.label)),
edges: visibleEdges,
paths: visiblePaths,
}
}
+60
View File
@@ -0,0 +1,60 @@
import type { StatisticsBreakdownRow, StatisticsDto, StatisticsPivotDim, StatisticsPivotDto } from "@mmapp/contracts/statistics"
import { servers as mockServers } from "@/lib/data"
const GB = 1_000_000_000
function rows(items: Array<[string, string, number]>, total: number, seconds: number): StatisticsBreakdownRow[] {
return items.map(([id, label, gb]) => {
const bytes = gb * GB
return { id, label, bytes, packets: Math.round(bytes / 1200), bps: Math.round((bytes * 8) / seconds), percent: Math.round((bytes / total) * 1000) / 10 }
})
}
const DIM_ROWS: Record<StatisticsPivotDim, Array<[string, string, number]>> = {
country: [["US", "США", 1310], ["DE", "Германия", 720], ["NL", "Нидерланды", 540], ["FI", "Финляндия", 260], ["SE", "Швеция", 180]],
service: [["youtube", "YouTube", 1140], ["cloudflare", "Cloudflare", 690], ["microsoft", "Microsoft", 430], ["telegram", "Telegram", 260], ["aws", "AWS", 210]],
asn: [["15169", "AS15169 Google", 1160], ["13335", "AS13335 Cloudflare", 700], ["8075", "AS8075 Microsoft", 430], ["16509", "AS16509 Amazon", 230]],
server: mockServers.slice(0, 5).map((s, i): [string, string, number] => [s.id, s.name, [1480, 1120, 640, 420, 210][i] ?? 100]),
user: [["u1", "admin-laptop", 980], ["u2", "ivanov-phone", 720], ["u3", "office-gw", 610], ["u4", "petrova-pc", 380], ["u5", "guest-wifi", 210]],
iface: [["wg0", "wg0", 1120], ["wg1", "wg1", 760], ["gre-nov", "gre-nov", 540], ["gre-fra", "gre-fra", 380]],
} as Record<StatisticsPivotDim, Array<[string, string, number]>>
/** Демо-куб для режима без живого API: стабильные числа, масштаб по длине периода и плоскостям. */
export function demoStatistics(from: string, to: string, planes: "unique" | "all"): StatisticsDto {
const start = Date.parse(from + "T00:00:00Z")
const end = Date.parse(to + "T00:00:00Z")
const days = Number.isFinite(start) && Number.isFinite(end) ? Math.max(1, Math.round((end - start) / 86_400_000) + 1) : 7
const scale = (days / 7) * (planes === "all" ? 1.27 : 1)
const scaled = (items: Array<[string, string, number]>) => items.map(([id, label, gb]): [string, string, number] => [id, label, Math.round(gb * scale * 10) / 10])
const users = scaled(DIM_ROWS.user)
const total = users.reduce((sum, [, , gb]) => sum + gb, 0) * GB * 1.65
const seconds = days * 86_400
const series = Array.from({ length: days }, (_, i) => ({
t: new Date(start + i * 86_400_000).toISOString(),
bytes: Math.round((total / days) * (0.82 + 0.36 * Math.abs(Math.sin(i * 1.7)))),
}))
return {
from, to, grain: "day",
kpis: { bytes: total, packets: Math.round(total / 1200), avgBps: Math.round((total * 8) / seconds), users: users.length, servers: DIM_ROWS.server.length, ifaces: DIM_ROWS.iface.length, topCountry: "США", topService: "YouTube" },
series,
users: rows(users, total, seconds),
servers: rows(scaled(DIM_ROWS.server), total, seconds),
interfaces: rows(scaled(DIM_ROWS.iface), total, seconds),
countries: rows(scaled(DIM_ROWS.country), total, seconds),
services: rows(scaled(DIM_ROWS.service), total, seconds),
asns: rows(scaled(DIM_ROWS.asn), total, seconds),
}
}
/** Демо-сводная: строки и колонки из тех же списков, ячейка — доля строки по весу колонки. */
export function demoStatisticsPivot(rowDim: StatisticsPivotDim, colDim: StatisticsPivotDim): StatisticsPivotDto {
const rowItems = DIM_ROWS[rowDim] ?? []
const colItems = DIM_ROWS[colDim] ?? []
const colWeight = colItems.reduce((sum, [, , gb]) => sum + gb, 0) || 1
const outRows = rowItems.map(([id, label, gb]) => {
const cells = Object.fromEntries(colItems.map(([cid, , cgb]) => [cid, Math.round(gb * (cgb / colWeight) * GB)]))
return { id, label, total: gb * GB, cells }
})
const columns = colItems.map(([id, label]) => ({ id, label, total: outRows.reduce((sum, row) => sum + (row.cells[id] ?? 0), 0) }))
return { rowDim, colDim, metric: "bytes", columns, rows: outRows, otherBytes: 0 }
}
+11
View File
@@ -388,6 +388,7 @@ export const flowMapServiceEdgeDtoSchema = z.object({
id: z.string(),
name: z.string(),
})).optional(),
observedOnly: z.literal(true).optional(),
})
export const flowMapServicePathDtoSchema = z.object({
@@ -395,6 +396,8 @@ export const flowMapServicePathDtoSchema = z.object({
clientName: z.string(),
viaId: z.string(),
viaName: z.string(),
viaIface: z.string().optional(),
/** Empty when IPFIX identified the exporter but the exit could not be inferred. */
enId: z.string(),
enName: z.string(),
serviceId: z.string(),
@@ -412,6 +415,13 @@ export const flowMapCountryServiceGroupDtoSchema = z.object({
export const flowMapHopsDtoSchema = z.object({
sourceWindow: flowSourceWindowSchema.optional(),
nodeUsers: z.record(z.string(), z.array(z.object({
clientId: z.string(),
clientName: z.string(),
bytes: z.number().nonnegative(),
bps: z.number().nonnegative(),
}))).optional(),
includesCurrentMinute: z.literal(true).optional(),
/** Link counters include private routed payload. Mesh visibility applies to the inferred graph. */
interfaceTraffic: z.array(z.object({
serverId: z.string(), iface: z.string(),
@@ -462,3 +472,4 @@ export type FlowMapServicePath = z.infer<typeof flowMapServicePathDtoSchema>
export type FlowMapCountryServiceGroup = z.infer<typeof flowMapCountryServiceGroupDtoSchema>
export type FlowMapHopsDto = z.infer<typeof flowMapHopsDtoSchema>
export type FlowMapInterfaceTraffic = NonNullable<FlowMapHopsDto["interfaceTraffic"]>[number]
export type FlowMapUser = NonNullable<FlowMapHopsDto["nodeUsers"]>[string][number]
+4 -2
View File
@@ -133,6 +133,7 @@ export async function getFlowMapHops(
excludeMesh?: boolean
excludeOverlay?: boolean
} = {},
init?: RequestInit,
): Promise<FlowMapHopsDto> {
return requestJson<FlowMapHopsDto>(baseUrl, `/api/traffic/flow/map-hops${flowQuery({
range: params.range ?? "5m",
@@ -142,7 +143,7 @@ export async function getFlowMapHops(
dedup: params.dedup,
excludeMesh: params.excludeMesh,
excludeOverlay: params.excludeOverlay,
})}`)
})}`, init)
}
export async function getFlowAnalytics(
@@ -156,8 +157,9 @@ export async function getFlowAnalytics(
excludeMesh?: boolean
excludeOverlay?: boolean
},
init?: RequestInit,
): Promise<FlowAnalyticsDto> {
return flowConfirmed(flowAnalyticsSchema, await requestJson<unknown>(baseUrl, `/api/traffic/flow/analytics${flowQuery(params)}`))
return flowConfirmed(flowAnalyticsSchema, await requestJson<unknown>(baseUrl, `/api/traffic/flow/analytics${flowQuery(params)}`, init))
}
export async function getFlowMonthly(
+6 -6
View File
@@ -20,14 +20,14 @@ for(const theme of ["dark","light"])for(const width of [320,1440])for(const path
})
test("Shell keyboard skip link moves focus to main and menus restore focus",async({page})=>{
await setup(page,"dark");await page.goto("/releases");await expect(page.getByText("Текущая версия",{exact:true})).toBeVisible();await page.keyboard.press("Tab");const skip=page.getByRole("link",{name:"К содержимому",exact:true});await expect(skip).toBeFocused();await page.keyboard.press("Enter");await expect(page.locator("#main-content")).toBeFocused()
const apps=page.getByRole("button",{name:"Приложения",exact:true});await apps.focus();await page.keyboard.press("Enter");await expect(page.getByRole("menu")).toBeVisible();await page.keyboard.press("Escape");await expect(apps).toBeFocused()
const monitor=page.getByRole("button",{name:"Монитор системы",exact:true});await monitor.focus();await page.keyboard.press("Enter");await expect(page.locator('[data-slot="popover-content"]')).toBeVisible();await page.keyboard.press("Escape");await expect(monitor).toBeFocused()
const apps=page.getByRole("button",{name:/^Переключатель приложений/});await apps.focus();await page.keyboard.press("Enter");await expect(page.getByRole("menu")).toBeVisible();await page.keyboard.press("Escape");await expect(apps).toBeFocused()
const monitor=page.getByRole("button",{name:/^Состояние системы/});await monitor.focus();await page.keyboard.press("Enter");await expect(page.locator('[data-slot="popover-content"]')).toBeVisible();await page.keyboard.press("Escape");await expect(monitor).toBeFocused()
})
test("System monitor recognizes confirmed legacy health consistently",async({page})=>{await setup(page,"dark");await page.route("**/health",r=>r.fulfill({json:{ok:true}}));await page.goto("/releases");await expect(page.getByRole("button",{name:"Монитор системы",exact:true})).toContainText("API доступен")})
test("System monitor recognizes confirmed legacy health consistently",async({page})=>{await setup(page,"dark");await page.route("**/health",r=>r.fulfill({json:{ok:true}}));await page.goto("/releases");await expect(page.getByRole("button",{name:/^Состояние системы/})).toContainText("Норма")})
for(const theme of ["dark","light"])for(const width of [320,1440])test("Open shell layers audit/"+theme+"/"+width,async({page},info)=>{
await setup(page,theme);await page.setViewportSize({width,height:900});await page.goto("/releases");await expect(page.getByRole("button",{name:"Монитор системы",exact:true})).toContainText("API доступен");await page.getByRole("button",{name:"Монитор системы",exact:true}).click();await expect(page.locator('[data-slot="popover-content"]')).toBeVisible();await page.addScriptTag({content:axe.source});
await setup(page,theme);await page.setViewportSize({width,height:900});await page.goto("/releases");await expect(page.getByRole("button",{name:/^Состояние системы/})).toContainText("Норма");await page.getByRole("button",{name:/^Состояние системы/}).click();await expect(page.locator('[data-slot="popover-content"]')).toBeVisible();await page.addScriptTag({content:axe.source});
const result=await page.evaluate(async()=>{const engine=(window as unknown as {axe:typeof axe}).axe;return engine.run('[data-slot="popover-content"]',{runOnly:{type:"tag",values:["wcag2a","wcag2aa","wcag21a","wcag21aa","wcag22aa"]}})});await info.attach("axe-open-monitor",{body:JSON.stringify(result,null,2),contentType:"application/json"});expect(result.violations.map(v=>({id:v.id,nodes:v.nodes.map(n=>({target:n.target,html:n.html,summary:n.failureSummary}))}))).toEqual([]);
await page.screenshot({path:"docs/ux-ui/screens/shell-monitor-"+theme+"-"+width+".png",animations:"disabled"});await page.keyboard.press("Escape");await page.getByRole("button",{name:"Приложения",exact:true}).click();await expect(page.getByRole("menu")).toBeVisible();await settleAnimations(page);const menu=await page.evaluate(async()=>{const engine=(window as unknown as {axe:typeof axe}).axe;return engine.run('[role="menu"]',{runOnly:{type:"tag",values:["wcag2a","wcag2aa","wcag21a","wcag21aa","wcag22aa"]}})});expect(menu.violations.map(v=>({id:v.id,nodes:v.nodes.map(n=>({target:n.target,html:n.html,summary:n.failureSummary}))}))).toEqual([]);
await page.screenshot({path:"docs/ux-ui/screens/shell-monitor-"+theme+"-"+width+".png",animations:"disabled"});await page.keyboard.press("Escape");if(width<768)await page.getByRole("button",{name:"Боковое меню",exact:true}).click();await page.getByRole("button",{name:/^Переключатель приложений/}).click();await expect(page.getByRole("menu")).toBeVisible();await settleAnimations(page);const menu=await page.evaluate(async()=>{const engine=(window as unknown as {axe:typeof axe}).axe;return engine.run('[role="menu"]',{runOnly:{type:"tag",values:["wcag2a","wcag2aa","wcag21a","wcag21aa","wcag22aa"]}})});expect(menu.violations.map(v=>({id:v.id,nodes:v.nodes.map(n=>({target:n.target,html:n.html,summary:n.failureSummary}))}))).toEqual([]);
})
for(const theme of ["dark","light"])test("Unconfirmed health remains unavailable/"+theme,async({page})=>{await setup(page,theme);await page.route("**/health",r=>r.fulfill({json:{ok:false,status:"unknown"}}));await page.goto("/releases");await expect(page.getByRole("button",{name:"Монитор системы",exact:true})).toContainText("Нет связи")})
for(const theme of ["dark","light"])test("Unconfirmed health remains unavailable/"+theme,async({page})=>{await setup(page,theme);await page.route("**/health",r=>r.fulfill({json:{ok:false,status:"unknown"}}));await page.goto("/releases");await expect(page.getByRole("button",{name:/^Состояние системы/})).toContainText("Сбой")})
+26 -29
View File
@@ -51,15 +51,9 @@ test("Дашборд: очередь над измерениями, полный
await setup(page, false, 7)
await expect(refresh(page)).toBeEnabled()
const queue = page.getByRole("region", { name: "Требует внимания", exact: true })
await expect(queue.getByText("7", { exact: true })).toBeVisible()
await expect(queue.getByRole("tab", { name: /^Все \d+$/ })).toBeVisible()
const serverLinks = queue.getByRole("link", { name: /^Узел \d/ })
await expect(serverLinks).toHaveCount(5)
const more = queue.locator("summary").filter({ hasText: "Ещё 2" })
await more.focus()
await more.press("Enter")
await expect(serverLinks).toHaveCount(7)
await more.press("Enter")
await expect(serverLinks).toHaveCount(5)
const queueBox = await queue.boundingBox()
const measurementBox = await page.getByText("Задержка до серверов", { exact: true }).boundingBox()
expect(queueBox!.y + queueBox!.height).toBeLessThan(measurementBox!.y)
@@ -80,7 +74,10 @@ test("Дашборд: очередь над измерениями, полный
test("Дашборд: первоначальная ошибка не подменяется нулями и исправным состоянием", async ({ page }) => {
const control = await setup(page, true)
await expect(refresh(page)).toBeEnabled()
await expect(page.getByText("Не обновлены источники: 9", { exact: true }).first()).toBeVisible()
await expect(page.getByText("Не все источники доступны.", { exact: true })).toBeVisible()
await page.getByRole("button", { name: "Объяснить", exact: true }).click()
await expect(page.getByRole("tab", { name: /^Источники и время получения/ })).toHaveAttribute("aria-selected", "true")
await expect(page.getByText("Не обновлены источники: 9", { exact: true })).toBeVisible()
await expect(page.getByRole("link").filter({ hasText: "Серверы онлайн" })).toContainText("—")
await expect(bgp(page)).toContainText("—")
await expect(page.getByText("Серверы без проблем", { exact: true })).toHaveCount(0)
@@ -88,7 +85,7 @@ test("Дашборд: первоначальная ошибка не подме
control.failed = false
await refresh(page).click()
await expect(bgp(page)).toContainText("321")
await expect(page.getByText("Не обновлены источники: 9", { exact: true })).toHaveCount(0)
await expect(page.getByText("Не все источники доступны.", { exact: true })).toHaveCount(0)
})
test("Дашборд: частичный сбой сохраняет данные, события и время последнего успеха", async ({ page }) => {
@@ -99,12 +96,12 @@ test("Дашборд: частичный сбой сохраняет данны
const receivedAt = await source.locator("time").getAttribute("datetime")
control.partial = true
await refresh(page).click()
await expect(source).toContainText("ошибка обновления")
await expect(source).toContainText(/ошибка обновления/i)
await expect(source.locator("time")).toHaveAttribute("datetime", receivedAt!)
await expect(bgp(page)).toContainText("321")
await expect(page.getByText("Событие сохранено", { exact: true })).toBeVisible()
await expect(page.getByText("GRE сохранён", { exact: true })).toBeVisible()
await expect(page.locator('[data-source="servers"]')).not.toContainText("ошибка")
await expect(page.locator('[data-source="servers"]')).not.toContainText(/ошибка/i)
await page.screenshot({ path: "test-results/dashboard-data-desktop.png", fullPage: true })
await page.setViewportSize({ width: 390, height: 844 })
await expect(source).toBeVisible()
@@ -113,7 +110,7 @@ test("Дашборд: частичный сбой сохраняет данны
control.prefixes = 654
await refresh(page).click()
await expect(bgp(page)).toContainText("654")
await expect(page.getByText(/Не обновлены источники:/)).toHaveCount(0)
await expect(page.getByText("Не все источники доступны.", { exact: true })).toHaveCount(0)
})
test("Дашборд: поздний ответ не заменяет свежие данные при фоновом обновлении", async ({ page }) => {
@@ -209,50 +206,50 @@ test('Сквозная приёмка: проблема → опрос серв
for(const broken of ["missing","partial","duplicate","counter","conflict"])test("Dashboard strict BGP unknown and last good/"+broken,async({page})=>{
const sessions=[bgpSession()],failure={serverId:2,serverName:"Узел без ответа",error:"timeout"};const payload=broken==="missing"?{sessions:[]}:broken==="partial"?{sessions,failures:[failure]}:broken==="duplicate"?{sessions:[...sessions,...sessions],failures:[]}:broken==="counter"?{sessions:[bgpSession(1,-1)],failures:[]}:{sessions,failures:[{...failure,serverId:1}]};
const control=await setup(page,false,1,payload);const source=page.locator('[data-source="bgp"]');await expect(refresh(page)).toBeEnabled();await expect(source).toContainText("ошибка");await expect(bgp(page)).toContainText("—");
control.bgpPayload=undefined;await refresh(page).click();await expect(bgp(page)).toContainText("321");const receivedAt=await source.locator("time").getAttribute("datetime");control.bgpPayload=payload;await refresh(page).click();await expect(source).toContainText("ошибка обновления");await expect(source.locator("time")).toHaveAttribute("datetime",receivedAt!);await expect(bgp(page)).toContainText("321");await expect(page.locator('[data-source="servers"]')).not.toContainText("ошибка");
control.bgpPayload=undefined;control.prefixes=999;await refresh(page).click();await expect(bgp(page)).toContainText("999");await expect(source).not.toContainText("ошибка");
const control=await setup(page,false,1,payload);const source=page.locator('[data-source="bgp"]');await expect(refresh(page)).toBeEnabled();await expect(source).toContainText(/ошибка/i);await expect(bgp(page)).toContainText("—");
control.bgpPayload=undefined;await refresh(page).click();await expect(bgp(page)).toContainText("321");const receivedAt=await source.locator("time").getAttribute("datetime");control.bgpPayload=payload;await refresh(page).click();await expect(source).toContainText(/ошибка обновления/i);await expect(source.locator("time")).toHaveAttribute("datetime",receivedAt!);await expect(bgp(page)).toContainText("321");await expect(page.locator('[data-source="servers"]')).not.toContainText(/ошибка/i);
control.bgpPayload=undefined;control.prefixes=999;await refresh(page).click();await expect(bgp(page)).toContainText("999");await expect(source).not.toContainText(/ошибка/i);
})
for(const unknown of ["prefix","state"])test("Dashboard BGP accepts observed unknown without inventing zero/"+unknown,async({page})=>{
const control=await setup(page);await expect(bgp(page)).toContainText("321");await expect(refresh(page)).toBeEnabled();control.bgpPayload={sessions:[unknown==="prefix"?bgpSession(1,null):{...bgpSession(),state:"Unknown"}],failures:[]};await refresh(page).click();await expect(bgp(page)).toContainText("—");await expect(bgp(page)).toContainText("префиксы неизвестны");await expect(bgp(page)).toContainText(unknown==="prefix"?"Сессий установлено: 1":"Сессий установлено: неизвестно");await expect(page.locator('[data-source="bgp"]')).not.toContainText("ошибка");
const control=await setup(page);await expect(bgp(page)).toContainText("321");await expect(refresh(page)).toBeEnabled();control.bgpPayload={sessions:[unknown==="prefix"?bgpSession(1,null):{...bgpSession(),state:"Unknown"}],failures:[]};await refresh(page).click();await expect(bgp(page)).toContainText("—");await expect(bgp(page)).toContainText("префиксы неизвестны");await expect(bgp(page)).toContainText(unknown==="prefix"?"Сессий установлено: 1":"Сессий установлено: неизвестно");await expect(page.locator('[data-source="bgp"]')).not.toContainText(/ошибка/i);
control.bgpPayload={sessions:[],failures:[]};await refresh(page).click();await expect(bgp(page)).toContainText("Сессий установлено: 0");await expect(bgp(page)).not.toContainText("—");
})
for(const broken of ["missing","duplicate","counter","null","length"])test("Dashboard traffic rejects unconfirmed totals and keeps last good/"+broken,async({page})=>{
const control=await setup(page);const source=page.locator('[data-source="traffic"]');await expect(refresh(page)).toBeEnabled();await expect(source.locator("time")).toHaveCount(2);const receivedAt=await source.locator("time").first().getAttribute("datetime");const rate={id:"1",rxNow:1000,txNow:500,rxSeries:[1000],txSeries:[500],observations:{rxNow:true,txNow:true,rxSeries:[true],txSeries:[true],sampledAt:"2026-09-20T00:00:00Z"}};control.trafficPayload=broken==="missing"?{}:broken==="duplicate"?{servers:[rate,rate]}:broken==="counter"?{servers:[{...rate,rxNow:-1}]}:broken==="null"?{servers:[{...rate,rxNow:null}]}:{servers:[{...rate,txSeries:[]}]};await refresh(page).click();await expect(source).toContainText("ошибка обновления");await expect(source.locator("time").first()).toHaveAttribute("datetime",receivedAt!);await expect(page.getByText("RX 1.00 Гбит/с",{exact:true})).toBeVisible();await expect(page.locator('[data-source="servers"]')).not.toContainText("ошибка");control.trafficPayload={servers:[]};await refresh(page).click();await expect(source).not.toContainText("ошибка");await expect(page.getByText("Нет исторических измерений за выбранный период",{exact:true})).toBeVisible();await expect(page.getByText("RX 0 Кбит/с",{exact:true})).toBeVisible();
const control=await setup(page);const source=page.locator('[data-source="traffic"]');await expect(refresh(page)).toBeEnabled();await expect(source.locator("time")).toHaveCount(2);const receivedAt=await source.locator("time").first().getAttribute("datetime");const rate={id:"1",rxNow:1000,txNow:500,rxSeries:[1000],txSeries:[500],observations:{rxNow:true,txNow:true,rxSeries:[true],txSeries:[true],sampledAt:"2026-09-20T00:00:00Z"}};control.trafficPayload=broken==="missing"?{}:broken==="duplicate"?{servers:[rate,rate]}:broken==="counter"?{servers:[{...rate,rxNow:-1}]}:broken==="null"?{servers:[{...rate,rxNow:null}]}:{servers:[{...rate,txSeries:[]}]};await refresh(page).click();await expect(source).toContainText(/ошибка обновления/i);await expect(source.locator("time").first()).toHaveAttribute("datetime",receivedAt!);await expect(page.getByText("RX 1.00 Гбит/с",{exact:true})).toBeVisible();await expect(page.locator('[data-source="servers"]')).not.toContainText(/ошибка/i);control.trafficPayload={servers:[]};await refresh(page).click();await expect(source).not.toContainText(/ошибка/i);await expect(page.getByText("Нет исторических измерений за выбранный период",{exact:true})).toBeVisible();await expect(page.getByText("RX 0 Кбит/с",{exact:true})).toBeVisible();
})
for(const state of ["legacy","unobserved","measured-zero","reset-rx","invalid-time","invalid-mask"])test("Dashboard traffic observation metadata/"+state,async({page})=>{
const control=await setup(page);const source=page.locator('[data-source="traffic"]');await expect(refresh(page)).toBeEnabled();await expect(page.getByText("RX 1.00 Гбит/с",{exact:true})).toBeVisible();const rate={id:"1",rxNow:0,txNow:0,rxSeries:[0],txSeries:[0]};const observations={rxNow:true,txNow:true,rxSeries:[true],txSeries:[true],sampledAt:"2026-10-03T00:00:00Z"};control.trafficPayload={servers:[state==="legacy"?rate:{...rate,observations:state==="unobserved"?{rxNow:false,txNow:false,rxSeries:[false],txSeries:[false],sampledAt:null}:state==="reset-rx"?{...observations,rxNow:false,rxSeries:[false]}:state==="invalid-time"?{...observations,sampledAt:"invalid"}:state==="invalid-mask"?{...observations,rxSeries:[]}:observations}]};await refresh(page).click();await expect(refresh(page)).toBeEnabled();
if(state.startsWith("invalid")){await expect(source).toContainText("ошибка обновления");await expect(page.getByText("RX 1.00 Гбит/с",{exact:true})).toBeVisible();return}
await expect(source).not.toContainText("ошибка");if(state==="measured-zero"){await expect(page.getByText("RX 0 Кбит/с",{exact:true})).toBeVisible();await expect(page.getByRole("region",{name:"История RX/TX",exact:true})).toBeVisible();await expect(page.getByText("Нет исторических измерений за выбранный период",{exact:true})).toHaveCount(0)}else{await expect(page.getByText("RX —",{exact:true})).toBeVisible();if(state==="reset-rx"){await expect(page.getByText("TX 0 Кбит/с",{exact:true})).toBeVisible();await expect(page.getByText("Нет измерений RX за выбранный период",{exact:true})).toBeVisible()}else{await expect(page.getByText("TX —",{exact:true})).toBeVisible();await expect(page.getByText("Нет исторических измерений за выбранный период",{exact:true})).toBeVisible()}}
if(state.startsWith("invalid")){await expect(source).toContainText(/ошибка обновления/i);await expect(page.getByText("RX 1.00 Гбит/с",{exact:true})).toBeVisible();return}
await expect(source).not.toContainText(/ошибка/i);if(state==="measured-zero"){await expect(page.getByText("RX 0 Кбит/с",{exact:true})).toBeVisible();await expect(page.getByRole("region",{name:"История RX/TX",exact:true})).toBeVisible();await expect(page.getByText("Нет исторических измерений за выбранный период",{exact:true})).toHaveCount(0)}else{await expect(page.getByText("RX —",{exact:true})).toBeVisible();if(state==="reset-rx"){await expect(page.getByText("TX 0 Кбит/с",{exact:true})).toBeVisible();await expect(page.getByText("Нет измерений RX за выбранный период",{exact:true})).toBeVisible()}else{await expect(page.getByText("TX —",{exact:true})).toBeVisible();await expect(page.getByText("Нет исторических измерений за выбранный период",{exact:true})).toBeVisible()}}
if(state==="legacy")await expect(page.getByText("Измерения не подтверждены API",{exact:true})).toBeVisible()
})
for(const kind of ["servers","probes"])for(const broken of ["missing","duplicate","numeric"])test("Dashboard strict catalog keeps source cache/"+kind+"/"+broken,async({page})=>{
const control=await setup(page);await expect(refresh(page)).toBeEnabled();const source=page.locator('[data-source="'+kind+'"]');const receivedAt=await source.locator("time").getAttribute("datetime");const server={id:1,name:"Узел",host:"192.0.2.1",site:"TEST",country:"RU",asn:"64512",type:"exit-node",enabled:true,status:"online",latency:1,os:"7",model:"CHR",sessions:0};const probe={id:"p1",srcServerId:"1",name:"Тест",target:"192.0.2.2",filter:"main",rtt:1,loss:0,status:"up",series:[1],enabled:true,showOnDashboard:true};
if(kind==="servers")control.serversPayload=broken==="missing"?{}:broken==="duplicate"?[server,server]:[{...server,latency:-1}];else control.probesPayload=broken==="missing"?{}:broken==="duplicate"?{probes:[probe,probe]}:{probes:[{...probe,loss:101}]};await refresh(page).click();await expect(source).toContainText("ошибка обновления");await expect(source.locator("time")).toHaveAttribute("datetime",receivedAt!);if(kind==="servers")await expect(page.getByRole("link").filter({hasText:"Серверы онлайн"})).toContainText("1 / 1");else await expect(page.getByText("Проверки без ошибок",{exact:true})).toHaveCount(0);
control.serversPayload=undefined;control.probesPayload=undefined;await refresh(page).click();await expect(source).not.toContainText("ошибка");
if(kind==="servers")control.serversPayload=broken==="missing"?{}:broken==="duplicate"?[server,server]:[{...server,latency:-1}];else control.probesPayload=broken==="missing"?{}:broken==="duplicate"?{probes:[probe,probe]}:{probes:[{...probe,loss:101}]};await refresh(page).click();await expect(source).toContainText(/ошибка обновления/i);await expect(source.locator("time")).toHaveAttribute("datetime",receivedAt!);if(kind==="servers")await expect(page.getByRole("link").filter({hasText:"Серверы онлайн"})).toContainText("из 1");else await expect(page.getByText("Проверки без ошибок",{exact:true})).toHaveCount(0);
control.serversPayload=undefined;control.probesPayload=undefined;await refresh(page).click();await expect(source).not.toContainText(/ошибка/i);
})
test("Dashboard unknown server status is not reported offline or healthy",async({page})=>{
const control=await setup(page);await expect(refresh(page)).toBeEnabled();control.serversPayload=[{id:1,name:"Неопрошенный узел",host:"192.0.2.1",site:"TEST",country:"RU",asn:"64512",type:"exit-node",enabled:true,status:null,latency:null,os:null,model:null,sessions:0}];await refresh(page).click();const tile=page.getByRole("link").filter({hasText:"Серверы онлайн"});await expect(tile).toContainText("Статус неизвестен: 1");await expect(tile).not.toContainText("не в сети");await expect(page.getByRole("region",{name:"Требует внимания",exact:true}).getByRole("link",{name:/Неопрошенный узел/})).toContainText("Статус неизвестен");await expect(page.getByText("Серверы без проблем",{exact:true})).toHaveCount(0);await expect(page.locator('[data-source="servers"]')).not.toContainText("ошибка");
const control=await setup(page);await expect(refresh(page)).toBeEnabled();control.serversPayload=[{id:1,name:"Неопрошенный узел",host:"192.0.2.1",site:"TEST",country:"RU",asn:"64512",type:"exit-node",enabled:true,status:null,latency:null,os:null,model:null,sessions:0}];await refresh(page).click();const tile=page.getByRole("link").filter({hasText:"Серверы онлайн"});await expect(tile).toContainText("Статус неизвестен: 1");await expect(tile).not.toContainText("не в сети");await expect(page.getByRole("region",{name:"Требует внимания",exact:true}).getByRole("link",{name:/Неопрошенный узел/})).toContainText("Статус неизвестен");await expect(page.getByText("Серверы без проблем",{exact:true})).toHaveCount(0);await expect(page.locator('[data-source="servers"]')).not.toContainText(/ошибка/i);
})
for(const state of ["legacy","unmeasured","zero","failure","gaps","invalid"])test("Dashboard ping distinguishes observed and missing measurements/"+state,async({page})=>{
const control=await setup(page);await expect(refresh(page)).toBeEnabled();const probe={id:"ping-observation",srcServerId:"1",name:"Измерение ping",target:"192.0.2.2",filter:"main",rtt:0,loss:0,status:"up",series:[0],enabled:true,showOnDashboard:true};const sample=(minute:number,rtt:number|null,status="up",loss=0)=>({sampledAt:"2026-10-03T00:"+String(minute).padStart(2,"0")+":00Z",rtt,status,loss});const samples=state==="unmeasured"?[]:state==="failure"?[sample(30,null,"down",100)]:state==="gaps"?[sample(29,5),sample(30,6),sample(32,0)]:state==="invalid"?[sample(30,0),sample(30,0)]:[sample(30,0)];control.probesPayload=state==="legacy"?{probes:[probe]}:{rangeStartAt:"2026-10-03T00:00:00Z",rangeEndAt:"2026-10-03T01:00:00Z",probes:[{...probe,observations:{samples}}]};await refresh(page).click();await expect(refresh(page)).toBeEnabled();const source=page.locator('[data-source="probes"]');if(state==="invalid"){await expect(source).toContainText("ошибка обновления");return}await expect(source).not.toContainText("ошибка");const row=page.locator('tr[data-row-id]').filter({hasText:"Измерение ping"});await expect(row).toHaveCount(1);
const control=await setup(page);await expect(refresh(page)).toBeEnabled();const probe={id:"ping-observation",srcServerId:"1",name:"Измерение ping",target:"192.0.2.2",filter:"main",rtt:0,loss:0,status:"up",series:[0],enabled:true,showOnDashboard:true};const sample=(minute:number,rtt:number|null,status="up",loss=0)=>({sampledAt:"2026-10-03T00:"+String(minute).padStart(2,"0")+":00Z",rtt,status,loss});const samples=state==="unmeasured"?[]:state==="failure"?[sample(30,null,"down",100)]:state==="gaps"?[sample(29,5),sample(30,6),sample(32,0)]:state==="invalid"?[sample(30,0),sample(30,0)]:[sample(30,0)];control.probesPayload=state==="legacy"?{probes:[probe]}:{rangeStartAt:"2026-10-03T00:00:00Z",rangeEndAt:"2026-10-03T01:00:00Z",probes:[{...probe,observations:{samples}}]};await refresh(page).click();await expect(refresh(page)).toBeEnabled();const source=page.locator('[data-source="probes"]');if(state==="invalid"){await expect(source).toContainText(/ошибка обновления/i);return}await expect(source).not.toContainText(/ошибка/i);const row=page.locator('tr[data-row-id]').filter({hasText:"Измерение ping"});await expect(row).toHaveCount(1);
if(state==="legacy"||state==="unmeasured"){await expect(row).toContainText("Неизвестно");await expect(page.getByRole("link").filter({hasText:"Проверки с проблемами"})).toContainText("неизвестны: 1");await expect(page.getByText("Проверки без ошибок",{exact:true})).toHaveCount(0);await expect(row).not.toContainText("100%");await expect(page.locator('[data-latency-source]')).toHaveCount(0)}else if(state==="failure"){await expect(row).toContainText("Оффлайн");await expect(row).toContainText("100%");await expect(page.getByRole("link").filter({hasText:"Проверки с проблемами"})).toContainText("1 ошибок")}else{await expect(row).toContainText("Онлайн");await expect(row).toContainText("0%");await expect(page.locator('[data-latency-isolated]')).toHaveCount(1);if(state==="gaps"){await expect(page.locator('.recharts-line-curve')).toHaveAttribute("d",/M.*M/);for(const width of [1440,320]){await page.setViewportSize({width,height:900});await page.getByRole("region",{name:"История RTT по источникам",exact:true}).scrollIntoViewIfNeeded();expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);await page.screenshot({path:"docs/ux-ui/screens/dashboard-observed-ping-"+width+".png",animations:"disabled"})}}else await expect(page.locator('[data-latency-segment]')).toHaveCount(0);await expect(source.locator("time").last()).toHaveAttribute("datetime",new Date(samples.at(-1)!.sampledAt).toISOString())}
})
for(const kind of ["gre","wg","vxlan"] as const)for(const broken of ["missing","partial","duplicate"])test("Dashboard overlay complete source and cache/"+kind+"/"+broken,async({page})=>{
const control=await setup(page);await expect(refresh(page)).toBeEnabled();const source=page.locator('[data-source="'+kind+'"]'),controlKey=kind==="gre"?"grePayload":kind==="wg"?"wgPayload":"vxlanPayload",rowsKey=kind==="wg"?"interfaces":"tunnels",row=kind==="gre"?dashboardGre:kind==="wg"?dashboardWg:dashboardVxlan;control[controlKey]={[rowsKey]:[row],failures:[]};await refresh(page).click();await expect(source).not.toContainText("ошибка");const receivedAt=await source.locator("time").getAttribute("datetime");control[controlKey]=broken==="missing"?{}:broken==="partial"?{[rowsKey]:[row],failures:[{serverId:"2",serverName:"Узел без ответа",error:"timeout"}]}:{[rowsKey]:[row,row],failures:[]};await refresh(page).click();await expect(source).toContainText("ошибка обновления");await expect(source.locator("time")).toHaveAttribute("datetime",receivedAt!);await expect(page.getByRole("link").filter({hasText:"Туннели работают"})).toContainText("Последний успешный снимок");await expect(page.locator('[data-source="servers"]')).not.toContainText("ошибка");if(kind==="gre")await expect(page.getByText("GRE сохранён",{exact:true})).toBeVisible();control[controlKey]={[rowsKey]:[],failures:[]};await refresh(page).click();await expect(source).not.toContainText("ошибка");if(kind==="gre")await expect(page.getByText("GRE сохранён",{exact:true})).toHaveCount(0)
const control=await setup(page);await expect(refresh(page)).toBeEnabled();const source=page.locator('[data-source="'+kind+'"]'),controlKey=kind==="gre"?"grePayload":kind==="wg"?"wgPayload":"vxlanPayload",rowsKey=kind==="wg"?"interfaces":"tunnels",row=kind==="gre"?dashboardGre:kind==="wg"?dashboardWg:dashboardVxlan;control[controlKey]={[rowsKey]:[row],failures:[]};await refresh(page).click();await expect(source).not.toContainText(/ошибка/i);const receivedAt=await source.locator("time").getAttribute("datetime");control[controlKey]=broken==="missing"?{}:broken==="partial"?{[rowsKey]:[row],failures:[{serverId:"2",serverName:"Узел без ответа",error:"timeout"}]}:{[rowsKey]:[row,row],failures:[]};await refresh(page).click();await expect(source).toContainText(/ошибка обновления/i);await expect(source.locator("time")).toHaveAttribute("datetime",receivedAt!);await expect(page.getByRole("link").filter({hasText:"Туннели работают"})).toContainText("Последний успешный снимок");await expect(page.locator('[data-source="servers"]')).not.toContainText(/ошибка/i);if(kind==="gre")await expect(page.getByText("GRE сохранён",{exact:true})).toBeVisible();control[controlKey]={[rowsKey]:[],failures:[]};await refresh(page).click();await expect(source).not.toContainText(/ошибка/i);if(kind==="gre")await expect(page.getByText("GRE сохранён",{exact:true})).toHaveCount(0)
})
for(const broken of ["missing","incomplete","foreign","invalid-date","corrupt-null","legacy","filters","speed"])test("Dashboard Internet path keeps last confirmed source/"+broken,async({page})=>{
const control=await setup(page);await expect(refresh(page)).toBeEnabled();const source=page.locator('[data-source="internetPath"]');await expect(source).not.toContainText("ошибка");const times=await source.locator("time").evaluateAll(nodes=>nodes.map(n=>n.getAttribute("datetime")));
const control=await setup(page);await expect(refresh(page)).toBeEnabled();const source=page.locator('[data-source="internetPath"]');await expect(source).not.toContainText(/ошибка/i);const times=await source.locator("time").evaluateAll(nodes=>nodes.map(n=>n.getAttribute("datetime")));
if(broken==="filters"||broken==="speed"){control.fallback=true;if(broken==="filters")control.filterPayload={rulesets:[],stale:true};else control.speedPayload={}}
else control.pathPayload=broken==="missing"?{}:broken==="corrupt-null"?{snapshot:null,sampledAt:"2026-09-20T00:00:00Z"}:{snapshot:{collectionComplete:broken==="legacy"?undefined:true,sampledAt:broken==="invalid-date"?"invalid":"2026-09-20T00:00:00Z",servers:[],greTunnels:[],filtersRulesets:[],speedProbes:broken==="incomplete"?undefined:[],routeLookupByServerId:broken==="foreign"?{"99":null}:{},wanRuntimeByHomeId:{}}};
await refresh(page).click();await expect(source).toContainText("ошибка обновления");expect(await source.locator("time").evaluateAll(nodes=>nodes.map(n=>n.getAttribute("datetime")))).toEqual(times);await expect(page.locator('[data-source="servers"]')).not.toContainText("ошибка");
control.pathPayload=undefined;control.filterPayload=undefined;control.speedPayload=undefined;control.fallback=false;await refresh(page).click();await expect(source).not.toContainText("ошибка");
await refresh(page).click();await expect(source).toContainText(/ошибка обновления/i);expect(await source.locator("time").evaluateAll(nodes=>nodes.map(n=>n.getAttribute("datetime")))).toEqual(times);await expect(page.locator('[data-source="servers"]')).not.toContainText(/ошибка/i);
control.pathPayload=undefined;control.filterPayload=undefined;control.speedPayload=undefined;control.fallback=false;await refresh(page).click();await expect(source).not.toContainText(/ошибка/i);
})
for(const state of ["unmeasured","measured","failed","unknown"])test("Dashboard Internet path hop observations/"+state,async({page})=>{
@@ -260,14 +257,14 @@ for(const state of ["unmeasured","measured","failed","unknown"])test("Dashboard
const nodes=["home-router","jump-host","exit-node"].map((type,i)=>({id:i+1,name:"Path node "+(i+1),host:"192.0.2."+(i+1),site:"TEST",country:"RU",asn:"64512",type,enabled:true,status:state==="unknown"&&i===0?null:"online",latency:99,os:"7",model:"CHR",sessions:0,wanUplinks:i===0?[{id:"wan1",name:"WAN",isp:"Test ISP",iface:"ether1",ip:"192.0.2.10",maxDl:999,maxUl:888}]:[]}));
const probe={id:"hop1",srcServerId:"1",dstServerId:"2",srcInterface:"ether1",dstInterface:"",enabled:true,lastPingRttMs:0,lastPingLossPct:0,lastTxAvgMbps:0,lastRxAvgMbps:5,lastPingAt:state==="unmeasured"?null:at,lastRunAt:state==="unmeasured"?null:at,lastStatus:state==="failed"?"error":"done",lastError:state==="failed"?"denied":null,lastPingError:state==="failed"?"denied":null};
control.pathPayload={snapshot:{collectionComplete:true,sampledAt:at,servers:nodes,greTunnels:[],filtersRulesets:[],speedProbes:[probe],routeLookupByServerId:{"1":{gateway:"192.0.2.254",routingMark:null}},wanRuntimeByHomeId:{"1":{defaultGateway:"192.0.2.254",defaultInterface:"ether1",uplinks:[{id:"wan1",name:"WAN",isp:"Test ISP",iface:"ether1",configuredIp:"192.0.2.10",leasedIp:"192.0.2.10",dhcpStatus:"bound",isDefault:true}]}}}};
await refresh(page).click();await expect(refresh(page)).toBeEnabled();await expect(page.locator('[data-source="internetPath"]')).not.toContainText("ошибка");const strip=page.getByText("JH/Exit — схема кандидатов. Default route подтверждает только WAN. Метрики — последние подтверждённые пробы участков.",{exact:true}).locator("..");await expect(strip).toBeVisible();await expect(strip).not.toContainText("999");await expect(strip).not.toContainText("99 мс");
await refresh(page).click();await expect(refresh(page)).toBeEnabled();await expect(page.locator('[data-source="internetPath"]')).not.toContainText(/ошибка/i);const strip=page.getByText("JH/Exit — схема кандидатов. Default route подтверждает только WAN. Метрики — последние подтверждённые пробы участков.",{exact:true}).locator("..");await expect(strip).toBeVisible();await expect(strip).not.toContainText("999");await expect(strip).not.toContainText("99 мс");
if(state==="measured"||state==="unknown"){await expect(strip.getByText("0 мс",{exact:true})).toBeVisible();await expect(strip.getByText("5 ↓ Мбит/с",{exact:true})).toBeVisible()}else{await expect(strip.getByText("0 мс",{exact:true})).toHaveCount(0);await expect(strip.getByText("5 ↓ Мбит/с",{exact:true})).toHaveCount(0)}
if(state==="unknown"){await expect(strip.getByText("Неизвестно",{exact:true})).toBeVisible();await expect(strip.getByText("Оффлайн",{exact:true})).toHaveCount(0)}
await page.setViewportSize({width:320,height:900});await expect(strip).toBeVisible();expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true)
})
test("Dashboard large attention queue mounts rows on demand",async({page},info)=>{
test.setTimeout(90000);const start=Date.now();await setup(page,false,1000);await expect(refresh(page)).toBeEnabled();const queue=page.getByRole("region",{name:"Требует внимания",exact:true});const links=queue.locator('a[href^="/servers?server="]');await expect(links).toHaveCount(5);const sample={fixtureRows:1000,readyMs:Date.now()-start,renderedAttentionRows:await links.count(),domNodes:await page.locator("*").count()};console.log(JSON.stringify(sample));await info.attach("large-attention-metrics",{body:JSON.stringify(sample),contentType:"application/json"});const summary=queue.locator("summary").filter({hasText:"Ещё 995"});await summary.focus();await summary.press("Enter");await expect(links).toHaveCount(55);await queue.getByRole("button",{name:"Показать ещё 50",exact:true}).click();await expect(links).toHaveCount(105);await summary.focus();await summary.press("Enter");await expect(links).toHaveCount(5);await summary.press("Enter");await expect(links).toHaveCount(55);await page.setViewportSize({width:320,height:900});expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);await links.first().click();await expect(page).toHaveURL(/servers\?server=1$/);await expect(page.getByRole("status",{name:"Сервер по ссылке"})).toContainText("Узел 1")
test.setTimeout(90000);const start=Date.now();await setup(page,false,1000);await expect(refresh(page)).toBeEnabled();const queue=page.getByRole("region",{name:"Требует внимания",exact:true});const links=queue.locator('a[href^="/servers?server="]');await expect(links).toHaveCount(50);const sample={fixtureRows:1000,readyMs:Date.now()-start,renderedAttentionRows:await links.count(),domNodes:await page.locator("*").count()};console.log(JSON.stringify(sample));await info.attach("large-attention-metrics",{body:JSON.stringify(sample),contentType:"application/json"});await queue.getByRole("button",{name:"Показать ещё 50",exact:true}).click();await expect(links).toHaveCount(100);await page.setViewportSize({width:320,height:900});expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);await links.first().click();await expect(page).toHaveURL(/servers\?server=1$/);await expect(page.getByRole("status",{name:"Сервер по ссылке"})).toContainText("Узел 1")
})
test("Dashboard active probes retain page after refreshed measurements",async({page})=>{
+1 -1
View File
@@ -31,7 +31,7 @@ test("поиск страниц: одинаковые названия, сино
for (const item of navigationItems) {
await expect(sidebar.locator(`a[href="${item.url}"]`)).toContainText(item.title)
}
const opener = page.getByRole("button", { name: "Приложения", exact: true })
const opener = page.getByRole("button", { name: "Источники и свежесть данных", exact: true })
await opener.focus()
await page.keyboard.press("Control+k")
const dialog = page.getByRole("dialog", { name: "Поиск страниц", exact: true })
+8 -7
View File
@@ -9,7 +9,6 @@ test("Карта: PostgreSQL даты не скрывают JumpHost и Exit Nod
const map=page.getByRole("group",{name:"Интерактивная карта сети"})
await expect(map.getByText("Узел JH",{exact:true})).toBeVisible()
await expect(map.getByText("Узел EN",{exact:true})).toBeVisible()
await expect(page.getByRole("combobox",{name:"Устройство на карте"})).toBeEnabled()
await expect(page.getByRole("alert").filter({hasText:"Первоначальная загрузка карты"})).toHaveCount(0)
})
for(const part of ["servers","gre","probes"] as const)for(const malformed of [false,true])test("Карта: первоначальный отказ и повтор "+part+"/"+malformed,async({page})=>{
@@ -28,10 +27,10 @@ for(const part of ["servers","gre","probes"] as const)test("Карта: част
await page.route("**/health",r=>r.fulfill({json:{ok:true}}))
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill(failing&&p===paths[part]?{status:503,json:{error:"Источник недоступен"}}:{json:body(p,failing?"Новый роутер":"Последний роутер")})})
await page.goto("/network-map")
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Последний роутер",{exact:true})).toBeVisible()
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByRole("button",{name:"Устройство Последний роутер",exact:true})).toBeVisible()
failing=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
await expect(page.getByRole("alert").filter({hasText:"Последний полный снимок"})).toBeVisible()
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Последний роутер",{exact:true})).toBeVisible()
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByRole("button",{name:"Устройство Последний роутер",exact:true})).toBeVisible()
await expect(page.getByText("Новый роутер",{exact:true})).toHaveCount(0)
})
@@ -39,11 +38,12 @@ test("Карта: неизвестный статус не становится
await page.route("**/health",r=>r.fulfill({json:{ok:true}}))
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;const data=body(p);return r.fulfill({json:p===paths.servers?[{...(data as object[])[0],status:null}]:data})})
await page.goto("/network-map")
await expect(page.getByText("1 неизвестно",{exact:true})).toBeVisible()
await expect(page.getByText("0 оффлайн",{exact:true})).toBeVisible()
await page.getByText("Сводка сети", {exact:true}).click()
await expect(page.getByRole("button",{name:"Неизвестно 1",exact:true})).toBeVisible()
await expect(page.getByRole("button",{name:"Оффлайн 0",exact:true})).toBeVisible()
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true}).click()
await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible()
await page.getByRole("button",{name:"Неизвестно",exact:true}).click()
await page.getByRole("button",{name:/^Фильтр/}).click();await page.getByRole("button",{name:"Неизвестно",exact:true}).click()
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true})).toBeVisible()
})
@@ -52,8 +52,9 @@ for(const polled of [false,true])test("Карта: реальные и неиз
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;const data=body(p);return r.fulfill({json:p===paths.servers?[{...(data as object[])[0],...(polled?{cpuLoad:0,totalMemory:1048576,freeMemory:1048576,uptime:"0s",polledAt:"2020-01-01T00:00:00Z"}:{})}]:data})})
await page.goto("/network-map");await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true}).click()
const panel=page.getByText("Ресурсы",{exact:true}).locator("..")
await panel.locator("summary").click()
await expect(panel.getByText("История CPU и диск API не передаются.",{exact:false})).toBeVisible()
await expect(panel.locator("svg")).toHaveCount(0)
await expect(panel.locator("svg polyline")).toHaveCount(0)
await expect(panel.getByText("HDD",{exact:true})).toBeVisible()
await expect(panel.getByText("— / —",{exact:true})).toHaveCount(polled?1:2)
if(polled){await expect(panel.getByText("0%",{exact:true})).toBeVisible();await expect(panel.getByText("0 МБ / 1 МБ",{exact:true})).toBeVisible();await expect(panel.getByText("0м",{exact:true})).toBeVisible()}
+80 -5
View File
@@ -9,18 +9,24 @@ test("Карта: открытые детали обновляются вмес
let changed=false
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...jh,name:changed?"Новый Jump":"Jump",status:changed?null:"online",cpuLoad:changed?0:20}]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
await page.goto("/network-map");await page.getByRole("button",{name:"Устройство Jump",exact:true}).click()
await expect(page.getByText("20%",{exact:true})).toBeVisible()
const metrics=page.getByText("CPU · RAM",{exact:true}).locator("..")
await expect(metrics).toContainText("20% · —")
await page.getByText("Ресурсы",{exact:true}).click()
const sessions=page.getByText("Сессий",{exact:true}).locator("..");await expect(sessions).toHaveText("Сессий—")
changed=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
await expect(page.getByText("0%",{exact:true})).toBeVisible();await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible()
await expect(metrics).toContainText("0% · —");await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible()
await expect(page.getByText("Jump",{exact:true})).toHaveCount(0);await expect(page.getByText("Новый Jump",{exact:true}).last()).toBeVisible()
})
test("Карта: модель WAN не утверждает активный маршрут и RTT линии",async({page})=>{
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
await page.goto("/network-map");await expect(page.getByText("Пунктир WAN→JH — модель связности; маршрут не подтверждён.",{exact:true})).toBeVisible()
await page.goto("/network-map")
const legend = page.getByRole("button", {name:"Легенда",exact:true})
await legend.click()
await expect(page.getByText("WAN → JH · модель связности",{exact:true})).toBeVisible()
await legend.click()
await expect(page.locator("svg text").filter({hasText:/^5 мс$/})).toHaveCount(0)
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Домашний",{exact:true}).click()
await expect(page.getByText("Аплинк каталога",{exact:true})).toBeVisible();await expect(page.getByText("Модель связей с JH · Ping модели",{exact:true})).toBeVisible()
await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:"Интерфейсы"}).click();await expect(page.getByText("Аплинк каталога",{exact:true})).toBeVisible();await expect(page.getByText("Модель связей с JH · Ping модели",{exact:true})).toBeVisible()
await expect(page.getByText("primary",{exact:true})).toHaveCount(0);await expect(page.getByText("backup",{exact:true})).toHaveCount(0)
})
test("Карта: выбранный GRE обновляется и неизвестный IPsec не означает Plain",async({page})=>{
@@ -31,7 +37,7 @@ test("Карта: выбранный GRE обновляется и неизве
await expect(page.getByText("gre-home",{exact:true}).last()).toBeVisible();await expect(page.getByText("Ping неизвестен",{exact:true})).toBeVisible()
changed=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
await expect(page.getByText("gre-new",{exact:true}).last()).toBeVisible();await expect(page.getByText("Недоступен",{exact:true})).toBeVisible()
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1");await expect(page.getByText("IPsec неизвестен",{exact:true})).toBeVisible()
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click();await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:/^GRE/}).click();await expect(page.getByText("IPsec неизвестен",{exact:true})).toBeVisible()
})
test("Карта: GRE сохраняет частичное измерение, ноль Ping и дату пробы",async({page})=>{
@@ -44,3 +50,72 @@ test("Карта: GRE сохраняет частичное измерение,
await expect(page.getByText("Проба measured-probe",{exact:false}).last()).toContainText("2020")
await expect(page.getByText("Проба measured-probe",{exact:false}).last()).toContainText("время TX/RX неизвестно")
})
test("Карточки Exit, JumpHost и сервиса показывают измерения и обрабатывают действия", async ({ page }, info) => {
const exit = { ...jh, id: 3, type: "exit-node", name: "fra-exit02", host: "fra-exit02.rtnt.top", country: "DE", latency: 31, cpuLoad: 18, uptime: "23d9h", totalMemory: 100, freeMemory: 64, os: "7.16.1", polledAt: "2026-11-25T09:02:11Z" }
const jump = { ...exit, id: 2, name: "nov-gw01", host: "nov-gw01.rtnt.top", type: "jump-host", status: "degraded", country: "RU" }
const service = { id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 0.29 }
const edge = { fromId: "3", toId: service.id, bytes: service.bytes, bps: service.bps, bpsFwd: 8000, bpsRev: 16000 }
const path = { clientId: "u1", clientName: "msk-hr01", viaId: "2", viaName: jump.name, enId: "3", enName: exit.name, serviceId: service.id, bytes: edge.bytes, bps: edge.bps }
const record = {serverId:"3",serverName:exit.name,src:"10.20.4.18",dst:"142.250.74.14",proto:6,protoName:"TCP",srcPort:45000,dstPort:443,bytes:1000,packets:1,bps:8000,inIface:"gre1",service:"YouTube",dstAsn:15169}
const country = {...service, id:"cc:other", label:"Прочее", category:"Страна"}
const dns = {...service, id:"cc:other|svc:dns", label:"DNS", category:"DNS"}
const rows = [13,17,15,27,51,55,48,33,16,12,15,18]
const sample = { rxNow: 15, txNow: 12, rxPeak: 55, txPeak: 55, rxTotal: 1, txTotal: 1, rxSeries: rows, txSeries: rows, observations: { rxNow: true, txNow: true, rxSeries: rows.map(() => true), txSeries: rows.map(() => true), sampledAt: "2026-11-25T09:02:11Z" } }
await page.route("**/api/**", route => {
const url = new URL(route.request().url()), endpoint = url.pathname
const daily = url.searchParams.get("range") === "24h"
const data = endpoint === "/api/servers" ? [exit, jump]
: endpoint === "/api/filters/gre-tunnels" ? { tunnels: [], failures: [] }
: endpoint === "/api/uptime/speed-probes" ? {probes: []}
: endpoint === "/api/traffic/flow/map-hops" ? {...empty,rangeMinutes:daily?1440:5,windowSec:daily?86400:300,totalBytes:daily?4100000000:3103448,namedBytes:daily?4100000000:service.bytes,services:[{...service,bytes:daily?4100000000:service.bytes}],servicePaths:[path],serviceEdges:[edge],countries:[country],countryServiceGroups:[{countryId:country.id,services:[dns],paths:[{...path,serviceId:dns.id,bytes:100000,bps:100000*8/300}],edges:[]}]}
: endpoint === "/api/traffic/flow/analytics" ? {bpsNow:8000,bytes:1000,packets:1,conversations:3,uniqueSrc:1,uniqueDst:3,topProto:"TCP",rxSeries:[],txSeries:[],applications:[],protocols:[],sources:[],destinations:[],interfaces:[],conversationsList:[record,...["unknown","US"].map(dstCountry=>({...record,service:"Прочее",category:"DNS",dstCountry,dst:dstCountry==="US"?"192.0.2.53":"198.51.100.53",dstPort:53}))],ifaces:[],live:true}
: endpoint === "/api/traffic/servers/3" ? {server:{...sample,id:"3"}}
: endpoint === "/api/traffic/servers/2" ? {server:{...sample,id:"2",observations:{...sample.observations,currentState:"error",error:"RouterOS API 401 на /interface",lastAttemptAt:"2026-11-25T09:31:08Z"}}}
: endpoint === "/api/auth/config" ? {required:false} : {}
return route.fulfill({json:data})
})
await page.goto("/network-map?server=3")
const card = page.getByRole("complementary",{name:"Детали объекта карты"})
await expect(card.getByRole("img",{name:"История измерений"})).toBeVisible()
await card.getByRole("button",{name:"Закрепить",exact:true}).click()
await expect(card.getByText("Закреплён",{exact:true}).locator("..")).toContainText("да")
await card.getByRole("button",{name:"Открепить",exact:true}).click()
await card.screenshot({path:info.outputPath("exit.png")})
await card.getByRole("button",{name:/YouTube/}).click()
await expect(card.getByText("Объём · 24 ч",{exact:true}).locator("..")).toContainText("4.10 ГБ")
await expect(card.getByText("10.20.4.18 → 142.250.74.14",{exact:true})).toBeVisible()
await expect(card.getByText("TCP/443",{exact:true})).toBeVisible()
await card.screenshot({path:info.outputPath("service.png")})
await card.getByRole("button",{name:"Фильтр по сервису"}).click()
await expect(page.getByText(/фильтр: YouTube/)).toBeVisible()
await card.getByRole("button",{name:"Снять фильтр"}).click()
await page.goto("/network-map?server=2")
await expect(card.getByText(/RouterOS API 401 на \/interface/)).toBeVisible()
await card.screenshot({path:info.outputPath("jump.png")})
await card.getByRole("button",{name:/fra-exit02/}).click()
await expect(card.getByRole("heading",{name:exit.name})).toBeVisible()
await page.getByRole("button",{name:"Страны",exact:true}).click()
await page.getByRole("button",{name:"Страна Прочее",exact:true}).press("Enter")
await card.getByRole("button",{name:/DNS/}).click()
await expect(card.getByText("Выход не определён", {exact:true})).toBeVisible()
await expect(card.getByText(/198\.51\.100\.53/)).toBeVisible()
await expect(card.getByText(/192\.0\.2\.53/)).toHaveCount(0)
})
test("Обновление NetFlow отображается внутри кнопки", async ({page}) => {
let release!: () => void
const wait = new Promise<void>(resolve => { release = resolve })
await page.route("**/api/**", async route => {
const path = new URL(route.request().url()).pathname
if (path === "/api/traffic/flow/map-hops") await wait
return route.fulfill({json:path === "/api/traffic/flow/map-hops" ? empty : path === "/api/servers" ? [jh] : path === "/api/filters/gre-tunnels" ? {tunnels:[],failures:[]} : path === "/api/uptime/speed-probes" ? {probes:[]} : path === "/api/auth/config" ? {required:false} : {}})
})
await page.goto("/network-map")
const refresh = page.getByRole("button",{name:"Обновить",exact:true})
await expect(refresh.locator("[data-slot=spinner]")).toBeVisible()
await expect(page.getByText("Обновление NetFlow…",{exact:true})).toHaveCount(0)
release()
await expect(refresh).toBeEnabled()
await expect(refresh.locator("[data-slot=spinner]")).toHaveCount(0)
})
+169 -22
View File
@@ -1,15 +1,79 @@
import {test,expect} from "@playwright/test"
import { installOpenLiveStream } from "./live-stream-fixture"
import { observedTrafficFixturePayload } from "./traffic-observation-fixture"
const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false}
const flowPath="/api/traffic/flow/map-hops"
test.beforeEach(async({page})=>{await page.route("**/health",r=>r.fulfill({json:{ok:true}}))})
const server={id:1,name:"Router",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online"}
test("Карта и трафик сохраняют пользователя и сервис, IX остаётся отдельным", async ({page}) => {
const clientId = "alice"
const timestamps = { createdAt: "2026-11-26T12:00:00Z", updatedAt: "2026-11-26T12:00:00Z" }
const binding = { ...timestamps, userId: clientId, id: "a1", serverId: 1,
serverName: "Вход", serverSite: "MSK", serverCountry: "RU", interfaceName: "gre-alice", interfaceType: "gre", comment: "" }
const user = { ...timestamps, id: clientId, name: "Алиса", login: "alice", email: "[email protected]", role: "viewer", active: true,
avatar: "A", lastSeen: null, sections: [], servers: [], bindings: [binding, {...binding, id: "a2", interfaceName: "gre-alice-2"}] }
const counters = ["a1", "a2"].map(bindingId => ({bindingId, status: "online", rxNow: 4, txNow: 6, rxPeak: 4, txPeak: 6, rxTotal: 0, txTotal: 0, rxSeries: [4], txSeries: [6]}))
const dns = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 300000, bps: 8000, share: 1}
const path = {clientId, clientName: "Алиса", viaId: "1", viaName: "Вход", enId: "", enName: "", serviceId: dns.id, bytes: dns.bytes, bps: dns.bps}
const requests: string[] = []
await page.route("**/api/**", route => {
const url = new URL(route.request().url())
requests.push(url.pathname + url.search)
const clientCard = { id: clientId, name: "Алиса", subtitle: "alice", site: "MSK", country: "RU", status: "online", rxNow: 0, txNow: 0, sessions: 1, bytes: dns.bytes, rxSeries: [], txSeries: [] }
const replies: Record<string, unknown> = {
"/api/auth/config": {required: false},
"/api/servers": [{...server, name: "Вход", type: "jump-host"}, {...server, id: 9, name: "Изолированный IX", host: "192.0.2.9", type: "ix-node"}],
"/api/filters/gre-tunnels": {tunnels: [], failures: []}, "/api/uptime/speed-probes": {probes: []},
"/api/ix/topology": {links: []}, "/api/ix/segments": {items: [{id: "segment", appliedRevision: 1}]},
"/api/ix/segments/segment/linux": {items: [{serverId: 9, interfaceName: "wg-linux", kind: "wireguard", name: "Linux VPS", enabled: true}]},
"/api/users": {users: [user]}, "/api/traffic/bound-interfaces": observedTrafficFixturePayload({interfaces: counters}),
"/api/traffic/flow/exporters": {exporters: []}, "/api/traffic/flow/clients": {clients: [clientCard]},
"/api/traffic/flows": {exportersOnline: 0, bytesPerMin: 0, uniqueSrc: 0, uniqueDst: 0, topProto: "TCP", talkers: [], listenerBound: true},
[flowPath]: {...empty, totalBytes: dns.bytes, namedBytes: dns.bytes, services: [dns], servicePaths: [path],
serviceEdges: [{fromId: "1", toId: dns.id, observedOnly: true, bytes: dns.bytes, bps: dns.bps, bpsFwd: 0, bpsRev: dns.bps}]},
}
return route.fulfill({json: replies[url.pathname] ?? {}})
})
await page.goto("/network-map")
const map = page.getByRole("group", {name: "Интерактивная карта сети"})
const panel = page.getByRole("complementary", {name: "Детали объекта карты"})
await expect(page.getByRole("button", {name: "Выбрать пользователя", exact: true})).toBeVisible()
await expect(map.getByRole("button", {name: "Устройство Изолированный IX"})).toHaveCount(0)
await map.getByRole("button", {name: "Сервис DNS", exact: true}).press("Enter")
await panel.getByRole("button", {name: "Фильтр по сервису"}).click()
await page.getByRole("button", {name: "Пользователи", exact: true}).click()
await page.getByRole("option", {name: /Алиса/}).click()
await expect.poll(() => requests.some(request => request === `${flowPath}?range=1m&userId=${clientId}`)).toBe(true)
await expect(panel.getByRole("heading", {name: "Алиса", exact: true})).toBeVisible()
await expect(panel.getByText(/gre-alice · gre, gre-alice-2/)).toBeVisible()
await expect(panel.getByText(/RX 8.*TX 12.*2\/2/)).toBeVisible()
await panel.getByRole("button", {name: /DNS/}).click()
await panel.getByRole("link", {name: "Открыть в «Трафике»"}).click()
await expect(page).toHaveURL(/\/traffic\?.*user=alice/)
await expect(page.getByRole("button", {name: "Клиенты", exact: true}).last()).toBeVisible()
await page.getByRole("link", {name: "Вернуться на карту"}).click()
await expect(panel.getByRole("heading", {name: "DNS", exact: true})).toBeVisible()
await page.getByRole("button", {name: "IX и клиенты"}).click()
await expect(map.getByRole("button", {name: "Устройство Вход"})).toHaveCount(0)
await expect(map.getByRole("button", {name: "Устройство Изолированный IX"})).toBeVisible()
await page.getByRole("button", {name: "Linux-клиенты", exact: true}).click()
await page.getByRole("option", {name: /Linux VPS/}).click()
await expect(panel.getByText("wg-linux · wireguard")).toBeVisible()
await expect(panel.getByText("Нет потоков с подтверждённой привязкой к пользователю.")).toBeVisible()
})
test("Карта не приписывает весь YouTube единственному выходу ARN", async ({page}) => {
const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1}
const edge = {fromId: "1", toId: service.id, bytes: 300000, bps: 8000, bpsFwd: 2000, bpsRev: 6000}
let known = false
await page.route("**/api/**", route => {
const path = new URL(route.request().url()).pathname
const url = new URL(route.request().url())
const path = url.pathname
if (path === flowPath && url.searchParams.get("range") === "24h") {
return route.fulfill({ json: { ...empty, rangeMinutes: 1440, windowSec: 86400, totalBytes: service.bytes, namedBytes: service.bytes, services: [service] } })
}
if (path === flowPath) expect(url.searchParams.get("range")).toBe("1m")
const responses: Record<string, unknown> = {
"/api/auth/config": {required: false}, "/api/servers": [{...server, type: "exit-node", name: "ARN"}],
"/api/filters/gre-tunnels": {tunnels: [], failures: []}, "/api/uptime/speed-probes": {probes: []},
@@ -20,7 +84,7 @@ test("Карта не приписывает весь YouTube единствен
await page.goto("/network-map")
await page.getByRole("button", {name: "Сервис YouTube", exact: true}).press("Enter")
const unknown = page.getByText("Выход не определён", {exact: true}).locator("..")
const badges = page.getByRole("button", {name: "Поток NetFlow между узлами"})
const badges = page.locator("[data-map-ribbon] > title")
await expect(unknown).toContainText("24 Кбит/с")
await expect(badges).toHaveCount(0)
known = true
@@ -31,6 +95,41 @@ test("Карта не приписывает весь YouTube единствен
await expect(badges).toContainText("↓6 Кбит/с ↑2 Кбит/с")
})
test("Карта: DNS виден от экспортёра, пользователи разбиты в обеих карточках", async ({page}) => {
const router = {...server, name: "MSK", type: "jump-host"}
const dns = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 300000, bps: 8000, share: 1}
const users = [
{clientId: "u1", clientName: "Алиса", bytes: 225000, bps: 6000},
{clientId: "—", clientName: "—", bytes: 75000, bps: 2000},
]
const servicePaths = users.map(u => ({...u, viaId: "1", viaName: "MSK", viaIface: "ether1", enId: "", enName: "", serviceId: dns.id}))
await page.route("**/api/**", route => {
const url = new URL(route.request().url())
const path = url.pathname
return route.fulfill({json: path === "/api/auth/config" ? {required: false}
: path === "/api/servers" ? [router] : path === "/api/filters/gre-tunnels" ? {tunnels: [], failures: []}
: path === "/api/uptime/speed-probes" ? {probes: []} : path === flowPath ? {
...empty,
...(url.searchParams.get("range") === "24h" ? {rangeMinutes: 1440, windowSec: 86400} : {}),
totalBytes: dns.bytes, services: [dns], servicePaths, nodeUsers: {"1": users},
serviceEdges: [{fromId: "1", toId: dns.id, observedOnly: true, bytes: dns.bytes, bps: dns.bps, bpsFwd: 0, bpsRev: dns.bps}],
} : {}})
})
await page.goto("/network-map")
await expect(page.locator("[data-map-ribbon][data-observation] > title")).toContainText("MSK → DNS")
await page.getByRole("button", {name: "Сервис DNS", exact: true}).press("Enter")
const panel = page.getByRole("complementary", {name: "Детали объекта карты"})
const breakdown = panel.getByRole("region", {name: "Трафик по пользователям"})
await expect(breakdown.getByText("Алиса", {exact: true}).locator("..")).toContainText("6 Кбит/с")
await expect(breakdown.getByText("Без привязки к пользователю")).toBeVisible()
await expect(panel.getByText("Экспортёр", {exact: true})).toBeVisible()
await expect(panel.getByText(/интерфейс ether1 · выход не подтверждён/i).first()).toBeVisible()
await panel.getByRole("button").filter({hasText: /Алиса.*Наблюдение IPFIX/}).click()
await expect(panel.getByRole("button", {pressed: true}).filter({hasText: "Наблюдение IPFIX"})).toHaveCount(1)
await page.getByRole("button", {name: "Устройство MSK", exact: true}).press("Enter")
await expect(breakdown.getByText("Алиса", {exact: true}).locator("..")).toContainText("75%")
})
for (const reverse of [false, true]) test(`Карта: малый NetFlow и текущие RX/TX GRE показаны отдельно, reverse=${reverse}`, async ({ page }) => {
const exit = { ...server, name: "ARN", type: "exit-node" }
const jump = { ...server, id: 2, name: "MSK-02", host: "192.0.2.2", type: "jump-host" }
@@ -48,15 +147,20 @@ for (const reverse of [false, true]) test(`Карта: малый NetFlow и т
const exact = { fromId: String(owner.id), fromLabel: owner.name, toId: "", toLabel: "", kind: "iface", iface: tunnel.name,
bytes: 3_750_000, bps: 100_000, bpsFwd: 100_000, bpsRev: 0 }
let exactNetflow = false
let nativeAvailable = false
let liveReads = 0
await page.route("**/api/**", route => {
const url = new URL(route.request().url())
if (/\/traffic\/servers\/\d+\/live$/.test(url.pathname)) {
if (url.pathname === `/api/traffic/servers/${peer.id}/live`) {
return route.fulfill({ status: 503, json: { error: "Нет замера" } })
}
if (url.pathname === `/api/traffic/servers/${owner.id}/live`) {
expect(url.pathname).toBe(`/api/traffic/servers/${owner.id}/live`)
expect(url.searchParams.get("iface")).toBe(tunnel.name)
expect(url.searchParams.get("once")).toBe("1")
liveReads++
return route.fulfill({ json: { rxMbps: 0.16168, txMbps: 0.119224, at: "2026-11-23T07:20:36Z", timestampKind: "backend-receipt" } })
return nativeAvailable ? route.fulfill({ json: { rxMbps: 80, txMbps: 1, at: new Date().toISOString(), timestampKind: "backend-receipt" } })
: route.fulfill({ status: 503, json: { error: "Нет замера" } })
}
const json = {
"/api/auth/config": { required: false },
@@ -71,43 +175,86 @@ for (const reverse of [false, true]) test(`Карта: малый NetFlow и т
return route.fulfill({ json })
})
await page.goto("/network-map")
const badge = page.getByRole("button", { name: "Поток NetFlow между узлами" })
await expect(badge).toContainText("Нет записей")
expect(liveReads).toBe(0)
const badge = page.getByRole("button", { name: /^Связь / })
await expect(badge.locator("text")).toHaveText("—")
await expect.poll(() => liveReads).toBeGreaterThan(0)
await badge.click()
const panel = page.getByRole("complementary", { name: "Детали объекта карты" })
await expect(panel.getByText("Нет записей", { exact: true })).toBeVisible()
const live = page.getByText("Live GRE · RX/TX сейчас", {exact: true}).locator("..")
await expect(live).toContainText("↓162 Кбит/с ↑119 Кбит/с")
await expect(live).toContainText("Нет замера")
await expect(page.getByText(/Последняя минута с данными/)).toBeVisible()
exactNetflow = true
await expect(badge).toContainText("14 бит/с", {timeout: 12000})
await expect(live).toContainText("↓162 Кбит/с ↑119 Кбит/с")
await expect(badge).toContainText("↓14 бит/с ↑0 Кбит/с")
await expect(badge).toHaveAccessibleName(/14 бит\/с/, {timeout: 12000})
await expect(panel.getByText("↓14 бит/с ↑0 Кбит/с", { exact: true })).toBeVisible()
await expect(page.getByText("За интервал · 525 Б · 3 пак.")).toBeVisible()
await expect(badge).not.toContainText("Live GRE")
nativeAvailable = true
await expect(badge).toHaveAccessibleName(/81[.,]0 Мбит\/с/, {timeout: 18000})
await expect(page.getByText("Макс. из замеров · Live", {exact: true}).locator("..")).toContainText("81")
await expect(live).toContainText("↓80")
await expect(panel.getByText("↓14 бит/с ↑0 Кбит/с", { exact: true })).toBeVisible()
})
test("Карта: два GRE одного роутера к одному узлу сохраняют отдельные счётчики", async ({ page }) => {
test("Карта: параллельные GRE с разными владельцами суммируются один раз", async ({ page }) => {
const peer = { ...server, id: 2, name: "Exit", host: "192.0.2.2", type: "exit-node" }
const tunnels = ["gre-low", "gre-other"].map(name => ({
const forward = ["gre-low", "gre-other"].map((name, i) => ({
name, id: name, serverId: "1", enabled: true, status: "up", localAddress: server.host, remoteAddress: peer.host,
localInnerIp: "", remoteInnerIp: "", poolId: "", ipsec: null, mtu: 1400, keepaliveInterval: 10, keepaliveRetries: 3,
localInnerIp: `10.0.${i}.1`, remoteInnerIp: `10.0.${i}.2`, poolId: "", ipsec: null, mtu: 1400, keepaliveInterval: 10, keepaliveRetries: 3,
dscp: "inherit", clampTcpMss: true, allowFastPath: false, comment: "",
}))
const interfaceTraffic = tunnels.map(({name}, i) => ({ serverId: "1", iface: name, rxBytes: 600 * (i + 1), txBytes: 0,
const reverse = forward.map(t => ({ ...t, name: t.name + "-peer", id: t.id + "-peer", serverId: "2",
localAddress: peer.host, remoteAddress: server.host, localInnerIp: t.remoteInnerIp, remoteInnerIp: t.localInnerIp }))
const tunnels = [forward[0], reverse[0], reverse[1], forward[1]]
const interfaceTraffic = forward.map(({name}, i) => ({ serverId: "1", iface: name, rxBytes: 600 * (i + 1), txBytes: 0,
rxPackets: i + 1, txPackets: 0, inWindow: true, lastBucketAt: "2026-11-23T07:00:00Z" }))
const sample = (rxMbps: number) => ({ rxMbps, txMbps: 0, at: new Date().toISOString(), timestampKind: "backend-receipt" })
let liveReads = 0
await page.route("**/api/**", route => {
const path = new URL(route.request().url()).pathname
const url = new URL(route.request().url())
const path = url.pathname
if (path === "/api/traffic/servers/1/live" && url.searchParams.get("once") === "1") {
expect(url.searchParams.get("ifaces")?.split(",").sort()).toEqual(["gre-low", "gre-other"])
liveReads++
return route.fulfill({ json: { interfaces: {
"gre-low": { ...sample(180), at: "2026-11-23T07:20:36Z" }, "gre-other": sample(10),
} } })
}
if (path === "/api/traffic/servers/2/live" && url.searchParams.get("once") === "1") {
expect(url.searchParams.get("ifaces")?.split(",").sort()).toEqual(["gre-low-peer", "gre-other-peer"])
return route.fulfill({ json: { interfaces: { "gre-low-peer": sample(80), "gre-other-peer": sample(10) } } })
}
return route.fulfill({ json: path === "/api/servers" ? [{ ...server, type: "jump-host" }, peer]
: path === "/api/filters/gre-tunnels" ? { tunnels, failures: [] }
: path === flowPath ? { ...empty, live: true, interfaceTraffic }
: path === "/api/uptime/speed-probes" ? { probes: [] } : path === "/api/auth/config" ? { required: false } : {} })
})
await page.goto("/network-map")
const badges = page.getByRole("button", { name: "Поток NetFlow между узлами" })
await expect(badges).toHaveCount(2)
await expect(badges.filter({hasText: "↓16 бит/с"})).toHaveCount(1)
await expect(badges.filter({hasText: "↓32 бит/с"})).toHaveCount(1)
await expect(page.getByRole("button", { name: /^Связь Router → Exit: 90.*GRE ×2$/ })).toHaveCount(1)
expect(liveReads).toBeGreaterThan(0)
await page.getByRole("button", { name: "Устройство Router", exact: true }).click()
const panel = page.getByRole("complementary", { name: "Детали объекта карты" })
await panel.getByRole("tab", { name: "Интерфейсы" }).click()
await expect(panel.getByText("gre-low", { exact: true }).locator("..")).toContainText("↓ 16 бит/с")
await expect(panel.getByText("gre-other", { exact: true }).locator("..")).toContainText("↓ 32 бит/с")
})
test("Карта: карточка узла показывает отдельно фактические RX/TX RouterOS", async ({ page }) => {
await page.route("**/api/**", route => {
const path = new URL(route.request().url()).pathname
return route.fulfill({ json: path === "/api/servers" ? [server] : path === flowPath ? empty
: path === "/api/filters/gre-tunnels" ? { tunnels: [], failures: [] }
: path === "/api/uptime/speed-probes" ? { probes: [] } : path === "/api/auth/config" ? { required: false } : {} })
})
await installOpenLiveStream(page, "/api/traffic/servers/1/live", { rxMbps: 80, txMbps: 1, at: new Date().toISOString(), timestampKind: "backend-receipt" })
await page.goto("/network-map")
await page.getByRole("button", { name: "Устройство Router", exact: true }).click()
const panel = page.getByRole("complementary", { name: "Детали объекта карты" })
await expect(panel.getByText("Входящий · Live")).toBeVisible()
await expect(panel.getByText("80.0 Мбит/с")).toBeVisible()
await expect(panel.getByText("Исходящий · Live")).toBeVisible()
await expect(panel.getByText("1.00 Мбит/с")).toBeVisible()
await page.clock.fastForward(15_001)
await expect(panel.getByText("Входящий · Live")).toHaveCount(0)
})
for(const malformed of [false,true])test("Карта: NetFlow отказ и повтор "+malformed,async({page})=>{
+16 -15
View File
@@ -8,20 +8,20 @@ test.beforeEach(async({page})=>{
await page.route("**/health",r=>r.fulfill({json:{ok:true}}))
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...home,name:"Домашний роутер с очень длинным названием и описанием устройства"},{...jh,name:"Промежуточный узел с длинной подписью"}]:p==="/api/filters/gre-tunnels"?{tunnels:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
})
for(const width of [1440,390,320])test("Карта: доступные детали и адаптивная оболочка "+width,async({page})=>{
for(const width of [1440,390,320])test("Карта: доступные детали и адаптивная оболочка "+width,async({page},testInfo)=>{
await page.setViewportSize({width,height:900});await page.goto("/network-map")
await expect(page.getByRole("combobox",{name:"Устройство на карте"})).toBeEnabled()
await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true)
await page.screenshot({path:"docs/ux-ui/screens/network-map-overview-"+(width===1440?"desktop":width===390?"mobile":"narrow")+".png"})
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1")
await page.screenshot({path:testInfo.outputPath("network-map-overview.png")})
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click()
const panel=page.getByRole("complementary",{name:"Детали объекта карты"})
await expect(panel).toBeVisible();await expect(panel.getByText("Ресурсы",{exact:true})).toBeVisible()
const bounds=await panel.boundingBox(),map=width>=1024?await page.getByRole("group",{name:"Интерактивная карта сети"}).boundingBox():null
const bounds=await panel.boundingBox(),map=await page.getByRole("group",{name:"Интерактивная карта сети"}).boundingBox()
expect(bounds!.width).toBeGreaterThan(250);expect(bounds!.height).toBeGreaterThan(350)
if(width<1024)await expect(page.getByRole("group",{name:"Интерактивная карта сети"})).toBeHidden()
else expect(map!.height).toBeGreaterThan(0)
expect(map!.height).toBeGreaterThanOrEqual(390)
if(width>=1024)expect(bounds!.x).toBeGreaterThan(map!.x+map!.width/2)
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true)
await page.screenshot({path:"docs/ux-ui/screens/network-map-detail-"+(width===1440?"desktop":width===390?"mobile":"narrow")+".png"})
await page.screenshot({path:testInfo.outputPath("network-map-detail.png")})
await panel.getByRole("button",{name:"Закрыть детали устройства"}).click()
await expect(panel).toHaveCount(0)
const node=page.getByRole("button",{name:/^Устройство Домашний/});await node.focus();await node.press("Enter");await expect(panel).toBeVisible()
@@ -58,7 +58,8 @@ test("Карта: пропорции камеры, ручной масштаб
await expect(page.getByRole("button",{name:"Обновить",exact:true})).toBeEnabled();await expect(map).toHaveAttribute("viewBox",manual!)
await page.getByRole("button",{name:"Вписать карту",exact:true}).click()
expect(await map.getAttribute("viewBox")).not.toBe(manual)
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1")
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click()
await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:"Интерфейсы"}).click()
const wan=page.getByRole("button",{name:"WAN WAN",exact:true});await wan.focus();await wan.press("Enter")
await expect(page).toHaveURL(/wan=0/);await expect(wan).toHaveAttribute("aria-pressed","true")
})
@@ -66,11 +67,11 @@ test("Карта: пропорции камеры, ручной масштаб
test("Карта: pointer capture, клавиатурный pan и возврат фокуса",async({page})=>{
await page.goto("/network-map");const map=page.getByRole("group",{name:"Интерактивная карта сети"}),node=page.getByRole("button",{name:/^Устройство Домашний/})
await expect(node).toBeVisible();await map.focus();const before=await map.getAttribute("viewBox");await map.press("ArrowDown");expect(await map.getAttribute("viewBox")).not.toBe(before)
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1")
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click()
const transform=await node.getAttribute("transform"),point=await node.evaluate((g:SVGGElement)=>{const matrix=g.getScreenCTM()!;return {x:matrix.e,y:matrix.f}})
await page.mouse.move(point.x,point.y);await page.mouse.down();await page.mouse.move(point.x+80,point.y+25,{steps:5});await page.mouse.up()
expect(await node.getAttribute("transform")).not.toBe(transform);await expect(page).toHaveURL(/server=1/)
await page.getByRole("button",{name:"Закрыть детали устройства"}).click();await expect(page.getByRole("combobox",{name:"Устройство на карте"})).toBeFocused()
await page.getByRole("button",{name:"Закрыть детали устройства"}).click();await expect(page.getByRole("textbox",{name:"Поиск узла или назначения"})).toBeFocused()
const box=(await map.boundingBox())!,pan=await map.getAttribute("viewBox")
await page.mouse.move(box.x+15,box.y+box.height-50);await page.mouse.down();await page.mouse.move(box.x-30,box.y+box.height-80,{steps:5});await page.mouse.up()
expect(await map.getAttribute("viewBox")).not.toBe(pan)
@@ -78,7 +79,7 @@ test("Карта: pointer capture, клавиатурный pan и возвра
})
test("Карта: touch pan и отмена жеста без залипания",async({page})=>{
await page.setViewportSize({width:390,height:900});await page.goto("/network-map")
const map=page.getByRole("group",{name:"Интерактивная карта сети"});await expect(page.getByRole("combobox",{name:"Устройство на карте"})).toBeEnabled()
const map=page.getByRole("group",{name:"Интерактивная карта сети"});await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
expect(await map.evaluate(e=>getComputedStyle(e).touchAction)).toBe("none")
const box=(await map.boundingBox())!,before=await map.getAttribute("viewBox"),session=await page.context().newCDPSession(page)
await session.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{x:box.x+20,y:box.y+box.height-70,id:1}]})
@@ -89,9 +90,9 @@ test("Карта: touch pan и отмена жеста без залипания
await page.getByRole("button",{name:/^Устройство Домашний/}).click();await expect(page.getByRole("complementary",{name:"Детали объекта карты"})).toBeVisible()
})
test("Карта: пустой источник отличается от пустого среза",async({page})=>{
await page.goto("/network-map");await expect(page.getByRole("combobox",{name:"Устройство на карте"})).toBeEnabled()
await page.getByRole("textbox",{name:"Поиск узла"}).fill("нет такого узла");await expect(page.getByRole("status").filter({hasText:"Узлы по заданным условиям"})).toBeVisible()
await page.getByRole("button",{name:"Сбросить срез карты"}).click();await expect(page.getByRole("textbox",{name:"Поиск узла"})).toHaveValue("")
await page.goto("/network-map");await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("нет такого узла");await expect(page.getByRole("status").filter({hasText:"Узлы по заданным условиям"})).toBeVisible()
await page.getByRole("button",{name:"Сбросить срез карты"}).click();await expect(page.getByRole("textbox",{name:"Поиск узла или назначения"})).toHaveValue("")
await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
await page.route("**/api/servers",r=>r.fulfill({json:[]}));await page.route("**/api/filters/gre-tunnels",r=>r.fulfill({json:{tunnels:[],failures:[]}}))
await page.getByRole("button",{name:"Обновить",exact:true}).click()
+23 -9
View File
@@ -17,17 +17,30 @@ test.beforeEach(async ({ page }) => {
test("Карта: раскрытая легенда объясняет статусы, типы, линии и неизвестные измерения", async ({ page }) => {
await page.goto("/network-map")
const trigger = page.getByRole("button", { name: "Легенда", exact: true })
const legend = page.getByRole("region", { name: "Легенда карты" })
await expect(legend).toBeVisible()
for (const text of ["Онлайн", "Внимание", "Оффлайн", "Неизвестно", "JumpHost", "Exit Node", "Home Router", "GRE + IPsec", "Поток NetFlow"]) await expect(legend.getByText(text, { exact: true })).toBeVisible()
await expect(legend).toContainText("нет измерения")
await expect(legend).toContainText("не пропускная способность канала")
await page.locator("[data-map-legend] summary").click()
await expect(legend).not.toBeVisible()
await page.locator("[data-map-legend] summary").press("Enter")
await trigger.click()
await expect(legend).toBeVisible()
const firstStatus = legend.getByText("Онлайн", { exact: true })
await expect.poll(() => firstStatus.evaluate(element => {
const { x, y, width, height } = element.getBoundingClientRect()
const hit = document.elementFromPoint(x + width / 2, y + height / 2)
return hit !== null && element.contains(hit)
})).toBe(true)
for (const text of ["Онлайн", "Внимание", "Оффлайн", "Неизвестно", "JumpHost", "Exit Node", "Home Router", "GRE + IPsec", "Связь с сервисом"]) await expect(legend.getByText(text, { exact: true })).toBeVisible()
await expect(legend).toContainText("нет измерения")
await expect(legend).toContainText("последний замер RX/TX интерфейса RouterOS")
await expect(legend).toContainText("среднюю скорость по принятым записям IPFIX")
await trigger.click()
await expect(legend).not.toBeVisible()
await trigger.press("Enter")
await expect(legend).toBeVisible()
await legend.getByText("Онлайн", { exact: true }).click()
await page.screenshot({ path: "tmp/map270-desktop.png" })
await page.keyboard.press("Escape")
await expect(legend).not.toBeVisible()
await expect(trigger).toBeFocused()
})
test("Карта: мышь не рисует прямоугольную рамку, клавиатурный фокус остаётся видимым", async ({ page }) => {
@@ -49,15 +62,16 @@ test("Карта: мышь не рисует прямоугольную рамк
test("Карта: легенда помещается на телефоне и сворачивается", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 })
await page.goto("/network-map")
const trigger = page.getByRole("button", { name: "Легенда", exact: true })
const legend = page.getByRole("region", { name: "Легенда карты" })
await expect(page.locator("[data-map-legend]")).not.toHaveAttribute("open", "")
await expect(trigger).toHaveAttribute("aria-expanded", "false")
await page.screenshot({ path: "tmp/map270-mobile.png" })
await page.locator("[data-map-legend] summary").click()
await trigger.click()
await expect(legend).toBeVisible()
const bounds = await legend.boundingBox()
expect(bounds!.x).toBeGreaterThanOrEqual(0)
expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(390)
await page.locator("[data-map-legend] summary").click()
await trigger.click()
await expect(legend).not.toBeVisible()
})
+81
View File
@@ -0,0 +1,81 @@
import { test, expect, type Page } from "@playwright/test"
// Подписи и карточки холста не наезжают друг на друга: проверяем видимые тела (data-map-box), а не фоновые полосы.
const empty = { hops: [], live: true, rangeMinutes: 5, windowSec: 300, totalBytes: 0, namedBytes: 0, unclassifiedBytes: 0, asnLoaded: false, countryLoaded: false, services: [], serviceEdges: [], servicePaths: [], countries: [], countryEdges: [], countryPaths: [], countryServiceGroups: [], mapServiceMinSharePct: 0, dedupApplied: false, excludeMeshApplied: false, excludeOverlayApplied: false }
const srv = (id: number, name: string, type: string, country = "RU", status = "online") =>
({ id, name, host: `192.0.2.${id}`, type, country, enabled: true, status, latency: 10 + id })
const gre = (id: string, owner: number, peer: number, status = "up") => ({
id, serverId: String(owner), name: id, localAddress: `192.0.2.${owner}`, remoteAddress: `192.0.2.${peer}`, localInnerIp: "", remoteInnerIp: "",
poolId: "", ipsec: null, mtu: 1400, keepaliveInterval: 10, keepaliveRetries: 3, dscp: "inherit", clampTcpMss: true, allowFastPath: false, comment: "", enabled: true, status,
})
async function serve(page: Page, servers: unknown[], tunnels: ReturnType<typeof gre>[], flow: Record<string, unknown>) {
await page.route("**/health", (r) => r.fulfill({ json: { ok: true } }))
await page.route("**/api/**", (r) => {
const p = new URL(r.request().url()).pathname
const json = p === "/api/servers" ? servers : p === "/api/filters/gre-tunnels" ? { tunnels, failures: [] }
: p === "/api/uptime/speed-probes" ? { probes: [] } : p === "/api/traffic/flow/map-hops" ? { ...empty, ...flow }
: p === "/api/ix/topology" ? { links: [] } : p === "/api/auth/config" ? { required: false } : {}
return r.fulfill({ json })
})
}
async function overlaps(page: Page) {
return page.getByRole("group", { name: "Интерактивная карта сети" }).evaluate((svg) => {
const boxes = [...svg.querySelectorAll("[data-map-box]")].map((el) => ({ kind: el.getAttribute("data-map-box")!, label: el.closest("[aria-label]")?.getAttribute("aria-label") ?? el.parentElement?.textContent ?? "", text: el.parentElement?.querySelector(":scope > text")?.textContent ?? "", r: el.getBoundingClientRect() }))
// Панель масштаба и миникарта лежат поверх холста — они тоже не должны закрывать карточки и подписи.
const overlays = [...document.querySelectorAll("[data-map-overlay]")].map((el) => ({ kind: el.getAttribute("data-map-overlay")!, label: "", r: el.getBoundingClientRect() }))
const hits: string[] = []
const pairs = [...boxes.flatMap((a, i) => boxes.slice(i + 1).map((b) => [a, b] as const)), ...overlays.flatMap((o) => boxes.map((b) => [o, b] as const))]
for (const [a, b] of pairs) {
const ix = Math.min(a.r.right, b.r.right) - Math.max(a.r.left, b.r.left), iy = Math.min(a.r.bottom, b.r.bottom) - Math.max(a.r.top, b.r.top)
if (ix > 1 && iy > 1) hits.push(`${a.kind} «${a.label}» × ${b.kind} «${b.label}»`)
}
return { overlays: overlays.length, rates: boxes.filter((b) => b.kind === "pill" && /бит\/с/.test(b.text)).length, pills: boxes.filter((b) => b.kind === "pill").length, cards: boxes.filter((b) => b.kind === "card").length, hits }
})
}
test("Карта: 3 JH → Exit + IX, параллельные GRE и 8 сервисов без наложений", async ({ page }) => {
const servers = [
srv(1, "msk-gw01.example.net", "jump-host"), srv(2, "msk-gw02.example.net", "jump-host"), srv(3, "nov-gw01.example.net", "jump-host"),
srv(4, "arn-gw01.example.net", "exit-node", "SE"), srv(5, "chr-ix.example.net", "ix-node", "PL"),
]
// У каждого JH два туннеля до выхода и запись встречного конца на выходе; один JH ещё и до IX.
const tunnels = [1, 2, 3].flatMap((jh) => [gre(`gre-${jh}a`, jh, 4), gre(`gre-${jh}b`, jh, 4, jh === 3 ? "down" : "up"), gre(`gre-4-${jh}`, 4, jh)])
tunnels.push(gre("gre-ix", 1, 5))
const names = ["Прочее", "YouTube", "Cloudflare", "main", "AWS", "Akamai", "Google", "Telegram"]
const services = names.map((label, i) => ({ id: "svc:" + i, label, category: "Веб", bytes: 9e6 - i * 1e6, bps: 6e6 - i * 7e5, share: 0.2 - i * 0.02 }))
const serviceEdges = services.map((s) => ({ fromId: "4", toId: s.id, bytes: s.bytes, bps: s.bps, bpsFwd: s.bps / 4, bpsRev: (s.bps * 3) / 4 }))
const interfaceTraffic = tunnels.map((t, i) => ({ serverId: t.serverId, iface: t.name, rxBytes: 4e6 + i * 1e5, txBytes: 1e6, rxPackets: 10, txPackets: 5, inWindow: true, lastBucketAt: "2026-11-23T07:00:00Z" }))
await serve(page, servers, tunnels, { services, serviceEdges, interfaceTraffic, totalBytes: 5e7, namedBytes: 5e7 })
await page.goto("/network-map")
await page.getByRole("button", { name: /^Остальные сервисы \(/ }).first().click()
await expect(page.getByRole("button", { name: "Сервис Telegram", exact: true })).toBeVisible()
await expect.poll(async () => (await overlaps(page)).cards).toBe(5)
const result = await overlaps(page)
expect(result.cards).toBe(5)
expect(result.overlays).toBe(2)
expect(result.hits).toEqual([])
// Скорость NetFlow пары не теряется: она на подписи или, если не влезла между карточками, — в title линии.
expect(result.rates + await page.locator("path > title", { hasText: /^Связь .*бит\/с/ }).count()).toBeGreaterThan(0)
// Имя хоста без домена, параллельные туннели — одной подписью.
await expect(page.getByRole("group", { name: "Интерактивная карта сети" }).getByText("msk-gw01", { exact: true })).toBeVisible()
const pair = /^Связь msk-gw01\.example\.net → arn-gw01\.example\.net: .*GRE ×2/
expect(await page.getByRole("button", { name: pair }).count()).toBeLessThanOrEqual(1)
expect(await page.locator("path > title", { hasText: pair }).count()).toBeGreaterThan(0)
})
test("Карта: сетка JH × Exit и аплинки WAN без наложений подписей", async ({ page }) => {
const wan = (i: number) => ({ id: "w" + i, name: "WAN" + i, iface: "ether" + i, isp: "ISP-" + i, ip: `198.51.100.${i}`, maxDl: 100, maxUl: 50 })
const servers = [
{ ...srv(1, "home-msk", "home-router"), wanUplinks: [wan(1), wan(2)] }, { ...srv(2, "home-spb", "home-router"), wanUplinks: [wan(3), wan(4)] },
srv(3, "mt-msk-core-01", "jump-host"), srv(4, "mt-msk-lab-01", "jump-host"), srv(5, "mt-ams-test-01", "jump-host", "NL"),
srv(6, "mt-fra-edge-01", "exit-node", "DE"), srv(7, "mt-sgp-edge-01", "exit-node", "SG", "offline"), srv(8, "mt-spb-edge-01", "exit-node"), srv(9, "mt-ams-edge-01", "exit-node", "NL", "degraded"),
]
const tunnels = [3, 4, 5].flatMap((jh) => [6, 7, 8, 9].map((en) => gre(`gre-${jh}-${en}`, jh, en, en === 7 ? "down" : "up")))
await serve(page, servers, tunnels, {})
await page.goto("/network-map")
await expect(page.getByRole("button", { name: /^Устройство mt-ams-edge-01/ })).toBeVisible()
await expect.poll(async () => (await overlaps(page)).pills).toBeGreaterThan(2)
expect((await overlaps(page)).hits).toEqual([])
})
+3 -3
View File
@@ -8,12 +8,12 @@ test.beforeEach(async({page})=>{
test("Карта URL: устройство/WAN, фильтр, поиск, назначения, reload и история",async({page})=>{
await page.goto("/network-map?server=1&wan=0&filter=unknown&q=Router&dest=countries&tag=keep#anchor")
await expect(page.getByText("Ресурсы",{exact:true})).toBeVisible()
await expect(page.getByRole("textbox",{name:"Поиск узла",exact:true})).toHaveValue("Router")
await expect(page.getByRole("textbox",{name:"Поиск узла или назначения",exact:true})).toHaveValue("Router")
await page.reload();await expect(page.getByText("Ресурсы",{exact:true})).toBeVisible()
await page.getByRole("button",{name:"Онлайн",exact:true}).click()
await page.getByRole("button",{name:/^Фильтр/}).click();await page.getByRole("button",{name:"Онлайн",exact:true}).click()
await expect(page).toHaveURL(/filter=online/);await page.goBack();await expect(page).toHaveURL(/filter=unknown/)
await page.getByRole("button",{name:"Сервисы",exact:true}).click();await expect(page).not.toHaveURL(/dest=countries/);await page.goBack();await expect(page).toHaveURL(/dest=countries/)
await page.getByRole("textbox",{name:"Поиск узла",exact:true}).fill("Router URL");await expect.poll(()=>new URL(page.url()).searchParams.get("q")).toBe("Router URL")
await page.getByRole("textbox",{name:"Поиск узла или назначения",exact:true}).fill("Router URL");await expect.poll(()=>new URL(page.url()).searchParams.get("q")).toBe("Router URL")
await expect(page).toHaveURL(/tag=keep/);await expect(page).toHaveURL(/#anchor$/)
await page.getByRole("button",{name:"Устройство Router URL",exact:true}).focus();await page.keyboard.press("Escape");await expect(page).not.toHaveURL(/server=/);await expect(page).not.toHaveURL(/wan=/)
await page.getByRole("button",{name:"Устройство Router URL",exact:true}).click();await expect(page).toHaveURL(/server=1/)
+2 -2
View File
@@ -32,10 +32,10 @@ for (const width of [320, 390, 1024, 1440]) {
})
expect(visibleBounds.filter(control => !control.inside)).toEqual([])
expect(await header.locator("ol").evaluate(list => [...list.children].every(child => child.tagName === "LI"))).toBe(true)
const apps = header.getByRole("button", { name: "Приложения", exact: true })
const apps = header.getByRole("button", { name: /^Состояние системы/ })
await apps.focus()
await page.keyboard.press("Enter")
await expect(page.getByRole("menu")).toBeVisible()
await expect(page.locator('[data-slot="popover-content"]')).toBeVisible()
await page.keyboard.press("Escape")
await expect(apps).toBeFocused()
if (width < 768) {
+2 -1
View File
@@ -9,7 +9,8 @@ for(const width of [1440,320])test(`Меню приложений использ
path==='/api/servers'?[]:path==='/api/evobgp/settings'?{enabled:false,baseUrl:'',secretConfigured:false}:{}})
})
await page.goto('/servers')
await page.getByRole('button',{name:'Приложения',exact:true}).click()
if(width<768)await page.getByRole('button',{name:'Боковое меню',exact:true}).click()
await page.getByRole('button',{name:/^Переключатель приложений/}).click()
await expect(page.getByRole('menuitem',{name:'Настроить на портале',exact:true})).toHaveAttribute('href','https://runtime.example.test/admin/apps')
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1)).toBe(true)
})
+1 -7
View File
@@ -2,11 +2,5 @@ import {test,expect,type Page} from "@playwright/test"
import {emptyAlerts,emptyOutbox} from "./fixtures/alerts"
const counts={servers:4,filterRules:0,uptimeProbes:0,uptimeSpeedProbes:0,monitoringItems:0,recursiveRoutes:0}
async function setup(page:Page,reply:(path:string)=>{status?:number;json:unknown}){await page.route("**/health",r=>r.fulfill({json:{status:"ok"}}));await page.route("**/api/**",r=>{const path=new URL(r.request().url()).pathname;return r.fulfill(path==="/api/auth/config"?{json:{required:false}}:path==="/api/alerts"?{json:emptyAlerts}:path==="/api/alerts/outbox"?{json:emptyOutbox}:reply(path))});await page.goto("/alerts")}
const badge=(page:Page,name:string)=>page.getByRole("navigation",{name:"Основная навигация"}).getByRole("link",{name:new RegExp(name)}).locator("span").last()
test("Sidebar missing optional counts remain unknown; confirmed zero is displayed",async({page})=>{await setup(page,path=>({json:path==="/api/sidebar-counts"?counts:path==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:[]}));await expect(badge(page,"Серверы")).toHaveText("4");await expect(badge(page,"GRE-туннели")).toHaveText("0");await expect(badge(page,"Пользователи")).toHaveText("Пользователи")})
test("Sidebar partial GRE refresh retains last complete count, other counts update independently",async({page})=>{await page.clock.install();let partial=false;await setup(page,path=>({json:path==="/api/sidebar-counts"?{...counts,servers:partial?5:4}:path==="/api/filters/gre-tunnels"?{tunnels:partial?[]:[{name:"g",serverId:"1"}],failures:partial?[{error:"offline"}]:[]}:[]}));await expect(badge(page,"GRE-туннели")).toHaveText("1");partial=true;await page.clock.fastForward(120001);await expect(badge(page,"Серверы")).toHaveText("5");await expect(badge(page,"GRE-туннели")).toHaveText("1")})
test("Sidebar GRE does not wait for unavailable summary reader",async({page})=>{await setup(page,path=>path==="/api/sidebar-counts"?{status:503,json:{error:"counts unavailable"}}:{json:path==="/api/filters/gre-tunnels"?{tunnels:[{name:"g",serverId:"1"}],failures:[]}:[]});await expect(badge(page,"GRE-туннели")).toHaveText("1");await expect(badge(page,"Серверы")).toHaveText("Серверы")})
test("Sidebar GRE arrives while summary request is pending",async({page})=>{let started=false,release!:()=>void;const gate=new Promise<void>(resolve=>release=resolve);await page.route("**/health",r=>r.fulfill({json:{status:"ok"}}));await page.route("**/api/**",async r=>{const path=new URL(r.request().url()).pathname;if(path==="/api/sidebar-counts"){started=true;await gate;try{await r.fulfill({json:counts})}catch{};return}return r.fulfill({json:path==="/api/auth/config"?{required:false}:path==="/api/alerts"?emptyAlerts:path==="/api/alerts/outbox"?emptyOutbox:path==="/api/filters/gre-tunnels"?{tunnels:[{name:"g",serverId:"1"}],failures:[]}:[]})});try{await page.goto("/alerts");await expect.poll(()=>started).toBe(true);await expect(badge(page,"GRE-туннели")).toHaveText("1");await expect(badge(page,"Серверы")).toHaveText("Серверы");release();await expect(badge(page,"Серверы")).toHaveText("4")}finally{release()}})
test("System monitor summary failure preserves API health and last confirmed counts",async({page})=>{await page.clock.install();let fail=false;await setup(page,path=>path==="/api/sidebar-counts"&&fail?{status:503,json:{error:"summary unavailable"}}:{json:path==="/api/sidebar-counts"?counts:path==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:[]});const button=page.getByRole("button",{name:"Монитор системы"});await expect(button).toContainText("API доступен");await button.click();const popover=page.locator('[data-slot="popover-content"]');await expect(popover.getByText("4шт.",{exact:true})).toBeVisible();fail=true;await page.clock.fastForward(30001);await expect(popover.getByRole("status")).toContainText("Сводка не обновлена");await expect(popover.getByText("4шт.",{exact:true})).toBeVisible();await expect(button).toContainText("API доступен")})
test("System monitor summary failure preserves API health and last confirmed counts",async({page})=>{await page.clock.install();let fail=false;await setup(page,path=>path==="/api/sidebar-counts"&&fail?{status:503,json:{error:"summary unavailable"}}:{json:path==="/api/sidebar-counts"?counts:path==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:[]});const button=page.getByRole("button",{name:/^Состояние системы/});await expect(button).toContainText("Норма");await button.click();const popover=page.locator('[data-slot="popover-content"]');await expect(popover.getByText("4шт.",{exact:true})).toBeVisible();fail=true;await page.clock.fastForward(30001);await expect(popover.getByRole("status")).toContainText("Сводка не обновлена");await expect(popover.getByText("4шт.",{exact:true})).toBeVisible();await expect(button).toContainText("Внимание");await expect(popover.getByText("OK",{exact:true})).toBeVisible()})
+9 -8
View File
@@ -45,11 +45,11 @@ test('Статистика: смена периода скрывает стар
await expect(page.getByText('Данные 2026-09-01', { exact: true })).toBeVisible()
control.hold = true
const waiting = page.waitForRequest(r => r.url().includes('/api/statistics?') && r.url().includes('from=2026-09-02'))
await page.evaluate(() => window.history.pushState(null, '', '/statistics?from=2026-09-02&to=2026-09-03'))
await page.evaluate(() => window.history.pushState(null, '', '/statistics?from=2026-09-02&to=2026-09-03&dim=users'))
await waiting
await expect(page.getByText('Загрузка статистики…', { exact: true })).toBeVisible()
await expect(page.getByText('Данные 2026-09-01', { exact: true })).toHaveCount(0)
await page.evaluate(() => window.history.pushState(null, '', '/statistics?from=2026-09-03&to=2026-09-03'))
await page.evaluate(() => window.history.pushState(null, '', '/statistics?from=2026-09-03&to=2026-09-03&dim=users'))
await expect(page.getByText('Данные 2026-09-03', { exact: true })).toBeVisible()
const old = page.waitForResponse(r => r.url().includes('/api/statistics?') && r.url().includes('from=2026-09-02'))
control.release()
@@ -62,7 +62,7 @@ test('Статистика: ошибка pivot не показывает мет
await setup(page)
await expect(page.getByText('Данные 2026-09-01', { exact: true })).toBeVisible()
await page.route('**/api/statistics/pivot?**', route => route.fulfill({ status: 500, json: { error: 'Сводка недоступна' } }))
await page.getByRole('button', { name: 'Сводка', exact: true }).click()
await page.getByRole('tab', { name: 'Сводная (куб)', exact: true }).click()
await expect(page.getByRole('alert').filter({ hasText: 'Ошибка загрузки' })).toContainText('Сводка недоступна')
await expect(page.getByLabel('Сводка трафика')).toHaveCount(0)
await expect(page.getByText('Нет данных куба', { exact: true })).toHaveCount(0)
@@ -108,7 +108,8 @@ for (const query of ['serverId=bad', 'planes=unknown', 'country=RU&country=DE'])
await expect(page.getByLabel('Сводка трафика')).toHaveCount(0)
expect(requests).toHaveLength(before)
await page.getByRole('button', { name: 'Сбросить параметры отчёта', exact: true }).click()
await expect(page.getByText('Данные 2026-09-01', { exact: true })).toBeVisible()
await expect(page.getByLabel('Сводка трафика')).toBeVisible()
await expect(page.getByRole('tab', { name: 'Обзор', exact: true })).toHaveAttribute('aria-selected', 'true')
const url = new URL(page.url())
expect(url.searchParams.get('from')).toBe('2026-09-01')
expect(url.searchParams.get('keep')).toBe('1')
@@ -156,11 +157,11 @@ test('Статистика: клавиатурный выбор среза и д
await expect(page.getByRole('listbox')).toHaveCount(0)
await expect(criterion).toBeFocused()
await page.route('**/api/statistics/pivot?**', route => route.fulfill({ json: { rowDim: 'country', colDim: 'service', metric: 'bytes', columns: [], rows: [], otherBytes: 0 } }))
const pivot = page.getByRole('button', { name: 'Сводка', exact: true })
const pivot = page.getByRole('tab', { name: 'Сводная (куб)', exact: true })
await pivot.focus()
await page.keyboard.press('Enter')
await expect(pivot).toHaveAttribute('aria-pressed', 'true')
await expect(page.getByRole('button', { name: 'Разрез', exact: true })).toHaveAttribute('aria-pressed', 'false')
await expect(pivot).toHaveAttribute('aria-selected', 'true')
await expect(page.getByRole('tab', { name: 'Срезы', exact: true })).toHaveAttribute('aria-selected', 'false')
await expect(page.getByRole('combobox', { name: 'Строки', exact: true })).toBeVisible()
await expect(page.getByRole('combobox', { name: 'Колонки', exact: true })).toBeVisible()
})
@@ -172,7 +173,7 @@ for (const pivot of [false, true]) {
const crashes: string[] = []
page.on('pageerror', error => crashes.push(error.message))
await page.route(pivot ? '**/api/statistics/pivot?**' : '**/api/statistics?**', route => route.fulfill({ json: {} }))
if (pivot) await page.getByRole('button', { name: 'Сводка', exact: true }).click()
if (pivot) await page.getByRole('tab', { name: 'Сводная (куб)', exact: true }).click()
else await page.reload()
await expect(page.getByRole('alert').filter({ hasText: 'Ошибка загрузки' })).toContainText(pivot ? 'Некорректный ответ сводной статистики' : 'Некорректный ответ статистики')
await expect(page.getByRole('button', { name: 'Повторить загрузку', exact: true })).toBeVisible()
+4
View File
@@ -30,6 +30,10 @@ async function setup(page: Page) {
test('Детали трафика: поздний период не заменяет текущий', async ({ page }) => {
const control = await setup(page)
const reading = page.getByRole('slider', {name: 'Точка на графике'})
await expect(reading).toHaveAttribute('aria-valuetext', /сейчас · RX 2.* · TX 3/)
await reading.press('Home')
await expect(reading).toHaveAttribute('aria-valuetext', /RX 1.* · TX 2/)
control.holdRange = '24h'
const started = page.waitForRequest(r => new URL(r.url()).pathname === '/api/traffic/servers/1' && r.url().includes('range=24h'))
await page.getByRole('button', { name: '24ч', exact: true }).click()
+20
View File
@@ -2,6 +2,26 @@ import { observedTrafficFixturePayload } from "./traffic-observation-fixture"
import { installOpenLiveStream, resumeLiveStream, sendLiveHeartbeat } from "./live-stream-fixture"
import { test, expect } from '@playwright/test'
test("Трафик открывает сервер из ссылки карты", async ({ page }) => {
const second = { id: "2", name: "Выбранный Exit", site: "TEST", country: "RU", status: "online", rxNow: 2, txNow: 3,
rxPeak: 5, txPeak: 6, rxTotal: 100, txTotal: 200, sessions: 1, rxSeries: [1, 2], txSeries: [2, 3] }
const first = { ...second, id: "1", name: "Первый роутер" }
const requested: string[] = []
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
await page.route("**/api/**", route => {
const { pathname } = new URL(route.request().url())
if (/\/traffic\/servers\/\d+\/live$/.test(pathname)) requested.push(pathname)
const data = pathname === "/api/auth/config" ? { required: false }
: pathname === "/api/traffic/servers" ? { servers: [first, second] }
: pathname === "/api/traffic/servers/2" ? { server: second }
: pathname === "/api/traffic/users" ? { users: [] } : { interfaces: [] }
return route.fulfill({ json: observedTrafficFixturePayload(data) })
})
await page.goto("/traffic?server=2")
await expect(page.getByLabel("Скорость выбранного сервера")).toBeVisible()
await expect.poll(() => requested).toEqual(["/api/traffic/servers/2/live"])
})
for (const variant of ['closed', 'invalid', 'http-error', 'silent', 'awaiting'] as const) {
test(`Трафик: SSE ${variant} не выдаёт старое измерение за live`, async ({ page }) => {
const server = { id: '1', name: 'Тестовый сервер', site: 'TEST', country: 'RU', status: 'online', rxNow: 2, txNow: 3, rxPeak: 5, txPeak: 6, rxTotal: 100, txTotal: 200, sessions: 1, rxSeries: [1, 2], txSeries: [2, 3] }
+59
View File
@@ -0,0 +1,59 @@
import { test } from "node:test"
import assert from "node:assert/strict"
import { MAP_CARD_H, MAP_CARD_W, MAP_PILL_H, mapLinkPath, mapLinkPoint, mapRibbons, placeMapLinkLabels, type MapBox } from "../../lib/network-map-layout"
const card = (x: number, y: number): MapBox => ({ x: x - MAP_CARD_W / 2, y: y - MAP_CARD_H / 2, w: MAP_CARD_W, h: MAP_CARD_H })
const hit = (a: MapBox, b: MapBox) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
const pill = (p: { x: number; y: number; w: number }): MapBox => ({ x: p.x - p.w / 2, y: p.y - MAP_PILL_H / 2, w: p.w, h: MAP_PILL_H })
test("кривая связи проходит через концы и середину", () => {
const l = mapLinkPath({ x: 0, y: 0 }, 10, { x: 200, y: 100 }, 10)
assert.deepEqual(mapLinkPoint(l, 0), { x: 10, y: 0 })
assert.deepEqual(mapLinkPoint(l, 1), { x: 190, y: 100 })
assert.deepEqual(mapLinkPoint(l, 0.5), { x: 100, y: 50 })
})
test("подписи не наезжают на карточки и друг на друга, длинная — укорачивается или пропадает", () => {
// Три JH слева сходятся в один EN справа; у каждой пары — длинный и короткий вариант подписи.
const jh = [100, 180, 260].map((y) => ({ x: 542, y }))
const en = { x: 780, y: 180 }
const obstacles = [...jh.map((p) => card(p.x, p.y)), card(en.x, en.y)]
const labels = jh.map((p, i) => ({
id: "jh" + i,
link: mapLinkPath(p, MAP_CARD_W / 2, en, MAP_CARD_W / 2),
texts: ["24 мс · 86 Мбит/с", "24 мс"],
}))
// Горизонтальная связь в узком зазоре: длинной подписи места нет нигде.
labels.push({ id: "flat", link: mapLinkPath({ x: 542, y: 400 }, MAP_CARD_W / 2, { x: 780, y: 400 }, MAP_CARD_W / 2), texts: ["очень длинная подпись связи"] })
obstacles.push(card(542, 400), card(780, 400))
const placed = placeMapLinkLabels(labels, obstacles)
assert.ok(placed.length >= 3, "подписи трёх сходящихся связей размещены")
assert.equal(placed.find((p) => p.id === "flat"), undefined, "не влезающая подпись не рисуется")
for (const [i, a] of placed.entries()) {
for (const o of obstacles) assert.equal(hit(pill(a), o), false, a.id + " поверх карточки")
for (const b of placed.slice(i + 1)) assert.equal(hit(pill(a), pill(b)), false, a.id + " поверх " + b.id)
}
})
test("ленты NetFlow уложены стопкой у узла и толще у большей скорости", () => {
const exit = { x: 780, y: 300 }
const flows = [
{ id: "a", from: exit, fromHalfW: 80, to: { x: 1080, y: 200 }, toHalfW: 140, bps: 300 },
{ id: "b", from: exit, fromHalfW: 80, to: { x: 1080, y: 400 }, toHalfW: 140, bps: 100 },
]
const [a, b] = mapRibbons(flows, 40)
assert.equal(a.w, 30)
assert.equal(b.w, 10)
// У выхода ленты лежат вплотную по центру карточки (стопка 40 px при пике 400 — сумма у выхода).
assert.match(a.d, /^M 860 295\.0 /)
assert.match(b.d, /^M 860 315\.0 /)
assert.match(a.d, / 940 200\.0$/)
})
test("совпадающие середины двух связей разводятся по своим кривым", () => {
const a = mapLinkPath({ x: 0, y: 0 }, 0, { x: 300, y: 200 }, 0)
const b = mapLinkPath({ x: 0, y: 200 }, 0, { x: 300, y: 0 }, 0)
const placed = placeMapLinkLabels([{ id: "a", link: a, texts: ["12 мс"] }, { id: "b", link: b, texts: ["14 мс"] }], [])
assert.equal(placed.length, 2)
assert.equal(hit(pill(placed[0]), pill(placed[1])), false)
})